diff --git a/.gitea/scripts/ci_checkout.sh b/.gitea/scripts/ci_checkout.sh index 37c4b52..aeaa55a 100755 --- a/.gitea/scripts/ci_checkout.sh +++ b/.gitea/scripts/ci_checkout.sh @@ -108,9 +108,23 @@ if [ -n "$BEFORE" ] && [ "$BEFORE" != "$ZERO" ]; then if git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then echo "✅ 事件 before ${BEFORE:0:12} 已在克隆里(本次推送范围可直接算)" else - gitauth fetch -q --depth 50 origin "$BEFORE" 2>/dev/null \ - && echo "✅ 已补取事件 before ${BEFORE:0:12}" \ - || echo "⚠️ 取不到事件 before ${BEFORE:0:12}:范围校验会明确失败,不会静默收缩" + # ⚠️ 为什么重试一次:浅克隆里用 `fetch --depth` 取一个**未公开**的对象(撤销/改写推送之后 + # 的旧提交就是这种)时,git 会在这次 fetch 中途重写 .git/shallow,随后发现自己读到的 + # 与开始时不同就整体中止:`fatal: shallow file has changed since we read it`。 + # 实测(run 305–317,含原地重跑)这一步必中止,而**同一仓库里紧接着重试同一条命令即成功**。 + # before 取不到 ⇒ commits 检查算不出范围 ⇒ 流水线红,且红的原因与代码质量无关。 + # 重试只负责"把 before 取进克隆",不收缩范围;两次都失败仍明确报警,由 commits 检查判红。 + FETCH_OK="" + FETCH_ERR="" + for _attempt in 1 2; do + FETCH_ERR="$(gitauth fetch -q --depth 50 origin "$BEFORE" 2>&1 >/dev/null || true)" + if git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then FETCH_OK=1; break; fi + done + if [ -n "$FETCH_OK" ]; then + echo "✅ 已补取事件 before ${BEFORE:0:12}" + else + echo "⚠️ 取不到事件 before ${BEFORE:0:12}:范围校验会明确失败,不会静默收缩(最后一次错误:${FETCH_ERR:0:160})" + fi fi else echo "(事件里没有 before / before 为全 0:新分支推送,范围按默认分支为基准判)" diff --git a/AGENTS.md b/AGENTS.md index 4d20155..c8958c4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,4 +68,7 @@ python3 ~/.hermes/scripts/gitea_api.py GET "/api/v1/repos/Weknora/knowledge-gove | # | 一句话 | 全文 | | --- | ------ | ---- | -| — | (待填) | — | +| 14 | 包一层装饰器就丢掉可选接口 ⇒ 写集合台账被静默跳过 | `docs/agents/traps.md` | +| 15 | Stat/Delete/Copy 与 Open/Put 吃不同的定位符形状 | `docs/agents/traps.md` | +| 16 | "资源不在预备份范围"≠"属于别的知识库",复用只认可审计证据 | `docs/agents/traps.md` | +| 17 | 分页窗口当索引:"当前生效版本"不能按最近 N 条找 | `docs/agents/traps.md` | diff --git a/CHANGELOG.md b/CHANGELOG.md index e416a07..39a7167 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,1551 @@ # Changelog +## 开发快照 0.1.399(系统设置分区调整:AI 模型连接 / 知识库映射) + +### Changed + +- 原「系统设置 → 服务配置」改名为「AI 模型连接」,只保留问答四字段分析与中文翻译共用的 + 模型连接(地址、模型、密钥操作、测试连接、保存),不再混放 WeKnora 连接。 +- WeKnora 测试/生产地址、生产租户与知识库 ID 迁到「知识库映射」,与测试入库、封存源、 + 生产目标同屏;两个 ID 收进「生产核验参数」,并注明只用于核验、不决定发布写入目标。 +- 连接配置在独立组件内维护自己的草稿:保存只提交连接的四项,刷新参数取服务器当前值; + 保存刷新策略也不会带上未保存的连接地址。 +- 凭据仍是服务器文件引用,连接卡只报状态,页面不提供 API Key 录入。 +- 同步更新 README、运维手册、验收清单中的入口路径。 + +## 开发快照 0.1.384(系统设置审查修复:能力心跳、封存源对照、分区合并) + +### Added + +- `GET /api/v1/system/worker-capabilities`:读取 worker 认领记录里的 job_types, + 页面据此显示“执行器已启用/已停用/无认领”,不再把 readiness 当成可接单。 +- 测试知识库绑定接口返回整库封存源与一致性状态,设置页同屏对照“入库目标 / 封存源”。 + +### Changed + +- 系统设置分区合并为“知识库映射”(测试入库 + 生产目标 + 封存源对照)。 +- 服务卡片分三行:地址可达、凭据与库读取、执行器能力。 + +## 开发快照 0.1.383(发布管理精简 + 系统设置审查修复) + +### Changed + +- 发布管理:顶部改为「状态卡 + 下一步」,一个主按钮(启动同步/查看任务)+ 一个准备按钮 + (封存/基线/签发授权);启动条件、检查清单、恢复验证收进「发布前检查」; + 目标维护、差异明细、来源身份收进「高级与历史」。去掉重复的版本入口与说明。 + +### Fixed + +- 服务配置与刷新策略各自保存边界:保存一方不再夹带另一方未保存的草稿(F03)。 +- 系统设置分区独立加载:监控/目录失败不再挡住成员与备份入口;保存后重新探测服务状态(F09)。 +- 解析停滞阈值接入活动配置(worker 60 秒内生效),收尾超时仍只保存并在页面标注未接入(F02)。 +- 重置密码改为受控遮罩对话框,不再用浏览器 prompt(F11)。 +- 生产绑定:文档级旧配置收进折叠区,凭据缺失时说明不影响整库执行器(F05/F06)。 +- 备份:主机未接通时明确「当前计划不会执行」,无运行记录时失败库显示未知(F07)。 +- 文案统一:生产租户 ID、备份执行主机、收尾超时告警;技术细节不再占据主视图(F10)。 + +## 开发快照 0.1.382(采集 agent 允许显式 peer uid) + +### Added + +- 采集 agent 新增 `--allow-peer-uid`:默认仍只允许与 agent 同 uid 的连接;容器以固定 + 非 root 用户运行时,由部署参数显式列出该 uid。socket 文件权限之外再加一层 uid 校验, + 放行清单来自部署,不是"谁都能连"。 + +## 开发快照 0.1.381(维护窗口支持显式 no-gate 测试模式) + +### Added + +- 维护窗口新增显式入口形态 `LIBRARY_TARGET_INGRESS_MODE=gate|none`,缺省 `gate`: + 不写这个变量时行为与之前完全一致(缺任何闸门项照原文案拒绝)。`none` 只给 + "整栈没有入口闸门"的 0.9.0 测试栈,且必须同时给 `LIBRARY_NO_INGRESS_ACK=test-only` + (逐字符相等,空值/大小写/前后空格都不算确认,拒绝并点名该变量)。 +- `none` 下允许缺 `LIBRARY_TARGET_INGRESS_URL/SERVICE/DRAIN_FILE`,但 + `LIBRARY_TARGET_INSTANCE`、`LIBRARY_TARGET_REDIS_ADDR/PASSWORD/DB` 与新增的 + `LIBRARY_TARGET_HEALTH_URL` 仍必需;半套闸门声明(mode=none 又给了闸门项)直接拒绝。 + 窗口内一笔闸门动作都不做,开窗顺序为"停写者 → 队列排空 → 导出",恢复后重启写者并等 + 健康探针返回 200 才算目标回来;崩溃恢复同样不会假装开过闸门。 +- 维护记录/冻结日志写入 `ingress_mode`、`ingress_ack`,`gate` 证据位置写 + `{"mode":"none","reason":"stack has no ingress gate (test-only)"}`(不写 closed/drained=false + 这种"关了但没排空"的假象),健康探针地址与"已验证"另记;恢复/接管要求记录的入口形态与 + 当前配置一致,否则拒绝。接口/页面的入口状态在 `none` 下显示"无闸门(测试模式)"。 + +### Tests + +- `internal/libraryfreeze`:no-gate 窗口可开且记录含 `ingress_mode=none`、无 `gate_reopened`、 + 健康探针在恢复后被调用;写者退出码非 0(被代理服务 SIGTERM 的常态)不再被当作排空依据, + 排空由"写者全停 + 队列静默"证明;健康探针不过 → `held/ingress_unverified`。 + gate 模式的记录仍写 `ingress_mode=gate` 且保留 closed/drained 原形状。 +- `internal/librarymaintenance` / `cmd/libraryctl`:缺确认串、确认串含空格、未知形态都拒绝并点名; + `none` + 确认串时可解析且不再要求入口三项;gate 缺入口项仍是原拒绝行为。 + +## 开发快照 0.1.380(采集绑定允许对外库未配置) + +### Fixed + +- `libraryctl` 读 `routing_kb_bindings` 不再要求两列都非空:`internal_kb_id` 必填, + 为空时报 `对内知识库未绑定(routing_kb_bindings.internal_kb_id 为空)`;`external_kb_id` + 允许为空(平台约定「对外库没有对应目标时留空」),绑定仍然有效,`status` 与 + `-scope internal` 照常可用。`-scope external` 在未配置时明确失败并报 + `对外知识库未配置(routing_kb_bindings.external_kb_id 为空)`,不回退到对内库。 + `preflight` / `capture` / `dead-letters` 三条命令都在连源库、开维护窗口之前 + 定住本次 scope 的目标库,缺绑定不会再退化成 `knowledge base not found in source`。 +- 读取 SQL 对两列 `COALESCE`:0.9.0 迁移把旧绑定清成 NULL 后,裸拼接会让文件模式 + (P1c 的 governance DSN)在 `Scan` 到 string 时失败,报出的还是 + `read routing bindings failed`;NULL 与空串现在同等处理,容器模式与文件模式共用 + 同一条查询与同一份解析语义。没有生效绑定行(空输出)归入「对内库未绑定」。 + +### Tests + +- 新增 `cmd/libraryctl` 绑定解析用例:internal 为空拒绝并点名(含 NULL 形状的 + `|`、空输出、空串);external 为空解析成功且 external scope 被拒、不回退; + 两列都有时行为不变(含 psql 行尾换行与首尾空格)。另有一条不连库的查询形状 + 断言,锁住两列都必须 `COALESCE`、且仍产出 `|`。 + +## 开发快照 0.1.379(采集接入 RDS 型 0.9.0 栈) + +### Added + +- `libraryctl` / `libraryagent` 的数据库来源可选:`-source-pg` 为空时用 `-source-app` + 容器环境里的 `DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD` 直连托管实例(RDS), + TLS 模式取 `LIBRARY_SOURCE_DB_SSLMODE`(默认 `require`,`disable` 仅在显式测试时允许); + `-governance-pg` 为空时从 `LIBRARY_GOVERNANCE_DSN_FILE` 指向的 0600 文件读治理库 DSN。 + 两个都配置时行为与原来完全一致(容器模式),0.7.1 栈不受影响。 +- 新增 `scripts/library-capture-v090.sh`:Compose 项目 `weknora-v090` 的整库采集入口, + 唯一写入者 `app`,其余服务逐个声明理由;两个数据库走外部模式(RDS),归档/日志根 + 默认 `/var/lib/knowledge-governance/{library,freeze}` 并可用环境变量覆盖; + `LIBRARYCTL_BIN` 未设置或不可执行时明确失败,不做"同目录二进制"回退。 +- `libraryctl status` 增印 `databases.source_db/governance_db` 模式(`container|external|file`), + `libraryagent -describe` 输出同样两项;地址与凭据一律不出现。 + +### Tests + +- DSN 来源三条路径(容器 / RDS / 治理库文件)各有用例;缺变量、缺文件、权限过宽、 + 非 PostgreSQL 内容都要求失败关闭,且断言错误里不含口令;`sslmode=prefer` 这类会静默 + 降级的取值直接拒绝。 +- v090 采集脚本进 CI:`bash -n` 语法检查 + 标志/服务声明断言,并拒绝 0.7.1 的 + 容器名与项目名出现在新入口里。 + +## 开发快照 0.1.378(发布写入支持 WeKnora 0.9.0) + +### Added + +- 整库发布写入路径支持 WeKnora 0.9.0(schema 134):生产整库目标在装配时解析目标 + profile,表集合、清理顺序、编目与整实例指纹都按解析结果取数——0.9.0 没有 + `wiki_log_entries`,不再对目标查询或删除该表;0.7.1 少一张必需表仍然失败,不靠 + 「表不存在就跳过」放行。 +- `chunks.seq_id` 语义保持:发布时由目标序列分配,回滚时按写前镜像原值重放; + 0.9.0 新增的 NOT NULL 列走目标默认值,不用来源值硬填。 +- 跨版本发布(74 快照 → 134 目标,或反之)明确拒绝,错误同时点名两个版本号。 + +### Fixed + +- 范围改写重建快照时会丢掉 `SchemaVersion`/`Profile`(归档重建、快照克隆两处): + 丢掉后下游按「未知版本 = 0.7.1」处理,0.9.0 的归档会被要求提供它根本没有的 + `wiki_log_entries`,跨版本闸门也形同不存在。现在快照复制一律带上 schema 契约。 +- 单文档发布包(`releasebundle`)仍只支持 0.7.1,但改为**明确拒绝并说明原因**: + 报错点名读到的版本与「0.9.0 应走整库发布路径」,不再与字段写错共用一句泛化错误。 + +### Tests + +- 真实 0.9.0 schema + 索引 + 对象存储上的发布路径:导出 → 封存 → 真实 + `ProductionLibraryTarget` 写入干净 134 目标 → 逐表内容核对(Wiki 非空、资源指向 + 目标桶/后端、`seq_id` 由目标序列分配)→ 用写前镜像恢复回滚并核对回到写前状态; + 另加 74→134 拒绝(含两个版本号)与「134 目标无 `wiki_log_entries` 不报错」的负例。 + +## 开发快照 0.1.376(WeKnora 0.9.0 整库发布 profile) + +### Added + +- 整库发布支持 WeKnora 0.9.0(schema 134):按版本号选中 profile,再用 information_schema + 探测必需表与必需列,缺项精确报到「表」或「表.列」;未知版本、脏库一律拒绝,不做 + 「版本大于某值就放行」的推断。 +- 0.9.0 的索引契约改从部署配置读取(该版本知识库不写 `vector_store_id`);两处来源都 + 拿不到时报错,而不是用空串去匹配索引;0.7.1 若两处都有但互相矛盾,同样拒绝。 +- 归档部件集合随 profile 变化:0.9.0 已删除 `wiki_log_entries`,因此该部件不再要求; + 其余 Wiki 部件仍是必需,空 Wiki 不能冒充完整。 + +### Fixed + +- 采集、导入、Wiki 替换与「去使能」四条路径原先写死 schema 74,遇到 0.9.0 直接失败; + 现在同版本(74↔74、134↔134)往返可用,跨版本搬运会明确拒绝而不是误放行。 + +### Tests + +- 真实 0.9.0 schema 与真实索引映射上跑完整往返:导出 → 封存(真实清单校验)→ 导入 + 干净库 → 再导出逐行内容一致;另加未知版本、脏库、缺表、缺列、索引名解析不到等负例。 + +## 开发快照 0.1.375(工作台界面:越疆配色、页头统一与筛选批量条) + +### Changed + +- 全站配色改取越疆官网:品牌钴蓝 #0039C8 为唯一强调与主操作色,文字与底色改为中性灰, + 侧栏改为明亮底;卡片细边 + 极轻投影。只改前端样式,业务语义、权限、确认流程与接口不变。 +- 六个模块页头统一(标题/说明/右侧操作位置与字号一致,左边缘对齐)。 +- 解析监控:指标卡口径改为徽标,文件处理标明「当前筛选 N 项 · 本页 M 项」,清除筛选显示 + 已生效筛选数,时间范围改为浮层,批量条只在选中后高亮。 +- 来源与目录:「已选 N 项」紧跟全选,策略按钮改为浅底语义色并只在选中后高亮整条, + 📁/📄 换为线性图标。 +- 问答流水:会触发后台写入的「立即同步」改为描边次按钮,与只读「查询」区分。 +- 侧栏底部环境标注由「本地治理环境」改为「云测试环境」。 + +### Fixed + +- 悬停侧栏导航时被全局按钮悬停样式刷成白底、选中项文字几乎不可见。 +- 若干样式引用了从未定义的 CSS 变量(--border、--card、--brand、--danger-ink 等), + 相应边框/颜色此前只靠回退值或根本不生效,现已指向正式令牌。 + +## 开发快照 0.1.369(周报发送记录读回与未知投递收口) + +### Fixed + +- 修复周报“发送记录”读取:查询只取 6 列却按 7 个字段扫描(多出 message_id),只要该周或历史 + 里存在任意一条发送记录,列表接口就整体报“周报邮件暂不可用”,发送成功后刷新页面必然报错。 + 现在查询与字段一一对应,并在读取出错时如实失败(不把截断的历史当成完整列表)。 +- 区分“发送失败”与“投递结果未知”:DATA 已提交、但没收到服务器最终 250(连接中断/超时)时, + 邮件可能已经进入收件人邮箱。此前的实现把它记成 failed 并允许下一分钟自动重发,可能重复投递。 + 现在这类结果保留“发送中(结果未知)”,自动与手工路径都不再重发,并提示先核对已发出的邮件; + 明确拒绝(认证失败、RCPT 550、连接建立前失败)仍记为失败并可重试一次。 +- SMTP 交互增加有限超时(默认 90 秒,随请求 ctx 收紧并可被取消打断),避免服务器接受 DATA + 后不再响应时把 worker 和发送记录挂死。 + +### Tests + +- 真实隔离 PostgreSQL:非空发送历史(sent + failed)下单周/全量读回必须成功并带回真实 + message_id(旧实现先 RED:ErrUnavailable);HTTP 发送记录接口在非空历史下 200。 +- 本机 TLS SMTP 桩 + 真实 SMTPMailer:成功、RCPT 550 明确拒绝、DATA 后丢失最终 250、 + DATA 阶段卡死(受 ctx 期限约束)四类结果分类正确;真实 deliver 在未知结果时留“发送中” + 且不再重发,在明确拒绝时记失败并允许重试一次成功。 + +## 开发快照 0.1.368(周报发送窗口与正式补发修复) + +### Fixed + +- 修复周报自动发送在“周日 23:00”这类配置下必然空转的问题:发送窗口现在按配置的发送日 + 推导要发的周(周日窗口发当天结束的那一周,其它工作日仍发上一完整周),不再等周一的 + 零点——那一刻配置的窗口已经过去。周一 09:00 的原有语义保持不变。 +- 自动发送只处理该窗口对应的那一周,不再按“所有已结束的周”补发,避免一次失败演变成 + 无界历史回填;其它周如有需要,由管理员显式补发。 +- 修正发送记录认领逻辑:只有 failed(或首次)记录会被重新认领,已发送(sent)返回幂等 + 结果并带出真实 message_id;上次结果未知的“发送中”记录不再被盲目重发,而是明确拒绝 + 并提示先核对邮箱。自动发送与手工补发并发或重复点击时只投递一次。 +- 失败不再笼统显示“稍后重试”,发送记录与界面都带上真实 SMTP 原因;失败/结果未知都不 + 会写成功。 + +### Added + +- 新增管理员“正式补发”入口(周报页按钮 + `POST /api/v1/qa-ops/master/weekly-mail/send/{week}`)。 + 必须登录管理员、同源操作意图,并精确指定周、已确认版本与正文 hash;只允许已结束的周, + 当前周需等到设定时点,未来周一律拒绝。正文、看板图片、主送/抄送与自动发送共用同一条 + 渲染与投递路径,正式收件人照旧;确认框显示真实收件人数与版本,补发结果写入正式发送 + 记录并可读回 message_id。它与“发送测试邮件”(只发 review 地址、不登记)是两件事。 + +### Tests + +- 真实隔离 PostgreSQL:周日 23:00 当周发送 RED/GREEN(旧实现真实复现 nothing_confirmed)、 + 到点前/未来周/未确认/正文或版本变化拒绝、周一发上一周的语义保持、手工补发只投递一次 + 并读回 message_id、未来周与未到时点被拒、自动+手动并发只投递一次、结果未知不重发、 + 失败如实记录且可重试一次。 +- HTTP 与前端:补发接口仅管理员+同源意图、拒绝原因具体、真实失败返回 502、预览显示正式 + 收件人数;前端解析拒绝无 message_id 的“成功”。 + +## 开发快照 0.1.366(启动收敛误判修复与误判核对审计) + +### Fixed + +- `ReconcileLibraryJobs` 启动收敛不再把仍为 pending/running、但 capture queue 已 + `completed` 的封存业务作业误判为“队列不存在”;completed 队列保留待核对状态, + failed/cancelled/missing 仍按真实队列状态处置。 +- 管理员核对入口增加唯一允许的“系统误判”失败形态:原 state=failed、stage 为空、 + snapshot 为空且 error/recovery 精确匹配历史启动误判;仍须 completed queue、 + export succeeded、唯一 test_sealed 版本、来源身份和归档字节复核。真实失败/取消/ + 其他 error 一律拒绝。 +- 新增 `library_job_repairs` 不可变审计表(migration 80):在同一事务内 CAS 比对原 + state/stage/error/recovery/finished_at,保存原值、actor、原因和精确证据后再修复原行; + 审计写入失败则回滚,不静默覆盖。 +- UI 仅在该精确误判形态显示“核对封存结果”,真实失败没有入口;成功后刷新原作业 + 和快照状态。 + +### Tests + +- 真实隔离 PostgreSQL:启动收敛 pending+completed 保留 RED/GREEN;真实 handler + 纵向启动→核对 pending 与系统误判 failed;审计原字段与重复幂等;错误 failed/取消/ + 缺失/错证据拒绝。 + +## 开发快照 0.1.365(封存终态回写与精确核对) + +### Fixed + +- `AdvanceLibraryJob` / `AdvanceLibraryJobGuarded` / `UpdateLibraryStage` 对 + `varchar` 状态/阶段列的参数显式使用 `::text`,修复真实 DDL 下 + `SQLSTATE 42P08 inconsistent types deduced for parameter $2`;封存终态不再 + 因类型推断失败而停留在 pending。 +- worker 封存开始状态/阶段写入失败时不再吞错进入源导出;成功终态的 stage 与 + job 回写失败返回错误,不把队列 completed 当成业务成功。 +- 新增管理员 `POST /api/v1/library/jobs/{id}/reconcile-capture`:只接受 + completed `library.capture`、精确 job/scope/source 的 `test_sealed` 版本、 + export succeeded 阶段和归档完整复核;修复该作业终态并记录幂等审计操作。 + 不重新封存、不产生快照、不写源或目标知识,不改首因及其他历史记录。 + +### Tests + +- 真实 `varchar(16)/varchar(32)` DDL 的 pending→running→failed→succeeded、 + snapshot/finished_at 与第一因保留回归;`r3i-42p08-red.txt` / `r3i-42p08-green.txt`。 +- worker 持久化失败注入测试;capture reconcile 错 queue/stage/version/source/ + archive 与幂等正例。 + +## 开发快照 0.1.364(恢复保留错误的第一因分类;部署基线稳定性) + +### Fixed + +- worker 恢复 `terminalLibraryCaptureError`,仅保留仍存在的两个确定性 marker: + `missing library generated question index`、`empty library index content`。已恢复 + 写入者后走 `jobs.Permanent(validation_failed)`,保留原错误消息;已取消的正文 + 索引覆盖 marker 和网络超时仍可重试,不再恢复推断门槛。 +- 本机部署 preflight 不再用 lifetime `RestartCount=0` 作为旧基线稳定性定义: + 绑定容器 ID/image/env/mount/StartedAt/RestartCount,间隔采样确认 running、 + StartedAt/RestartCount 不变;历史非零但稳定允许,采样变化/切换实例拒绝。 + 新 api/worker/web 容器仍要求 running、ready、零重启。 + +### Tests + +- 保留错误分类 RED→GREEN:`r3g-terminal-red.txt` / `r3g-terminal-green.txt`。 +- 部署 strict fake 增加旧基线非零稳定正例、RestartCount 递增拒绝、实例 ID 切换 + 拒绝;本机候选包重新绑定最终 SHA。 + +## 开发快照 0.1.363(取消封存索引推断规则,原样捕获源集合) + +### Removed + +- 删除治理封存按 `status`、`chunk_type`、`parent/mixed/flat` 推断“某 chunk 必须有 + 基础正文索引”的规则:移除 `needOriginal`、`mixedDocs`、索引覆盖循环及相关状态 + 字段。源端有没有独立正文索引不再阻断封存。 +- 删除 `parent_chunk_id` 的类型搭配门槛:不再要求 parent 只能是 `parent_text`,也不 + 对 summary/OCR/caption 指定 parent 类型。保留父引用存在、同 knowledge 等实际引用 + 完整性;不补关联、不改源数据。 +- 同步移除该推断在 preflight/archive/load/replay/writeset 的共用校验和当时已无 + 用途的 worker 永久失败分类;旧快照、旧失败记录原样保留,不篡改历史状态。 +- 0.1.362 的索引覆盖门槛未部署,现被本版本取消;0.1.362 原文保留为历史,不再作为 + 当前契约。 + +### Retained + +- 实际导出 PG/ES 集合、原始正文/问题 metadata/向量/引用原样保存;tenant/KB/ + knowledge/chunk 身份、表清单/摘要、资源字节、Wiki 引用、问题索引的 + `source_id`/内容精确核对继续保留。 +- 范围错误、悬空引用、摘要/资源/清单损坏等真实完整性负例仍拒绝;不把源端没有 + 独立正文索引误报为导出丢失。 +- 维护恢复、备份、目标 ID 映射、旧库保护、授权、原账号/session 与第一因保存不变。 + +### Tests + +- 新 RED→GREEN:status0/2 正文缺独立索引仍原样封存;同 knowledge 但类型不匹配的 + parent 不再被类型规则拒绝。`r3f-remove-rules-red.txt` / + `r3f-new-contract-green.txt`。 +- 复用 E1 正例:PG text/summary + 问题 metadata + ES 原始 JSON/vector,经真实 + `ArchiveLibraryCandidate`/`validateArchivedLibraryClosure` 逐行逐记录读回; + 非空问题 `source_id` 和 summary→text 均保留。 +- 旧索引覆盖负例已按新契约改为原样捕获正例;真实完整性负例保留。 + +## 开发快照 0.1.362(原生 parent-child 索引覆盖适配,未部署;索引门槛后由 0.1.363 取消) + +### Fixed + +- **v071 候选封存覆盖校验**:解析 `chunks.parent_chunk_id`,按 knowledge 区分原生 + parent-child 文档与 flat 文档。mixed 文档只要求有 parent 的 text 原文索引;flat + 文档仍要求每段 text 索引;`parent_text` 仍仅作上下文不要求索引;显式 + `status=2` 缺失仍拒绝。未把问题索引当正文索引,未泛化放行所有无 parent/status0 + 行,也未放宽 scope、摘要、资源、Wiki、问题索引和父引用完整性。 +- **父关联完整性**:非空 `parent_chunk_id` 必须指向同一 knowledge 的真实 chunk; + text→parent_text 与 summary/OCR/caption→text 按真实角色核对;standalone 空字段 + 不强制建立关系,不受其他文档 parent 豁免。 +- **读回/重放**:归档和解档共用同一严格校验;合成 mixed 夹具证明 PG 全部 4 个 + chunk 与 2 条原始 ES 记录均保留,未过滤、重写或新增向量。 + +### Tests + +- 非敏感合成夹具的真实 `ArchiveLibraryCandidate` RED→GREEN:mixed native 正例、 + flat 文档缺索引拒绝、parented child 缺索引拒绝、status=2 缺索引拒绝、悬空父引用 + 拒绝;`r3d-native-red.txt` / `r3d-native-green.txt`。 + + +## 开发快照 0.1.361(封存阶段真源、精确验证列表与捕获终态) + +### Fixed + +- **F02 封存阶段**:测试封存作业只显示“只读导出测试版本”一个真实阶段;顶部说明改为 + 只读导出、不修改目标生产,不再套用备份生产/同步 Wiki/生产验证/生产生效,也不再 + 声称目标维护。运行、失败终态均保留真实 export 状态与原因。 +- **F03 列表与精确详情一致**:版本列表按每个快照的 `snapshot_id` 精确查询恢复验证 + 记录,与详情使用同一 endpoint/身份;同 scope 最新 passed 不再给其他快照染色。 + 未演练显示未验证,读取失败单独显示。 +- **封存失败保留第一因**:对已恢复写入者且确定不可重试的捕获校验错误 + (legacy chunk index coverage、缺失生成问题索引、缺失索引分块、空索引正文)使用 + 永久失败,不再自动产生第二次 attempt 让 “already exists” 覆盖第一因;业务 job + 的 error 在失败重试中保留第一条,成功时清除。瞬时不可达/超时仍按原重试预算。 +- **F01 host 工具边界**:本机 host `libraryctl` 仍是 `f9c15a8f...dirty`,360 的 + api/worker/web 升级不会替换该二进制;封存实际仍走旧 host 工具。最终 SHA 的 + host 工具包单独准备,未切换。 + +### Tests + +- 同一挂载封存 running→failed、失败原因、只读阶段;列表精确 snapshot 验证记录; + PostgreSQL 精确 snapshot 查询与失败首因保留;隔离 ES Current→Prepare→Verify + 重跑 PASS(临时独立 ES,完成后删除)。 + + +## 开发快照 0.1.360(tableState 文本身份、快照统计归属与精确验证记录) + +### Fixed + +- **tableState 文本身份回归**:非 resources 分支恢复直接扫描 `(id)::text`,不再把普通 + doc id/UUID/复合键/数字 ID 送入 `queryRows` 的 JSON canonical 校验;resources 仍走 + F01 精确引用快照路径。新增隔离 PG 的字符串、UUID、复合键、数字 ID 回归。 +- **F11 统计**:HTTP 快照投影补 `bindings`、`wiki_log_entries`;组件按当前作业自己的 + `target_snapshot_id/snapshot_id` 选快照,取不到显示未知,不借最新 test_sealed;阶段 + 无 detail 时按 running/pending/failed/unknown 展示,不把缺失 completed 当完成。 +- **F03 精确快照验证记录**:GET verifications 支持 `snapshot_id` 精确查询,返回 + `snapshot_latest` 并只按该快照回答 verified;快照抽屉的“查看校验记录”按选中快照 + 加载,不借用其他快照/最新 N 条记录。 +- **F08 主机计划展示**:显示主机探测时间;无真实 next-run 时明确“已配置每日…尚未核验 + 下一次实际执行”;最近成功单列并显示未读取,不以最近运行或 manifest 无 failure 冒充。 + +### Tests + +- 隔离 PG tableState 文本 ID、F01 20k 资源闭包对拍、HTTP totals/精确 snapshot verification + 回归;前端作业快照/阶段状态、恢复验证报告与确认块回归。实际 Current→Prepare→Verify + ES 集成尝试受共享 ES 磁盘 watermark 阻塞,未冒充通过。 + +## 开发快照 0.1.359(发布管理 F01–F11:资源闭包、状态真源与易用性) + +### Fixed + +- **F01 小目标大租户捕获/校验慢**:资源闭包不再按租户扫描 `resources` 并对每个资源反复 + 扫描所有正文表。先从已限定范围的 `resource_bindings` 与正文句柄集合提取精确 + `resource_id` / `handle`,再按索引取资源;捕获、预备份指纹、写前镜像、恢复后内容校验 + 共用同一条 `scopedResourceRows` 路径。绑定资源与无绑定的正文引用都保留,缺资源仍失败。 + 隔离 PG 夹具(20,000 条无关资源)旧扫描约 683ms、新导出约 41ms,闭包逐 ID 相等; + 真实 168k 规模与端到端维护耗时须父在目标环境复测。 +- **F02/F03 阶段与验证证据**:恢复验证使用自己的 capture → 基线校验 → canary → 恢复 → + 登记证据阶段,不再把登记证据叫“新版本生效”;顶部优先显示当前在飞作业。已验证且 + API reason 为空时不再同屏显示“还没有读到验证状态”;pending/loading/error/passed + 分开,最近一次通过可展开本次报告。 +- **F04/F06/F07/F08/F09/F10/F11**:发布页显示实际目标实例/项目/知识库;运行中主按钮改为 + “查看当前任务”并禁止重复启动;快照抽屉默认只列已登记版本,提供类型筛选、分页和 + 选中项滚动定位;下次计划缺失时显示未读取而不沿用陈旧时间;每个 scope 使用自己的 + overview(不同 scope/错配响应不借观测);新操作/切 scope 清除旧通知;数据卡明确 + “存储行”口径并在无总量时不伪造“未上报”。 +- **F05 高影响确认**:恢复验证与按版本恢复先显示目标、影响和恢复方式的一次确认,确认后 + 才投递;不新增审批门槛。 + +### Tests + +- 新增 F01 隔离 PG 资源闭包对拍与耗时;前端恢复验证通过/报告/确认、验证阶段、快照筛选、 + 运行中主按钮等挂载/静态回归。 + +## 开发快照 0.1.358(业务 HTTP 超时不再被探针上限截断) + +### Fixed + +- **F13 超时回归**:`weknoraaccess.Client` 不再把显式配置的 + `TEST_WEKNORA_HTTP_TIMEOUT`(默认 60s)强制截成 10s。只有未配置/非正值才回落到 + 与原 appconfig 一致的 60s;readiness 探测自身的 10s 上限保持独立。11s 本地响应在 + 60s 配置下可完成,显式 50ms 短超时仍生效。 + +## 开发快照 0.1.357(取件后自动解析、定位一次性请求、worker 有效配置) + +### Fixed + +- **F17 取件成功没有自动上传解析**:`MarkArtifactFetched` 与“本地已验证内容复用”两条路径在 + 同一事务内调用 `autoStartVerifiedPublicationsTx`:仅当来源仍启用、保存策略与 + `catalog_import_intents.visibility` 仍匹配、文件名过滤未命中、publication 未 superseded、 + 目标仍是当前 `routing_kb_bindings`(env 只作未绑定兜底)时,才把 planned→pending 并入队 + 唯一 `test.upload`;确认记录与作业幂等防双入队。356 已卡 planned/verified 的记录可通过对 + 同一文件再次保存当前策略,经同一自动接续路径恢复,不手工补队列、不启动全库补扫。 + 来源页成功提示同步改为“取件校验完成后自动上传解析”,不再指向已删除的“待入库开始处理”。 +- **F14 查看处理被默认筛选清空**:来源→监控的一次性定位改为套用干净筛选(清空 + status/action/stage/since/until),已完成文件可直接出现;定位请求应用后即消费。 +- **F14 旧定位请求重放**:来源目录定位增加一次性请求身份与父级消费语义;同一旧请求不会在 + sources/revision 重载或重挂载时把用户手工切换的目录拽回,新显式定位仍生效。 +- **F13 worker 有效配置与 API 分叉**:抽出 `readiness.Resolver` 作为端点/当前绑定/凭据唯一 + 解析来源;worker 的 upload/poll/validate/remove 改用 `weknoraaccess` 动态客户端,每次调用 + 重读网页端点、持久化绑定与同一 key 文件,不再在启动时固化 env 端点/客户端。 + +### Tests + +- 真实隔离 PG:策略→路由→取件 verified→唯一上传任务、重复完成幂等、复用已验证内容、 + 356 卡住记录重存恢复;禁用来源/阻止策略/文件名过滤/superseded/绑定改变均不入队。 +- 前端挂载回归:已完成文件定位不被 `status=active` 遮蔽;定位→手工换目录→保存策略/刷新后 + 位置保持,新请求仍能定位。 +- worker 动态客户端同进程端点、凭据、绑定改变均跟随;真实 CI 与本地门禁保持不变。 + +## 开发快照 0.1.356(三模块正常入口与追溯修复) + +### Fixed + +- **F12 实时刷新镜像缺扫描模块**:`Dockerfile` 的运行阶段补齐 + `scripts/dws_dingtalk_scan.py`(`live_catalog_refresh.py` 的导入闭包)。真实刷新作业 + `job-6e18ea86dce10d5472978573a4022a1a` 在源读取前即 `ModuleNotFoundError`,旧快照保留; + 最终镜像以 `--network none`、无挂载/凭据、entrypoint override 的纯导入与 CLI 依赖探针验证。 +- **F13 就绪探测绑定旧库**:`cmd/api/main.go` 不再在启动时捕获 env 知识库 ID,新增 + `internal/readiness` 每次探测重新解析「网页保存的端点 + 当前持久化绑定 + 同一份 API Key」; + 404/未配置/不可达分别归类,健康行带脱敏探测对象(实例 + 短 ID),存活与业务就绪分开显示。 +- **F14 来源目录在处理记录中丢失**:路由/取件时把 `relative_path`/父目录写入 `source_items`; + 历史空值只在读时按「同连接 + 同 item」的 `catalog_import_intents` 补齐,不按文件名猜配、 + 不覆盖已有路径。解析监控的列表/详情/目录搜索同一口径,并提供来源与监控之间的往返定位。 +- **F15 同名目标难辨**:目标选项与行内显示「名称 + 短 ID + 当前绑定/历史」,随页返回当前 + 生效绑定;新增「仅当前绑定」快捷筛选,计数仍是后端全量口径,历史文档保留。 +- **F16 刷新失败仍显示后台运行**:终态移除「后台运行」,失败显示失败时间、旧快照时间、 + 脱敏原因与作业 ID,并提供重试入口;运行中禁止重复提交,完成后不再显示重试。 + +### Added + +- 新增 `runtime-scripts` 门禁:静态比对运行镜像脚本依赖闭包,缺模块的正负例都必须可见, + 避免「源码能导入、镜像少 COPY 一个文件」再次只在真实刷新时暴露。 + +### Tests + +- 新增就绪解析/探测的真实 HTTP 用例、来源目录读时与写入侧隔离用例(一次性 PG schema)、 + 同名目标标签用例,以及刷新卡 running→failed/completed 的挂载级状态转换用例。 + +## 开发快照 0.1.355(同号版本说明归属修正) + +### Docs + +- **修正 0.1.28 / `f33730ed…` 的说明归属**:该 merge 真实边界是第一父 `c1d49adb…` + → `f33730ed…`(135 文件 +14226/-42),内容为开发版本历史修复(精确 SHA 说明提取、 + commit-specific→archive→tag、TargetSHAs/sourceHead、开发快照工具),并集成更早的 QA + 运营查询/组织/质量统计分支;不再复用同号 `3e7fcce0…` 的“持久本地副本/5 分钟同步/ + AI Markdown 预览”正文,也不声称该 merge 新增本地副本或已部署/验收。 +- 另一条 0.1.28(`3e7fcce0…`)仍使用其自身提交说明;其余 269 回填与 82 篇旧说明未改。 +- 新增同号不同 SHA 选择回归;270 条第一父统计/block hash oracle 仍为 0 mismatch。 + +## 开发快照 0.1.354(历史说明 merge/rename 精确修订) + +### Docs + +- **修订 3 条历史说明并复核全部 270 条统计**:0.1.207 / 0.1.35 按真实第一父 + `git diff ` 重写为文件范围与功能摘要(不再只有 merge 标题/泛句); + 0.1.340 统计修正为 +2485/-336,补上 + `{cmd/librarydrill => internal/libraryverify}/canary_test.go` 的 +1/-1。 +- **0.1.28 既有正文保留**,仅补 `目标提交` 并纠正 manifest 的文件/统计元数据。 +- 生成/核验器改为第一父、NUL 分隔、rename-aware diff;独立 Git oracle 复核全部 270 条 + 文件数/增删与 block hash。已有 82 条正文不变;未改版本计算、同步实现或历史提交/tag。 + +## 开发快照 0.1.353(补齐逐版本开发说明) + +### Docs + +- **按权威 version→commit 映射补齐 270 条历史开发版本说明**:每条使用独立 + `## 开发快照 snapshot/v - <日期>` 与 `目标提交:`,正文来自该提交 + 自身新增的 CHANGELOG 段,或按真实 commit body / name-status / numstat 归纳的文件与统计; + 测试/文档 only 提交明确标注不新增产品功能。 +- **已有 82 条开发说明未改写**;109 条 historical 记录不伪造版本号。新增 exact-SHA 验收覆盖 + 270 条目标块、错 SHA 拒绝与全 352 开发记录非空;未改版本计算、正式版基线与同步实现。 + +## 开发快照 0.1.352(版本说明标题格式兼容) + +### Fixed + +- **版本页可展开开发说明**:识别 `## 开发快照 (说明)` 标题,与旧 + `## 开发快照 snapshot/v - ...` 并存;版本号精确匹配,`0.1.35` 不会命中 + `0.1.351`,只读取到下一个二级标题,空正文不返回。 +- 历史提交仍按 commit-specific CHANGELOG、exact-SHA archive、annotated snapshot tag + 顺序取说明;archive 的 `目标提交` 绑定与正式版基线不变,未补写历史说明。 + +## 开发快照 0.1.351(索引预检使用目标映射 ID) + +### Fixed + +- **目标库索引预检不再误报旧库占用源 `_id`**:`PlanWriteSet` 的早期 index preflight 与 + plan/Apply 统一使用 `scoped-sha256-v1` 映射后的目标物理 ID;旧库占用源索引 ID 不再阻断 + 首次同步。仍逐 ID 校验目标 tenant/KB 归属、完整 `_mget` 响应与并发版本。 +- **负例保持**:映射后的目标 ID 真被其他 KB 占用仍拒绝;legacy/no-mapping 路径继续按原 + `_id` 校验并拒绝冲突。资源不映射、共享资源行/字节保护不变。 + +## 开发快照 0.1.350(首次复用取消本库历史来源门槛) + +### Changed + +- **首次同步可复用同 tenant 已有资源**:取消“资源必须在本目标历史成功同步/预备份范围内”的 + 额外阻断;目标为空、资源已被同 tenant 旧知识库绑定时,只要目标行逐列等于本次映射行、 + 且对象实际字节与归档摘要一致,即可复用。旧库 resource 行、绑定与对象不删不改。 +- **保留安全边界**:行内容不一致、对象字节不同、跨 tenant 仍拒绝;复用证据新增 v3 + (无历史 provenance,但仍记录行摘要与逐对象字节证据),v1/v2 旧证据语义不变。 + +### Notes + +- 更完整的资源归属审计(谁在何时首次写入、跨库引用关系)记入 `docs/BACKLOG.md`,后续补充。 + +## 开发快照(目标库独立 ID 映射,保留旧库) + +### Changed + +- **同一源快照可导入同实例的第二个知识库**:写入目标前按 `sha256(目标 tenant + 目标 KB + 表 + 源身份)` + 派生目标侧 UUID(knowledges / chunks / knowledge_tags / wiki_pages / wiki_folders / + wiki_page_issues / resource_bindings)。同一目标重复同步、重试与跨版本得到同一 ID,不同目标 + 或不同表得到不同 ID;旧库原有行不再与本次写入撞主键,也不会被删除。 +- **引用字段一起改写**:chunks 的 parent/pre/next 与 relation/metadata 中的精确身份、 + wiki_pages 的 chunk_refs / source_refs(保留 `id|title` 与顺序、重复)、folder_id、 + resource_bindings.owner_id、索引文档物理 ID 与 chunk_id/knowledge_id/source_id/tag_id; + 正文、标题、向量、引用顺序与重复项保持不变,不重新解析、不重新 Embedding。 +- **resources 保持原 ID**:资源是多知识库共享的字节载体,继续走既有"内容相同 + 来源可审计"复用 + 与归属证明;只改绑定行的 id/owner_id,不改 resource_id。 +- **写集合、校验、索引计划与恢复共用同一映射**:写集合登记目标身份,verify 按目标身份比对; + 恢复重放目标写前镜像时不二次映射。引用指向未登记身份时直接拒绝,不做模糊替换。 + + +## 开发快照(共享桶维护式更新:取消整桶独占前置) + +### Changed + +- **对象网关不再要求整桶独占证明**:`Gateway.Ready` 只核 journal、PG 持久化设置与后端版本能力, + 删除 `Isolation`/`AuditVerifier` 与 `OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`、 + `OBJECT_GATEWAY_ID` 的启动与逐请求校验;旧部署残留值被忽略,不再阻塞默认共享桶路径。治理 PG + SELECT-only authority、plan/owner/attempt/epoch 绑定、intent-before-send、单次写与精确回滚不变。 +- **目标 KB 更新走维护窗口**:停目标测试 WeKnora 写入应用容器并读回确认 → 备份本次目标 KB/对象范围 + → 用原 plan/WriteSet 更新 → 启动原容器 → 健康与页面验收;失败按原备份恢复。不再要求排空整桶 + 全部 writer、RAM 权限清单或独立只读 OSS AK,现有 AK 继续用于 PUT/GET/DELETE/列版本。 + +### Changed + +- **对象网关不再要求整桶独占证明**:启动只核 journal、PG 持久化设置与后端版本能力,旧部署残留的 + `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY` 被忽略,不再阻塞共享桶路径。 + 治理 PG SELECT-only authority、plan/owner/attempt/epoch 绑定、intent-before-send、单次写与精确回滚不变。 +- **更新方式改为维护停写**:停目标测试 WeKnora 写入应用容器并读回确认 → 既有维护/预备份链记录目标 KB 范围 → + 原 plan/WriteSet 经正式 Apply 更新 → 启动原容器 → 健康与页面验收;失败走既有恢复链回放原预备份。 + 不再要求排空整桶全部 writer、RAM 权限清单或独立只读 OSS AK,现有 AK 继续用于 PUT/GET/DELETE/列版本。 + +### Fixed + +- **共享桶不再因同 key 外部写者误报成功**:create 后除精确版本读回外核对当前 latest;并发写者产生更新的当前版本时, + 明确返回冲突并保留双方版本,不做任何未记账的删除,也不会在 Reconcile 里把已被外部写者接管的 key 报成 committed。 + 版本化存储的 PUT 不是原子 create-if-absent,同 key 并发不自动合并,需按回执人工处置。 + +## 开发快照(B1-R1 / B2-R1 / B5-R1 真实链收口) + +### Fixed + +- **B1-R1 受限演练恢复计划**:写集合新增 `restore-drill` 种类——共享 V2 信封、contract 1 与 schema 摘要, + 对象/索引/本地 ID 映射必须为空,来源 tenant/KB 必填;任一项非空即拒绝,旧执行器不能把它当发布计划 + 接管。恢复演练入口 `RestoreDrill` 与对象网关签发的零对象计划使用同一 attempt/写前镜像身份。 +- **B2-R1 verify 作业的不可变 operation**:`POST /api/v1/library/verifications` 在创建作业前先建 + operation(`ensureLibraryIntent`),作业携带 `operation_id` 与稳定幂等键;同一幂等键对应不同请求返回 + 409。worker owned attempt 与同 job recover 的网关 claim 都按原 operation + recovery job/operation + 核验,缺 operation 的 verify 作业在真实恢复中 fail closed。 +- **B5-R1 迟到响应不得污染新 scope**:恢复验证面板按 scope 世代 + 动作序号判定在飞动作;切 scope 即作废 + 旧 POST/回调,迟到响应不能改写新 scope 观测、不能触发父级旧 job 回调、不能清掉新动作的 pending。 + 新增真实挂载反例用例覆盖旧 internal POST 晚到的场景。 + +## 开发快照(GPT-6 正常 UI 发布审核 B1–B5 修复) + +### Fixed + +- **B1 恢复验证的恢复身份/计划**:共享演练不再把同一份快照同时当作来源与写前镜像 + (真实恢复合同会在任何写之前拒绝)。同一维护切点内做两次**真实**捕获:写前镜像 + (恢复实际回放的预备份)与来源身份(独立密封、内容相同、身份不同);两者与作业/ + 目标/tenant/KB 一起持久化,写集合在第一笔写入之前落盘并登记。演练恢复走限定范围的 + 安全入口 `RestoreDrill`:复用同一份 DS01 身份合同与同一批 Apply 原语,四个阶段按 + 写前镜像整段回放(先清 scope 再插入归档行)并做整实例指纹校验,不是"只删 canary"; + 有恢复派发闸口的目标拒绝该入口。 +- **B2 演练接进治理维护生命周期**:worker 在开窗口前写实例级 + scope 级维护行, + 写入边界更新真实入口状态;成功或"未写内容的安全收尾"才释放占用并开入口,held 时 + 保留行(入口 closed、状态 needs_restore)。同 job 的现有恢复入口贯通 verify: + 恢复队列准入、中断接管与 `library.recover` 的 kind 过滤都接受 verify;预备份引用与 + 写集合摘要按 (scope, job, 写前镜像) 精确登记,恢复入口能取回。失败文案由报告的 + restore_check 与窗口终态产生,不再用"有快照"冒充"已恢复并复核"。 +- **B3 证据优先级统一**:API 与 worker 都以证据为先——明确 failed/invalid 或读取错误 + 必拒绝,即使 `PRODUCTION_BACKUP_RESTORE_VERIFIED=true`;历史 env 兜底只保留在 + "明确没有证据行/存储无证据能力"时。未读取证据的旧调用点语义不变。 +- **B4 恢复验证作业联动父页面**:GET `/api/v1/library/verifications` 从真实业务行 + 投影在飞 verify 作业(running/job_id/state/stage);子面板接受作业后回调父页面 + `onAccepted`,父页面立即 load 并纳入轮询,终态回调 `onComplete` 再做一次读回, + 正常一次点击无需手工刷新即可同步进度/终态/闸口。 +- **B5 观测绑定 scope 与请求代次**:切 scope 立即丢弃旧观测;晚到的旧响应按代次丢弃; + HTTP 失败/不可解析/响应 scope 不一致都明确显示读取失败,保留旧数据时必须标成 + "上次观测已过期(刷新失败)",不再显示"已验证(当前目标)"。 + +### Notes + +- 迁移 79 仍只向上应用;`migrator` 没有自动 down 路径,部署回滚保留 79 与既有证据, + 不执行有损 `down.sql`。F1(备份主机连接/命令状态细分)仍为非阻塞后续。 +- 未部署、未调用业务目标、未切换服务;本轮只做隔离验证与固定 SHA 的候选提交。 + +## 开发快照(DS01 收口:CAS 点实时租约、恢复投递归属、治理权威域与绑定冲突分类) + +### Fixed + +- **F2.a CAS 点实时租约**:`Acquire` 在取得 effect 行锁(最后一个可能阻塞的锁)之后、 + 状态 CAS 之前,按数据库 `clock_timestamp()` 重核 job/attempt/恢复投递租约;`Confirm` + 同样先锁 effect 行再核。等锁跨过到期一律零许可、状态保持 `prepared`。新增真 PG + 反例:等 effect 行锁期间租约过期。 +- **F2.b 恢复投递同事务绑定**:同一短事务内 `FOR UPDATE` 锁 queue 与 recovery operation, + 复核 queue id/type/state/payload 的 window+scope、idempotency key、当前 owner/attempt/ + lease,并按原 window 的不可变锚点重算 `LibraryRecoveryDigest`,与 operation 的 + `request_digest` 逐位比较;错 queue/window/digest/owner/过期/错备份/错 plan 全部零许可。 + 投递 owner 合成规则收敛到 `governance.LibraryDeliveryOwner` 一份。 +- **F3.identity 治理权威域与构建身份**:激活证据升至 v3,必须携带 PG 集群 + `system_identifier` + 库 OID、完整 40 位构建 SHA 与协议兼容批次;激活与每次使用点都 + 现场重读 `pg_control_system()`/`pg_database.oid`/`pg_is_in_recovery()` 并比对,拒绝 + 同名异域、副本、unknown 构建、同 display 不同不兼容 SHA 与错目标指纹。协议批次相等 + 只约束派发语义,不能证明某个 SHA 属于该批次;构建身份精确绑定运行完整 SHA,没有 + 可核受信批次成员证明的跨 SHA 兼容默认关闭(明确报 `cross-sha ... disabled`), + 不新建签名设施,也不引入第二份声明式 allowlist。 +- **F4.binding 绑定冲突类型化**:`RestoreDispatchStatus.BindingConflict` 与"仅禁止重发" + 的 `Held` 分开;准入、确认、既有意图续作与收尾在 prepared/dispatching/marker_confirmed/ + done 任一状态都拒绝绑定冲突;合法 dispatching + 精确 marker 仍可确认一次。 +- 真 PG/adapter 反例:effect 锁等待过期、恢复投递九类错配、错治理域/错批次/unknown、 + 四状态绑定冲突与合法 marker 正例。 +- **整库封存来源校验失败不再悬挂**:快照来源与配置不一致时,队列作业已 failed 而页面 + 一直显示"导出中"(实测 `libseal-lib-internal-20261102T234053`)。现在失败同时写入 + `library_job_stages` 与 `library_jobs`(failed + 原错 + "修配置后重新封存"),原错 + 不被遮蔽;来源一致的成功路径不变。 + +### Added + +- **D16.N2 真实 legacy+missing 边界证据**:隔离场景在旧协议恢复标记 create 之前拒绝传输, + 现场由真实 `restore-mark-intent` 文件、确实缺失的目标文档与零 DS01 台账三件事共同构成; + 同一冻结二进制的新正式 worker 经 recover API 消费后 held,PG/对象/索引/effect 文件零变更、 + 台账不回填、入口 409。旧 N2 的 marker-present 事实与原始 raw 保留、不覆盖。 + +## 开发快照(DS01 激活证据 v2:只认真实维护 journal) + +### Fixed + +- **激活不再接受调用方自填的停写声明**:协议升至 v2,证据只声明目标/实例/治理库/构建、 + 维护作业、journal 文件名与 sha256、旧 writer 集合;"已退出、已排空"由 Store 直接读取 + 维护窗口写下的 journal(入口 `drained` 且 `active_at_close=0`、后台 quiesce 全零并有 + 停写后复核、每个 writer 有 `stop_requested` 与退出码)与治理库 + `library_instance_maintenance` 行(同作业/实例/指纹/level、未释放、writer 集合一致) + 核出。任一不符不建 active 行。 +- **受信证据根缺失即关闭**:未配置 `LIBRARY_TARGET_JOURNAL_ROOT` + (`WithRestoreDispatchEvidence`)时返回 `ErrRestoreDispatchActivationDisabled`, + 不再退回"三个非空字符串 + 一个摘要就开门"。 +- **构建绑定**:证据 `protocol_build` 必须等于运行二进制的 `version.DisplayVersion()`; + 未注入构建身份时失败关闭。 +- 增加真 PG 反例:伪造/替换 journal 摘要、错 writer 集合、未退出、未排空、过期、 + 治理库/指纹/构建不符、窗口已释放、journal 已 recovered、未配置受信根。 +- 旧 `beforeCommit` 用例更名为"未提交回滚零许可",与 G1 的真实 COMMIT 回包丢失区分。 + +### Changed + +- 正式 worker 装配把 `LIBRARY_TARGET_JOURNAL_ROOT` 传给治理 Store,激活门只能在该根下 + 读 journal;`docs/architecture/ds01-activation-evidence.md` 记录逐项不变量与边界。 + +## 开发快照(DS01 复核修复:真实绑定、同事务授权、可核激活与完整未决分类) + +### Fixed + +- **正式装配绑定**:`OpenProductionStack` 现在把 scope/实例与本次真实 attempt 身份传入目标; + 来源快照与写前镜像分别取自原 `WriteSet.TargetSnapshotID` 与本次 backup,不再把同一个 + `RestoreSnapshotID` 同时当来源和 before-image。缺锚点或二者相同在写之前失败关闭。 +- **派发线性化**:激活撤销与 `prepared→dispatching` CAS 在同一事务里用 activation 行锁串行化; + lease 在取锁之后用 `clock_timestamp()` 判定;同事务核对原 job/operation/attempt、来源/写集/ + 维护窗口与恢复投递(queue + recovery operation)绑定;同 effect 换 plan 摘要被拒绝。 +- **可核激活**:激活改为消费带 sha256 的证据文件(目标身份/指纹/实例、治理库名、协议构建、 + 逐 writer 的退出与排空观察、有效期);撤销不可回退为 `NULL`、activation 行不可删除, + down 在仅有 activation/撤销证据时也拒绝。 +- **准入/收尾完整分类**:绑定冲突、`prepared` 与 marker/claimed/finalize 矛盾在零目标写之前 + held;合法 `dispatching`+精确 marker 仍走确认分支。收尾改用原 window 权威台账全集(跨 plan), + 拒绝计划外记录、换 plan 别名与缺 `restored` 证据的 effect。 +- **可恢复区段**:`prepared` 已提交但 mark-intent 未落盘时,核对绑定一致且无矛盾后补写同一 + 意图并继续;无台账的旧意图仍 held,r33 不回填。 + +### Security + +- 绑定冻结实际目标实例/指纹/索引 UUID,同名重建的目标或索引会让旧证明失效;它们用于识别 + 对象,不用于证明历史未发送。协议仍不声称 ES 端 fence 或旧 `dispatching` owner 零迟到写。 + +## 开发快照(DS01:删除型恢复的派发台账与唯一发送许可) + +### Added + +- 治理库新增 `library_index_restore_dispatch` 与 `library_index_restore_dispatch_activation`(迁移 78): + 恢复标记 create 的"是否已有人取得发送许可"成为单调持久事实(`prepared` → `dispatching` → + `marker_confirmed`),唯一 key 绑定目标/原作业/原计划/索引/文档,绑定与状态由触发器拒绝改写与回退, + down 迁移在已有记录时拒绝执行。 +- 新增 `LIBRARY_RESTORE_DISPATCH_V2`(默认关闭)。开关只表示"允许装配";真正发放许可还要求治理库 + 对该目标存在未撤销的激活登记(`library_index_restore_dispatch_activation`),配置 true 不是独占证明。 + +### Changed + +- 删除型恢复(`Before` 非空、`After` 为空,恢复写入是独占 `_create`)只从唯一 dispatcher 取得一次性 + 许可:独立短事务按 job→operation→active attempt→effect 取锁并 CAS,**COMMIT 明确成功后才发送**; + 发送请求关闭传输层重放(`GetBody=nil`),失败不自动重试。 +- `Restore` 在任何 PG/对象/索引写之前做纯读未决准入:旧 `restore-mark-intent` 无台账、 + `dispatching` 且目标无精确 marker 一律 held;收尾前再拒绝一次未决效果,避免"先写一半再报 held"。 +- 自动 rollback 与维护恢复共用同一目标装配与准入(baseline 永不获得该许可)。 + +### Security + +- 只承认新协议 `prepared` 区段的跨进程续作;不回填历史 intent、不把 `missing`/`stats`/内存计数当 + 未派发证明,不触碰 r33。协议不声称解决 ES 端 fencing,也不声称接管后旧 owner 零迟到写。 + +## 开发快照(发布管理:空目标观测与基线入口) + +### Fixed + +- 发布管理:还没有读到生产目标状态时(首次加载、整库状态读取失败、当前范围没有数据) + 不再把本地默认值当成"目标非空",也不再提供会返回 409/503 的"建立目标权威基线"入口; + 有效四类响应(有权威版本 / 已读且为空 / 非空无版本 / 不可读)的呈现与入口保持不变。 +- 发布管理:刷新失败但仍保留上一次目标观测时,页面标明"上次观测 · 刷新失败,可能已过期", + 不把旧结果当成刚刚验证过的状态。 + +## 开发快照(发布 HTTP 成功闭环:真实监听 POST /library/syncs → handoff → executor → 幂等重放) + +### Added + +- 新增单一场景用例 `TestFormalPublishHTTPReplaySucceededR39`(`KG_R38_SCENARIO=publish-http`): + 发布作业只来自真实监听的 `POST /api/v1/library/syncs`(管理员会话 + 真实授权), + 不调用 `store.CreateLibraryDispatch` 冒充 HTTP,也不再走 httptest。 +- 新增 `r39` 证据链:来源身份先声明后封存(独立推导 `source_id`,来源行真实落进隔离 + PostgreSQL schema 再读回)、目标基线走正式 `POST /api/v1/library/baselines`(真实整库 + 捕获 + 校验 + `target_baseline` 证据,不手写生效版本)、handoff 用真实 `local` transport + 与真实 `libraryctl` 的 `snapshot-pack/unpack/verify`、发布后逐表/引用/索引向量/对象版本 + GET SHA 的独立 oracle,以及对同一 body 原样重放(`reused=true`,治理行/目标内容/索引/ + 对象版本逐字节不变)。 +- 新增外置运行器 `publish_http_runner.py`:沿用已审 `r38_runner.py` 的"创建前登记 + + 创建后补不可变 ID"与四次源码门禁,清理仍交给已审 `r38_cleanup.py`(run 目录名以 + `r38-` 开头),不重跑旧 runner、不改它的证据。 + +### Changed + +- 本批次只新增一个单场景测试与外置 wrapper,旧 r38 故障恢复分支(含 `:775` 的测试直建 + dispatch)一行未改,仍按原语义保留。 + +## 开发快照(DS03 早段 PG 恢复:合法来源 + database 23505 → held → 同窗口恢复) + +### Added + +- 新增早段 database 恢复失败用例 `TestFormalMaintenanceRecoveryPGEarlyRestoreHeldThenRecovered` + (`KG_R38_SCENARIO=pg-early`):仍然复用 `after:wiki` 发布校验失败入口,唯一新增故障是恢复 + **第一段 database** 的真实主键冲突——发布整库替换已删掉 before-image 目标文档,先用一行 + "外部范围、同主键"的 `knowledges` 占住该 id,恢复自己那条 `INSERT` 得到服务器 + `SQLSTATE 23505`。失败文案必须同时含 `恢复阶段 database 失败` 与 `SQLSTATE 23505`, + 且不得出现 wiki 阶段或 ES/对象文案。 +- 新增本轮专用来源副本 `r38LegalSourceSpec`:只把未删除来源文档改成 + `parse_status=completed`、`pending_subtasks_count=0`,共享 `ds02SourceRows` 一行不改。 + 封版前用产品自己的 `checkLibrarySourceSettlement` 在真实 PostgreSQL 上结算这份声明 + (隔离 schema,避免来源 id 与发布写入共用主键),并保留原 pending=1 被正式契约拒绝的负控; + 负控行按 id+租户+库精确删除并读回 0。 +- 新增早段 held 证据 `r38PGEarlyFaultHeld`:故障行仍在;同一 `INSERT` 复测仍被服务器以 + 23505 拒绝且没有多出行;database 阶段整段回滚,所以十张表都还是发布写入后的内容 + (与 applied 逐表多重集相等,且至少一张表不同于 before-image);索引仍是发布那一代, + 既没有恢复 marker 也没有 restored 回执。 + +### Changed + +- `r38_runner.py` 的隔离资源改为**先登记再创建**:network/DB/container 在创建调用之前把 + 名字与归属写进 `state.resources`,创建成功后补不可变 ID(DB 补 oid),创建响应丢失时 + 保留 `create-unknown` 清单;登记保存失败直接中止,不再先创建后登记。 +- `r38_cleanup.py` 的网络读回只接受 daemon 明确的 not-found(`no such network`/`not found`): + rm/inspect 的连接、认证、解析错误一律落 `cleanup-incomplete` 且非零,绝不当作"不存在"; + name/label 必须与本轮登记一致,否则零删除。创建响应丢失的 container/DB 按登记名 + + 项目 label 重新证明归属,归属不明失败关闭、不猜删。 + +### Fixed + +- `r38_runner.py` 的末次(finally)provenance 快照此前只记录不比较:现在 HEAD/tree_digest/ + 干净状态任一项变化都会让整体非零,状态保留原测试结果并附加 + `source-gate-failed-after-final`,精确清理照走,不再出现只有最后一次采集变化却 + `passed-cleaned`。 +- 离线控件补齐对应精确反例(末次 tree/HEAD/dirty、网络 daemon 错误/rm 失败/label 不符/ + 未登记名、创建响应丢失的 container/DB、登记保存失败),期望条数由程序统计, + 原 10+7 案例与旧失败证据保持不变。 + +--- + +## 开发快照(DS03 PG 恢复失败:held → 同窗口二次恢复) + +### Added + +- 新增 PG 恢复失败用例 `TestFormalMaintenanceRecoveryPGRestoreHeldThenRecovered`:复用已证明的 + `after:wiki` 定点进入回滚,唯一新增故障是真实 PG 错误——恢复最后一段 PG 写入(wiki 阶段) + 会把 before-image 的日志行按原 id 插回目标范围;先用一行"外部范围、同主键"的日志占住该 id, + 那条真实 `INSERT` 得到服务器 `SQLSTATE 23505`。用例记录 SQLSTATE、同一语句的探针读回 + (没有多出行)与失败阶段事务回滚;`恢复阶段 wiki 失败` 与 `SQLSTATE 23505` 必须同时在失败文案里。 +- 新增 held 现场证据:故障行未被自动解除;held 是真实的部分恢复状态——database 阶段已提交、 + 四张 wiki 表仍是发布写入、共享 `resources` 的新增行按设计留到四阶段全部成功后再清, + 逐表与 applied/before-image 比对并断言失败阶段是整段回滚而不是半写。 +- 新增同窗口续作证据:解除故障只删除那行外来日志;同一 `window_job_id` 的 + `POST /api/v1/library/maintenance/recover` 完成后复核十表、引用承诺、对象版本字节、索引 + 与网关回执/投递,并保存 replay 原始读回。 + +### Changed + +- 隔离夹具在 `reset` 时消费运行器登记的唯一索引(`KG_R38_INDEX`),并在第一次写入前把实际 + namespace 落到本轮目录;清理器核对「运行器登记 / 夹具落盘 / 实际清理」是同一个名字, + 登记不一致时拒绝删除,不再只依赖 `t.Cleanup`。 + +### Fixed + +- 证据目录的运行器:构建后/执行后比较 HEAD、干净状态与源码树摘要,构建后不符直接拒跑用例、 + 执行后不符结论作废(不再出现源码已改却 `passed-cleaned`);finally 里的 provenance 异常 + 不再跳过精确清理。 +- 证据目录的清理器:PG 环境发现等前置动作失败也落 `resources-cleaned.json` 与非零终态; + 已有的 `cleanup-incomplete` 结果文件不再因"文件存在"而返回 0。 + +--- + +## 开发快照(DS03 对象恢复父复验:十表全形状与对象版本字节) + +### Added + +- 对象恢复分支的 before-image 与来源快照都改成十表全非空:直接复用 DS02 已验的十表声明 + (`ds02SourceRows`/`ds02Expected`/本地号映射 oracle),目标自己的标签、标签关系、Wiki 目录、 + 页面问题、Wiki 日志不再是空表;同租户邻库与外部租户行作为哨兵逐表非空。 +- 新增逐种引用承诺计数:父子分块、标签关系、资源绑定、目录父子、Wiki 目录/来源/分块引用、 + 页面问题与日志引用,在声明来源、发布实际写入、恢复后 before-image 三处都要求 `matched>0`。 +- 新增对象版本字节指纹:对 before-image 每个受保护 `versionId` 单独 `GET` 计算 SHA256,恢复后 + 同 `version` 再独立计算一次并逐条比较;ETag/size 只作旁证,不再充当"逐字节相同"的证据。 +- 新增发布期/恢复期映射对应证据:发布期写集合摘要同时出现在预备份版本证据、网关回执与投递 + 计划里;恢复意图的 `request_digest` 由窗口/作业/目标/来源/备份/该摘要独立重算后逐字符比较。 +- 新增重放后的原始读回:PG 十表、索引、对象版本清单与版本字节、网关回执/投递都落盘,供父 + 独立比对,而不是只记录一条 PASS。 + +### Changed + +- 隔离运行器把主命令、label、完整 SHA、版本号、二进制摘要与测试名写进同一份 `run-identity.json`, + 报告头与 raw 统一取自该文件,避免"头写旧运行、身份是新运行"。 +- 运行器与清理器的 label 前缀统一为 `ds03-object-*`(对象分支),清理仍只清本轮登记资源并 + 只使用已核对的不可变容器 Id。 + +### Fixed + +- 对象恢复用例的对象分支改用真实 v071 十表 catalog 建表,目标行本地号放在序列起点之前,并让 + 目标旧文档预置目标知识库绑定的 embedding 模型,使"恢复回放"回到的写前状态是真实形状。 + +## 开发快照(DS03 对象恢复传输失败 → held → 同窗口恢复) + +### Added + +- 新增对象恢复失败分支的真实隔离用例 `TestFormalMaintenanceRecoveryObjectRestoreHeldThenRecovered`: + 在对象网关前拒绝一次"回滚删除本轮创建对象"的请求(派发前 503,转发计数 0,不产生网关 + intent/receipt),让自动回滚真实失败并进入窗口 held + scope/instance `needs_restore`; + 撤障后仍用同一 `POST /api/v1/library/maintenance/recover`、同一 window/job/backup/plan/mapping + 完成恢复,并逐项读回 PG 十表整行、ES 完整 `_source`、对象全部分页版本/delete markers 与字节摘要。 +- 新增四类进程身份证据:api / worker / object-gateway / 测试进程分别绑定最终源码树、binary + sha256、`/proc//exe` 实际 executable 与 commit;测试进程自证 executable 摘要,不匹配即失败。 +- 新增对象网关拒绝现场:被拒请求的 operation/key/action/plan/epoch、目标 receiver、转发计数、 + 网关侧 intent/receipt 行数、引用到的 durable create receipt,以及对象恢复的 `delete-intent` 效果。 + +### Changed + +- r38 对象分支不再把旧的 ES clean-dispatch 503 改名成对象故障:ES 回滚写入必须真正完成, + 失败必须来自对象恢复边界;未走正式发布 API 的入口在证据中明确标注"发布 API 入口未证"。 +- 对象清单改为分页枚举全部 versions 与 delete markers,版本指纹包含 ETag 与字节数。 + +### Fixed + +- 修正隔离运行器工具(证据根,不改变产品版本):对象删除前先核对容器 name/Id/label,之后 + 破坏性操作只用不可变 Id;清理异常(含 PG 读回 RuntimeError)统一落 `cleanup-incomplete` + 失败终态与清理结果文件并非零退出,不再持久 `passed`。 + +## 开发快照(DS02 oracle 独立性、映射语义与运行器失败关闭) + +### Added + +- 新增独立本地号映射 oracle:只接收测试声明的来源行、独立推导的期望目标行、真实目标行 + 与持久账本,按 `(table,column,source,target)` 精确集合比较;目标互换、不存在的目标、 + 被替换的来源、少项/多项/重复、错列都会被判红,而合法账本与真实行逐列相等才算绿。 +- 新增十表范围声明(测试自带 `tenant_id`/`knowledge_base_id` 规则并与真实 schema 列集合 + 对拍),不再复用产品的范围分类生成期望。 +- 新增逐种引用覆盖:`chunk.pre/next/parent_chunk_id`、`wiki_folders.parent_id`、 + `wiki_pages.source_refs/chunk_refs`、`wiki_page_issues.suspected_knowledge_ids`、 + `wiki_log_entries.pages_affected` 等各自 `violations=0` 且非空命中;没有外键契约的软 + 导航字段(`parent_slug`、`in_links/out_links`、`relation_chunks`)显式列为范围外。 +- 新增外围哨兵:`chunk-foreign` 文档完整 `_source` 逐字段比较、`res-other` 对象字节比较, + 两者各有"改坏必须红"的负控制。 +- 新增冻结输入 bundle(十表来源行、目标种子、序列种子、ES 文档、对象字节、完整 DDL, + 时间固定、逐表 hash):旧源码 `6fe98c9` 与当前源码读取同一份文件、同一 sha256。旧侧真实 + 复现 `wiki_log_entries_pkey / SQLSTATE 23505`,新侧同一输入发布成功并通过独立 oracle。 + 该跨租户 bundle 是**受约束回归对照**:6fe98c9 在 wiki 之前无法跨租户搬运资源,旧侧归档 + 只能省略 `resources` / `resource_bindings` 两表,因此不能据此声称"同输入已收口"。 +- 新增十表同输入对照(同租户、不同知识库):`ds02-identical-input-bundle.json` 两侧各自 + 规范化并封存完整十表来源归档(含 `resources` / `resource_bindings`),旧侧 `6fe98c9` 用 + 真实 PG/ES/MinIO 对象适配复现 `wiki_log_entries_pkey / SQLSTATE 23505`,新侧同输入 + `succeeded` 并通过映射/内容 oracle。两侧在执行前各自动导出逐表来源归档、实际目标种子、 + 完整 DDL、三条序列、ES 文档与对象字节;唯一 namespace 替换(对象桶名 `%BUCKET%`) + 按同一规范归一后语义输入 hash 相同,物理桶名单独记录。 +- 新增测试进程身份断言:runner 注入 test-only nonce/commit/源码树摘要,测试进程自报 + `os.Executable` 的 sha256,与 runner 期望逐字符比较;构建与执行前后各算一次二进制哈希。 +- 新增隔离运行器 v2(`ds02_runner_v2.py`,v1 保留):超时/构建/准备异常都走 finally 清理, + 源码、HEAD、工作区、二进制哈希、bundle 字节、required 缺失/跳过任一变化即失败; + 清理前重核 namespace 前缀与容器 Id/label,读回区分"确实不存在"与认证/连接错误; + `--keep-failure` 保留现场并写 `resources-kept.json`。 + +### Changed + +- DS02 的零 Embedding 断言改为按"发布段"记账:ES 与对象存储两个可达 client 注入同一 + 记录器,按目的地址(路径含 embed/encode 或已知模型域名)识别向量化调用,并补了另一个 + client 走自定义 `/v1/encode` 的负控制;声明范围只到本测试的 client 清单,正式 + API→worker 全链仍留给 DS03。 +- 映射 RED 与摘要 gate 分开:语义变异只改内存账本副本(目标存储不动),归档字节变异只 + 证明 `LoadWriteSet` 摘要拒收,不再拿后者冒充映射断言。 +- 日志内容变异重命名为 `log-content`,不再当作 mapping RED。 +- 历史兼容矩阵改用同一份真实 v071 catalog 初始化,三条本地号序列显式断言存在并逐例比较 + before/after 摘要(不再有空集合"不变")。 +- 旧侧对照措辞修正为"精确旧 SHA 回归对照":不再用 `git rev-list --count` 的 258 当版本号; + 该工作树资源 identity 实际是 0.1.148,没有原发布产物就不做历史考古。 + +### Fixed + +- 修正旧 oracle 只检查"每表来源/目标数量与重复"导致的三种盲区(目标互换、错误来源集合、 + 不存在的目标号)。 +- 修正引用断言把 pre/next/parent 混在一个 OR 里、无法证明 parent 分支有覆盖的问题。 +- 修正"序列不变"在最小 schema 上没有序列可比的空覆盖。 +- 修正运行器把 namespace 解析失败静默跳过、删除前不重核所有权、读回把任何非零退出都当 + "不存在"、失败路径不保证清理的问题。 + +## 开发快照(整库发布的数据/证明 oracle 与历史兼容矩阵) + +### Added + +- 新增 `TestDS02FullShapeOracleIsolated`:复用现有十表全形状夹具,用**独立 oracle** + 逐列比对目标行内容、逐种引用(父子/标签/资源/知识库/Wiki,含 parent 分支与 + source_refs/chunk_refs/suspected ids)、索引正文与向量、目标及外围对象字节,并按发布段 + 断言 Embedding 调用为 0。期望值由夹具声明推导(来源→目标范围映射、资源定位符与 + `location_hash` 在本测试里重算),不调用被测映射器生成;`parent_slug` 与 in/out_links + 这类没有外键契约的软导航字段明确列为范围外。 +- 新增 Wiki 日志映射 oracle:来源日志数字 id 与目标本地号按独立期望精确配对,并用 + 真实目标行逐列对应;持久账本正例通过同一 checker,语义副本变异(互换/不存在/替换来源/ + 少项/多项/重复/错列)必须红。 +- 新增对照夹具探针(旧代码工作树):精确旧 SHA `6fe98c9` 在同一隔离库/桶/索引里以 + 同一份冻结 bundle 复现 `wiki_log_entries_pkey` / SQLSTATE 23505;当前代码同一输入发布 + 成功并分配本地号,其它知识库的历史行不变。这是**旧源码回归对照**,不是原 0.1.258 发布 + 产物;该工作树的资源身份实际是 0.1.148,`git rev-list --count` 的 258 只是自根提交数。 +- 新增 `TestDS02LegacyCompatibilityMatrixIsolated`:旧 manifest、V1 台账、空作业/ + 目标身份等缺证明组合必须在正式入口被拒绝,拒绝前后 PG 逐行 + 索引 + 对象版本 + + 序列哈希不变;不做 V1→V2 迁移。 + +### Changed + +- 隔离运行器补齐 provenance:运行前后完整 HEAD/工作区/源码逐文件哈希(含未跟踪)、 + 测试二进制 sha256 与 go build metadata/版本注入、逐用例 PASS/FAIL/SKIP、真实目标 + 身份;一次性资源先登记,结束后按登记名成对删除并逐个读回(容器 inspect 失败、 + 库/索引/桶查询为 0/404)。 + +## 开发快照(正式 worker / 维护恢复入口的 held → 恢复闭环验收) + +### Added + +- 新增正式链路验收 `TestFormalMaintenanceRecoveryHeldThenRecovered`(只在 `KG_R38_RUN` 指定的 + 一次性隔离部署里运行,常规运行与 CI 跳过):真实 publish 在 database/resources/index/wiki 四类 + 真实写入完成后,由"校验读回内容与快照不一致"失败进入自动回滚;回滚在 + `restore-finalize-intent` 已落盘、marker 仍停在自己世代时被传输层拒绝 clean 派发(拒绝 = 不转发、 + 不丢响应),窗口保持 held,实例/scope 两个维护记录写 `needs_restore`,写入口返回 409;撤掉一次性 + 故障后 `POST /api/v1/library/maintenance/recover` 以同一 window/job/backup 续作成功,PG 逐行、 + 对象版本集合与 ES `_source` 全量恢复,入口重新返回 200。 +- 该用例中的对象 receipt 全部由真实对象网关写入产生(committed/removed 两条不可变回执 + 对应 + delivery/plan 摘要),没有人工造回执,也没有改核心状态。 + +### Changed + +- 本轮只新增验收与运行器,产品行为、协议与判据均未改变;删除型恢复的 R02-b 缺口保持原样。 + +## 开发快照(删除型索引恢复不再把 ES 统计计数器当证据) + +### Fixed + +- 撤销上一快照的"写计数器栅栏"授权:ES `_stats` 的写计数是**分片生命周期**统计,官方 + 文档明确写"分片迁到另一节点时该分片的统计会被清零";索引 uuid 不变并不绑定统计的 + 生命周期,清零后重新累计到与冻结值相同(ABA)无法排除。统计相等不是不可变证据, + 现在既不落盘也不读取,恢复路径里没有"凭计数放行写入"的分支。 +- 删除型索引恢复(恢复写入是独占 `_create`)只有在**本次尝试开始时不存在任何恢复意图** + 且文档确实缺失时才允许重做("先落意图、后派发"的不变量说明本作业没派发过)。既存的 + `restore-mark-intent` 配上缺失文档没有持久、不可重用的"没写进去"证据,一律 held、 + 零写入。该自动重试缺口已按现状记入验收矩阵,不宣称这是用户接受的能力收窄。 +- 保留可证明的路径:`restore-finalize-intent` 已落盘、真实 marker 仍停在自己那份世代上时 + 继续干净收尾;删除补偿(`Before` 为空)在文档仍是 applied 结果、世代仍是 applied + 回执时重放 `DELETE`。 +- 验收用例新增 ABA 反例:stats 一直返回同一 uuid 同一计数(传输层故障模拟),而真实 ES + 里 marker 已写入又被删除;恢复必须 held。没有重启共享 ES,也没有伪造文档观测。 + +## 开发快照(恢复"确定没写进去"的判据改为可证明的栅栏/世代) + +### Fixed + +- 索引恢复不再把"文档缺失"当成"证明从未发送":恢复 marker 写成功、回执丢失、随后又被删除, + 与从未写过在索引里完全同形。删除型恢复写入是**独占 `_create`**,现在只有在第一次派发前 + 冻结的**索引写计数器栅栏**(索引 uuid + `index_total` + `delete_total`)逐位未变时才允许重做; + 栅栏推进、栅栏缺失或读取失败一律 held,不认领(B19 不放宽)。 +- `restore-finalize-intent` 已落盘、干净收尾写入在派发前被拒绝后,重试不再永久 held:标记体 + 仍停在自己那份世代(内容 == 冻结标记体,`_seq_no`/`_primary_term` == 意图回执)即证明干净 + 写入没有落地,按同一 CAS 继续收尾;内容或世代对不上仍然 held。 +- 删除补偿(`Before` 为空、恢复写入是 `DELETE`)在派发前被拒绝后同样可以续作:文档仍是 + applied 结果、世代仍是 applied 回执才重放 `DELETE`;文档已变或世代不符仍然 held。 +- 下一条旧快照里"删除即缺失、判据只有世代"的表述仅适用于更新型恢复;删除型以本条冻结的 + 索引写计数器栅栏为准。 + +### Changed + +- 对象验收证据改用 `ListObjectVersions`(键 + versionId + ETag/字节数/删除标记):`ListObjectsV2` + 只枚举当前可见对象,不能证明历史版本。 + +## 开发快照(索引恢复在"确定没写进去"时可按证据重做) + +### Fixed + +- 恢复/回滚的索引步骤若在**持久意图之后、派发之前**确定失败(控制流拒绝),重试不再被永久判成 + `unknown restoration lacks exact operation marker/content/CAS` 而 held:只要观察到的内容仍等于自己 + 确认过的 applied 结果(删除即缺失)、且世代与那份回执完全一致,就说明这份恢复意图一次都没到达 + 索引,按原 before-image 重做不会覆盖任何别人的字节。 +- 判据仍然只有世代,不认"内容看起来一样":内容对但世代对不上、应用期停在标记态却对不上标记体或 + 世代,一律保持 held(B19 不放宽)。 +- 新增一次性恢复写入派发边界(`restoreMarkerFault`,生产恒为 nil),用来把"边界上确定没写进去"与 + "写入结果不确定"分开演练;真实 ES / PostgreSQL / 对象存储仍是唯一权威。 + +## 开发快照(归档改成不可覆盖副本,current 不再先被移走) + +### Fixed + +- 维护窗口的旧请求归档不再 `rename` 走当前 journal:先写一份**不可覆盖**的副本 + (`O_EXCL`,同名已存在时必须字节相同、不同则明确拒绝),当前 journal 保持可用, + 直到新一次尝试通过 `save` 原子替换成功。此前若 `pending/prepare/inventory/save` 任一步失败, + 目录里连一份可读的 current 都不剩;进程在归档与写入之间中断也一样。 +- 归档名按**被归档请求自己的 attempt** 派生(v1 旧记录为 `attempt0`),新尝试从 `attempt+1` 开始, + 因此连续失败的多代不会撞名;撞名且内容不同一律拒绝,不覆盖。 +- 开新尝试额外要求 `source`、`target_fingerprint` 与当前实例一致,且入口若关过必须已有 + `gate_reopened` 证据;否则仍按"需要恢复"拒绝。 + +## 开发快照(续作被上一次已收尾的维护请求挡住) + +### Fixed + +- 维护窗口协调器:上一次尝试在**没有写过任何目标内容**的情况下失败并已正常收尾后,同一作业的续作 + 现在可以开新一次尝试,而不是被 `freeze request already exists` 挡住、让合法的 resume 变成一条没有 + 恢复路径的 202。旧请求不删除也不覆盖:归档到 `archive/-attempt.json`,新请求用 + `superseded_from` 指向它,`job / operation / backup` 身份保持不变。 +- 一旦上一次尝试已经 `contentRisk=true`(写过目标),仍然拒绝开新窗口并保留原来的 + `recovery or a new request is required` 语义 —— 那种情况必须按原 before-image 恢复,不能重来一遍。 +- 已成功收尾的窗口继续按幂等回放处理,不重复停写者/关入口的副作用。 + +## 开发快照(续作失败把作业留成假 active) + +### Fixed + +- 作业续作(`POST /api/v1/library/jobs/{id}/resume`)不再先提交 `state=pending` 再单独入队。 + 旧实现里队列行主键由业务作业 id 派生(`QueueJobIDFor`),第二次续作时 `INSERT` 撞主键, + 入队失败返回 500,而作业已经被改成 `pending` 且没有可用队列行 —— 从此永久卡住, + 后续恢复请求全部被 `409 library_restore_active` 挡住。 + 现在「结束上一代 attempt + 业务作业置 pending + 队列行 upsert(含租约检查)」在同一个事务里完成: + 入队失败整笔回滚、作业状态不变;租约仍有效时返回 `library_resume_busy` 而不是半态。 +- 续作改为拒绝 `stage=rollback` 的作业(`409 library_resume_requires_recover`):这类作业已经回滚, + 正确出口是维护恢复(`/library/maintenance/recover`),它绑定原 `window_job_id` 并使用原 before-image; + 继续续作等于丢开前镜像重来。拒绝文案按维护记录如实给出窗口是否仍被持有,不一律宣称"仍持有"。 +- 阶段/状态/执行权与队列载荷全部在**事务内锁住的那一行**上校验并重建(`SELECT … FOR UPDATE`): + 调用方手里的旧快照不再参与决策,避免用过期 stage 复活已变化的作业;并发重复续作只有一个成功, + 另一个得到 `library_resume_busy` 或 `library_resume_state_changed`,不会重复投递。 + +## 开发快照(发布页维护文案与版本记录页加载失败) + +### Fixed + +- 发布管理:作业失败但维护窗口已释放时,不再显示"目标保持维护、入口未开、收尾未完成"的 held 诊断; + 改为如实记录"作业失败(维护窗口已释放)"。只有仍被持有的失败作业才给 held 处置文案(此前仅按 failed 渲染)。 +- 版本记录:同步进行中的 run(`finished_at` 为空)不再让整页 500。部署重启会自动触发一次同步, + 原先该行的空时间戳扫描失败 → `Get /api/v1/version-history` 返回 500。 +- 版本记录页:请求失败时不再声称"当前运行版本未知"或"版本记录未接线",并显示服务端返回的 + `error`/`code`(例如 `version_history_unavailable`),把"未配置"和"后端故障"分开。 + +- 版本记录客户端:500/409 的异常消息复用已解析的响应体,不再二次 `response.json()` + (真实 `Response` 上会抛 `Body already read`,被 catch 吞掉后只剩状态码);错误详情现在稳定带出服务端 `error` 与 `code`。 + +### Tests + +- `web/src/versionHistory.test.ts`:用真实 `Response` 构造 500,断言消息含 `error` 与 `code`(伪 mock 可重复 `json()` 会掩盖 double-read)。 +- `internal/platform/postgres/version_history_sync_state_integration_test.go`:进行中 run(NULL finished_at) + 读取同步状态与分页都必须成功。 +- `web/src/releaseTargetsMaintenance.test.tsx`:已释放的失败作业不出现 held 文案;仍持有时保留。 +- `web/src/VersionHistory.test.tsx`:加载失败时不出现"未接线/未知",并显示服务端原因。 + +## 开发快照(隔离验收现场保留,仅测试侧) + +### Changed + +- 隔离演练支持 `KG_R8_KEEP_SCENE=1` 保留现场:不删索引/对象桶,并把网关审计公钥与派生令牌落到 0600 文件, + 便于对本机一次性目标做真实 UI/API 验收;默认不设该变量时仍在断言后精确清理。 +- 产品代码、数据契约与生产行为不变;不构成生产授权,也不替代真实演练证据。 + +### Security + +- 保留现场只作用于一次性 PG/ES/MinIO;生产闸口、凭据、ACL 与宿主操作仍未授权。 + +## 开发快照(源契约绑定与引用闭包) + +### Fixed + +- 新源捕获在同一只读事务中封存表结构、约束、索引与序列定义;发布前核源/目标目录一致性。旧快照与V1台账不改写、不重算历史摘要。 +- 写前验证归档关系闭包与目标已有关系;源导出拒绝被JOIN掩盖的缺父、跨父和未知资源owner,不靠删除孤儿消除差异。 +- 目标预备份、计数与恢复统一覆盖knowledge/Wiki正文及嵌套metadata的稳定资源引用;保留历史孤儿和共享资源原值,未知引用表示明确拒绝。 +- 恢复前重新检查本次新建资源的未知绑定和外库正文/metadata引用;有计划外读者时在任何索引/对象/PG修改前held,父键锁内再次检查所有正文和绑定,防止先删对象才发现不可恢复。 +- 实时模型准入拒绝空模型名,避免将未知模型误判为可兼容。 + +### Security + +- 数据契约仅在一次性本机PG/ES/MinIO验证;正常业务租约、云权限、WeKnora源码及业务Schema不改。clean未知仍held,不降低所有权证明。[逐表契约与覆盖边界](docs/library-data-contract.md)。 + +## 开发快照(独立恢复请求与索引恢复归属) + +### Fixed + +- 独立恢复队列与原发布发送身份分离,可信控制源核持久请求、当前租约、原 operation、来源、目标、预备份和 WriteSet;恢复意图不再被原发布自动接管抢跑,恢复中断由新执行代次继续。 +- 索引 before-image 恢复写入采用绑定原计划的暂态标记;真实提交但丢响应后,仅完整标记正文和CAS证据匹配才允许收尾,不重发已提交的标记写入。完成回执同时校验精确代次。 + +### Security + +- 发布或恢复的 clean-finalization 丢失响应时,相同干净正文不能证明写入归属,继续 held;旧恢复unknown缺少写前标记证据也不自动认领。 +- 自动授权只读角色增加 jobs 表 SELECT 核验;仍禁止其治理写权限。正式独立恢复与故障链仅为本机隔离验收,正常租约未缩短,未部署业务或变更云侧凭据/ACL/网络;整体验收未闭合前不发布。[身份、证据与剩余边界](docs/object-write-gateway.md)。 + +## 开发快照(可信控制交付与发送身份接管) + +### Added + +- 正式 worker 在持久化原写集合摘要后,通过数据身份向网关申请绑定当前执行代次的授权;可信控制域独立读取治理锚点和原计划,普通 worker 不持有控制凭据。 +- 网关持久保存不可变 attempt/grant 交付记录;发送身份与当前授权 epoch 分离,新执行代次可以对账原发送并继续未发送对象,未知请求仍阻断交接。 + +### Changed + +- **破坏性**:关闭旧 ObjectImporter staging/promotion、legacy release-worker 和写型诊断/E2E 入口;正式发布 stack 对所有对象 provider 强制网关,不回退直写。只读 capture 保留。[接入与回退边界](docs/object-write-gateway.md)。 + +### Security + +- 自动授权核验原预备份锚点、目标、有效 attempt/owner/租约及原计划内容;拒绝跨代次替换计划。控制读取使用独立 SELECT-only 登录角色,旧手动控制端点在自动模式关闭。 +- 正式 worker 已在专属本机隔离栈完成 PG 后、对象提交后两次 SIGKILL 与原计划接管;独立读回验证三代授权、一份原发送回执和唯一对象版本。演练仅在显式隔离构建中缩短租约,正常构建维持10分钟,不接受环境变量缩短。真实部署独占与整模块验收尚未完成,仍禁止部署部分候选;未切生产凭据、ACL 或网络,未新增云对象写入。 + +## 开发快照(统一对象写入网关候选) + +### Added + +- 新增对象写入网关与独立控制客户端:冻结逐key允许集合、持久epoch/intent/精确版本回执、同key串行化与未知请求阻断交接;网关模式拒绝无计划Put/Copy和直写回退。保持资源UUID、物理路径及历史摘要不变。 + +### Fixed + +- 已确认归属及CAS代次的索引补偿删除,在真实删除成功却丢失响应后可按精确缺失完成恢复;重新创建的文档代次仍拒绝接管,不盲重发删除。 + +### Security + +- 网关逐请求绑定协议与目标,控制/数据身份分离;拒绝不完整回执、无持久日志、只读或失败的日志事务、未登记计划及缺失/过期的审核签名。治理证据禁止更新、删除和截断。 +- 此候选尚未完成正式worker控制grant自动交付、跨新epoch接管及真实写入口独占验证,禁止部署部分业务实现;生产凭据/ACL/网络未改,未进行网关云OSS端到端写。[配置、信任边界与剩余项](docs/object-write-gateway.md)。 + +## 开发快照(旧封存来源关联与归档持久性) + +### Added + +- 管理员可从发布页选择历史快照,核验原捕获执行器身份、期望指纹及清单后关联当前来源。关联只追加治理审计证据,不重新封存、不修改原摘要,也不代替发布授权。 + +### Fixed + +- 归档初始化同步根目录及父目录,目录同步失败时拒绝继续,避免仅同步文件仍遗漏目录项持久性。 + +## 开发快照(存储回执与隔离恢复) + +### Fixed + +- 每次同步冻结实际目标预备份与独立计划;重复 Wiki slug 在写前拒绝,晚期失败仍清理本次新增对象并保留复用资源。 +- 索引逐 ID 记录不可变回执;带操作归属标记的写入在真实服务提交后丢失响应时,可由新进程确认并补偿,不凭相同正文猜测归属。 +- 对象阶段进程中断验证覆盖实际 MinIO 提交后、回执落盘前的 SIGKILL 与持久计划恢复。 +- 不可变副作用证据拒绝祖先软链接,并逐级同步新目录的父目录;同步错误返回失败,不再只同步最末两级。 + +### Changed + +- 增加原生 OSS 精确版本协议及显式隔离测试入口,已完成明确隔离前缀内的真实版本写入、精确读回与无残留清理,尚未替代生产条件创建路径;无充分证据的 unknown 分支、跨域 fencing 和全部验收仍未闭合,禁止发布部分实现。[兼容与未完成边界](docs/library-migration-contract.md)。 + +## 开发快照(发布身份与不可变计划基础) + +### Fixed + +- 整库发布保留 UUID 和复合键,Wiki 数值身份与大整数内容不再经过浮点数;chunks、标签与 Wiki 日志使用持久化的目标本地编号映射,接管时校验来源和映射覆盖。 +- worker 装饰器转发既有写集合接管能力;写集合及资源复用证据不可覆盖,返回前同步文件与目录。 +- 预备份保留实际范围内的软删除行和关联;同租户异知识库不再被误判为来源残留,关系表按精确二元组识别。 +- 索引按全局文档 ID 拒绝跨知识库覆盖,采用 create/乐观并发条件写入并检查逐项结果;共享资源内容差异写前拒绝,相同资源按证据只读复用。 + +### Changed + +- 本开发快照尚未完成整模块验收,禁止据此开启发布写门:对象版本化精确清理仅完成 MinIO 局部验证,OSS 适配、执行栅栏、来源候选/UI 和真实 worker 连续两次中断验证仍待闭合。[兼容与未完成边界](docs/library-migration-contract.md)。 + +## 开发快照(云对象存储寻址兼容) + +### Fixed + +- 整库发布与恢复按存储提供方选择寻址方式:MinIO 保留路径式,OSS/S3 使用虚拟主机式,不再因强制路径式而被 OSS 拒绝资源上传。 + +## 开发快照(跨库分块序列分配) + +### Fixed + +- 发布分块时由目标数据库分配本地 `seq_id`,不再复制源库序列而撞上其它知识库的唯一索引;文档和分块 UUID 不变。 +- 失败恢复仍重放预备份中的原始序列,并保留整实例逐行核验;发布内容校验仅排除分块的本地序列,不放宽正文和其它字段校验。 + +## 开发快照(云执行器授权配置与启动核验) + +### Fixed + +- 云发布执行器开启写入前检查授权人和私有 token 文件,按固定容器路径只读挂载;配置缺失在替换旧容器前拒绝。 +- 部署脚本连续检查容器运行及重启计数,启动失败或重启循环不再误报成功;部署回归纳入必需契约检查。 + +## 开发快照(维护探针排空修复) + +### Fixed + +- 维护健康探针在请求完成后关闭连接,避免自身的空闲 keep-alive 被入口计为在途连接并导致排空超时;不改变业务连接或长流的排空规则。 + +## 开发快照(空目标恢复演练) + +### Fixed + +- 恢复演练使用独立标签作为漂移探针,支持空目标,不再依赖改写已有文档;探针写入前持久化精确写集合并标记内容风险,恢复只清理本次新建身份。 + +## 开发快照(空目标首次同步准入) + +### Fixed + +- 发布概览与同步提交统一探测未知目标:真实空库允许进入首次同步条件判断,无法连接不再误报为非空库。探测超时后拒绝放行,授权、恢复演练及写入闸口仍须满足。 + +## 开发快照(发布目标历史隔离) + +### Fixed + +- 切换发布目标后,不再把旧实例的当前生效版本、预备份、恢复候选和授权当成新实例事实;当前指针按目标与对内/对外范围独立保存,旧作业不可被新目标接管。 +- 本机隧道与云端直连共用逻辑目标身份,源封存保持可见;历史记录及证据保留,不自动归属新目标。 + +### Changed + +- **破坏性**:治理库迁移 077 增加目标身份,须停旧消费者后升级;已有目标绑定证据时禁止直接降级。[升级与回退边界](docs/library-target-identity.md)。 + +## 开发快照(云端归档清单读回) + +### Fixed + +- 快照清单通过指定执行器容器读取,不再将容器内归档路径当作 SSH 宿主机路径;避免已导入的快照被误报不存在,保留真实缺失与执行错误的区别。 + +## 开发快照(云端快照搬运默认值与接收目录) + +### Fixed + +- 修复快照搬运未显式设置大小和超时上限时默认值丢失,导致正常包被按零字节上限拒绝;默认上限为 8 GiB、超时 10 分钟,显式配置仍生效。 +- 云发布执行器挂载独立的接收包目录,宿主机与容器路径保持一致,修复文件已传到主机但执行器无法装入或导出的故障。 + +## 开发快照(handoff 阶段生命周期 · 回传空页重置 · 目标基线原产地) + +### Changed + +- handoff 的阶段与所有权收敛为一组事务方法:`BeginLibraryHandoff`(事务内建/推进 running 阶段并确认所有权)、 + `CompleteLibraryHandoff`(同一事务:投递发布队列作业 + 交接 queue_job_id + 阶段 succeeded)、 + `FailLibraryHandoff`(同一事务:阶段 failed + 作业 failed)。阶段行按 (job_id, stage) upsert, + 不再依赖 `SyncStages` 里是否预置了 handoff 行。 +- 回传单轮抽成 `pullRound`:**空页重置游标**(引用数正好是 pageSize 整数倍时,否则游标停在最老处、 + 之后新增的引用永远取不到),且游标跨轮保留(单轮 20 页只是预算)。 + +### Fixed + +- 传输阶段在真实 UI 上不可见:此前 running 阶段是无条件 `UpdateLibraryStage`(读 owner 再写,存在竞态), + 成功阶段在交接后按旧 owner 写必然 0 行,且 `library_job_stages` 里根本没有 handoff 行。 + 现在阶段创建/推进/成功/失败都与 job 行的所有权判定在同一事务里完成,交接提交后阶段一定是 succeeded。 +- 删除 handoff 路径残留的无条件 `UpdateLibraryStage`:它与 `BeginLibraryHandoff` 事务里的写重复, + 并在 Begin 返回到这次写之间给交接留出竞态窗口。现在 handoff 的所有阶段写只发生在 + Begin/Complete/Fail 三个持有 job 行锁的事务方法里;新增源码契约测试防止回流。 +- 身份判定漏掉"目标权威基线":`library_baseline` 是目标侧真实捕获,但只登记 `production_effective` + (证据 action=target_baseline_init / origin=target_baseline)。现在原产地按捕获证据判定: + 封存=源、预备份=目标、带基线证据的 effective=目标;普通 effective 与 recovery_verified 只是引用, + 不决定原产地;无捕获证据或源/目标同时成立仍拒绝。 + +## 开发快照(交接所有权 · 回传游标 · 快照原产地) + +### Changed + +- **handoff → release 的交接改为按所有权 CAS**:`EnqueueAndAttachLibraryJob` 接受"调用方声明的前驱队列作业号", + 只允许"当前无人持有"或"当前正是这个 handoff"时替换;任意替换一律拒绝。发布/恢复的发布作业 ID 仍是 + `QueueJobIDFor(job)`,接管/续作路径不变。 +- 回传枚举的游标**跨轮保留**:单轮仍有 20 页工作量预算,但下一轮从上次位置继续,读到不足一页才回到起点, + 所以第 2001 条以后的引用不会被每轮重置的游标永久漏取。 +- 快照**原产地只由捕获事件决定**:`test_sealed`(源)与 `production_prebackup`(目标)互斥; + `production_effective` / `recovery_verified` 只是引用同一份快照的完成事件,不再参与身份推断 + ——"先封存、后发布成功"的正常链路不会再被自己的完成事件判成身份冲突。 + +### Fixed + +- **正常流程必现阻断**:API 先关联 handoff 队列作业,而交接只接受"未关联"状态,导致每一次正常发布都被自己的 + 所有权检查挡住。另修 handoff 队列作业号:`jobs.id` 为 varchar(36),原实现拼接后缀超长,插入即失败; + 现在由 `governance.LibraryHandoffQueueJobID` 生成合法且确定的 ID。 +- **迟到 handoff 污染已交接作业**:失败出口(含 Push 错误)改为按所有权 CAS,只在本 handoff 仍持有业务作业时 + 才写 state/stage/recovery;已交接或已终态时零修改,也不再写"未进入维护窗口"这种只对本次执行成立的结论。 + 阶段写入同样带所有权判定(所有权只由 `library_jobs.queue_job_id` 决定,与阶段行是否存在无关)。 + +## 开发快照(跨主机自动归档交接:搬运先于维护 · 双向校验 · 云端版本回传) + +### Added + +- **发布/恢复作业先搬运、后执行**:快照搬运接线(`LIBRARY_HANDOFF_*`)时,API 把作业投递成 + `library.snapshot.handoff`(capture 角色消费),由它把不可变快照送到云端 release-executor 并 + **双向校验**(本机 `Load` 逐 blob 重算 → 云端 `snapshot-unpack` 再逐 blob 重算 → 版本清单摘要自证 → + scope/tenant/知识库身份与治理库作业一致)之后,才投递真正把目标置入维护窗口的 `library.sync|restore`。 + 搬运失败/超时/校验不过时发布作业**根本不存在**,目标不会被停用、不写任何知识。 +- 新包 `internal/libraryhandoff`:`Push`(本机→云端)与 `Fetch`(云端→本机)共用一套校验与暂存规则; + 远端命令是固定 argv(容器名/路径来自部署配置,调用方只能给快照 ID 与期望身份);同一快照用本机 + flock 串行化,云端内容寻址 + Link 幂等;同 ID 异内容直接拒绝;暂存 bundle 用后即删,归档本体不自动清理。 +- capture 角色新增**云端版本回传**扫描:按治理库已成功作业的 `snapshot_id`,把本机缺失的云端快照 + `Fetch` 回本机归档,因此页面/API 既有的列表、详情、差异、存储与历史恢复路径读到的都是真实字节。 +- `libraryctl snapshot-push` / `snapshot-fetch`:运维可直接搬一份快照并打印逐 blob 身份用于对拍。 + +### Changed + +- `LIBRARY_WORKER_ROLE` 的副作用边界继续收敛:搬运与回传只注册在 capture 角色;若把搬运接线到 + `full` 角色(同时消费发布作业)启动即失败,避免与云端执行器抢同一批作业。 +- `library_jobs` 的孤儿收拾按角色负责的 kind 过滤;治理库 DDL 仍只属于控制面进程。 + +### Fixed + +- 入口闸门不再在 10 秒静默后掐断上游流:建连超时与读超时分离(连上即 `settimeout(None)`), + 半关闭按 TCP 语义单向传播,避免响应被截断;排空超时仍以 exit 2 表达失败。 + +## 开发快照(发布管理统一修复:执行身份 · 终态收尾 · 准入与数据身份) + +### Changed + +- **发布意图与执行代次分开**:`library.sync` / `library.restore` / 续作改用 operation(一次明确意图)+ attempt(执行代次)。同一个 `operation_key` 重发命中同一条意图(不重复执行),不带或换键就是新意图——A→B→A 的第三次发布不再拿到第一次的历史成功作业。请求体新增可选 `operation_key`。 +- 版本台账改为**不可变事件 + current 指针**:不同 operation 引用同一快照是两条事件,`source_job_id`/`evidence`/`created_at` 不再被后来的执行覆盖;"谁是当前"由单调次序的条件更新决定。治理库新增迁移 76(`library_operations` / `library_attempts` / `library_current_versions`),不触碰 WeKnora Schema、源码或镜像。 +- 按预备份恢复成功后登记**恢复事实**并推进 current:页面、差异与后续作业看到的是恢复出来的内容身份,而不是继续宣称已失败的新版本生效;原失败作业与失败版本保持不变。 +- 接管或恢复时,执行目标消费已持久化写集合里的复用决定;**读不懂计划的实现直接拒绝写入**(不再"账本说没动共享对象、实际又重写一遍")。 +- 预备份合同改为目标实时状态(schema/模型/映射),不再把来源快照的声明当目标合同。 +- **续作沿用原业务作业,只新增执行代次**:维护窗口 owner、freeze journal、预备份与写集合都按业务作业 id 落盘,因此不再为续作另造 `-resume` 作业行;发起续作会显式结束上一代执行(旧代次标记 superseded,行保留)。 +- 执行域准入改为**可执行校验**:worker 注册整库发布 handler 之前,读目标实况(知识库/租户/schema/索引)、旧 release 路由绑定的目标知识库、以及未释放的维护窗口持有者;任一读不到、与配置不一致、或旧路由指向同一个知识库,就拒绝执行(明确失败,不做任何维护动作,也不停止既有服务)。 + +### Fixed + +- 半写窗口接管时,前置检查(入口/后台静默/停写者)任一失败都不再重新开放目标:持久 `ContentRisk` 优先于"本进程还没写"。 +- 服务启动或健康校验失败时不再调用开入口:入口保持关闭,交恢复流程处理。 +- journal 已是 `succeeded` / `recovered` 的终态重放可从持久事实重建收尾凭据,不再永久卡住维护锁。 +- 心跳失租会立刻取消 handler;业务状态、阶段进度、版本事件与维护锁释放都带执行代次(epoch)守卫。 +- 迟到的旧代次不能推进 current,也不能释放/改写另一个代次的窗口。 +- 续作沿用原 operation 与首次锚点,不另造丢谱系的新意图。 +- 收尾续作(finalize-only)与正常出口共用同一证据构造:缺少真实字节数或写集合摘要即拒绝登记生效版本。 +- 通用 `POST /api/v1/jobs` 拒绝 `library.*` 保留类型;worker 在动维护前核对业务行、kind/scope 与队列关联。 +- 全库搬运改写定位符时重算 `location_hash = sha256(最终 physical_path)`,与文档级导入共用同一实现。 +- 整库发布在副作用前核对目标**实时**模型契约:同维不同模型、模型不可读、dirty schema 一律拒绝。 +- 容量门禁接到 worker 执行前(预算不足或读不到即拒绝);存储预览按全量依赖判定保护,保护依据读不到时拒绝生成可删候选,备份类型只认显式登记。 +- 维护状态/入口/释放的守卫**按被更新行自己的作业号**取身份(此前把 `$1` 硬编码成作业号,而维护类入口的 `$1` 是 scope/instance,导致正常写入与释放全部匹配不到作业);同一代码路径同时用"作业号不匹配必须失败"的负例锁住。 +- 同一作业允许**多个不可变执行代次**:认领递增 epoch 并新增 attempt 行(不再复用唯一索引改写旧代次),重复调用幂等续租,别人持有未过期租约时明确让路;被接管的旧代次标记 abandoned,迟到的 write/renew/finish 一律按 `ErrLibraryEpochStale` 拒绝。 +- 首次锚点登记改为事务内 `FOR UPDATE` + 只填空 + 逐字段回读核对;`NULL` 与零值不再混淆(真实 PG 上验证,未知 ≠ 0)。 +- current 的次序键取**意图创建时间**:旧意图的迟到事实被 `ErrLibraryCurrentStale` 拒绝,不会把当前生效版本推回历史;恢复通过新的 `kind=recover` 意图(内容更旧、意图更新)推进。 +- 版本事件冲突只做**加法**(已有键永远赢、来源作业/意图/登记时刻冻结),且只有真正新插入(`xmax=0`)才推进 current,纯重放不再二次推进。 +- 集成测试护栏:`TEST_DATABASE_URL` 必须指向看起来是一次性的测试库(或在确属一次性库时显式声明),并先清理上次中断留下的同名 schema;`kg-pgtest-*` 专用容器内一用例一 schema,结束即删。 +- 发布页:状态读取核 HTTP 状态与响应结构;按预备份恢复纳入轮询并在维护关闭后读回终态;Wiki 差异覆盖标题/摘要/父级变化。 +- CI 版本契约门同时核进程退出码、必需测试真 PASS 与负例失败归因(编译/网络错误不算预期断言生效)。 + +## 开发快照(接管复用预备份不再抹掉写集合证据) + +### Fixed + +- **崩溃接管复用预备份时,已经登记的写集合证据被整份覆盖,恢复链断在第二次中断**: + `BackupPrepared` 原先每一轮都新造一份证据,而版本登记是整份替换 + (`evidence = EXCLUDED.evidence`)。接管路径上复用声明只带快照 id(没有字节数), + 写集合预检又只在首轮执行,于是 `writeset_digest`/`writeset_rows` 被抹掉、 + `backup_bytes` 记成 0;同一作业再中断一次就再也取不回写集合,只能在 + `verify_effective` 上失败(2026-10-30T00:58Z 演练实例 `…-1793321916382871758-retry`, + 摘要 `fddd98cf70…` → 空)。现在证据按"同一作业 + 同一份预备份"合并进已持久化那一行, + 身份不符一律拒绝;接管复用从首次登记的证据取回真实字节(缺失即拒), + 生效版本证据统一构造。同一作业的写集合只允许落定一次,摘要冲突即失败。 + +## 开发快照(接管身份判据 + 真实中断演练的杀法与期望) + +### Fixed + +- **同一个快照由别的作业登记成生效版本时,接管会把它当成本作业"只差收尾"**: + `classifyTakeover` 原先只看"当前生效版本的目标快照是否等于我的目标快照",而版本行 + 主键由 `(kind, scope, 快照)` 决定、写入是 upsert(会改写 `source_job_id`), + 所以"生产上有这个快照"被误当成"本作业写完了"。2026-10-29T19:16Z 的真实后果: + 作业只写完了 `database` 阶段(`resources/index/wiki/verify` 仍 pending), + 人工拉起后被判 `succeeded`,并把生效版本归属改写成自己。现在分类带作业身份 + (`effectiveOwnedBy`):归属别的作业 ⇒ `foreign_effective`,走拒绝接管的失败出口 + (不写目标、不释放维护、终态失败并指明预备份),不再按同快照收尾。 + 同一份身份判定与基线共用,快照相等不再单独构成"完成"证据。 + +### Changed + +- **中断演练脚本改用"进程崩溃"语义,并把期望内容按快照推导**: + `scripts/library-kill-takeover.sh` 不再 `docker kill`(那是 Docker 手动停止, + `unless-stopped` 也不拉起,上一轮就因此空等 420s、最后靠人工 `docker start`)。 + 现在向容器 PID1 从宿主机发 SIGKILL,用 `docker events` 的 `exitCode=137` 作证据, + 限期等 restart policy 拉起;策略没起来才显式 `docker start`,并在证据里记成 + `restart_source=manual_start`,绝不当自动恢复。期望内容按目标快照的 manifest 推导 + (`knowledges/chunks/wiki_pages`),`resources` 不进默认期望(同租户其它知识库的 + 资源会保留)。新增:`--kind sync|restore`、`--snapshot` 强校验、目标快照等于中断前 + 生效版本时**杀之前就拒绝**、五个写入阶段全部 `succeeded` 才算完整续作、 + 独立写集合校验器缺失即失败、首屏证据读回用 `owner_scope`。 + +## 开发快照(当前生效版本精确查询 + 真实中断演练的固定屏障) + +### Fixed + +- **"当前生效版本"靠最近 50 条找,历史一长就把已生效读成没有**:接管分类 + (`classifyTakeover`)、基线判定(`classifyBaselineVersions`)与"已知索引映射" + 都把分页窗口当索引;窗口之外的生效版本被读成"不存在"之后,接管会把已经上线的 + 目标重写一遍,基线入口会为已有权威版本的目标再建一次基线。现在统一走两条精确 + 查询:`LibraryCurrentVersion`(`kind='production_effective' AND superseded_at IS NULL`, + 每 scope 至多一行)与 `LibraryVersionOfSnapshot`(按快照身份取回"已顶替"证据)。 + 同一含义只保留一份实现:同步与恢复共用 `knownIndexMapping`。 +- **同一判断在接口侧也要改,不是"只是展示"**:整库页的生产版本、生产同步闸口 + (这是**创建**判据:读错会放行一次不必要的覆盖)、建立基线入口(读错会覆盖 + 别人的版本)、归档保留里"生产生效版本"的保护标记,全部改用精确查询;查询失败 + 一律 fail closed(500/拒绝),不猜。历史列表仍是分页展示,`LibraryVersions` + 的 1..100 上限没动。 + +### Added + +- **真实 worker 中断演练的固定同步屏障**(`internal/testbarrier`,默认关闭): + 只有 `KG_TEST_BARRIER_DIR` 与 `KG_TEST_BARRIER_POINTS` 同时在场才生效,且只在 + 本机测试栈通过 compose overlay 注入。worker 每个阶段写完后写现场文件并停在固定 + 点位,演练方看到它再 SIGKILL——命中是确定的,不是靠 sleep 猜时间。进程被杀后 + 重启的 worker 看到同一份现场文件直接通过,不会把接管再拦住。 +- `scripts/library-kill-takeover.sh`:前置体检(目标拓扑、无在飞作业、无未释放 + 维护窗口、镜像真的带屏障代码)→ 注入屏障 → 等命中 → 锁住这一个作业 → 读回写 + 集合台账并独立校验摘要 → SIGKILL 容器 → 等同一作业被接管 → 校对目标内容、 + 维护释放与服务恢复 → 撤掉注入。只有整条链路成立才 exit 0;missed / 超时 / + 接管失败分别用不同退出码,**"没做"与"做成"分开**。 + +## 开发快照(真实同步/恢复后的页面修正与写集合转发) + +### Fixed + +- **写集合台账在真作业里根本没生成**:worker 把目标包成 `contentTrackedTarget` + 以标记"内容可能半写",但包装层没转发 `PlanWriteSet`,而 orchestrator 是用 + **类型断言** `target.(WriteSetPlanner)` 决定要不要算写集合的 —— 断言恒为假, + 台账既不落盘也不登记。真实后果:10-29 两次真作业的预备份证据里都没有 + `writeset_digest`,归档根下没有 `writesets/`,一旦 worker 崩在写入中间接管必然 + 失败。现在包装层显式转发;内层不支持预检时返回硬错误,不退回"没有台账也照写"。 +- **`S3ObjectStore.Stat`/`Delete`/`Copy` 与 `Open`/`Put` 吃不同的定位符**:真实资源 + 路径是 `storage:///:///`,前三个用只认单层的 + `validObjectLocator` 并把整串当对象键,于是"对象在桶里但校验读不到"。现在四个 + 入口共用 `validObjectKey` + `providerPathFromLocator`。集成用例改成喂真实定位符, + 负例覆盖键不存在 / provider 不符 / 路径穿越 / 复制源不存在;写集合集成用例里 + 那条"读不到也当通过"的容忍断言改为真断言。 +- **已成功/已失败的作业在页面上仍写"尚未启动""此时尚未运行"**:生产版本行与作业条 + 的文案原来写死,阶段条只认 `kind=sync`。现在按作业类型与终态显示,恢复/基线也 + 用同一串阶段读自己的阶段行(不再一律"本次作业尚未开始")。 +- **预备份已登记却显示"尚未创建/无记录"**:`overview.prebackup` 原来只认"与拟发布 + 快照同内容的那一份",而恢复作业登记的是**恢复前**的备份,两者必然不同。现在显示 + 最近一次已登记预备份,并给出所属作业与"是否为当前拟发布目标";闸口判定不变。 +- **所有归档都被标成"测试封存"**:归档根下同时有目标基线与每次预备份。overview 新增 + 轻量版本清单(不含 evidence),抽屉按登记过的 kind 标注每份快照,未登记的归档 + 如实写"未登记(归档文件,不作为发布候选)"。 +- **基线与恢复被写成"生产同步"/"封存进行中"**:作业类型改成逐类映射 + (测试封存 / 生产同步 / 按版本恢复 / 建立目标基线),页签徽标、作业头、明细表同步。 +- **轮询只覆盖封存队列**:点了同步/恢复/建立基线之后页面根本不刷新,看上去像"还没 + 启动",而失败作业又可能被无限轮询。现在轮询覆盖"投递 → 终态读回":投递中的动作、 + 封存队列作业、任一 scope 的在飞持久作业都算在跑;读到终态(成功/失败/取消)再读 + 回一次就停。 +- **维护窗口的起始时间永远是第一次建立基线那一刻**:`acquired_at` 没进 + `ON CONFLICT DO UPDATE`,新作业接管已释放的窗口时不会换时间。库级与实例级两份 + SQL 都改成"同一作业重入才保留旧值,新作业接管用本次时间"。 + +### Added + +- `docs/agents/traps.md` trap-14(包装层丢掉可选接口 ⇒ 台账静默跳过)、 + trap-15(对象存储各入口定位符形状不一致)。 +- 真实 PostgreSQL 用例:维护窗口起始时间只属于当前这次占用。 +- 真实 MinIO 用例:正例用 `storage://` 定位符走 Put/Open/Stat/Copy/Delete,负例四种。 + ## 开发快照(基线崩溃续作、维护原状态保留与真实恢复演练工具) ### Fixed @@ -853,6 +2399,11 @@ ### Added +- 数据源配置新增 PP API 地址、账号与密码更新、真实登录及目录连接检查;配置校验通过才生效,临时故障保留待验证修改,扫描与取件共用生效配置。 +- 钉钉添加来源统一使用 DWS 官方授权,增加真实空间校验、中途失效恢复与账号变化保护,取消登记自动回落旧扫码侧车;认证操作接入既有审计。 + +- 数据源配置新增 DWS 登录与重新授权入口,使用钉钉官方设备授权;成功后刷新账号并独立检查目录访问权限。支持取消、过期和重试,授权仅限发起的管理员会话。[操作说明](docs/DWS_LOGIN.md) + - 新增解析监控统一工作台:顶部运行指标与依赖卡片、下方单一文件处理表;来源文件与目标测试库归并最新版本,动作、阶段、状态分列,后端统一筛选、计数及分页。支持单条/跨页勾选重试和版本、失败、重试详情;测试库移除重试独立核验治理规则,不误走上传流程。取消六分页和手动开始入口,生产授权仍在发布管理;本次不改变后台自动调度策略,自动处理闭环需另行端到端验收。 - 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。 @@ -888,6 +2439,12 @@ ### Fixed +- 发布作业详情在目标仍被维护时返回维护状态与人为处置说明(持有作业、入口状态、目标身份、下一步),不提供"强制成功"入口;缺归属证据的收尾保持维护锁定。 +- 发布或恢复完成后,Wiki 与日志页面的分页游标视为失效:页面提示刷新后重新分页(本地编号会被重新编排),不把旧游标的错位当成数据损坏。 +- 发布在预备份后、规划前与首笔写入前按治理库授权行重新判定:授权被撤销或过期即停,保留预备份且不写目标;不再只信内存里的有效期。 +- 整库发布绑定序列归属及完整迁移目录,识别分块与 Wiki 的规范嵌套引用;未知结构或跨父引用在写入前拒绝,保留正常资料的发布与恢复路径。 +- 发布使用执行时真实时钟,在预备份后与首个业务阶段前复核授权;预备份绑定对象精确版本,拒绝读取期间被替换的对象(包括同字节新版本)。 + - 修复钉钉新登记来源仍按旧离线目录身份取件的问题:从当前来源配置读取空间坐标,实时枚举所在目录并严格匹配节点身份;同名文件不替代、目录不完整不误报删除。修复解析监控遗漏 `version_id` 取件任务及缺少业务元数据的失败记录,正确显示失败原因、重试入口与历史。 - 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。 @@ -1237,21 +2794,22 @@ - 删除问答记录、同步栏和区域页中的冗余解释文字、读取时间与源连接提示,保留真实错误、未同步、权限阻断和安全告警。 ## 开发快照 snapshot/v0.1.28 - 2026-10-18 - -### Added - -- 问答运营新增持久本地副本,每 5 分钟后台同步并支持立即同步;列表、详情、检索、质量范围和使用统计改为读取本地数据库。 -- AI 答案详情提供安全 Markdown 预览与原文查看,支持表格、代码块和链接;不执行原始 HTML,外部图片默认不请求。 +目标提交:f33730ed7437536c3d1e01cc2f20231af076b531 ### Changed +- **Merge PR #8:开发版本历史修复(并集成更早的 QA 运营分支)** +第一父 `c1d49adb…` → 本合并 `f33730ed…`:135 个文件,+14226/-42;第二父 `74ba737b…`。 +本合并的版本历史变更:新增 `internal/governance/development_notes.go` 按精确提交 SHA +提取开发说明;`internal/versionhistory/rules.go` 按 commit-specific CHANGELOG → +exact-SHA archive → annotated snapshot tag 顺序取说明;`sync.go` 支持 TargetSHAs、 +includeDeliveredCommits 与 sourceHead 绑定;`scripts/development_snapshot.py` 提供开发 +快照计划/显式发布入口(不调用 publish)。 -- 增加治理侧问答副本表与同步状态;同步由普通 worker 执行,使用独立只读源连接,源失败保留最后成功副本,权限校验失败阻断读取。 -- 副本激活与质量输入变化的复核失效同事务提交;同步持久去重、租约校验及重启恢复不改变源问答或现有生产写入。 - -### Fixed - -- 本地读取不再逐条重复写质量留档或解压完整范围长答案来统计字段,保留完整列、输入版本一致性和真实缺失值。 -- 初次观察即已同步完成时自动重查列表,避免较早的首次未同步错误一直停留。 +同一第一父边界还集成了更早的 QA 运营查询/组织/质量统计分支: +`internal/qaopsorg`、`internal/qaopsquality`、`internal/httpapi/qa_monthly.go`、 +`web/src/QAOperations.tsx`、`web/src/QAQuality.tsx` 等。该部分是集成既有分支,不是本 +merge 新开发;不声称已部署或验收。 +统计:135 个文件,+14226/-42。 ## 开发快照 snapshot/v0.1.27 - 2026-10-18 @@ -1576,3 +3134,4994 @@ - **验收口径**:`docs/USER_FLOWS_ACCEPTANCE.md`(C1~C9)与 `docs/OPERATIONS_RUNBOOK.md`。 ⚠️ 上面的端口与容器名前缀是**本机运行栈**的实测值;换环境要按那边的运行栈改,别无脑照抄。 + + +## 开发快照 snapshot/v0.1.349 - 2026-11-04 +目标提交:0d9091e4644cf3eb053fe2c852bdbab90a51cc24 + +### Fixed +- **fix(library): 目标隔离映射兼容旧计划与真实回归** +空 mode 计划不映射;索引 source_id 按语义映射;relation 按字段表解析。 +隔离回归按持久映射 ID 断言,DS02 故障注入真实命中。 + +改动范围:`internal/releaseadapter/v071/library_target_ids.go`、`internal/releaseadapter/v071/library_target_path.go`、`internal/releaseadapter/v071/library_verify_content.go`、`internal/releaseadapter/v071/data_closure_r10_test.go`、`internal/releaseadapter/v071/data_contract_r10_test.go`、`internal/releaseadapter/v071/data_matrix_r11_test.go` 等 15 个 +统计:15 个文件,+428/-91。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/data_closure_r10_test.go`、`internal/releaseadapter/v071/data_contract_r10_test.go`、`internal/releaseadapter/v071/data_matrix_r11_test.go`、`internal/releaseadapter/v071/data_schema_r11_test.go` 等 12 个 + +## 开发快照 snapshot/v0.1.348 - 2026-11-04 +目标提交:e0fc2c32b89b7ac74f2346057b43436f9404ba3a + +### Changed +- **feat(library): 目标库隔离 ID 映射并保留旧库** +- **同一源快照可导入同实例的第二个知识库**:写入目标前按 `sha256(目标 tenant + 目标 KB + 表 + 源身份)` + 派生目标侧 UUID(knowledges / chunks / knowledge_tags / wiki_pages / wiki_folders / + wiki_page_issues / resource_bindings)。同一目标重复同步、重试与跨版本得到同一 ID,不同目标 + 或不同表得到不同 ID;旧库原有行不再与本次写入撞主键,也不会被删除。 +- **引用字段一起改写**:chunks 的 parent/pre/next 与 relation/metadata 中的精确身份、 + wiki_pages 的 chunk_refs / source_refs(保留 `id|title` 与顺序、重复)、folder_id、 + resource_bindings.owner_id、索引文档物理 ID 与 chunk_id/knowledge_id/source_id/tag_id; + 正文、标题、向量、引用顺序与重复项保持不变,不重新解析、不重新 Embedding。 +- **resources 保持原 ID**:资源是多知识库共享的字节载体,继续走既有"内容相同 + 来源可审计"复用 + 与归属证明;只改绑定行的 id/owner_id,不改 resource_id。 +- **写集合、校验、索引计划与恢复共用同一映射**:写集合登记目标身份,verify 按目标身份比对; + 恢复重放目标写前镜像时不二次映射。引用指向未登记身份时直接拒绝,不做模糊替换。 + +改动范围:`internal/libraryrelease/writeset.go`、`internal/releaseadapter/v071/library_index_plan.go`、`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/library_scope_remap.go`、`internal/releaseadapter/v071/library_target_ids.go`、`internal/releaseadapter/v071/library_target_path.go` 等 13 个 +统计:13 个文件,+1324/-5。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/library_target_ids_integration_test.go`、`internal/releaseadapter/v071/library_target_ids_test.go`、`internal/releaseadapter/v071/library_target_real_seal_test.go` + +## 开发快照 snapshot/v0.1.347 - 2026-11-04 +目标提交:604295549840dd2f4fbe2f91f4ac74d529cc5ca2 + +### Fixed +- **fix(objectgateway): 入口测试夹具改用无口令 PG URL** +现象:CI run 347 / job 362 在 security-secrets 失败,指向 +cmd/object-gateway/main_test.go:30 的 pg-url 类别。 + +根因:该 DSN 只用于 127.0.0.1:1 故意不可达连接,验证启动能越过 +配置阶段到达 journal/后端准入,本身不需要任何口令,却写成了带口令形式。 + +取舍:直接换成合法无口令 URL,不拆秘密字符串隐藏检测、不改扫描器/基线/ +必需项范围。产品代码与测试行为不变。 + +证据:check_secrets.py 由 exit 1(指向该行)转为 exit 0;go test +./cmd/object-gateway 通过;umask 022 下 make verify 16 项本地必需全 success。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`cmd/object-gateway/main_test.go` +统计:1 个文件,+1/-1。 + +### Tests +本次提交包含测试/夹具变更:`cmd/object-gateway/main_test.go` + +## 开发快照 snapshot/v0.1.346 - 2026-11-04 +目标提交:a55319d9726f063baf43b7fe1e3fb7768946a4d8 + +### Fixed +- **fix(objectgateway): 取消整桶独占前置并按维护停写更新** +- **对象网关不再要求整桶独占证明**:`Gateway.Ready` 只核 journal、PG 持久化设置与后端版本能力, + 删除 `Isolation`/`AuditVerifier` 与 `OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`、 + `OBJECT_GATEWAY_ID` 的启动与逐请求校验;旧部署残留值被忽略,不再阻塞默认共享桶路径。治理 PG + SELECT-only authority、plan/owner/attempt/epoch 绑定、intent-before-send、单次写与精确回滚不变。 +- **目标 KB 更新走维护窗口**:停目标测试 WeKnora 写入应用容器并读回确认 → 备份本次目标 KB/对象范围 + → 用原 plan/WriteSet 更新 → 启动原容器 → 健康与页面验收;失败按原备份恢复。不再要求排空整桶 + 全部 writer、RAM 权限清单或独立只读 OSS AK,现有 AK 继续用于 PUT/GET/DELETE/列版本。 + +- **对象网关不再要求整桶独占证明**:启动只核 journal、PG 持久化设置与后端版本能力,旧部署残留的 + `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY` 被忽略,不再阻塞共享桶路径。 + 治理 PG SELECT-only authority、plan/owner/attempt/epoch 绑定、intent-before-send、单次写与精确回滚不变。 +- **更新方式改为维护停写**:停目标测试 WeKnora 写入应用容器并读回确认 → 既有维护/预备份链记录目标 KB 范围 → + 原 plan/WriteSet 经正式 Apply 更新 → 启动原容器 → 健康与页面验收;失败走既有恢复链回放原预备份。 + 不再要求排空整桶全部 writer、RAM 权限清单或独立只读 OSS AK,现有 AK 继续用于 PUT/GET/DELETE/列版本。 + +- **共享桶不再因同 key 外部写者误报成功**:create 后除精确版本读回外核对当前 latest;并发写者产生更新的当前版本时, + 明确返回冲突并保留双方版本,不做任何未记账的删除,也不会在 Reconcile 里把已被外部写者接管的 key 报成 committed。 + 版本化存储的 PUT 不是原子 create-if-absent,同 key 并发不自动合并,需按回执人工处置。 + +改动范围:`cmd/object-gateway/main.go`、`internal/objectgateway/attestation_legacy.go`、`internal/objectgateway/audit.go`、`internal/objectgateway/create.go`、`internal/objectgateway/gateway.go`、`internal/objectgateway/http.go` 等 25 个 +统计:25 个文件,+510/-171。 + +### Tests +本次提交包含测试/夹具变更:`cmd/object-gateway/main_test.go`、`internal/objectgateway/acquire_integration_test.go`、`internal/objectgateway/audit_test.go`、`internal/objectgateway/create_test.go` 等 14 个 + +## 开发快照 snapshot/v0.1.345 - 2026-11-03 +目标提交:017765763a74919fdcc0591454ae85d3415f6a43 + +### Fixed +- **fix(library): 维护卡只展示 owner_job_id 匹配的作业详情** +问题:维护窗口 record.owner_job_id 指向失败/待恢复的作业 A,但页面把同 scope +最新作业(更新的成功封存 B)当窗口进度,needs_restore 被显示成“导出 · 已完成”, +需要处理的原窗口因此看起来已经结束。 + +改法: +- maintenanceSummary 只接受“按 owner_job_id 读到的持有作业”,id 不一致一律按 + 未读取处理;进度/错误/恢复说明只来自该作业,不拿最新作业兜底。 +- 新增 fetchLibraryJobDetail 读取既有只读接口 GET /api/v1/library/jobs/{id}, + 明确区分 loaded / missing(404) / error(非2xx、结构不符、id 串包) / unread, + 不把读取失败吞成“不存在”。 +- 恢复可用性只由“维护仍持有 + 本窗口作业未收口 + 当前 scope 等于 owner_scope” + 决定;running/pending 不并发恢复,已释放/无记录不提供恢复,跨 scope 给切换提示。 +- 入口状态明确标注“维护记录,未实时探测”;held 时说明只有维护记录释放才算结束; + held 但持有作业已完成时写“维护记录未对账”,不提供强制成功。 +- load 增加请求代次守卫,晚回包不覆盖更新的窗口;作业详情返回的 id 与请求不符 + 按读取失败处理。 + +未改后端准入、网关协议或任何维护记录;未部署。 + +改动范围:`web/src/ReleaseTargets.mount.test.tsx`、`web/src/ReleaseTargets.tsx`、`web/src/librarySnapshots.ts`、`web/src/releaseTargetsMaintenance.test.tsx` +统计:4 个文件,+545/-27。 + +## 开发快照 snapshot/v0.1.344 - 2026-11-03 +目标提交:bd452e85b3b40083ac13c35cd9afa04dd978c714 + +### Tests +- **test(library): 维护 scope 终态按正式释放语义断言 released** +ReleaseLibraryMaintenance 的真实终态是 state=released + released_at,原断言写成 verified 会误红;改为按生产语义核对 released/open。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`cmd/worker/library_three_blockers_chain_test.go` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.343 - 2026-11-03 +目标提交:71f23c67639f3ea8f0171a56d0198ac815ca216a + +### Tests +- **test(library): 用结构化 URL 构造 reader DSN 夹具** +保持同一解析断言,避免源文件出现字面带口令连接串被密钥扫描器误报。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`cmd/worker/library_three_blockers_chain_test.go` +统计:1 个文件,+6/-1。 + +## 开发快照 snapshot/v0.1.342 - 2026-11-03 +目标提交:b4add6c9b0912294ceb9e00a8d54a4bd955f9135 + +### Fixed +- **fix(library): 收口 B1-R1/B2-R1/B5-R1 并让恢复链经过正式队列终态** +- **B1-R1 受限演练恢复计划**:写集合新增 `restore-drill` 种类——共享 V2 信封、contract 1 与 schema 摘要, + 对象/索引/本地 ID 映射必须为空,来源 tenant/KB 必填;任一项非空即拒绝,旧执行器不能把它当发布计划 + 接管。恢复演练入口 `RestoreDrill` 与对象网关签发的零对象计划使用同一 attempt/写前镜像身份。 +- **B2-R1 verify 作业的不可变 operation**:`POST /api/v1/library/verifications` 在创建作业前先建 + operation(`ensureLibraryIntent`),作业携带 `operation_id` 与稳定幂等键;同一幂等键对应不同请求返回 + 409。worker owned attempt 与同 job recover 的网关 claim 都按原 operation + recovery job/operation + 核验,缺 operation 的 verify 作业在真实恢复中 fail closed。 +- **B5-R1 迟到响应不得污染新 scope**:恢复验证面板按 scope 世代 + 动作序号判定在飞动作;切 scope 即作废 + 旧 POST/回调,迟到响应不能改写新 scope 观测、不能触发父级旧 job 回调、不能清掉新动作的 pending。 + 新增真实挂载反例用例覆盖旧 internal POST 晚到的场景。 + +改动范围:`internal/httpapi/library_verify.go`、`internal/libraryrelease/writeset.go`、`internal/libraryverify/verify.go`、`internal/releaseadapter/v071/gateway_object_store.go`、`internal/releaseadapter/v071/library_production_target.go`、`web/src/RestoreVerificationSection.mounted.test.tsx` 等 12 个 +统计:12 个文件,+1515/-18。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_three_blockers_chain_test.go`、`internal/httpapi/library_verify_test.go`、`internal/libraryverify/canary_test.go` + +## 开发快照 snapshot/v0.1.341 - 2026-11-03 +目标提交:f9457fab52eb84c7af0edad492aad23fa59658ea + +### Fixed +- **fix(library): 打通恢复验证的正常恢复与页面联动** +- **B1 恢复验证的恢复身份/计划**:共享演练不再把同一份快照同时当作来源与写前镜像 + (真实恢复合同会在任何写之前拒绝)。同一维护切点内做两次**真实**捕获:写前镜像 + (恢复实际回放的预备份)与来源身份(独立密封、内容相同、身份不同);两者与作业/ + 目标/tenant/KB 一起持久化,写集合在第一笔写入之前落盘并登记。演练恢复走限定范围的 + 安全入口 `RestoreDrill`:复用同一份 DS01 身份合同与同一批 Apply 原语,四个阶段按 + 写前镜像整段回放(先清 scope 再插入归档行)并做整实例指纹校验,不是"只删 canary"; + 有恢复派发闸口的目标拒绝该入口。 +- **B2 演练接进治理维护生命周期**:worker 在开窗口前写实例级 + scope 级维护行, + 写入边界更新真实入口状态;成功或"未写内容的安全收尾"才释放占用并开入口,held 时 + 保留行(入口 closed、状态 needs_restore)。同 job 的现有恢复入口贯通 verify: + 恢复队列准入、中断接管与 `library.recover` 的 kind 过滤都接受 verify;预备份引用与 + 写集合摘要按 (scope, job, 写前镜像) 精确登记,恢复入口能取回。失败文案由报告的 + restore_check 与窗口终态产生,不再用"有快照"冒充"已恢复并复核"。 +- **B3 证据优先级统一**:API 与 worker 都以证据为先——明确 failed/invalid 或读取错误 + 必拒绝,即使 `PRODUCTION_BACKUP_RESTORE_VERIFIED=true`;历史 env 兜底只保留在 + "明确没有证据行/存储无证据能力"时。未读取证据的旧调用点语义不变。 +- **B4 恢复验证作业联动父页面**:GET `/api/v1/library/verifications` 从真实业务行 + 投影在飞 verify 作业(running/job_id/state/stage);子面板接受作业后回调父页面 + `onAccepted`,父页面立即 load 并纳入轮询,终态回调 `onComplete` 再做一次读回, + 正常一次点击无需手工刷新即可同步进度/终态/闸口。 +- **B5 观测绑定 scope 与请求代次**:切 scope 立即丢弃旧观测;晚到的旧响应按代次丢弃; + HTTP 失败/不可解析/响应 scope 不一致都明确显示读取失败,保留旧数据时必须标成 + "上次观测已过期(刷新失败)",不再显示"已验证(当前目标)"。 + +- 迁移 79 仍只向上应用;`migrator` 没有自动 down 路径,部署回滚保留 79 与既有证据, + 不执行有损 `down.sql`。F1(备份主机连接/命令状态细分)仍为非阻塞后续。 +- 未部署、未调用业务目标、未切换服务;本轮只做隔离验证与固定 SHA 的候选提交。 + +改动范围:`cmd/librarydrill/main.go`、`cmd/worker/library_recovery.go`、`cmd/worker/library_verify.go`、`internal/httpapi/library_verify.go`、`internal/httpapi/server.go`、`internal/libraryrelease/writeset.go` 等 22 个 +统计:22 个文件,+1145/-136。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_verify_test.go`、`internal/httpapi/library_verify_test.go`、`internal/libraryverify/canary_test.go`、`internal/libraryverify/restore_identity_test.go` + +## 开发快照 snapshot/v0.1.340 - 2026-11-03 +目标提交:5e1482e349e23728f8f2f1aeb770422eba2e5b5f + +### Changed +- **feat(library): 恢复验证成为可页面发起的真实作业** +根因:生产可恢复性只有 PRODUCTION_BACKUP_RESTORE_VERIFIED 这个手填 env 开关, +页面没有任何入口去真跑一次恢复;CLI(librarydrill)又不是 worker 能复用的实现, +所以"已验证"既证明不了跑过、也证明不了跑的是当前目标。 + +改动: +- 共享实现 internal/libraryverify(维护隔离→捕获→基线校验→canary→恢复→复核→关窗口), + cmd/librarydrill 改为薄封装,CLI 与 worker 只允许一份执行体。 +- verify 成为独立业务作业:kind + VerifyStages(capture/verify/canary/restore/finalize), + 与 sync/restore/baseline 共用同一把写互斥;迁移 79 加 kind 约束、重建部分唯一索引、 + 新建 library_restore_verifications(按 target_id 绑定,换库/索引/桶旧证据自动失效, + 同 target+scope+job 幂等)。 +- worker:admitLibraryJob + runOwnedLibraryAttempt 之后调用共享实现,阶段实时写 + library_job_stages,结束后写真实终态;通过写 passed 证据,失败写 failed+原因(不伪成功); + 中断接管按同一作业 id 收掉维护窗口。 +- API:POST/GET /api/v1/library/verifications(管理员;闸口关闭/维护中拒绝;返回完整 + 整库目标、最近证据、失败原因),OpenAPI 同步。 +- 闸口:同步/恢复/续作的证据判断改为读当前目标证据;历史 env 仅在证据缺失时兜底, + 证据存在时以证据为准。 +- 页面:生产保护与恢复面板加「恢复验证」块(完整 KB/索引/桶、状态、最近证据、失败原因、 + 管理员按钮、5s 轮询),作业类型补 verify 文案。 + +测试:make verify 16/16 全绿(go 1387 例 + web 454 例 + 契约/迁移/密钥/依赖锁定); +新增用例覆盖证据四条件、闸口证据优先、页面无证据/失败/通过三种呈现与管理员可见性。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`cmd/librarydrill/canary.go`、`cmd/librarydrill/main.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_release_handlers.go` 等 47 个 +统计:47 个文件,+2485/-336;含重命名 `{cmd/librarydrill => internal/libraryverify}/canary_test.go`(+1/-1)。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_role_test.go`、`cmd/worker/library_verify_test.go`、`internal/appconfig/library_role_test.go`、`internal/backuphost/runner_test.go` 等 10 个 + +## 开发快照 snapshot/v0.1.339 - 2026-11-02 +目标提交:4421dd38cec74fcfcdde177e65238a9ca38c42e5 + +### Fixed +- **fix(worker): 封存来源校验失败写入失败终态** +- **整库封存来源校验失败不再悬挂**:快照来源与配置不一致时,队列作业已 failed 而页面 + 一直显示"导出中"(实测 `libseal-lib-internal-20261102T234053`)。现在失败同时写入 + `library_job_stages` 与 `library_jobs`(failed + 原错 + "修配置后重新封存"),原错 + 不被遮蔽;来源一致的成功路径不变。 + +改动范围:`cmd/worker/library_source_candidate.go`、`cmd/worker/main.go`、`CHANGELOG.md`、`cmd/worker/library_seal_source_failure_test.go` +统计:4 个文件,+124/-1。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_seal_source_failure_test.go` + +## 开发快照 snapshot/v0.1.338 - 2026-11-02 +目标提交:22fb33aa7573f56903a588bf6ca27b9d01e8a006 + +### Tests +- **test(library): 两次recover的202响应留在raw里** +第一/第二次 recover 的 HTTP 202 与队列 id 原先只在用例断言里,raw 只留了失败结果。 +补两份 accepted 回应,报告可直接引用接口受理证据而不是转述断言。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_ds01_negative_r38_test.go` +统计:1 个文件,+3/-0。 + +## 开发快照 snapshot/v0.1.337 - 2026-11-02 +目标提交:0d180aa401e388667b01475f497e5afc91396ccf + +### Tests +- **test(library): 台账行按列原文留档** +`to_jsonb` 行里有数字/布尔/NULL 列,直接解到 map[string]string 在真实数据上 +报 "cannot unmarshal number into Go value of type string"。改为解到 +json.RawMessage 再按列名存原文,比较的仍是每一列的精确值。 + +第二轮失败运行已按登记精确清理并读回。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_ds01_negative_r38_test.go` +统计:1 个文件,+10/-4。 + +## 开发快照 snapshot/v0.1.336 - 2026-11-02 +目标提交:0a87dc8e037c4d7c61b8c566e9e9ca10e8b62308 + +### Tests +- **test(library): 修正D06台账读回的SQL别名** +`SELECT to_jsonb(x)` 缺表别名,真实跑出 SQLSTATE 42703,基线抓取在启动第一个 +新 PID 之前就中止。补 AS x,其余不变。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_ds01_negative_r38_test.go` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.335 - 2026-11-02 +目标提交:96472c1ddee829b58e7daf5f099a852c666b1b33 + +### Tests +- **test(library): D06场景同样激活恢复派发协议** +首轮 D06 跑出 worker 日志"restore marker dispatch protocol is not activated", +现场缺 05b-activation:激活条件只写了 ds01/ds01-n1,漏了新分支。补进 ds01Second, +否则场景停在激活前,acquire 永远到不了 durable dispatching。 + +首次失败运行按登记精确清理并读回(cleaned_readback)。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.334 - 2026-11-02 +目标提交:bad9034cf76e69c5b11009b469c5f5ca48a9433f + +### Tests +- **test(library): 增加D06第二次真实重启held场景** +N1 只证到"旧执行者被杀→一个新 PID 接管仍 held",没有证明第二个新 PID 再接管 +仍然 held。D06 要求同一 window/plan/effect 上连续两次真实换进程:第一次接管后 +真实终止那个新执行者、等真实租约过期、起第二个新 PID,再走同一 recover API。 + +新增 ds01-n1-second 场景复用 N1 的 dispatching+missing 边界,用同一份冻结基线 +(目标 PG 逐行、ES 命中代次、对象版本与逐字节摘要、effect 文件键值、marker 转发、 +派发台账整行、journal 状态)对两次接管分别做前后对拍;进程证据补 argv/scenario/ +可执行摘要,drill 构建标签一并落盘,避免把 4s 缩短租约当成生产默认。 + +仅测试夹具与证据,不改生产实现,不新增版本。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_ds01_negative_r38_test.go`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:2 个文件,+372/-33。 + +## 开发快照 snapshot/v0.1.333 - 2026-11-02 +目标提交:f330a75641cc1a69c1253458b079e69419709384 + +### Tests +- **test(library): 使用点复核同SHA错display** +激活点已覆盖同 SHA 错 display;使用点原先只构造了 unknown 与跨 SHA 篡改。 +补一条同 SHA、错 display 的台账篡改,证明使用点同样核运行 display,不只是比 SHA。 +仅测试夹具,不改生产实现。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/platform/postgres/library_restore_dispatch_final_binding_test.go` +统计:1 个文件,+4/-0。 + +## 开发快照 snapshot/v0.1.332 - 2026-11-02 +目标提交:19ec03c4171e8700425c01d960d1ba5ae17c3c40 + +### Docs +- **docs: 说明跨SHA兼容默认关闭** +同名异域、副本、unknown 构建、同 display 不同不兼容 SHA 与错目标指纹。协议批次相等 + 只约束派发语义,不能证明某个 SHA 属于该批次;构建身份精确绑定运行完整 SHA,没有 + 可核受信批次成员证明的跨 SHA 兼容默认关闭(明确报 `cross-sha ... disabled`), + 不新建签名设施,也不引入第二份声明式 allowlist。 + +改动范围:`CHANGELOG.md` +统计:1 个文件,+4/-2。 + +## 开发快照 snapshot/v0.1.331 - 2026-11-02 +目标提交:6209072e43172c4d52c595b9330c6c7fbab2615a + +### Fixed +- **fix(library): 跨SHA兼容需受信证明默认拒绝** +原实现把 ProtocolEpoch 相等当作构建兼容证明:任何 40 位小写 hex SHA 加一个非空 +display 都会被记成 compatible_upgrade 并允许激活,换一个 SHA 即可绕开同 SHA 的 +display 绑定,构建身份仍是声明式。 + +收口为精确绑定运行完整 SHA:同 SHA 必须 display 相符,不同 SHA 一律失败关闭, +错误明确写"cross-sha compatible activation is disabled without a verifiable +protocol build membership proof"。不新建签名基础设施,也不引入第二份 allowlist; +使用点与激活点调用同一函数,行为一致。台账不重写、旧激活行保留(不匹配即 held)。 + +改动范围:`internal/libraryrelease/restore_dispatch_activation.go`、`internal/platform/postgres/library_restore_dispatch.go`、`internal/platform/postgres/library_restore_dispatch_activation.go` +统计:3 个文件,+18/-16。 + +## 开发快照 snapshot/v0.1.330 - 2026-11-02 +目标提交:e61f05c98cfd2cef067f3303965b543097d733eb + +### Tests +- **test(library): 跨SHA兼容升级保留为拒绝RED** +同协议批次下换一个合法 40 位 SHA 不能被 epoch 相等证明;激活与使用点都必须 +拒绝。当前实现仍会接受(compatible_upgrade=true),此提交先把期望钉在拒绝上, +作为修复前的 RED 证据;同 SHA 正例与同 SHA 错 display 拒绝一并保留。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/platform/postgres/library_restore_dispatch_final_binding_test.go` +统计:1 个文件,+32/-10。 + +## 开发快照 snapshot/v0.1.329 - 2026-11-02 +目标提交:a9d5adf78f1213ca9f058588ae3f4ba4b040f41e + +### Fixed +- **fix(library): 使用点核对恢复目标指纹而非维护窗口指纹** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`internal/platform/postgres/library_restore_dispatch.go` +统计:1 个文件,+10/-4。 + +## 开发快照 snapshot/v0.1.328 - 2026-11-02 +目标提交:e8f80694735dc12db4412a2c3f6724f390e87517 + +### Tests +- **test(library): 使用点区分维护窗口与恢复目标指纹** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/platform/postgres/library_restore_dispatch_final_binding_test.go` +统计:1 个文件,+11/-4。 + +## 开发快照 snapshot/v0.1.327 - 2026-11-02 +目标提交:b7d6661a4e774721c05f3cb085fcb87e4658d15e + +### Docs +- **docs: 记录 D16 N2 真实 legacy 意图与缺失目标证据** +- **D16.N2 真实 legacy+missing 边界证据**:隔离场景在旧协议恢复标记 create 之前拒绝传输, + 现场由真实 `restore-mark-intent` 文件、确实缺失的目标文档与零 DS01 台账三件事共同构成; + 同一冻结二进制的新正式 worker 经 recover API 消费后 held,PG/对象/索引/effect 文件零变更、 + 台账不回填、入口 409。旧 N2 的 marker-present 事实与原始 raw 保留、不覆盖。 + +改动范围:`CHANGELOG.md` +统计:1 个文件,+7/-0。 + +## 开发快照 snapshot/v0.1.326 - 2026-11-02 +目标提交:97da6ceba86862703a6ed848d511161711bb5b88 + +### Tests +- **test(library): N2 缺失边界只允许 legit 意图且零 marker** +旧协议的标记 create 在传输层被拒,现场应只有 apply/restore 意图,没有 +claimed/finalize/restored;索引 doc 必须缺失,转发计数为零。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+21/-0。 + +## 开发快照 snapshot/v0.1.325 - 2026-11-02 +目标提交:7cdbb74c8fd75c76abeb480516781e8c98713ef5 + +### Tests +- **test(library): 补 D16 N2 真实 legacy 意图与缺失目标边界** +N2-missing 场景在旧协议回滚的恢复标记 create 之前拒绝传输,使边界成为 +"真实 mark-intent 已落盘、目标文档确实缺失、零 DS01 台账"。随后由同一冻结 +二进制的新正式 worker 走 recover API;观测 PG/对象/索引/effect 文件零变更、 +台账不回填、入口 409。旧 N2 的 marker-present 事实与 raw 不覆盖。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_ds01_negative_r38_test.go`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:2 个文件,+60/-10。 + +## 开发快照 snapshot/v0.1.324 - 2026-11-02 +目标提交:1aa60c159ebaac6c47799cd41bca6931ea3f85a1 + +### Tests +- **test(library): F4 正例按基线计数标记转发** +写入精确 marker 本身会经过 wire;断言应比较确认前后的增量,而不是绝对值。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/library_index_ds01_fixes_test.go` +统计:1 个文件,+4/-2。 + +## 开发快照 snapshot/v0.1.323 - 2026-11-02 +目标提交:245cefd6b0206827ba99ff88f92b206ef45cc335 + +### Fixed +- **fix(library): 收紧 DS01 派发租约/投递/治理身份与绑定冲突** +- **F2.a CAS 点实时租约**:`Acquire` 在取得 effect 行锁(最后一个可能阻塞的锁)之后、 + 状态 CAS 之前,按数据库 `clock_timestamp()` 重核 job/attempt/恢复投递租约;`Confirm` + 同样先锁 effect 行再核。等锁跨过到期一律零许可、状态保持 `prepared`。新增真 PG + 反例:等 effect 行锁期间租约过期。 +- **F2.b 恢复投递同事务绑定**:同一短事务内 `FOR UPDATE` 锁 queue 与 recovery operation, + 复核 queue id/type/state/payload 的 window+scope、idempotency key、当前 owner/attempt/ + lease,并按原 window 的不可变锚点重算 `LibraryRecoveryDigest`,与 operation 的 + `request_digest` 逐位比较;错 queue/window/digest/owner/过期/错备份/错 plan 全部零许可。 + 投递 owner 合成规则收敛到 `governance.LibraryDeliveryOwner` 一份。 +- **F3.identity 治理权威域与构建身份**:激活证据升至 v3,必须携带 PG 集群 + `system_identifier` + 库 OID、完整 40 位构建 SHA 与协议兼容批次;激活与每次使用点都 + 现场重读 `pg_control_system()`/`pg_database.oid`/`pg_is_in_recovery()` 并比对,拒绝 + 同名异域、副本、unknown 构建、同 display 不同不兼容 SHA 与错目标指纹。同一兼容批次 + 内的不同完整 SHA 记为 `compatible_upgrade`,不静默等同。 +- **F4.binding 绑定冲突类型化**:`RestoreDispatchStatus.BindingConflict` 与"仅禁止重发" + 的 `Held` 分开;准入、确认、既有意图续作与收尾在 prepared/dispatching/marker_confirmed/ + done 任一状态都拒绝绑定冲突;合法 dispatching + 精确 marker 仍可确认一次。 +- 真 PG/adapter 反例:effect 锁等待过期、恢复投递九类错配、错治理域/错批次/unknown、 + 四状态绑定冲突与合法 marker 正例。 + +改动范围:`cmd/worker/library_writer.go`、`internal/governance/library_recovery_identity.go`、`internal/libraryrelease/index_restore_dispatch.go`、`internal/libraryrelease/restore_dispatch_activation.go`、`internal/platform/postgres/library_restore_dispatch.go`、`internal/platform/postgres/library_restore_dispatch_activation.go` 等 16 个 +统计:16 个文件,+1126/-93。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/library_restore_dispatch_final_binding_test.go`、`internal/platform/postgres/library_restore_dispatch_linearization_test.go`、`internal/platform/postgres/library_restore_dispatch_test.go`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` 等 6 个 + +## 开发快照 snapshot/v0.1.322 - 2026-11-02 +目标提交:1e2bb385c77f3fe3b93152922e7666736a356936 + +### Tests +- **test(library): 激活时留档 journal 原始字节** +为什么:同一维护窗口在激活后还会继续写 journal(failed/recovered),事后无法从 +最终目录重算 activation 登记的摘要。激活当即把字节原样复制为 05b-journal-snapshot, +让"摘要 == 当时证据"可独立复核。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+9/-2。 + +## 开发快照 snapshot/v0.1.321 - 2026-11-02 +目标提交:bf7f5fa03c75752f237735ada53e808e3d19a397 + +### Tests +- **test(library): P1 用只读可用性投影核对恢复后业务准入** +为什么:POST /api/v1/library/restores 是"新建恢复作业"的入口,恢复后重复 POST +会制造第二次恢复;原任务的"同一受保护入口 409→200"应映射到零写副作用的 +GET /library/restore-availability:held 时报维护原因且 allowed=false,恢复后 +维护原因消失。不重复 POST,也不放宽权限。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+39/-2。 + +## 开发快照 snapshot/v0.1.320 - 2026-11-02 +目标提交:24608e132bcc5026d8a305e545c69347533a595c + +### Fixed +- **fix(library): 区分维护窗口指纹与恢复目标指纹** +为什么:维护窗口记录的是部署/实例指纹(journal 与 library_instance_maintenance), +observeRestoreTarget 返回的是内容/索引/桶身份;两者本来不同层(r38 实测 +dbe7… vs bb3f…)。v2 证据拆成 target_fingerprint 与 restore_target_fingerprint: +前者绑定窗口与治理行,后者绑定激活时的实时只读观察,避免用一个值冒充两层。 + +改动范围:`internal/libraryrelease/restore_dispatch_activation.go`、`internal/platform/postgres/library_restore_dispatch_activation.go`、`docs/architecture/ds01-activation-evidence.md`、`internal/platform/postgres/library_restore_dispatch_test.go`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go`、`internal/releaseadapter/v071/library_index_ds01_test.go` +统计:6 个文件,+33/-17。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/library_restore_dispatch_test.go`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go`、`internal/releaseadapter/v071/library_index_ds01_test.go` + +## 开发快照 snapshot/v0.1.319 - 2026-11-02 +目标提交:80254756f1e0ef604b448ab98d7fe02f8c0e80dd + +### Tests +- **test(library): adapter 激活夹具绑定维护窗口时间** +为什么:维护行由 attach 以 now() 建立,而 journal 的停写/排空观察早于它; +激活门正确拒绝"窗口在观察之后才开"。夹具把 acquired_at 校正到观察之前。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/library_index_ds01_test.go` +统计:1 个文件,+2/-1。 + +## 开发快照 snapshot/v0.1.318 - 2026-11-02 +目标提交:37f2dc73f92b1c2f8d826315ac19743ec640fae5 + +### Tests +- **test(library): 修正激活台账 JSONB 断言与 PG runner 工作目录** +为什么:jsonb::text 带空格,紧凑匹配才对;测试二进制必须在包目录下运行, +否则读不到 migrations/000078 的下迁移文件(这是 runner 的调用方式问题, +不是产品行为)。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/platform/postgres/library_restore_dispatch_linearization_test.go` +统计:1 个文件,+3/-2。 + +## 开发快照 snapshot/v0.1.317 - 2026-11-02 +目标提交:9e31a6f95641b78c577a9aa4b70c5956ddef2afd + +### Fixed +- **fix(library): 激活台账沿用协议版本 1,夹具绑定维护窗口时间** +为什么:迁移 78 的 activation.protocol_version 约束是派发协议身份(=1), +证据文档 v2 只改变激活输入契约,不应触发 schema 变更;把两者混成一个数字会让 +"证据格式升级"变成一次不必要的 DDL。测试夹具补建/校正维护行(owner job、 +services、acquired_at 早于停写观察),否则真实校验会正确拒绝"窗口在排空之后才开"。 + +改动范围:`internal/platform/postgres/library_restore_dispatch.go`、`docs/architecture/ds01-activation-evidence.md`、`internal/platform/postgres/library_restore_dispatch_test.go` +统计:3 个文件,+27/-5。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/library_restore_dispatch_test.go` + +## 开发快照 snapshot/v0.1.316 - 2026-11-02 +目标提交:1c58f1ef7eb43c0848626d965420901906602af4 + +### Fixed +- **fix(library): DS01 激活消费真实维护 journal 证据** +- **激活不再接受调用方自填的停写声明**:协议升至 v2,证据只声明目标/实例/治理库/构建、 + 维护作业、journal 文件名与 sha256、旧 writer 集合;"已退出、已排空"由 Store 直接读取 + 维护窗口写下的 journal(入口 `drained` 且 `active_at_close=0`、后台 quiesce 全零并有 + 停写后复核、每个 writer 有 `stop_requested` 与退出码)与治理库 + `library_instance_maintenance` 行(同作业/实例/指纹/level、未释放、writer 集合一致) + 核出。任一不符不建 active 行。 +- **受信证据根缺失即关闭**:未配置 `LIBRARY_TARGET_JOURNAL_ROOT` + (`WithRestoreDispatchEvidence`)时返回 `ErrRestoreDispatchActivationDisabled`, + 不再退回"三个非空字符串 + 一个摘要就开门"。 +- **构建绑定**:证据 `protocol_build` 必须等于运行二进制的 `version.DisplayVersion()`; + 未注入构建身份时失败关闭。 +- 增加真 PG 反例:伪造/替换 journal 摘要、错 writer 集合、未退出、未排空、过期、 + 治理库/指纹/构建不符、窗口已释放、journal 已 recovered、未配置受信根。 +- 旧 `beforeCommit` 用例更名为"未提交回滚零许可",与 G1 的真实 COMMIT 回包丢失区分。 + +- 正式 worker 装配把 `LIBRARY_TARGET_JOURNAL_ROOT` 传给治理 Store,激活门只能在该根下 + 读 journal;`docs/architecture/ds01-activation-evidence.md` 记录逐项不变量与边界。 + +改动范围:`cmd/worker/main.go`、`internal/libraryfreeze/freeze.go`、`internal/libraryfreeze/journal_evidence.go`、`internal/libraryrelease/restore_dispatch_activation.go`、`internal/platform/postgres/library_restore_dispatch.go`、`internal/platform/postgres/library_restore_dispatch_activation.go` 等 16 个 +统计:16 个文件,+1101/-237。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/library_identity_integration_test.go`、`internal/platform/postgres/library_restore_dispatch_g1_test.go`、`internal/platform/postgres/library_restore_dispatch_linearization_test.go`、`internal/platform/postgres/library_restore_dispatch_test.go` 等 6 个 + +## 开发快照 snapshot/v0.1.315 - 2026-11-02 +目标提交:3b7ad9061c7068980971c7fc4a66cd3b03198a8f + +### Tests +- **test(library): 补 DS01 正式 worker 的 dispatching/legacy 负例** +新增两个隔离场景:N1 在 CAS 已提交、发送前终止旧 worker,新 worker 从 recover +路径必须零新写并保持 dispatching;N2 让旧协议只留下 mark-intent、无台账,协议开启 +后的新 worker 同样 held 且不回填。两者都核对 PG/索引/对象零增量与入口仍 409。 + +改动范围:`internal/releaseadapter/v071/library_index_restore_dispatch.go`、`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/formal_ds01_negative_r38_test.go`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:4 个文件,+263/-15。 + +## 开发快照 snapshot/v0.1.314 - 2026-11-02 +目标提交:882e38591d919886446b49523ad315678c6eddc6 + +### Fixed +- **fix(library): 恢复投递身份不进入 effect 摘要** +自动回滚先建立 prepared(没有 recovery queue),随后 recovery worker 用同一 +window/backup/plan 续作时带了新的投递身份;把它算进摘要会让合法续作被判成 +"绑定与不可变计划冲突"。owner/epoch 与 recovery queue/operation 属于执行锚点, +继续在同一事务里逐项核对,但不改变逻辑 effect 身份。 + +改动范围:`internal/libraryrelease/index_restore_dispatch.go`、`internal/libraryrelease/index_restore_dispatch_test.go` +统计:2 个文件,+35/-16。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryrelease/index_restore_dispatch_test.go` + +## 开发快照 snapshot/v0.1.313 - 2026-11-02 +目标提交:a1112d368a127ab73f706617200182ec47ed5e7a + +### Tests +- **test(library): DS01 重启旧 worker 时接受预期 kill 退出** +主动终止的进程 Wait 返回 signal: killed,不是失败;改为显式读回 /proc/ +不存在后,再用同一冻结二进制启动新 worker。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+4/-1。 + +## 开发快照 snapshot/v0.1.312 - 2026-11-02 +目标提交:ca32f2e661d06f9b2dd76b6f1ba4a6086dbf5364 + +### Tests +- **test(library): DS01 正式 worker 场景按零目标写断言** +D16 分支在派发 CAS 之前被拒,目标不该出现恢复标记;旧断言沿用 ES clean 分支, +期待 chunk-target 仍在。改为:DS01 held 边界要求 chunk-target 缺失、0 次 marker +create、0 次传输层拒绝,并在 recovery 后核对台账 marker_confirmed 且只转发一次。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+13/-1。 + +## 开发快照 snapshot/v0.1.311 - 2026-11-02 +目标提交:513aa9e6f5e87b916583fa1d3d418363f547dcfd + +### Fixed +- **fix(library): 收紧恢复派发真实绑定与同事务授权** +- **正式装配绑定**:`OpenProductionStack` 现在把 scope/实例与本次真实 attempt 身份传入目标; + 来源快照与写前镜像分别取自原 `WriteSet.TargetSnapshotID` 与本次 backup,不再把同一个 + `RestoreSnapshotID` 同时当来源和 before-image。缺锚点或二者相同在写之前失败关闭。 +- **派发线性化**:激活撤销与 `prepared→dispatching` CAS 在同一事务里用 activation 行锁串行化; + lease 在取锁之后用 `clock_timestamp()` 判定;同事务核对原 job/operation/attempt、来源/写集/ + 维护窗口与恢复投递(queue + recovery operation)绑定;同 effect 换 plan 摘要被拒绝。 +- **可核激活**:激活改为消费带 sha256 的证据文件(目标身份/指纹/实例、治理库名、协议构建、 + 逐 writer 的退出与排空观察、有效期);撤销不可回退为 `NULL`、activation 行不可删除, + down 在仅有 activation/撤销证据时也拒绝。 +- **准入/收尾完整分类**:绑定冲突、`prepared` 与 marker/claimed/finalize 矛盾在零目标写之前 + held;合法 `dispatching`+精确 marker 仍走确认分支。收尾改用原 window 权威台账全集(跨 plan), + 拒绝计划外记录、换 plan 别名与缺 `restored` 证据的 effect。 +- **可恢复区段**:`prepared` 已提交但 mark-intent 未落盘时,核对绑定一致且无矛盾后补写同一 + 意图并继续;无台账的旧意图仍 held,r33 不回填。 + +- 绑定冻结实际目标实例/指纹/索引 UUID,同名重建的目标或索引会让旧证明失效;它们用于识别 + 对象,不用于证明历史未发送。协议仍不声称 ES 端 fence 或旧 `dispatching` owner 零迟到写。 + +改动范围:`internal/libraryrelease/index_restore_dispatch.go`、`internal/libraryrelease/restore_dispatch_activation.go`、`internal/librarystack/stack.go`、`internal/platform/postgres/library_restore_dispatch.go`、`internal/platform/postgres/migrations/000078_library_restore_dispatch.down.sql`、`internal/platform/postgres/migrations/000078_library_restore_dispatch.up.sql` 等 22 个 +统计:22 个文件,+2199/-227。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryrelease/index_restore_dispatch_test.go`、`internal/librarystack/stack_test.go`、`internal/platform/postgres/library_restore_dispatch_g1_test.go`、`internal/platform/postgres/library_restore_dispatch_linearization_test.go` 等 8 个 + +## 开发快照 snapshot/v0.1.310 - 2026-11-02 +目标提交:3bce6c7a3fb1b870c4dcbca554b1ba75f464e5f9 + +### Fixed +- **fix(library): 撤销派发激活后不得用旧证据重开** +为什么:撤销若只是把 revoked_at 置空,等于"撤销"变成界面动作; +部署想重开必须给出新的排空证据或换目标身份,不能复用同一条。 + +验证:真 PG 用例先绿,再把 SQL 变异回 DO UPDATE ⇒ 用例红于 +"revoked activation was reopened with the same evidence",还原后再绿。 + +改动范围:`internal/platform/postgres/library_restore_dispatch.go`、`internal/platform/postgres/library_restore_dispatch_test.go` +统计:2 个文件,+38/-6。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/library_restore_dispatch_test.go` + +## 开发快照 snapshot/v0.1.309 - 2026-11-02 +目标提交:18a4b83f7844589fced0d7d86b5897b2d945e3b7 + +### Tests +- **test(library): 派发用例输出台账状态与回执证据** +用例本身要能在 raw 里留下"转发次数 + 台账 state/owner/nonce/绑定/回执", +否则审核只能看到 PASS 字样,无法核对状态链与许可归属。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/library_index_ds01_test.go` +统计:1 个文件,+17/-0。 + +## 开发快照 snapshot/v0.1.308 - 2026-11-02 +目标提交:7b2ab642f7788466c8bb0cdf662c9c49825483cf + +### Docs +- **docs(changelog): 记录 DS01 恢复派发开发快照** +- 治理库新增 `library_index_restore_dispatch` 与 `library_index_restore_dispatch_activation`(迁移 78): + 恢复标记 create 的"是否已有人取得发送许可"成为单调持久事实(`prepared` → `dispatching` → + `marker_confirmed`),唯一 key 绑定目标/原作业/原计划/索引/文档,绑定与状态由触发器拒绝改写与回退, + down 迁移在已有记录时拒绝执行。 +- 新增 `LIBRARY_RESTORE_DISPATCH_V2`(默认关闭)。开关只表示"允许装配";真正发放许可还要求治理库 + 对该目标存在未撤销的激活登记(`library_index_restore_dispatch_activation`),配置 true 不是独占证明。 + +- 删除型恢复(`Before` 非空、`After` 为空,恢复写入是独占 `_create`)只从唯一 dispatcher 取得一次性 + 许可:独立短事务按 job→operation→active attempt→effect 取锁并 CAS,**COMMIT 明确成功后才发送**; + 发送请求关闭传输层重放(`GetBody=nil`),失败不自动重试。 +- `Restore` 在任何 PG/对象/索引写之前做纯读未决准入:旧 `restore-mark-intent` 无台账、 + `dispatching` 且目标无精确 marker 一律 held;收尾前再拒绝一次未决效果,避免"先写一半再报 held"。 +- 自动 rollback 与维护恢复共用同一目标装配与准入(baseline 永不获得该许可)。 + +- 只承认新协议 `prepared` 区段的跨进程续作;不回填历史 intent、不把 `missing`/`stats`/内存计数当 + 未派发证明,不触碰 r33。协议不声称解决 ES 端 fencing,也不声称接管后旧 owner 零迟到写。 + +改动范围:`CHANGELOG.md`、`docs/architecture/ds01-restore-dispatch.md` +统计:2 个文件,+96/-0。 + +## 开发快照 snapshot/v0.1.307 - 2026-11-02 +目标提交:0a7c9f85105657ed91e9bf0a156952dfc8d36947 + +### Changed +- **feat(worker): 接线恢复派发台账并按激活登记启用** +为什么:派发协议只在 worker 里装配却没人接,就等于只写了 store +mock。同步失败的自动 rollback 与维护恢复都必须拿到同一份台账; +baseline 只读装配永远不传,避免建基线顺带获得恢复写许可。 + +开关 LIBRARY_RESTORE_DISPATCH_V2 默认关闭,且只是"允许装配": +治理库没有该目标的未撤销激活登记时,Prepare/Acquire 直接 fail closed。 + +验证:cmd/worker 单测覆盖默认关闭/显式开启/无台账三态; +v071 真 ES 用例里自动 rollback 与手动恢复走的是同一个 Restore。 + +改动范围:`cmd/libraryresidue/main.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_recovery.go`、`cmd/worker/library_wiring.go`、`internal/appconfig/config.go`、`internal/librarystack/stack.go` 等 7 个 +统计:7 个文件,+80/-16。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_restore_dispatch_wiring_test.go` + +## 开发快照 snapshot/v0.1.306 - 2026-11-02 +目标提交:e09fddcb74b49cea56256106e632c29b404f6446 + +### Changed +- **feat(library): 删除型恢复按台账准入并唯一发送** +为什么:恢复在发现 index held 之前可能已经回放 database/resources; +"最后数据相同"不等于"本次零派发"。改为 Restore 在任何写之前按整份 +冻结计划做纯读准入,收尾前再拒绝未决 effect。 + +删除型恢复的 _create 只从唯一 dispatcher 发出:preflight/故障钩子 +在 CAS 之前,许可来自 COMMIT 明确的短事务;发送请求 GetBody=nil, +传输层无法重放。旧意图无台账、dispatching 无精确 marker 一律 held。 + +验证:真 ES+真 PG 覆盖旧意图零写 held、prepared 续作到终态 +(create 恰 1 次)、dispatching+missing 两轮零写、新 OS 进程续作正例。 + +改动范围:`internal/releaseadapter/v071/library_index_effects.go`、`internal/releaseadapter/v071/library_index_restore_claim.go`、`internal/releaseadapter/v071/library_index_restore_dispatch.go`、`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/search.go`、`internal/releaseadapter/v071/data_admission_r10_test.go` 等 7 个 +统计:7 个文件,+945/-35。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/data_admission_r10_test.go`、`internal/releaseadapter/v071/library_index_ds01_test.go` + +## 开发快照 snapshot/v0.1.305 - 2026-11-02 +目标提交:fad26166a466de2d3533523e4fad69f93af01bc2 + +### Changed +- **feat(library): 新增恢复标记派发台账与一次性许可** +为什么:删除型恢复的独占 create 在 ES 侧没有"从未写过"的持久证据, +missing/stats/内存计数都不能当未派发证明。改成为每个固定 effect 维护 +单调台账:prepared -> dispatching -> marker_confirmed,绑定换不了、 +状态回退不了、行删不掉。 + +许可只在独立短事务里 CAS 并 COMMIT 明确成功后返回,消费一次即作废; +提交结果不明时不发许可。激活登记是配置之外的第二个条件。 + +验证:真实 PG(隔离 schema)覆盖并发唯一赢家、旧 epoch 拒绝、 +单调/绑定/删行拒绝、提交不明零许可、无激活 fail closed、down 拒绝抹证据。 + +改动范围:`internal/libraryrelease/index_restore_dispatch.go`、`internal/platform/postgres/library_restore_dispatch.go`、`internal/platform/postgres/migrations/000078_library_restore_dispatch.down.sql`、`internal/platform/postgres/migrations/000078_library_restore_dispatch.up.sql`、`internal/libraryrelease/index_restore_dispatch_test.go`、`internal/platform/postgres/library_restore_dispatch_test.go` 等 7 个 +统计:7 个文件,+1060/-2。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryrelease/index_restore_dispatch_test.go`、`internal/platform/postgres/library_restore_dispatch_test.go`、`internal/platform/postgres/migrations_test.go` + +## 开发快照 snapshot/v0.1.304 - 2026-11-02 +目标提交:47be4ae502b728222b219aeb1d630ad273690eb5 + +### Fixed +- **fix(web): 未读到目标观测不再误报非空并标注旧观测** +- 发布管理:还没有读到生产目标状态时(首次加载、整库状态读取失败、当前范围没有数据) + 不再把本地默认值当成"目标非空",也不再提供会返回 409/503 的"建立目标权威基线"入口; + 有效四类响应(有权威版本 / 已读且为空 / 非空无版本 / 不可读)的呈现与入口保持不变。 +- 发布管理:刷新失败但仍保留上一次目标观测时,页面标明"上次观测 · 刷新失败,可能已过期", + 不把旧结果当成刚刚验证过的状态。 + +改动范围:`web/package-lock.json`、`web/package.json`、`web/src/ReleaseTargets.mount.test.tsx`、`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx`、`CHANGELOG.md` +统计:6 个文件,+892/-24。 + +## 开发快照 snapshot/v0.1.303 - 2026-11-02 +目标提交:6827fa922fc688c2af43bde0baef2ce0bc34fad2 + +### Fixed +- **fix(candidate): 夹具用产品探针证空并复用真实索引 mapping** +首轮试跑暴露三处夹具缺陷(都在 test-only 文件里,产品代码未动): +- 目标骨架只核 knowledge_bases:最小夹具 schema 没有 tenants 表,改为按 KB 行数与 + 产品 ScopeContentEmpty 的十表计数证空; +- 运行期索引曾把 GET _mapping 的结果再包一层 mappings,ES 400; + 现在直接回放原 mapping 文档(properties 层级与封存时完全一致); +- 目标指纹改在夹具分配桶名之后用同一份 env 计算,运行器再把桶名写进 API/worker env。 + +试跑两次均按 cleanup_empty_target_ui.py 精确清理并读回(resources 全不存在)。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/candidate_ui_fixture_test.go` +统计:1 个文件,+6/-9。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/candidate_ui_fixture_test.go` + +## 开发快照 snapshot/v0.1.302 - 2026-11-02 +目标提交:c31a7df4cae151daa6515f0e754f388c7764eebb + +### Changed +- **style(test-scope): 可选范围只追加两条,恢复原有紧凑格式** +上一笔把 scripts/test-scope.json 整体重排成缩进格式,diff 变成 196 行噪音。 +这里恢复文件原本的一行一条格式,只保留新增的 TestCandidateEmptyTargetFixture / +TestCandidateAttestation 两条;内容(112 条可选)未变。 + +改动范围:`scripts/test-scope.json` +统计:1 个文件,+33/-165。 + +## 开发快照 snapshot/v0.1.301 - 2026-11-02 +目标提交:770252b55aef80f777820e37bd9944a875858ddf + +### Tests +- **test(candidate): 空目标候选夹具与网关审计续签** +父要在真实浏览器里点"签发授权 → 启动同步",需要一个目标确实为空、来源确实存在 +的候选环境。两个 test-only 入口(默认 skip,已登记 scripts/test-scope.json 的可选范围): + +- TestCandidateEmptyTargetFixture:用已有 DS02/r38 夹具装配十表全非空的独立 fullshape + 测试来源并封存,登记为 test_sealed;同时用产品自己的 ScopeContentEmpty 证明目标范围 + 为空(KB/tenant 骨架在、十表内容 0 行),并另建同 mapping 的运行期索引(夹具索引会在 + 测试结束时删除)。目标指纹用夹具真实桶名重算,保证与 API/worker 同一份 env 一致。 +- TestCandidateAttestation:签发/续签 object-gateway 审计(有效期上限 1 小时), + 四个证据摘要绑真实文件(写入者清单、只读策略、reader 拒写探测、真实排空记录)。 + +不改产品代码、不放宽任何准入;来源明确标 fixture-assembled-legal-fullshape, +不冒称原 C01 两份封存或 Capture/Export HTTP。 + +改动范围:`scripts/test-scope.json`、`internal/releaseadapter/v071/candidate_ui_fixture_test.go` +统计:2 个文件,+534/-31。 + +## 开发快照 snapshot/v0.1.300 - 2026-11-02 +目标提交:c256f2985cadf1ce7617bbc86312b9a8e21e79b0 + +### Fixed +- **fix(web): 空/非空/不可读目标分开呈现并收窄建基线入口** +后端 overview 早已区分 known / unknown+empty_baseline / unknown 非空 / unreachable, +页面只判断 state === 'known',把"已证空"和"读不到"都写成"未知",并在两种情况下 +都给出"建立目标权威基线"入口——而该接口对空目标返回 409 +library_baseline_target_empty、对读不到的目标返回 503 library_baseline_unprobeable。 +按后端真实契约做最小分类: + +- LibraryKnown 补 empty_baseline 与 unreachable 两个已存在的字段/状态; +- 页面按四类分别呈现:known 显示生效版本+快照摘要;空目标写明"已读且为空/首次发布/ + 写前仍生成完整预备份";非空缺权威版本才指向基线入口;不可读照实说读取失败; +- baselineNeeded 从"非 known"收窄为"非空且无权威版本",不动授权、写闸、预备份、 + 容量与 worker 执行准入等任何后端检查,也不放宽后端的 409。 + +行为测试新增四类状态、空→不可读→空刷新不残留旧状态、空目标无候选时按钮禁用; +原"非 known 一律未知"的断言随文案更正。本地门禁 16 项 success +(tests-web 498 passed,tsc -b 无错)。 + +改动范围:`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx`、`web/src/librarySnapshots.ts` +统计:3 个文件,+175/-11。 + +## 开发快照 snapshot/v0.1.299 - 2026-11-02 +目标提交:f1cddfb60117dada470af05f0b400c3e78984ee9 + +### Tests +- **test(r39): 重放前后逐对象实取字节摘要比对** +原重放段只比 Listing 的 key@versionId#etag#size,同一版本号下的字节 +被改写它看不见,因此"重放后字节不变"缺实测证据。 + +改为重放前后各调一次 r38ObjectVersionDigests:逐 key+versionId 真实 +GET 并本地算 SHA256,落完整版本清单(含版本、ETag、size、摘要), +再逐项比较;GET 失败、清单缺条目、版本增减或摘要不同都判失败。 +治理 PG/ES/ledger/receipt 零新增断言保持原样。 + +离线负控 TestR39ReplayObjectByteControl:固定"旧判据对字节改写报相同" +的盲区,并要求新判据在同一元数据上报 bytes changed、正例不误报、 +空清单/缺摘要必须红;用变异(去掉摘要比较)确认该负控会红后恢复。 + +台账:04-baseline-and-auth.json 分开记录授权 201 与基线 202, +不再让后一次状态码覆盖前一次。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_publish_http_r39_helpers_test.go`、`internal/releaseadapter/v071/formal_publish_http_r39_replay_bytes_control_test.go`、`internal/releaseadapter/v071/formal_publish_http_r39_test.go` +统计:3 个文件,+176/-8。 + +## 开发快照 snapshot/v0.1.298 - 2026-11-02 +目标提交:d2ff089b9554708dff7c473d3f25246920fadac0 + +### Changed +- **ci(checkout): 补取事件 before 失败时重试一次并保留错误** +浅克隆里用 fetch --depth 取一个未公开的对象(改写推送后的旧提交就是这种)时, +git 会在这次 fetch 中途重写 .git/shallow,随后中止: +fatal: shallow file has changed since we read it。 +before 取不到 ⇒ commits 检查算不出范围 ⇒ 整条流水线红,红的原因与代码质量无关。 + +证据(真实 CI):run 305–317 共 13 次(含 317 的原地重跑)全部停在这一步; +同一仓库里紧接着重试同一条命令即成功。用同一 runner 镜像在容器里跑 +"bootstrap + ci_checkout.sh --post-checkout"(真实事件负载)复现出该 fatal, +原脚本报"取不到事件 before",改后报"已补取事件 before eaf389e506f5", +随后 ci_gate 算出 事件 Git 范围 eaf389e..12b3769|1 条提交 并通过。 + +只加一次重试与错误回显:范围选择、判红口径、fail-closed 语义都没动 —— +两次都失败仍明确报警,由 commits 检查判红,不收缩范围、不放行。 + +改动范围:`.gitea/scripts/ci_checkout.sh` +统计:1 个文件,+17/-3。 + +## 开发快照 snapshot/v0.1.297 - 2026-11-02 +目标提交:12b37690ec95afef6c7fd4a6e575a13f4104bd52 + +### Tests +- **test(r39): 真实HTTP发布成功闭环与同请求幂等** +- 新增单一场景用例 `TestFormalPublishHTTPReplaySucceededR39`(`KG_R38_SCENARIO=publish-http`): + 发布作业只来自真实监听的 `POST /api/v1/library/syncs`(管理员会话 + 真实授权), + 不调用 `store.CreateLibraryDispatch` 冒充 HTTP,也不再走 httptest。 +- 新增 `r39` 证据链:来源身份先声明后封存(独立推导 `source_id`,来源行真实落进隔离 + PostgreSQL schema 再读回)、目标基线走正式 `POST /api/v1/library/baselines`(真实整库 + 捕获 + 校验 + `target_baseline` 证据,不手写生效版本)、handoff 用真实 `local` transport + 与真实 `libraryctl` 的 `snapshot-pack/unpack/verify`、发布后逐表/引用/索引向量/对象版本 + GET SHA 的独立 oracle,以及对同一 body 原样重放(`reused=true`,治理行/目标内容/索引/ + 对象版本逐字节不变)。 +- 新增外置运行器 `publish_http_runner.py`:沿用已审 `r38_runner.py` 的"创建前登记 + + 创建后补不可变 ID"与四次源码门禁,清理仍交给已审 `r38_cleanup.py`(run 目录名以 + `r38-` 开头),不重跑旧 runner、不改它的证据。 + +- 本批次只新增一个单场景测试与外置 wrapper,旧 r38 故障恢复分支(含 `:775` 的测试直建 + dispatch)一行未改,仍按原语义保留。 + +改动范围:`CHANGELOG.md`、`internal/releaseadapter/v071/formal_publish_http_r39_helpers_test.go`、`internal/releaseadapter/v071/formal_publish_http_r39_test.go` +统计:3 个文件,+1608/-0。 + +## 开发快照 snapshot/v0.1.296 - 2026-11-01 +目标提交:a1472ff29fad05013819640b53bca42c214b455f + +### Fixed +- **fix(ds03): 早段held断言按发布代次比较整份索引** +首轮到达held时按chunk-target取文档失败:早段数据库阶段失败前索引仍是 +发布写入的源码分块,before-image的chunk-target本就不该出现。改为整份 +读回等于applied,并显式断言chunk-target未提前回来。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+25/-22。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` + +## 开发快照 snapshot/v0.1.295 - 2026-11-01 +目标提交:f076c3af9cbba8a23f6e8f9749e926ea963fd118 + +### Fixed +- **fix(ds03): 负控行复用声明形状以满足非空列** +首轮真实早段运行在插入 pending=1 负控行时被 knowledges 的 NOT NULL +约束拒绝(enable_status),说明控制行缺少声明形状。改为复制本轮 +canonical 来源行再覆盖 id/范围/pending,负控仍由正式结算拒绝。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go` +统计:1 个文件,+11/-3。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go` + +## 开发快照 snapshot/v0.1.294 - 2026-11-01 +目标提交:59eb12296a7fa4abdc9ec149426c72ee68a9e779 + +### Docs +- **docs(ds03): 记录早段PG恢复与工具登记/读回修复** +- 新增早段 database 恢复失败用例 `TestFormalMaintenanceRecoveryPGEarlyRestoreHeldThenRecovered` + (`KG_R38_SCENARIO=pg-early`):仍然复用 `after:wiki` 发布校验失败入口,唯一新增故障是恢复 + **第一段 database** 的真实主键冲突——发布整库替换已删掉 before-image 目标文档,先用一行 + "外部范围、同主键"的 `knowledges` 占住该 id,恢复自己那条 `INSERT` 得到服务器 + `SQLSTATE 23505`。失败文案必须同时含 `恢复阶段 database 失败` 与 `SQLSTATE 23505`, + 且不得出现 wiki 阶段或 ES/对象文案。 +- 新增本轮专用来源副本 `r38LegalSourceSpec`:只把未删除来源文档改成 + `parse_status=completed`、`pending_subtasks_count=0`,共享 `ds02SourceRows` 一行不改。 + 封版前用产品自己的 `checkLibrarySourceSettlement` 在真实 PostgreSQL 上结算这份声明 + (隔离 schema,避免来源 id 与发布写入共用主键),并保留原 pending=1 被正式契约拒绝的负控; + 负控行按 id+租户+库精确删除并读回 0。 +- 新增早段 held 证据 `r38PGEarlyFaultHeld`:故障行仍在;同一 `INSERT` 复测仍被服务器以 + 23505 拒绝且没有多出行;database 阶段整段回滚,所以十张表都还是发布写入后的内容 + (与 applied 逐表多重集相等,且至少一张表不同于 before-image);索引仍是发布那一代, + 既没有恢复 marker 也没有 restored 回执。 + +- `r38_runner.py` 的隔离资源改为**先登记再创建**:network/DB/container 在创建调用之前把 + 名字与归属写进 `state.resources`,创建成功后补不可变 ID(DB 补 oid),创建响应丢失时 + 保留 `create-unknown` 清单;登记保存失败直接中止,不再先创建后登记。 +- `r38_cleanup.py` 的网络读回只接受 daemon 明确的 not-found(`no such network`/`not found`): + rm/inspect 的连接、认证、解析错误一律落 `cleanup-incomplete` 且非零,绝不当作"不存在"; + name/label 必须与本轮登记一致,否则零删除。创建响应丢失的 container/DB 按登记名 + + 项目 label 重新证明归属,归属不明失败关闭、不猜删。 + +- `r38_runner.py` 的末次(finally)provenance 快照此前只记录不比较:现在 HEAD/tree_digest/ + 干净状态任一项变化都会让整体非零,状态保留原测试结果并附加 + `source-gate-failed-after-final`,精确清理照走,不再出现只有最后一次采集变化却 + `passed-cleaned`。 +- 离线控件补齐对应精确反例(末次 tree/HEAD/dirty、网络 daemon 错误/rm 失败/label 不符/ + 未登记名、创建响应丢失的 container/DB、登记保存失败),期望条数由程序统计, + 原 10+7 案例与旧失败证据保持不变。 + +--- + +改动范围:`CHANGELOG.md` +统计:1 个文件,+42/-0。 + +## 开发快照 snapshot/v0.1.293 - 2026-11-01 +目标提交:6ec18212948f368a266d3274bcf2f203535805bb + +### Tests +- **test(ds03): 新增合法来源早段PG恢复用例** +复用一个已证明的 after:wiki 发布失败入口,唯一新增故障是恢复第一段 database +的真实主键冲突(外部范围同主键 knowledges 行,SQLSTATE 23505)。来源输入改用 +R38 专用副本(未删除文档 completed/pending=0),封版前用产品自己的 +checkLibrarySourceSettlement 在真实 PG 上结算,并保留原 pending=1 被正式契约 +拒绝的负控;共享 ds02SourceRows 与 quiesce 都不改。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:2 个文件,+435/-14。 + +## 开发快照 snapshot/v0.1.292 - 2026-11-01 +目标提交:099e58b5dc902e7f463a8404d3aa864481547c27 + +### Docs +- **docs(ds03): 修正PG用例变更记录与故障机制** +`after:wiki` 定点进入回滚,唯一新增故障是真实 PG 错误——恢复最后一段 PG 写入(wiki 阶段) + 会把 before-image 的日志行按原 id 插回目标范围;先用一行"外部范围、同主键"的日志占住该 id, + 那条真实 `INSERT` 得到服务器 `SQLSTATE 23505`。用例记录 SQLSTATE、同一语句的探针读回 + (没有多出行)与失败阶段事务回滚;`恢复阶段 wiki 失败` 与 `SQLSTATE 23505` 必须同时在失败文案里。 +- 新增 held 现场证据:故障行未被自动解除;held 是真实的部分恢复状态——database 阶段已提交、 + 四张 wiki 表仍是发布写入、共享 `resources` 的新增行按设计留到四阶段全部成功后再清, + 逐表与 applied/before-image 比对并断言失败阶段是整段回滚而不是半写。 +- 新增同窗口续作证据:解除故障只删除那行外来日志;同一 `window_job_id` 的 + +改动范围:`CHANGELOG.md` +统计:1 个文件,+8/-7。 + +## 开发快照 snapshot/v0.1.291 - 2026-11-01 +目标提交:e760d85427ff733726a591778d97e6fdbeae4dc6 + +### Tests +- **test(ds03): 新增PG恢复失败后同窗口续作用例** +- 新增 PG 恢复失败用例 `TestFormalMaintenanceRecoveryPGRestoreHeldThenRecovered`:复用已证明的 + `after:wiki` 定点进入回滚,唯一新增故障来自本轮一次性业务库里真实的 PG 错误——恢复事务写 + `knowledges` 时触发器 `RAISE EXCEPTION ... USING ERRCODE='42501'`。用例记录触发器 DDL、 + 服务器返回的 SQLSTATE、探针语句与读回(该语句没有留下任何行),并断言失败事务整体回滚后 + 目标仍是发布写入后的内容;`恢复阶段 database 失败` 与 `SQLSTATE 42501` 必须同时出现在失败文案里。 +- 新增 held 现场证据:故障未被自动解除(开关仍开、触发器仍在),目标行逐表等于 `after:wiki` + 处的 applied 读回,索引仍是发布写入后的内容(恢复没有走到索引阶段)。 +- 新增同窗口续作证据:解除故障只 DROP 本轮触发器/函数/开关表;同一 `window_job_id` 的 + `POST /api/v1/library/maintenance/recover` 完成后复核十表、引用承诺、对象版本字节、索引 + 与网关回执/投递,并保存 replay 原始读回。 + +- 隔离夹具在 `reset` 时消费运行器登记的唯一索引(`KG_R38_INDEX`),并在第一次写入前把实际 + namespace 落到本轮目录;清理器核对「运行器登记 / 夹具落盘 / 实际清理」是同一个名字, + 登记不一致时拒绝删除,不再只依赖 `t.Cleanup`。 + +- 证据目录的运行器:构建后/执行后比较 HEAD、干净状态与源码树摘要,构建后不符直接拒跑用例、 + 执行后不符结论作废(不再出现源码已改却 `passed-cleaned`);finally 里的 provenance 异常 + 不再跳过精确清理。 +- 证据目录的清理器:PG 环境发现等前置动作失败也落 `resources-cleaned.json` 与非零终态; + 已有的 `cleanup-incomplete` 结果文件不再因"文件存在"而返回 0。 + +--- + +改动范围:`CHANGELOG.md`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go`、`internal/releaseadapter/v071/library_writeset_integration_test.go` +统计:3 个文件,+307/-27。 + +## 开发快照 snapshot/v0.1.290 - 2026-11-01 +目标提交:98e7279632227aea8ce2281db5843264ccb6d423 + +### Tests +- **test(ds03): 新增对象版本逐条绑定移除回执** +把"发布真实新增的版本在恢复后消失"从"桶里没有这个 key"加强到:每个新增 +versionId 都必须有同 key + 同 versionId 的网关 removed 回执,并断言绑定条数>0; +回执/投递的 plan 仍必须等于发布期写集合摘要。 + +验证:go vet 通过;make verify 在本提交前的同一源码状态已 16 项全 success, +最终证据用提交后的完整 SHA 重跑。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+28/-1。 + +## 开发快照 snapshot/v0.1.289 - 2026-11-01 +目标提交:30f223bcc4ef19aea5622468c2baf39d08e5b6c7 + +### Tests +- **test(ds03): 对象恢复补十表全形状与版本字节指纹** +- 对象恢复分支的 before-image 与来源快照都改成十表全非空:直接复用 DS02 已验的十表声明 + (`ds02SourceRows`/`ds02Expected`/本地号映射 oracle),目标自己的标签、标签关系、Wiki 目录、 + 页面问题、Wiki 日志不再是空表;同租户邻库与外部租户行作为哨兵逐表非空。 +- 新增逐种引用承诺计数:父子分块、标签关系、资源绑定、目录父子、Wiki 目录/来源/分块引用、 + 页面问题与日志引用,在声明来源、发布实际写入、恢复后 before-image 三处都要求 `matched>0`。 +- 新增对象版本字节指纹:对 before-image 每个受保护 `versionId` 单独 `GET` 计算 SHA256,恢复后 + 同 `version` 再独立计算一次并逐条比较;ETag/size 只作旁证,不再充当"逐字节相同"的证据。 +- 新增发布期/恢复期映射对应证据:发布期写集合摘要同时出现在预备份版本证据、网关回执与投递 + 计划里;恢复意图的 `request_digest` 由窗口/作业/目标/来源/备份/该摘要独立重算后逐字符比较。 +- 新增重放后的原始读回:PG 十表、索引、对象版本清单与版本字节、网关回执/投递都落盘,供父 + 独立比对,而不是只记录一条 PASS。 + +- 隔离运行器把主命令、label、完整 SHA、版本号、二进制摘要与测试名写进同一份 `run-identity.json`, + 报告头与 raw 统一取自该文件,避免"头写旧运行、身份是新运行"。 +- 运行器与清理器的 label 前缀统一为 `ds03-object-*`(对象分支),清理仍只清本轮登记资源并 + 只使用已核对的不可变容器 Id。 + +- 对象恢复用例的对象分支改用真实 v071 十表 catalog 建表,目标行本地号放在序列起点之前,并让 + 目标旧文档预置目标知识库绑定的 embedding 模型,使"恢复回放"回到的写前状态是真实形状。 + +改动范围:`CHANGELOG.md`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_fullshape_test.go`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:3 个文件,+911/-22。 + +## 开发快照 snapshot/v0.1.288 - 2026-11-01 +目标提交:2cbeca8d1d865d3b2b0b0d1e6c04567991a394f8 + +### Tests +- **test(ds03): 记录对象拒绝的网关原始响应** +拒绝事件补 503 与原始正文,证据可直接引用网关响应,而不只依赖客户端错误文本。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+3/-1。 + +## 开发快照 snapshot/v0.1.287 - 2026-11-01 +目标提交:b39902ef9060b955436d47ae9c705efe0cf81abf + +### Tests +- **test(ds03): 修正对象效果文件字段读取** +对象效果 JSON 使用 resource_id/key 小写标签;按 Key 匹配会得到空集合, +导致已发生的 delete-intent 被误报为缺失。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.286 - 2026-11-01 +目标提交:68f03bb30e3bd1b2d2bf812583904691b6a85e7b + +### Tests +- **test(ds03): 对象恢复传输失败后同窗口恢复** +- 新增对象恢复失败分支的真实隔离用例 `TestFormalMaintenanceRecoveryObjectRestoreHeldThenRecovered`: + 在对象网关前拒绝一次"回滚删除本轮创建对象"的请求(派发前 503,转发计数 0,不产生网关 + intent/receipt),让自动回滚真实失败并进入窗口 held + scope/instance `needs_restore`; + 撤障后仍用同一 `POST /api/v1/library/maintenance/recover`、同一 window/job/backup/plan/mapping + 完成恢复,并逐项读回 PG 十表整行、ES 完整 `_source`、对象全部分页版本/delete markers 与字节摘要。 +- 新增四类进程身份证据:api / worker / object-gateway / 测试进程分别绑定最终源码树、binary + sha256、`/proc//exe` 实际 executable 与 commit;测试进程自证 executable 摘要,不匹配即失败。 +- 新增对象网关拒绝现场:被拒请求的 operation/key/action/plan/epoch、目标 receiver、转发计数、 + 网关侧 intent/receipt 行数、引用到的 durable create receipt,以及对象恢复的 `delete-intent` 效果。 + +- r38 对象分支不再把旧的 ES clean-dispatch 503 改名成对象故障:ES 回滚写入必须真正完成, + 失败必须来自对象恢复边界;未走正式发布 API 的入口在证据中明确标注"发布 API 入口未证"。 +- 对象清单改为分页枚举全部 versions 与 delete markers,版本指纹包含 ETag 与字节数。 + +- 修正隔离运行器工具(证据根,不改变产品版本):对象删除前先核对容器 name/Id/label,之后 + 破坏性操作只用不可变 Id;清理异常(含 PG 读回 RuntimeError)统一落 `cleanup-incomplete` + 失败终态与清理结果文件并非零退出,不再持久 `passed`。 + +改动范围:`CHANGELOG.md`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:2 个文件,+423/-23。 + +## 开发快照 snapshot/v0.1.285 - 2026-11-01 +目标提交:93c0f34aac02af0341dc7d9dfb35f669a21c6dd3 + +### Tests +- **test(ds02): 同租户不同知识库十表同输入对照** +该跨租户 bundle 是**受约束回归对照**:6fe98c9 在 wiki 之前无法跨租户搬运资源,旧侧归档 + 只能省略 `resources` / `resource_bindings` 两表,因此不能据此声称"同输入已收口"。 +- 新增十表同输入对照(同租户、不同知识库):`ds02-identical-input-bundle.json` 两侧各自 + 规范化并封存完整十表来源归档(含 `resources` / `resource_bindings`),旧侧 `6fe98c9` 用 + 真实 PG/ES/MinIO 对象适配复现 `wiki_log_entries_pkey / SQLSTATE 23505`,新侧同输入 + `succeeded` 并通过映射/内容 oracle。两侧在执行前各自动导出逐表来源归档、实际目标种子、 + 完整 DDL、三条序列、ES 文档与对象字节;唯一 namespace 替换(对象桶名 `%BUCKET%`) + 按同一规范归一后语义输入 hash 相同,物理桶名单独记录。 + +改动范围:`CHANGELOG.md`、`internal/releaseadapter/v071/ds02_identical_input_test.go` +统计:2 个文件,+743/-2。 + +## 开发快照 snapshot/v0.1.284 - 2026-11-01 +目标提交:98ccb9366e4070b2ffa2d080186c2ce023e370a0 + +### Tests +- **test(ds02): 负控制落盘并修正 gofmt** +为什么:CI 在 07a9caf 上 format 红(ds02_identity_test.go 未 gofmt),本地那次 +make verify 跑在文件生成之前,不能算数;同时 /v1/encode 负控制只有断言、没有 +落盘证据,复验时无法回看分类结果。 + +改了什么:gofmt 两个测试文件;负控制把实际出站条目与被判为 embedding 的差异 +写进 raw(negative-control),正例仍只对发布段计数。 + +验证:make verify 16 项全绿;随后以新 SHA 重跑 DS02 隔离套件。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/ds02_identity_test.go`、`internal/releaseadapter/v071/ds02_oracle_test.go` +统计:2 个文件,+4/-2。 + +## 开发快照 snapshot/v0.1.283 - 2026-11-01 +目标提交:07a9caf22b61586bd790bd8a78c08be66a5a5e27 + +### Tests +- **test(ds02): 收紧映射/引用/哨兵与进程身份 oracle** +- 新增独立本地号映射 oracle:只接收测试声明的来源行、独立推导的期望目标行、真实目标行 + 与持久账本,按 `(table,column,source,target)` 精确集合比较;目标互换、不存在的目标、 + 被替换的来源、少项/多项/重复、错列都会被判红,而合法账本与真实行逐列相等才算绿。 +- 新增十表范围声明(测试自带 `tenant_id`/`knowledge_base_id` 规则并与真实 schema 列集合 + 对拍),不再复用产品的范围分类生成期望。 +- 新增逐种引用覆盖:`chunk.pre/next/parent_chunk_id`、`wiki_folders.parent_id`、 + `wiki_pages.source_refs/chunk_refs`、`wiki_page_issues.suspected_knowledge_ids`、 + `wiki_log_entries.pages_affected` 等各自 `violations=0` 且非空命中;没有外键契约的软 + 导航字段(`parent_slug`、`in_links/out_links`、`relation_chunks`)显式列为范围外。 +- 新增外围哨兵:`chunk-foreign` 文档完整 `_source` 逐字段比较、`res-other` 对象字节比较, + 两者各有"改坏必须红"的负控制。 +- 新增冻结输入 bundle(十表来源行、目标种子、序列种子、ES 文档、对象字节、完整 DDL, + 时间固定、逐表 hash):旧源码 `6fe98c9` 与当前源码读取同一份文件、同一 sha256。旧侧真实 + 复现 `wiki_log_entries_pkey / SQLSTATE 23505`,新侧同一输入发布成功并通过独立 oracle。 + 差异单列:6fe98c9 在 wiki 之前无法跨租户搬运资源,旧侧归档省略 `resources` / + `resource_bindings` 两表,其余八表与碰撞行逐字节相同;新侧按十表完整运行。 +- 新增测试进程身份断言:runner 注入 test-only nonce/commit/源码树摘要,测试进程自报 + `os.Executable` 的 sha256,与 runner 期望逐字符比较;构建与执行前后各算一次二进制哈希。 +- 新增隔离运行器 v2(`ds02_runner_v2.py`,v1 保留):超时/构建/准备异常都走 finally 清理, + 源码、HEAD、工作区、二进制哈希、bundle 字节、required 缺失/跳过任一变化即失败; + 清理前重核 namespace 前缀与容器 Id/label,读回区分"确实不存在"与认证/连接错误; + `--keep-failure` 保留现场并写 `resources-kept.json`。 + +- DS02 的零 Embedding 断言改为按"发布段"记账:ES 与对象存储两个可达 client 注入同一 + 记录器,按目的地址(路径含 embed/encode 或已知模型域名)识别向量化调用,并补了另一个 + client 走自定义 `/v1/encode` 的负控制;声明范围只到本测试的 client 清单,正式 + API→worker 全链仍留给 DS03。 +- 映射 RED 与摘要 gate 分开:语义变异只改内存账本副本(目标存储不动),归档字节变异只 + 证明 `LoadWriteSet` 摘要拒收,不再拿后者冒充映射断言。 +- 日志内容变异重命名为 `log-content`,不再当作 mapping RED。 +- 历史兼容矩阵改用同一份真实 v071 catalog 初始化,三条本地号序列显式断言存在并逐例比较 + before/after 摘要(不再有空集合"不变")。 +- 旧侧对照措辞修正为"精确旧 SHA 回归对照":不再用 `git rev-list --count` 的 258 当版本号; + 该工作树资源 identity 实际是 0.1.148,没有原发布产物就不做历史考古。 + +- 修正旧 oracle 只检查"每表来源/目标数量与重复"导致的三种盲区(目标互换、错误来源集合、 + 不存在的目标号)。 +- 修正引用断言把 pre/next/parent 混在一个 OR 里、无法证明 parent 分支有覆盖的问题。 +- 修正"序列不变"在最小 schema 上没有序列可比的空覆盖。 +- 修正运行器把 namespace 解析失败静默跳过、删除前不重核所有权、读回把任何非零退出都当 + "不存在"、失败路径不保证清理的问题。 + + 逐列比对目标行内容、逐种引用(父子/标签/资源/知识库/Wiki,含 parent 分支与 + source_refs/chunk_refs/suspected ids)、索引正文与向量、目标及外围对象字节,并按发布段 + 断言 Embedding 调用为 0。期望值由夹具声明推导(来源→目标范围映射、资源定位符与 + `location_hash` 在本测试里重算),不调用被测映射器生成;`parent_slug` 与 in/out_links + 这类没有外键契约的软导航字段明确列为范围外。 +- 新增 Wiki 日志映射 oracle:来源日志数字 id 与目标本地号按独立期望精确配对,并用 + 真实目标行逐列对应;持久账本正例通过同一 checker,语义副本变异(互换/不存在/替换来源/ + 少项/多项/重复/错列)必须红。 +- 新增对照夹具探针(旧代码工作树):精确旧 SHA `6fe98c9` 在同一隔离库/桶/索引里以 + 同一份冻结 bundle 复现 `wiki_log_entries_pkey` / SQLSTATE 23505;当前代码同一输入发布 + 成功并分配本地号,其它知识库的历史行不变。这是**旧源码回归对照**,不是原 0.1.258 发布 + 产物;该工作树的资源身份实际是 0.1.148,`git rev-list --count` 的 258 只是自根提交数。 + +改动范围:`scripts/test-scope.json`、`CHANGELOG.md`、`internal/releaseadapter/v071/ds02_bundle_test.go`、`internal/releaseadapter/v071/ds02_identity_test.go`、`internal/releaseadapter/v071/ds02_legacy_compat_test.go`、`internal/releaseadapter/v071/ds02_mapping_oracle_test.go` 等 9 个 +统计:9 个文件,+1477/-140。 + +## 开发快照 snapshot/v0.1.282 - 2026-11-01 +目标提交:eea0a0ec3b929b91e95d1464310d6eb337c2de11 + +### Tests +- **test(release): 整库发布独立oracle与历史兼容矩阵** +- 新增 `TestDS02FullShapeOracleIsolated`:复用现有十表全形状夹具,用**独立 oracle** + 逐列比对目标行内容、全部父子/标签/资源/知识库/Wiki 引用、索引正文与向量、对象 + 字节,并断言发布过程中 Embedding 调用为 0。期望值由夹具声明推导(来源→目标范围 + 映射、资源定位符与 `location_hash` 在本测试里重算),不调用被测映射器生成。 +- 新增 Wiki 日志映射双射断言:来源日志数字 id 与目标本地号一一对应、无重复、内容 + 元组多重集相等。 +- 新增对照夹具探针(旧代码工作树):0.1.258(6fe98c9)在同一隔离库/桶/索引里以 + 相同输入复现 `wiki_log_entries_pkey` / SQLSTATE 23505;当前代码同一输入发布成功 + 并分配本地号,其它知识库的历史行不变。 +- 新增 `TestDS02LegacyCompatibilityMatrixIsolated`:旧 manifest、V1 台账、空作业/ + 目标身份等缺证明组合必须在正式入口被拒绝,拒绝前后 PG 逐行 + 索引 + 对象版本 + + 序列哈希不变;不做 V1→V2 迁移。 + +- 隔离运行器补齐 provenance:运行前后完整 HEAD/工作区/源码逐文件哈希(含未跟踪)、 + 测试二进制 sha256 与 go build metadata/版本注入、逐用例 PASS/FAIL/SKIP、真实目标 + 身份;一次性资源先登记,结束后按登记名成对删除并逐个读回(容器 inspect 失败、 + 库/索引/桶查询为 0/404)。 + +改动范围:`scripts/test-scope.json`、`CHANGELOG.md`、`internal/releaseadapter/v071/ds02_legacy_compat_test.go`、`internal/releaseadapter/v071/ds02_oracle_test.go` +统计:4 个文件,+1045/-0。 + +## 开发快照 snapshot/v0.1.281 - 2026-11-01 +目标提交:1d2fff8639613eb11514c6d94d805b2f71e86e6c + +### Tests +- **test(release): 正式 worker 与维护恢复入口的 held→恢复闭环验收** +- 新增正式链路验收 `TestFormalMaintenanceRecoveryHeldThenRecovered`(只在 `KG_R38_RUN` 指定的 + 一次性隔离部署里运行,常规运行与 CI 跳过):真实 publish 在 database/resources/index/wiki 四类 + 真实写入完成后,由"校验读回内容与快照不一致"失败进入自动回滚;回滚在 + `restore-finalize-intent` 已落盘、marker 仍停在自己世代时被传输层拒绝 clean 派发(拒绝 = 不转发、 + 不丢响应),窗口保持 held,实例/scope 两个维护记录写 `needs_restore`,写入口返回 409;撤掉一次性 + 故障后 `POST /api/v1/library/maintenance/recover` 以同一 window/job/backup 续作成功,PG 逐行、 + 对象版本集合与 ES `_source` 全量恢复,入口重新返回 200。 +- 该用例中的对象 receipt 全部由真实对象网关写入产生(committed/removed 两条不可变回执 + 对应 + delivery/plan 摘要),没有人工造回执,也没有改核心状态。 + +- 本轮只新增验收与运行器,产品行为、协议与判据均未改变;删除型恢复的 R02-b 缺口保持原样。 + +改动范围:`CHANGELOG.md`、`internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go` +统计:2 个文件,+1008/-0。 + +## 开发快照 snapshot/v0.1.280 - 2026-11-01 +目标提交:066dc45a2563e924db49c98327f129c034c8667b + +### Fixed +- **fix(release): 删除型索引恢复不再用 ES 统计计数放行** +- 撤销上一快照的"写计数器栅栏"授权:ES `_stats` 的写计数是**分片生命周期**统计,官方 + 文档明确写"分片迁到另一节点时该分片的统计会被清零";索引 uuid 不变并不绑定统计的 + 生命周期,清零后重新累计到与冻结值相同(ABA)无法排除。统计相等不是不可变证据, + 现在既不落盘也不读取,恢复路径里没有"凭计数放行写入"的分支。 +- 删除型索引恢复(恢复写入是独占 `_create`)只有在**本次尝试开始时不存在任何恢复意图** + 且文档确实缺失时才允许重做("先落意图、后派发"的不变量说明本作业没派发过)。既存的 + `restore-mark-intent` 配上缺失文档没有持久、不可重用的"没写进去"证据,一律 held、 + 零写入。该自动重试缺口已按现状记入验收矩阵,不宣称这是用户接受的能力收窄。 +- 保留可证明的路径:`restore-finalize-intent` 已落盘、真实 marker 仍停在自己那份世代上时 + 继续干净收尾;删除补偿(`Before` 为空)在文档仍是 applied 结果、世代仍是 applied + 回执时重放 `DELETE`。 +- 验收用例新增 ABA 反例:stats 一直返回同一 uuid 同一计数(传输层故障模拟),而真实 ES + 里 marker 已写入又被删除;恢复必须 held。没有重启共享 ES,也没有伪造文档观测。 + +改动范围:`internal/releaseadapter/v071/library_index_effects.go`、`internal/releaseadapter/v071/library_index_restore_claim.go`、`CHANGELOG.md`、`docs/library-acceptance-matrix.md`、`internal/releaseadapter/v071/library_index_known_recovery_test.go`、`internal/releaseadapter/v071/library_index_recovery_gaps_test.go` +统计:6 个文件,+261/-156。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/library_index_known_recovery_test.go`、`internal/releaseadapter/v071/library_index_recovery_gaps_test.go` + +## 开发快照 snapshot/v0.1.279 - 2026-11-01 +目标提交:ff257064c3bef2fef7baf837cc597eda72e6d11b + +### Fixed +- **fix(release): 索引恢复用写计数器栅栏与世代证明续作** +- 索引恢复不再把"文档缺失"当成"证明从未发送":恢复 marker 写成功、回执丢失、随后又被删除, + 与从未写过在索引里完全同形。删除型恢复写入是**独占 `_create`**,现在只有在第一次派发前 + 冻结的**索引写计数器栅栏**(索引 uuid + `index_total` + `delete_total`)逐位未变时才允许重做; + 栅栏推进、栅栏缺失或读取失败一律 held,不认领(B19 不放宽)。 +- `restore-finalize-intent` 已落盘、干净收尾写入在派发前被拒绝后,重试不再永久 held:标记体 + 仍停在自己那份世代(内容 == 冻结标记体,`_seq_no`/`_primary_term` == 意图回执)即证明干净 + 写入没有落地,按同一 CAS 继续收尾;内容或世代对不上仍然 held。 +- 删除补偿(`Before` 为空、恢复写入是 `DELETE`)在派发前被拒绝后同样可以续作:文档仍是 + applied 结果、世代仍是 applied 回执才重放 `DELETE`;文档已变或世代不符仍然 held。 +- 下一条旧快照里"删除即缺失、判据只有世代"的表述仅适用于更新型恢复;删除型以本条冻结的 + 索引写计数器栅栏为准。 + +- 对象验收证据改用 `ListObjectVersions`(键 + versionId + ETag/字节数/删除标记):`ListObjectsV2` + 只枚举当前可见对象,不能证明历史版本。 + +改动范围:`internal/releaseadapter/v071/library_index_effects.go`、`internal/releaseadapter/v071/library_index_restore_claim.go`、`CHANGELOG.md`、`internal/releaseadapter/v071/library_index_known_recovery_test.go`、`internal/releaseadapter/v071/library_index_recovery_gaps_test.go` +统计:5 个文件,+619/-47。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/library_index_known_recovery_test.go`、`internal/releaseadapter/v071/library_index_recovery_gaps_test.go` + +## 开发快照 snapshot/v0.1.278 - 2026-11-01 +目标提交:de867078c6da4a7aeac0a403b89cb8c9cf218e61 + +### Changed +- **style(release): gofmt 索引恢复验收测试** +CI 的 format 项只在已跟踪文件上扫,提交前测试文件还是未跟踪状态,本机 make verify +没看到它;补一次 gofmt,不改行为。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/releaseadapter/v071/library_index_known_recovery_test.go` +统计:1 个文件,+1/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/library_index_known_recovery_test.go` + +## 开发快照 snapshot/v0.1.277 - 2026-11-01 +目标提交:b15633d37c340f4ee971aca845aa0ebe5db4fb98 + +### Fixed +- **fix(release): 索引恢复在确定没写进去时按世代证据重做** +- 恢复/回滚的索引步骤若在**持久意图之后、派发之前**确定失败(控制流拒绝),重试不再被永久判成 + `unknown restoration lacks exact operation marker/content/CAS` 而 held:只要观察到的内容仍等于自己 + 确认过的 applied 结果(删除即缺失)、且世代与那份回执完全一致,就说明这份恢复意图一次都没到达 + 索引,按原 before-image 重做不会覆盖任何别人的字节。 +- 判据仍然只有世代,不认"内容看起来一样":内容对但世代对不上、应用期停在标记态却对不上标记体或 + 世代,一律保持 held(B19 不放宽)。 +- 新增一次性恢复写入派发边界(`restoreMarkerFault`,生产恒为 nil),用来把"边界上确定没写进去"与 + "写入结果不确定"分开演练;真实 ES / PostgreSQL / 对象存储仍是唯一权威。 + +改动范围:`internal/releaseadapter/v071/library_index_effects.go`、`internal/releaseadapter/v071/library_index_restore_claim.go`、`internal/releaseadapter/v071/library_production_target.go`、`CHANGELOG.md`、`internal/releaseadapter/v071/library_index_known_recovery_test.go` +统计:5 个文件,+337/-9。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/library_index_known_recovery_test.go` + +## 开发快照 snapshot/v0.1.276 - 2026-11-01 +目标提交:c938a4f4bf257be90ba8963328ec5368e92b2903 + +### Fixed +- **fix(freeze): 归档改为不可覆盖副本,保留 current 到新请求写入成功** +- 维护窗口的旧请求归档不再 `rename` 走当前 journal:先写一份**不可覆盖**的副本 + (`O_EXCL`,同名已存在时必须字节相同、不同则明确拒绝),当前 journal 保持可用, + 直到新一次尝试通过 `save` 原子替换成功。此前若 `pending/prepare/inventory/save` 任一步失败, + 目录里连一份可读的 current 都不剩;进程在归档与写入之间中断也一样。 +- 归档名按**被归档请求自己的 attempt** 派生(v1 旧记录为 `attempt0`),新尝试从 `attempt+1` 开始, + 因此连续失败的多代不会撞名;撞名且内容不同一律拒绝,不覆盖。 +- 开新尝试额外要求 `source`、`target_fingerprint` 与当前实例一致,且入口若关过必须已有 + `gate_reopened` 证据;否则仍按"需要恢复"拒绝。 + +改动范围:`internal/libraryfreeze/window.go`、`CHANGELOG.md`、`internal/libraryfreeze/archive_safety_r31_test.go` +统计:3 个文件,+224/-10。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryfreeze/archive_safety_r31_test.go` + +## 开发快照 snapshot/v0.1.275 - 2026-11-01 +目标提交:ba1989b04217b0b268e1068ab1ff40ac270029af + +### Fixed +- **fix(freeze): 收尾后的同作业续作可开新尝试并归档旧请求** +- 维护窗口协调器:上一次尝试在**没有写过任何目标内容**的情况下失败并已正常收尾后,同一作业的续作 + 现在可以开新一次尝试,而不是被 `freeze request already exists` 挡住、让合法的 resume 变成一条没有 + 恢复路径的 202。旧请求不删除也不覆盖:归档到 `archive/-attempt.json`,新请求用 + `superseded_from` 指向它,`job / operation / backup` 身份保持不变。 +- 一旦上一次尝试已经 `contentRisk=true`(写过目标),仍然拒绝开新窗口并保留原来的 + `recovery or a new request is required` 语义 —— 那种情况必须按原 before-image 恢复,不能重来一遍。 +- 已成功收尾的窗口继续按幂等回放处理,不重复停写者/关入口的副作用。 + +改动范围:`internal/libraryfreeze/freeze.go`、`internal/libraryfreeze/window.go`、`CHANGELOG.md`、`internal/libraryfreeze/resume_attempt_r30_test.go` +统计:4 个文件,+187/-2。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryfreeze/resume_attempt_r30_test.go` + +## 开发快照 snapshot/v0.1.274 - 2026-11-01 +目标提交:a98828dc4a5eb064066e7bfd31a9e513b2f56a34 + +### Fixed +- **fix(library): 续作在事务内校验阶段并原子入队** +- 续作改为拒绝 `stage=rollback` 的作业(`409 library_resume_requires_recover`):这类作业已经回滚, + 正确出口是维护恢复(`/library/maintenance/recover`),它绑定原 `window_job_id` 并使用原 before-image; + 继续续作等于丢开前镜像重来。拒绝文案按维护记录如实给出窗口是否仍被持有,不一律宣称"仍持有"。 +- 阶段/状态/执行权与队列载荷全部在**事务内锁住的那一行**上校验并重建(`SELECT … FOR UPDATE`): + 调用方手里的旧快照不再参与决策,避免用过期 stage 复活已变化的作业;并发重复续作只有一个成功, + 另一个得到 `library_resume_busy` 或 `library_resume_state_changed`,不会重复投递。 + +改动范围:`internal/httpapi/library_restore.go`、`internal/platform/postgres/library_jobs.go`、`CHANGELOG.md`、`internal/httpapi/library_flow_test.go`、`internal/httpapi/library_resume_r26_test.go`、`internal/platform/postgres/library_resume_r25_test.go` +统计:6 个文件,+363/-43。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_flow_test.go`、`internal/httpapi/library_resume_r26_test.go`、`internal/platform/postgres/library_resume_r25_test.go` + +## 开发快照 snapshot/v0.1.273 - 2026-11-01 +目标提交:e292b6f674bcefe893c6f295190c68ec5d20b5c1 + +### Fixed +- **fix(library): 续作改为单事务入队,回滚作业转维护恢复** +- 作业续作(`POST /api/v1/library/jobs/{id}/resume`)不再先提交 `state=pending` 再单独入队。 + 旧实现里队列行主键由业务作业 id 派生(`QueueJobIDFor`),第二次续作时 `INSERT` 撞主键, + 入队失败返回 500,而作业已经被改成 `pending` 且没有可用队列行 —— 从此永久卡住, + 后续恢复请求全部被 `409 library_restore_active` 挡住。 + 现在「结束上一代 attempt + 业务作业置 pending + 队列行 upsert(含租约检查)」在同一个事务里完成: + 入队失败整笔回滚、作业状态不变;租约仍有效时返回 `library_resume_busy` 而不是半态。 +- 续作改为拒绝 `stage=rollback` 的作业(`409 library_resume_requires_recover`):这类作业已经回滚并 + 保留维护窗口,正确出口是维护恢复(`/library/maintenance/recover`),它会绑定原 `window_job_id` + 并使用原 before-image;继续续作等于丢开前镜像重来。 + +改动范围:`internal/httpapi/library_restore.go`、`internal/platform/postgres/library_jobs.go`、`CHANGELOG.md`、`internal/platform/postgres/library_resume_r25_test.go` +统计:4 个文件,+217/-22。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/library_resume_r25_test.go` + +## 开发快照 snapshot/v0.1.272 - 2026-11-01 +目标提交:30686dd288448a243bcfcd9e5e3742060ffef379 + +### Fixed +- **fix(ui): 版本记录错误详情复用已解析响应体,不再二次读 Body** +- 版本记录客户端:500/409 的异常消息复用已解析的响应体,不再二次 `response.json()` + (真实 `Response` 上会抛 `Body already read`,被 catch 吞掉后只剩状态码);错误详情现在稳定带出服务端 `error` 与 `code`。 + +- `web/src/versionHistory.test.ts`:用真实 `Response` 构造 500,断言消息含 `error` 与 `code`(伪 mock 可重复 `json()` 会掩盖 double-read)。 + +改动范围:`web/src/versionHistory.test.ts`、`web/src/versionHistory.ts`、`CHANGELOG.md` +统计:3 个文件,+25/-11。 + +## 开发快照 snapshot/v0.1.271 - 2026-11-01 +目标提交:8ce78e28fabf99eb0093abb7d051c779fda71658 + +### Docs +- **docs(changelog): 开发快照按内容命名,不写死开发号** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅文档变更,不改变运行时行为。 + +改动范围:`CHANGELOG.md` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.270 - 2026-11-01 +目标提交:044fb37b2c7ae14153db35920fec4350963bd9ad + +### Changed +- **style(test): gofmt 补文件结尾换行** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/platform/postgres/version_history_sync_state_integration_test.go` +统计:1 个文件,+1/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/version_history_sync_state_integration_test.go` + +## 开发快照 snapshot/v0.1.269 - 2026-11-01 +目标提交:e34306b2dbbe58bde2de613be62291fe84c4cdcc + +### Fixed +- **fix(ui): 已释放窗口不再渲染 held 文案,版本页不再把 500 说成未接线** +- 发布管理:作业失败但维护窗口已释放时,不再显示"目标保持维护、入口未开、收尾未完成"的 held 诊断; + 改为如实记录"作业失败(维护窗口已释放)"。只有仍被持有的失败作业才给 held 处置文案(此前仅按 failed 渲染)。 +- 版本记录:同步进行中的 run(`finished_at` 为空)不再让整页 500。部署重启会自动触发一次同步, + 原先该行的空时间戳扫描失败 → `Get /api/v1/version-history` 返回 500。 +- 版本记录页:请求失败时不再声称"当前运行版本未知"或"版本记录未接线",并显示服务端返回的 + `error`/`code`(例如 `version_history_unavailable`),把"未配置"和"后端故障"分开。 + +- `internal/platform/postgres/version_history_sync_state_integration_test.go`:进行中 run(NULL finished_at) + 读取同步状态与分页都必须成功。 +- `web/src/releaseTargetsMaintenance.test.tsx`:已释放的失败作业不出现 held 文案;仍持有时保留。 +- `web/src/VersionHistory.test.tsx`:加载失败时不出现"未接线/未知",并显示服务端原因。 + +改动范围:`internal/platform/postgres/version_history.go`、`web/src/App.test.tsx`、`web/src/App.tsx`、`web/src/BackupScheduleSection.test.tsx`、`web/src/BackupScheduleSection.tsx`、`web/src/DingtalkSessionControl.test.tsx` 等 76 个 +统计:76 个文件,+12036/-2503。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/version_history_sync_state_integration_test.go`、`web/src/documentFixture.ts` + +## 开发快照 snapshot/v0.1.268 - 2026-11-01 +目标提交:943b617b1f778a5a75db13eb2d9e50b8180f3569 + +### Tests +- **test(isolated): 支持保留隔离演练现场供本机 UI/API 验收** +- 隔离演练支持 `KG_R8_KEEP_SCENE=1` 保留现场:不删索引/对象桶,并把网关审计公钥与派生令牌落到 0600 文件, + 便于对本机一次性目标做真实 UI/API 验收;默认不设该变量时仍在断言后精确清理。 +- 产品代码、数据契约与生产行为不变;不构成生产授权,也不替代真实演练证据。 + +- 保留现场只作用于一次性 PG/ES/MinIO;生产闸口、凭据、ACL 与宿主操作仍未授权。 + +改动范围:`CHANGELOG.md`、`internal/releaseadapter/v071/formal_worker_integration_test.go`、`internal/releaseadapter/v071/library_writeset_integration_test.go` +统计:3 个文件,+31/-0。 + +## 开发快照 snapshot/v0.1.266 - 2026-11-01 +目标提交:99055a582eea241909089ec78ee6fadc45fdcdb6 + +### Tests +- **test(library): 补孤儿校验锚点失败与介质失效的真实隔离用例** +孤儿校验:缺 knowledge_id 的索引文档被拒绝、未知 knowledge_id 如实报孤儿、 +数据库层中途失败(真实 statement timeout,SQLSTATE 57014)冒泡为错误而不是 +"没有孤儿"。 + +锚点:真实 PG 约束拒绝写版本锚点时,作业在任何阶段写入前失败、目标零写入、 +版本表不留本次行;去掉故障后同一请求写满四阶段。 + +介质失效:归档 part 缺失/摘要不符时恢复停在内容层,保持 held + RestoreBlocked, +服务与入口都不恢复、校验不再跑。 + +改动范围:`scripts/test-scope.json`、`cmd/worker/library_anchor_r13_integration_test.go`、`internal/libraryfreeze/recover_window_test.go`、`internal/releaseadapter/v071/data_orphan_r13_test.go` +统计:4 个文件,+239/-0。 + +## 开发快照 snapshot/v0.1.267 - 2026-11-01 +目标提交:90ab1c3a5ede520fecd2d71362c0699dd16e992b + +### Docs +- **docs: 记录已接受的游标与 clean 边界** +- 发布作业详情在目标仍被维护时返回维护状态与人为处置说明(持有作业、入口状态、目标身份、下一步),不提供"强制成功"入口;缺归属证据的收尾保持维护锁定。 +- 发布或恢复完成后,Wiki 与日志页面的分页游标视为失效:页面提示刷新后重新分页(本地编号会被重新编排),不把旧游标的错位当成数据损坏。 + +改动范围:`CHANGELOG.md`、`docs/library-data-contract.md` +统计:2 个文件,+9/-0。 + +## 开发快照 snapshot/v0.1.265 - 2026-11-01 +目标提交:0df0e3cb1e076e1a19bfd7da9eee38ba9ea29c47 + +### Changed +- **feat(library): 作业详情显示维护状态与人工处置** +发布作业详情在目标仍被维护时返回 maintenance(持有作业、入口状态、目标身份、 +备注、是否已释放)与 next_step;作业本身继续带 operation_id/attempt_epoch/预备份/ +目标快照与错误说明,能定位到"哪个意图、哪份基线、哪个目标"。 + +不提供强制成功/强制开门入口:缺归属证据的收尾保持维护锁定,按预备份与校验证据 +人工核验后再放行(用户已接受的可用性边界)。页面同时提示发布/恢复后旧分页游标 +失效、需要刷新重新分页。 + +改动范围:`internal/httpapi/library_flow.go`、`web/src/ReleaseTargets.tsx`、`internal/httpapi/library_held_detail_r13_test.go` +统计:3 个文件,+115/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_held_detail_r13_test.go` + +## 开发快照 snapshot/v0.1.264 - 2026-11-01 +目标提交:f4bd1980bfeda7f4d5e9f5138d13e025726ca82e + +### Docs +- **docs: 记录 r12 数据契约的软删除/索引/游标边界** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/library-data-contract.md` +统计:1 个文件,+10/-0。 + +## 开发快照 snapshot/v0.1.263 - 2026-11-01 +目标提交:8df19f9368193a83393f2422b7808fe7e0b00077 + +### Tests +- **test(library): 补软删除共享资源与索引 oracle 隔离用例** +真实本机 PG/ES/MinIO 上补五组场景:7 张带 deleted_at 表的软删除 before-image 与 +恢复逐列复原;同 _id 属其它知识库时外部文档 _source/seq_no/term 逐字节不变; +正文/向量/metadata 任一篡改都让独立 oracle 变红;晚阶段失败后既有对象精确版本 +不变;同 ID 共享资源在 handle/定位/字节三类差异下写前拒绝。另在复用用例里补 +"no-op 复用不改写对象版本"的断言。 + +需隔离服务的用例继续在 test-scope.json 显式声明:普通 CI 跳过不算通过。 + +改动范围:`scripts/test-scope.json`、`internal/releaseadapter/v071/data_state_r12_test.go`、`internal/releaseadapter/v071/library_reuse_integration_test.go` +统计:3 个文件,+301/-0。 + +## 开发快照 snapshot/v0.1.262 - 2026-11-01 +目标提交:8d838d9cb40143b1400b95757aeb9bb0f03be2ab + +### Changed +- **feat(library): 整库发布身份、写集合与收尾边界** +执行时真实时钟与持久授权回读(撤销/过期即停并保留预备份)、写集合写前落盘、 +租约与 attempt 身份、恢复队列与原发送身份分离、成功收尾必须释放维护后再登记终态。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`cmd/release-channel-e2e/main.go`、`cmd/release-diag/main.go`、`cmd/release-worker/runtime.go`、`cmd/worker/library_attempt_timing.go` 等 82 个 +统计:82 个文件,+4808/-550。 + +## 开发快照 snapshot/v0.1.261 - 2026-11-01 +目标提交:5afd8c0140e3929ed2165057e3154c372cf6eea3 + +### Docs +- **docs: 更新整库数据契约与变更记录** +- 新源捕获在同一只读事务中封存表结构、约束、索引与序列定义;发布前核源/目标目录一致性。旧快照与V1台账不改写、不重算历史摘要。 +- 写前验证归档关系闭包与目标已有关系;源导出拒绝被JOIN掩盖的缺父、跨父和未知资源owner,不靠删除孤儿消除差异。 +- 目标预备份、计数与恢复统一覆盖knowledge/Wiki正文及嵌套metadata的稳定资源引用;保留历史孤儿和共享资源原值,未知引用表示明确拒绝。 +- 恢复前重新检查本次新建资源的未知绑定和外库正文/metadata引用;有计划外读者时在任何索引/对象/PG修改前held,父键锁内再次检查所有正文和绑定,防止先删对象才发现不可恢复。 +- 实时模型准入拒绝空模型名,避免将未知模型误判为可兼容。 + +- 数据契约仅在一次性本机PG/ES/MinIO验证;正常业务租约、云权限、WeKnora源码及业务Schema不改。clean未知仍held,不降低所有权证明。[逐表契约与覆盖边界](docs/library-data-contract.md)。 + +- 独立恢复队列与原发布发送身份分离,可信控制源核持久请求、当前租约、原 operation、来源、目标、预备份和 WriteSet;恢复意图不再被原发布自动接管抢跑,恢复中断由新执行代次继续。 +- 索引 before-image 恢复写入采用绑定原计划的暂态标记;真实提交但丢响应后,仅完整标记正文和CAS证据匹配才允许收尾,不重发已提交的标记写入。完成回执同时校验精确代次。 + +- 发布或恢复的 clean-finalization 丢失响应时,相同干净正文不能证明写入归属,继续 held;旧恢复unknown缺少写前标记证据也不自动认领。 +- 自动授权只读角色增加 jobs 表 SELECT 核验;仍禁止其治理写权限。正式独立恢复与故障链仅为本机隔离验收,正常租约未缩短,未部署业务或变更云侧凭据/ACL/网络;整体验收未闭合前不发布。[身份、证据与剩余边界](docs/object-write-gateway.md)。 + +- 正式 worker 在持久化原写集合摘要后,通过数据身份向网关申请绑定当前执行代次的授权;可信控制域独立读取治理锚点和原计划,普通 worker 不持有控制凭据。 +- 网关持久保存不可变 attempt/grant 交付记录;发送身份与当前授权 epoch 分离,新执行代次可以对账原发送并继续未发送对象,未知请求仍阻断交接。 + +- **破坏性**:关闭旧 ObjectImporter staging/promotion、legacy release-worker 和写型诊断/E2E 入口;正式发布 stack 对所有对象 provider 强制网关,不回退直写。只读 capture 保留。[接入与回退边界](docs/object-write-gateway.md)。 + +- 自动授权核验原预备份锚点、目标、有效 attempt/owner/租约及原计划内容;拒绝跨代次替换计划。控制读取使用独立 SELECT-only 登录角色,旧手动控制端点在自动模式关闭。 +- 正式 worker 已在专属本机隔离栈完成 PG 后、对象提交后两次 SIGKILL 与原计划接管;独立读回验证三代授权、一份原发送回执和唯一对象版本。演练仅在显式隔离构建中缩短租约,正常构建维持10分钟,不接受环境变量缩短。真实部署独占与整模块验收尚未完成,仍禁止部署部分候选;未切生产凭据、ACL 或网络,未新增云对象写入。 + +- 新增对象写入网关与独立控制客户端:冻结逐key允许集合、持久epoch/intent/精确版本回执、同key串行化与未知请求阻断交接;网关模式拒绝无计划Put/Copy和直写回退。保持资源UUID、物理路径及历史摘要不变。 + +- 已确认归属及CAS代次的索引补偿删除,在真实删除成功却丢失响应后可按精确缺失完成恢复;重新创建的文档代次仍拒绝接管,不盲重发删除。 + +- 网关逐请求绑定协议与目标,控制/数据身份分离;拒绝不完整回执、无持久日志、只读或失败的日志事务、未登记计划及缺失/过期的审核签名。治理证据禁止更新、删除和截断。 +- 此候选尚未完成正式worker控制grant自动交付、跨新epoch接管及真实写入口独占验证,禁止部署部分业务实现;生产凭据/ACL/网络未改,未进行网关云OSS端到端写。[配置、信任边界与剩余项](docs/object-write-gateway.md)。 + +- 管理员可从发布页选择历史快照,核验原捕获执行器身份、期望指纹及清单后关联当前来源。关联只追加治理审计证据,不重新封存、不修改原摘要,也不代替发布授权。 + +- 归档初始化同步根目录及父目录,目录同步失败时拒绝继续,避免仅同步文件仍遗漏目录项持久性。 + +- 每次同步冻结实际目标预备份与独立计划;重复 Wiki slug 在写前拒绝,晚期失败仍清理本次新增对象并保留复用资源。 +- 索引逐 ID 记录不可变回执;带操作归属标记的写入在真实服务提交后丢失响应时,可由新进程确认并补偿,不凭相同正文猜测归属。 +- 对象阶段进程中断验证覆盖实际 MinIO 提交后、回执落盘前的 SIGKILL 与持久计划恢复。 +- 不可变副作用证据拒绝祖先软链接,并逐级同步新目录的父目录;同步错误返回失败,不再只同步最末两级。 + +- 增加原生 OSS 精确版本协议及显式隔离测试入口,已完成明确隔离前缀内的真实版本写入、精确读回与无残留清理,尚未替代生产条件创建路径;无充分证据的 unknown 分支、跨域 fencing 和全部验收仍未闭合,禁止发布部分实现。[兼容与未完成边界](docs/library-migration-contract.md)。 + +- 整库发布保留 UUID 和复合键,Wiki 数值身份与大整数内容不再经过浮点数;chunks、标签与 Wiki 日志使用持久化的目标本地编号映射,接管时校验来源和映射覆盖。 +- worker 装饰器转发既有写集合接管能力;写集合及资源复用证据不可覆盖,返回前同步文件与目录。 +- 预备份保留实际范围内的软删除行和关联;同租户异知识库不再被误判为来源残留,关系表按精确二元组识别。 +- 索引按全局文档 ID 拒绝跨知识库覆盖,采用 create/乐观并发条件写入并检查逐项结果;共享资源内容差异写前拒绝,相同资源按证据只读复用。 + +- 本开发快照尚未完成整模块验收,禁止据此开启发布写门:对象版本化精确清理仅完成 MinIO 局部验证,OSS 适配、执行栅栏、来源候选/UI 和真实 worker 连续两次中断验证仍待闭合。[兼容与未完成边界](docs/library-migration-contract.md)。 + +- 发布在预备份后、规划前与首笔写入前按治理库授权行重新判定:授权被撤销或过期即停,保留预备份且不写目标;不再只信内存里的有效期。 +- 整库发布绑定序列归属及完整迁移目录,识别分块与 Wiki 的规范嵌套引用;未知结构或跨父引用在写入前拒绝,保留正常资料的发布与恢复路径。 +- 发布使用执行时真实时钟,在预备份后与首个业务阶段前复核授权;预备份绑定对象精确版本,拒绝读取期间被替换的对象(包括同字节新版本)。 + +改动范围:`CHANGELOG.md`、`docs/library-data-contract.md`、`docs/library-migration-contract.md` +统计:3 个文件,+212/-0。 + +## 开发快照 snapshot/v0.1.260 - 2026-11-01 +目标提交:8febe12d7df42a0a945445d709a379c52de9d4c1 + +### Tests +- **test(library): 隔离数据契约与 r11 身份自然键矩阵** +真实本机 PG/ES/MinIO:v071 目录镜像 10 模式、结构引用/游标 15 模式、 +8 表×2 外部范围身份矩阵、13 模式自然键(含软删除与合法同 parent 正例)、 +备份期间三注入、收尾故障与授权撤销两个真实治理 PG 用例。 + +需隔离服务的用例在 test-scope.json 显式声明:普通 CI 跳过不算通过。 + +改动范围:`scripts/test-scope.json`、`cmd/worker/library_attempt_timing_test.go`、`cmd/worker/library_contract_adopter_test.go`、`cmd/worker/library_finalize_r11_integration_test.go`、`cmd/worker/library_grant_revoke_r11_integration_test.go`、`cmd/worker/library_lease_test.go` 等 62 个 +统计:62 个文件,+7329/-167。 + +## 开发快照 snapshot/v0.1.259 - 2026-11-01 +目标提交:5eef13b6151a1f4b56861568cf38b3008df6c534 + +### Changed +- **feat(object-gateway): 统一对象写网关与不可变治理日志** +方案A:所有对象写入经 loopback 网关,持久计划/grant/intent/逐版本 receipt 与 +attempt→grant delivery 落在治理 PG;scope 由 provider+endpoint+bucket 决定, +同一物理桶只允许一个写域。版本 append 不等于 CAS,未锚定计划在首笔业务写前拒绝。 + +本提交只含网关与其适配层接线、协议文档;生产独占、凭据切换与桶设置未改动。 + +改动范围:`cmd/object-gateway-control/main.go`、`cmd/object-gateway/main.go`、`internal/objectgateway/acquire.go`、`internal/objectgateway/audit.go`、`internal/objectgateway/claim_context.go`、`internal/objectgateway/gateway.go` 等 29 个 +统计:29 个文件,+3287/-0。 + +### Tests +本次提交包含测试/夹具变更:`cmd/release-worker/legacy_gate_test.go`、`internal/objectgateway/acquire_integration_test.go`、`internal/objectgateway/audit_test.go`、`internal/objectgateway/gateway_integration_test.go` 等 12 个 + +## 开发快照 snapshot/v0.1.258 - 2026-10-30 +目标提交:d0c6d57283f4a5bc16db2dfd97d2eb3c737aaad7 + +### Fixed +- **fix(storage): 按提供方选择整库对象寻址方式** +- 整库发布与恢复按存储提供方选择寻址方式:MinIO 保留路径式,OSS/S3 使用虚拟主机式,不再因强制路径式而被 OSS 拒绝资源上传。 + +改动范围:`internal/librarystack/stack.go`、`CHANGELOG.md`、`internal/librarystack/stack_test.go` +统计:3 个文件,+28/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/librarystack/stack_test.go` + +## 开发快照 snapshot/v0.1.257 - 2026-10-30 +目标提交:ee9d0787946c7cef2f7fe3b918c34cd6e6818aa9 + +### Fixed +- **fix(release): 分配目标分块序列并保持原值恢复** +- 发布分块时由目标数据库分配本地 `seq_id`,不再复制源库序列而撞上其它知识库的唯一索引;文档和分块 UUID 不变。 +- 失败恢复仍重放预备份中的原始序列,并保留整实例逐行核验;发布内容校验仅排除分块的本地序列,不放宽正文和其它字段校验。 + +改动范围:`internal/releaseadapter/v071/library_production_target.go`、`scripts/test-scope.json`、`CHANGELOG.md`、`internal/releaseadapter/v071/library_chunk_sequence_integration_test.go`、`internal/releaseadapter/v071/library_chunk_sequence_test.go` +统计:5 个文件,+117/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/library_chunk_sequence_integration_test.go`、`internal/releaseadapter/v071/library_chunk_sequence_test.go` + +## 开发快照 snapshot/v0.1.256 - 2026-10-30 +目标提交:a50cd734233e07fff941d6a3778f48f4d95c6de5 + +### Fixed +- **fix(deploy): 校验云执行器授权配置与稳定启动** +- 云发布执行器开启写入前检查授权人和私有 token 文件,按固定容器路径只读挂载;配置缺失在替换旧容器前拒绝。 +- 部署脚本连续检查容器运行及重启计数,启动失败或重启循环不再误报成功;部署回归纳入必需契约检查。 + +改动范围:`deploy/cloud-test/run-release-executor.sh`、`deploy/cloud-test/test_deployment.py`、`deploy/cloud-test/test_release_executor.py`、`CHANGELOG.md`、`deploy/cloud-test/deployment_test.go` +统计:5 个文件,+163/-4。 + +### Tests +本次提交包含测试/夹具变更:`deploy/cloud-test/deployment_test.go` + +## 开发快照 snapshot/v0.1.255 - 2026-10-30 +目标提交:286f1fb375331658e86ebb84278e061a5d2954a1 + +### Fixed +- **fix(maintenance): 避免健康探针连接阻塞入口排空** +- 维护健康探针在请求完成后关闭连接,避免自身的空闲 keep-alive 被入口计为在途连接并导致排空超时;不改变业务连接或长流的排空规则。 + +改动范围:`internal/librarymaintenance/target.go`、`CHANGELOG.md`、`internal/librarymaintenance/probe_drain_test.go` +统计:3 个文件,+46/-0。 + +### Tests +本次提交包含测试/夹具变更:`internal/librarymaintenance/probe_drain_test.go` + +## 开发快照 snapshot/v0.1.254 - 2026-10-30 +目标提交:3e4020c327c7226859da6cd7d9b5812ebfd5d519 + +### Fixed +- **fix(drill): 支持空目标并在探针写入前落盘恢复证据** +- 恢复演练使用独立标签作为漂移探针,支持空目标,不再依赖改写已有文档;探针写入前持久化精确写集合并标记内容风险,恢复只清理本次新建身份。 + +改动范围:`cmd/librarydrill/canary.go`、`cmd/librarydrill/main.go`、`CHANGELOG.md`、`cmd/librarydrill/canary_test.go` +统计:4 个文件,+118/-30。 + +### Tests +本次提交包含测试/夹具变更:`cmd/librarydrill/canary_test.go` + +## 开发快照 snapshot/v0.1.253 - 2026-10-30 +目标提交:56f8f4fd7ea659b897cc127ed7760429ef1fc6bf + +### Fixed +- **fix(library): 统一空目标概览与首次同步准入** +- 发布概览与同步提交统一探测未知目标:真实空库允许进入首次同步条件判断,无法连接不再误报为非空库。探测超时后拒绝放行,授权、恢复演练及写入闸口仍须满足。 + +改动范围:`internal/httpapi/library_flow.go`、`CHANGELOG.md`、`internal/httpapi/library_overview_empty_test.go` +统计:3 个文件,+135/-6。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_overview_empty_test.go` + +## 开发快照 snapshot/v0.1.252 - 2026-10-30 +目标提交:7ab2eb1ccf4c3bc716ca6c103c163b9b8ae49cfe + +### Fixed +- **fix(library): 按目标身份隔离版本授权与执行历史** +- 切换发布目标后,不再把旧实例的当前生效版本、预备份、恢复候选和授权当成新实例事实;当前指针按目标与对内/对外范围独立保存,旧作业不可被新目标接管。 +- 本机隧道与云端直连共用逻辑目标身份,源封存保持可见;历史记录及证据保留,不自动归属新目标。 + +- **破坏性**:治理库迁移 077 增加目标身份,须停旧消费者后升级;已有目标绑定证据时禁止直接降级。[升级与回退边界](docs/library-target-identity.md)。 + +改动范围:`cmd/api/main.go`、`cmd/worker/main.go`、`internal/appconfig/library_target.go`、`internal/platform/postgres/library_jobs.go`、`internal/platform/postgres/library_operations.go`、`internal/platform/postgres/migrations/000077_library_target_identity.down.sql` 等 15 个 +统计:15 个文件,+473/-72。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_target_integration_test.go`、`internal/appconfig/library_target_test.go`、`internal/platform/postgres/library_target_test.go`、`internal/platform/postgres/migrations_test.go` + +## 开发快照 snapshot/v0.1.251 - 2026-10-30 +目标提交:323f9ae50230dc00608f32b9ad53e32f02973cc6 + +### Fixed +- **fix(handoff): 在执行器容器内读取云端归档清单** +- 快照清单通过指定执行器容器读取,不再将容器内归档路径当作 SSH 宿主机路径;避免已导入的快照被误报不存在,保留真实缺失与执行错误的区别。 + +改动范围:`internal/libraryhandoff/handoff.go`、`CHANGELOG.md`、`internal/libraryhandoff/ssh_manifest_test.go` +统计:3 个文件,+62/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryhandoff/ssh_manifest_test.go` + +## 开发快照 snapshot/v0.1.250 - 2026-10-30 +目标提交:52c0186172319c08ab3d62bb4473707e0492fbc1 + +### Fixed +- **fix(handoff): 修复搬运默认上限及云端接收目录挂载** +- 修复快照搬运未显式设置大小和超时上限时默认值丢失,导致正常包被按零字节上限拒绝;默认上限为 8 GiB、超时 10 分钟,显式配置仍生效。 +- 云发布执行器挂载独立的接收包目录,宿主机与容器路径保持一致,修复文件已传到主机但执行器无法装入或导出的故障。 + +改动范围:`internal/libraryhandoff/handoff.go`、`deploy/cloud-test/run-release-executor.sh`、`deploy/cloud-test/test_deployment.py`、`CHANGELOG.md`、`deploy/cloud-test/README.md`、`internal/libraryhandoff/defaults_test.go` +统计:6 个文件,+51/-3。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryhandoff/defaults_test.go` + +## 开发快照 snapshot/v0.1.249 - 2026-10-30 +目标提交:657fd251fbcc2d1e8d1724b182ac98ec608cfa07 + +### Fixed +- **fix(deploy): 显式启动发布worker并声明受控运行身份** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`deploy/cloud-test/run-release-executor.sh`、`deploy/cloud-test/test_deployment.py`、`deploy/cloud-test/README.md` +统计:3 个文件,+10/-1。 + +## 开发快照 snapshot/v0.1.248 - 2026-10-30 +目标提交:468ae6491891607645ff9c90c1358eb37e288729 + +### Fixed +- **fix(deploy): 修正云执行器套接字与凭据挂载契约** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`deploy/cloud-test/pg-forward.sh`、`deploy/cloud-test/release-executor.env.example`、`deploy/cloud-test/run-release-executor.sh`、`deploy/cloud-test/test_deployment.py`、`deploy/cloud-test/README.md`、`deploy/cloud-test/deployment_test.go` +统计:6 个文件,+118/-10。 + +### Tests +本次提交包含测试/夹具变更:`deploy/cloud-test/deployment_test.go` + +## 开发快照 snapshot/v0.1.247 - 2026-10-30 +目标提交:06c2db19fcd7a4bf3c7f0bbee0686ca730c4933e + +### Fixed +- **fix(library): 删除 handoff 路径残留的无条件 stage 写** +- 删除 handoff 路径残留的无条件 `UpdateLibraryStage`:它与 `BeginLibraryHandoff` 事务里的写重复, + 并在 Begin 返回到这次写之间给交接留出竞态窗口。现在 handoff 的所有阶段写只发生在 + Begin/Complete/Fail 三个持有 job 行锁的事务方法里;新增源码契约测试防止回流。 + +改动范围:`cmd/worker/library_handoff.go`、`scripts/test-scope.json`、`CHANGELOG.md`、`cmd/worker/library_handoff_stage_contract_test.go` +统计:4 个文件,+92/-2。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_handoff_stage_contract_test.go` + +## 开发快照 snapshot/v0.1.246 - 2026-10-30 +目标提交:70c181370db2339c9157c3f41c055e388e158e3e + +### Fixed +- **fix(library): handoff 阶段事务化、回传空页重置与目标基线原产地** +- handoff 的阶段与所有权收敛为一组事务方法:`BeginLibraryHandoff`(事务内建/推进 running 阶段并确认所有权)、 + `CompleteLibraryHandoff`(同一事务:投递发布队列作业 + 交接 queue_job_id + 阶段 succeeded)、 + `FailLibraryHandoff`(同一事务:阶段 failed + 作业 failed)。阶段行按 (job_id, stage) upsert, + 不再依赖 `SyncStages` 里是否预置了 handoff 行。 +- 回传单轮抽成 `pullRound`:**空页重置游标**(引用数正好是 pageSize 整数倍时,否则游标停在最老处、 + 之后新增的引用永远取不到),且游标跨轮保留(单轮 20 页只是预算)。 + +- 传输阶段在真实 UI 上不可见:此前 running 阶段是无条件 `UpdateLibraryStage`(读 owner 再写,存在竞态), + 成功阶段在交接后按旧 owner 写必然 0 行,且 `library_job_stages` 里根本没有 handoff 行。 + 现在阶段创建/推进/成功/失败都与 job 行的所有权判定在同一事务里完成,交接提交后阶段一定是 succeeded。 +- 身份判定漏掉"目标权威基线":`library_baseline` 是目标侧真实捕获,但只登记 `production_effective` + (证据 action=target_baseline_init / origin=target_baseline)。现在原产地按捕获证据判定: + 封存=源、预备份=目标、带基线证据的 effective=目标;普通 effective 与 recovery_verified 只是引用, + 不决定原产地;无捕获证据或源/目标同时成立仍拒绝。 + +改动范围:`cmd/worker/library_handoff.go`、`internal/platform/postgres/library_jobs.go`、`CHANGELOG.md`、`cmd/worker/library_handoff_chain_test.go` +统计:4 个文件,+420/-246。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_handoff_chain_test.go` + +## 开发快照 snapshot/v0.1.245 - 2026-10-30 +目标提交:8a68ed1819afb159e7d269f7b92819e539527794 + +### Fixed +- **fix(library): 交接所有权 CAS、回传游标跨轮与快照原产地** +- **handoff → release 的交接改为按所有权 CAS**:`EnqueueAndAttachLibraryJob` 接受"调用方声明的前驱队列作业号", + 只允许"当前无人持有"或"当前正是这个 handoff"时替换;任意替换一律拒绝。发布/恢复的发布作业 ID 仍是 + `QueueJobIDFor(job)`,接管/续作路径不变。 +- 回传枚举的游标**跨轮保留**:单轮仍有 20 页工作量预算,但下一轮从上次位置继续,读到不足一页才回到起点, + 所以第 2001 条以后的引用不会被每轮重置的游标永久漏取。 +- 快照**原产地只由捕获事件决定**:`test_sealed`(源)与 `production_prebackup`(目标)互斥; + `production_effective` / `recovery_verified` 只是引用同一份快照的完成事件,不再参与身份推断 + ——"先封存、后发布成功"的正常链路不会再被自己的完成事件判成身份冲突。 + +- **正常流程必现阻断**:API 先关联 handoff 队列作业,而交接只接受"未关联"状态,导致每一次正常发布都被自己的 + 所有权检查挡住。另修 handoff 队列作业号:`jobs.id` 为 varchar(36),原实现拼接后缀超长,插入即失败; + 现在由 `governance.LibraryHandoffQueueJobID` 生成合法且确定的 ID。 +- **迟到 handoff 污染已交接作业**:失败出口(含 Push 错误)改为按所有权 CAS,只在本 handoff 仍持有业务作业时 + 才写 state/stage/recovery;已交接或已终态时零修改,也不再写"未进入维护窗口"这种只对本次执行成立的结论。 + 阶段写入同样带所有权判定(所有权只由 `library_jobs.queue_job_id` 决定,与阶段行是否存在无关)。 + +改动范围:`cmd/worker/library_handoff.go`、`internal/governance/library_flow.go`、`internal/httpapi/library_flow.go`、`internal/platform/postgres/library_jobs.go`、`scripts/test-scope.json`、`CHANGELOG.md` 等 11 个 +统计:11 个文件,+499/-56。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_handoff_chain_test.go`、`cmd/worker/library_handoff_integration_test.go`、`cmd/worker/library_handoff_pagination_test.go`、`internal/httpapi/library_handoff_queue_test.go` + +## 开发快照 snapshot/v0.1.244 - 2026-10-30 +目标提交:9300865d23436a7426b535e1577ab2557b5dc57c + +### Fixed +- **fix(library): 搬运复用前复验字节、回传游标分页与发布队列事务交接** +父独立审查退回的四个 finding,逐项修在本包内,不改架构。 + +1 复用路径没复验字节:remoteEvidence 只读清单+摘要就宣布可用。现在新增 +libraryctl snapshot-verify(整版逐部件重算)并在复用前调用;blob 缺失/篡改必须 +在入发布队列之前失败。新增真实 local 跨进程用例:清单不动、删 blob / 改 blob 后 +再 Push 必须拒绝。 + +2 回传枚举被固定 LIMIT 50 截断:LibraryJobSnapshots 只取成功作业且按摘要字典序。 +改为 LibrarySnapshotCandidates:合并 library_versions、library_jobs.snapshot_id、 +library_jobs.target_snapshot_id 三处引用,按 (created_at, snapshot_id) 游标分页; +回传循环翻页到不足一页为止。失败/待恢复作业留下的预备份、第 51 条以后、历史恢复 +输入快照都能被枚举。另修"本地只有清单、blob 已损坏就永远跳过":改用整版 Load 判定, +并给 Unpack 增加显式 RepairCorruptBlobs(只在权威云端读回时开启)。 + +3 身份映射错误:搬运拿目标 tenant/KB 去核对封存快照,而封存清单写的是**源**身份 +(云测试验收目标 a8e9c8ad/2e980686 与源 KB 必然不同)。现在 expectedSnapshotIdentity +按版本台账判定:test_sealed → 用部署注入的源绑定(LIBRARY_SOURCE_TENANT_ID / +LIBRARY_SOURCE_KB_*);预备份/生效/恢复版本 → 用目标绑定;没有登记或两类冲突一律拒绝。 +身份永远来自独立绑定与台账,不接受包自证。 + +4 两步入队有竞态:Enqueue 成功后云执行器可能立刻领取并开始维护,Attach 失败却把作业 +标失败并声称"未维护"。改为 EnqueueAndAttachLibraryJob 单事务(锁行 + 插入 + 关联 + +状态守卫),要么都成功要么都不发生;重复执行幂等,已关联别的队列作业则拒绝。 +另修终态重放:AdvanceLibraryJob 无状态守卫,迟到的失败出口会把已成功作业改写; +新增 AdvanceLibraryJobIfActive(仅 pending/running 可推进),拿不到就明确记录"未覆盖"。 + +测试:libraryhandoff 用例覆盖跨租户/错误 scope/清单在而字节坏/本地损坏自愈; +隔离 fixture 库覆盖"校验通过才入队、失败不入队"、>50 条分页与失败作业预备份、 +幂等重放不重复投递、迟到失败不改写终态。 + +未部署、未推送、未构建镜像;真实跨主机 SSH 链路仍未验证。 + +改动范围:`cmd/libraryctl/main.go`、`cmd/worker/library_handoff.go`、`internal/appconfig/config.go`、`internal/libraryhandoff/handoff.go`、`internal/librarysnapshot/transfer.go`、`internal/platform/postgres/library_jobs.go` 等 10 个 +统计:10 个文件,+640/-64。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_handoff_integration_test.go`、`cmd/worker/library_handoff_pagination_test.go`、`internal/libraryhandoff/handoff_test.go` + +## 开发快照 snapshot/v0.1.243 - 2026-10-30 +目标提交:6400fd1bbedb1e9e7d58c3e60b8b9f69d8c903a4 + +### Changed +- **feat(library): 快照搬运先于维护、双向校验与云端版本回传** +- **发布/恢复作业先搬运、后执行**:快照搬运接线(`LIBRARY_HANDOFF_*`)时,API 把作业投递成 + `library.snapshot.handoff`(capture 角色消费),由它把不可变快照送到云端 release-executor 并 + **双向校验**(本机 `Load` 逐 blob 重算 → 云端 `snapshot-unpack` 再逐 blob 重算 → 版本清单摘要自证 → + scope/tenant/知识库身份与治理库作业一致)之后,才投递真正把目标置入维护窗口的 `library.sync|restore`。 + 搬运失败/超时/校验不过时发布作业**根本不存在**,目标不会被停用、不写任何知识。 +- 新包 `internal/libraryhandoff`:`Push`(本机→云端)与 `Fetch`(云端→本机)共用一套校验与暂存规则; + 远端命令是固定 argv(容器名/路径来自部署配置,调用方只能给快照 ID 与期望身份);同一快照用本机 + flock 串行化,云端内容寻址 + Link 幂等;同 ID 异内容直接拒绝;暂存 bundle 用后即删,归档本体不自动清理。 +- capture 角色新增**云端版本回传**扫描:按治理库已成功作业的 `snapshot_id`,把本机缺失的云端快照 + `Fetch` 回本机归档,因此页面/API 既有的列表、详情、差异、存储与历史恢复路径读到的都是真实字节。 +- `libraryctl snapshot-push` / `snapshot-fetch`:运维可直接搬一份快照并打印逐 blob 身份用于对拍。 + +- `LIBRARY_WORKER_ROLE` 的副作用边界继续收敛:搬运与回传只注册在 capture 角色;若把搬运接线到 + `full` 角色(同时消费发布作业)启动即失败,避免与云端执行器抢同一批作业。 +- `library_jobs` 的孤儿收拾按角色负责的 kind 过滤;治理库 DDL 仍只属于控制面进程。 + +- 入口闸门不再在 10 秒静默后掐断上游流:建连超时与读超时分离(连上即 `settimeout(None)`), + 半关闭按 TCP 语义单向传播,避免响应被截断;排空超时仍以 exit 2 表达失败。 + +改动范围:`cmd/api/main.go`、`cmd/libraryctl/main.go`、`cmd/worker/library_handoff.go`、`cmd/worker/main.go`、`internal/httpapi/library_flow.go`、`internal/httpapi/library_restore.go` 等 18 个 +统计:18 个文件,+1801/-12。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_handoff_integration_test.go`、`internal/httpapi/library_handoff_queue_test.go`、`internal/libraryhandoff/handoff_test.go` + +## 开发快照 snapshot/v0.1.242 - 2026-10-30 +目标提交:e6472b0ec67684a6e0e09372d67699ac9454f0b3 + +### Changed +- **feat(library): 云测试发布目标接入的角色分离、快照搬运与图谱门禁** +为什么改:发布执行链是"与目标同机"假设写死的(本机 docker.sock、本机 drain.json、 +本机 Redis/PG),把目标换成云测试不能只改展示 URL;直接搬整套 worker 又会抢走 +本机封存/QA/周报队列并按本机配置写错目标。所以先把"谁消费哪段队列"变成显式角色, +再补齐跨主机搬运与目标侧门禁。 + +角色(LIBRARY_WORKER_ROLE=full/release-executor/capture)不只影响 handler 列表, +还决定是否拥有 DDL(release-executor 只读校验迁移版本,落后即拒绝启动)、 +收拾哪些 library_jobs.kind、是否跑 release 接管扫描、是否起 scheduler/QA/周报/探测。 +capture 保留本机原有全部业务;release-executor 只挂 sync/restore/recover/baseline。 + +快照跨主机:新增内容寻址的 bundle(版本清单先落、blob 按 sha256 命名、清单最后 +Link 作提交点),pack/unpack 幂等且拒绝覆盖与同名不同内容;执行器使用前仍逐 blob +重算 sha256,因此传输不可变有两道证据。 + +目标侧门禁:目标知识库 graph_enabled=true 时拒绝发布(发布只写 PG/ES/OSS,不写 +Neo4j;未知也拒绝),只读检测、不改目标配置、不做图谱迁移。 + +云端入口:新增 drain 感知的 ingress 闸门(建连超时与读超时分离,半关闭单向传播, +SIGTERM 排空后写 drain.json 并 exit 0/2)、compose 叠加片段(app 不再发布端口、 +frontend 与 adapter 的入口收敛到闸门、指向真实网络 weknora-test-v071-network)、 +执行器启动脚本与治理 PG 反向隧道脚本(默认 unix socket,不占 TCP)。 + +验证:deploy/cloud-test/test_gate.py 13 项全 PASS(含 12 秒静默流、半关闭、2MiB 完整、 +排空 exit 0/active_at_close=1、排空超时 exit 2、上游不可达不挂住);go test 相关包全绿; +scripts/ci_checks.py 16 项全部 success(EXIT=0,1241 用例通过/0 失败/191 已声明可选集成跳过); +云测试只读预检 17 项 / 6 FAIL,FAIL 项即当前部署缺口(无闸门、app 仍发布端口、 +adapter 与 frontend 仍直连 app、云端归档根未建),未部署、未改云端任何状态。 + +改动范围:`cmd/libraryctl/main.go`、`cmd/worker/library_release_handlers.go`、`cmd/worker/main.go`、`internal/appconfig/config.go`、`internal/appconfig/library_role.go`、`internal/librarysnapshot/transfer.go` 等 24 个 +统计:24 个文件,+2409/-117。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_role_test.go`、`internal/appconfig/library_role_test.go`、`internal/librarysnapshot/transfer_test.go`、`internal/platform/postgres/library_reconcile_test.go` 等 5 个 + +## 开发快照 snapshot/v0.1.241 - 2026-10-30 +目标提交:a7d643635ad8de1fae3a1e65dd93edc436e17c28 + +### Fixed +- **fix(library): 守卫按行取作业身份、同作业多代次、原作业续作与执行域准入** +- **续作沿用原业务作业,只新增执行代次**:维护窗口 owner、freeze journal、预备份与写集合都按业务作业 id 落盘,因此不再为续作另造 `-resume` 作业行;发起续作会显式结束上一代执行(旧代次标记 superseded,行保留)。 +- 执行域准入改为**可执行校验**:worker 注册整库发布 handler 之前,读目标实况(知识库/租户/schema/索引)、旧 release 路由绑定的目标知识库、以及未释放的维护窗口持有者;任一读不到、与配置不一致、或旧路由指向同一个知识库,就拒绝执行(明确失败,不做任何维护动作,也不停止既有服务)。 +- 维护状态/入口/释放的守卫**按被更新行自己的作业号**取身份(此前把 `$1` 硬编码成作业号,而维护类入口的 `$1` 是 scope/instance,导致正常写入与释放全部匹配不到作业);同一代码路径同时用"作业号不匹配必须失败"的负例锁住。 +- 同一作业允许**多个不可变执行代次**:认领递增 epoch 并新增 attempt 行(不再复用唯一索引改写旧代次),重复调用幂等续租,别人持有未过期租约时明确让路;被接管的旧代次标记 abandoned,迟到的 write/renew/finish 一律按 `ErrLibraryEpochStale` 拒绝。 +- 首次锚点登记改为事务内 `FOR UPDATE` + 只填空 + 逐字段回读核对;`NULL` 与零值不再混淆(真实 PG 上验证,未知 ≠ 0)。 +- current 的次序键取**意图创建时间**:旧意图的迟到事实被 `ErrLibraryCurrentStale` 拒绝,不会把当前生效版本推回历史;恢复通过新的 `kind=recover` 意图(内容更旧、意图更新)推进。 +- 版本事件冲突只做**加法**(已有键永远赢、来源作业/意图/登记时刻冻结),且只有真正新插入(`xmax=0`)才推进 current,纯重放不再二次推进。 +- 集成测试护栏:`TEST_DATABASE_URL` 必须指向看起来是一次性的测试库(或在确属一次性库时显式声明),并先清理上次中断留下的同名 schema;`kg-pgtest-*` 专用容器内一用例一 schema,结束即删。 + +改动范围:`cmd/worker/library_baseline.go`、`cmd/worker/library_completion.go`、`cmd/worker/library_domain.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_recovery.go`、`cmd/worker/library_writer.go` 等 26 个 +统计:26 个文件,+1553/-217。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_backup_reuse_test.go`、`cmd/worker/library_identity_helpers_test.go`、`cmd/worker/library_takeover_historical_integration_test.go`、`cmd/worker/library_takeover_integration_test.go` 等 7 个 + +## 开发快照 snapshot/v0.1.240 - 2026-10-30 +目标提交:afe9affc2aea5b84d936c257ad853a58770e4d2a + +### Changed +- **style: gofmt 新增的三个文件** +为什么:远端 CI 的格式门在推送后判红(run 258,job build,format=failure), +本地 `make verify` 那次跑的是"拉取前"的文件集,漏掉了随后新增/改写的三个文件。 +失败项:internal/httpapi/library_intent_test.go、internal/jobs/lease_loss_test.go、 +internal/platform/postgres/library_protection.go。 + +怎么验:`gofmt -l internal/ cmd/` 输出为空;`python3 scripts/check_format.py` rc=0 +(Go:✅,前端:✅)。只改空白,不改逻辑。 + +改动范围:`internal/platform/postgres/library_protection.go`、`internal/httpapi/library_intent_test.go`、`internal/jobs/lease_loss_test.go` +统计:3 个文件,+3/-3。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_intent_test.go`、`internal/jobs/lease_loss_test.go` + +## 开发快照 snapshot/v0.1.239 - 2026-10-30 +目标提交:98294b9583c0c877f5dd31db61e5146ff548010b + +### Fixed +- **fix(library): 统一执行身份、终态收尾、准入与数据身份** +- **发布意图与执行代次分开**:`library.sync` / `library.restore` / 续作改用 operation(一次明确意图)+ attempt(执行代次)。同一个 `operation_key` 重发命中同一条意图(不重复执行),不带或换键就是新意图——A→B→A 的第三次发布不再拿到第一次的历史成功作业。请求体新增可选 `operation_key`。 +- 版本台账改为**不可变事件 + current 指针**:不同 operation 引用同一快照是两条事件,`source_job_id`/`evidence`/`created_at` 不再被后来的执行覆盖;"谁是当前"由单调次序的条件更新决定。治理库新增迁移 76(`library_operations` / `library_attempts` / `library_current_versions`),不触碰 WeKnora Schema、源码或镜像。 +- 按预备份恢复成功后登记**恢复事实**并推进 current:页面、差异与后续作业看到的是恢复出来的内容身份,而不是继续宣称已失败的新版本生效;原失败作业与失败版本保持不变。 +- 接管或恢复时,执行目标消费已持久化写集合里的复用决定;**读不懂计划的实现直接拒绝写入**(不再"账本说没动共享对象、实际又重写一遍")。 +- 预备份合同改为目标实时状态(schema/模型/映射),不再把来源快照的声明当目标合同。 + +- 半写窗口接管时,前置检查(入口/后台静默/停写者)任一失败都不再重新开放目标:持久 `ContentRisk` 优先于"本进程还没写"。 +- 服务启动或健康校验失败时不再调用开入口:入口保持关闭,交恢复流程处理。 +- journal 已是 `succeeded` / `recovered` 的终态重放可从持久事实重建收尾凭据,不再永久卡住维护锁。 +- 心跳失租会立刻取消 handler;业务状态、阶段进度、版本事件与维护锁释放都带执行代次(epoch)守卫。 +- 迟到的旧代次不能推进 current,也不能释放/改写另一个代次的窗口。 +- 续作沿用原 operation 与首次锚点,不另造丢谱系的新意图。 +- 收尾续作(finalize-only)与正常出口共用同一证据构造:缺少真实字节数或写集合摘要即拒绝登记生效版本。 +- 通用 `POST /api/v1/jobs` 拒绝 `library.*` 保留类型;worker 在动维护前核对业务行、kind/scope 与队列关联。 +- 全库搬运改写定位符时重算 `location_hash = sha256(最终 physical_path)`,与文档级导入共用同一实现。 +- 整库发布在副作用前核对目标**实时**模型契约:同维不同模型、模型不可读、dirty schema 一律拒绝。 +- 容量门禁接到 worker 执行前(预算不足或读不到即拒绝);存储预览按全量依赖判定保护,保护依据读不到时拒绝生成可删候选,备份类型只认显式登记。 +- 发布页:状态读取核 HTTP 状态与响应结构;按预备份恢复纳入轮询并在维护关闭后读回终态;Wiki 差异覆盖标题/摘要/父级变化。 +- CI 版本契约门同时核进程退出码、必需测试真 PASS 与负例失败归因(编译/网络错误不算预期断言生效)。 + +改动范围:`cmd/worker/library_admission.go`、`cmd/worker/library_baseline.go`、`cmd/worker/library_capacity.go`、`cmd/worker/library_completion.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_recovery.go` 等 52 个 +统计:52 个文件,+2818/-195。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_capacity_test.go`、`cmd/worker/library_writeset_resume_integration_test.go`、`cmd/worker/library_writeset_test.go`、`internal/httpapi/library_flow_test.go` 等 12 个 + +## 开发快照 snapshot/v0.1.238 - 2026-10-30 +目标提交:4f0852a94dd36aca68b646f192b4dc2e6ba51ac1 + +### Fixed +- **fix(ci): 契约门同时核进程退出码与负例归因** +为什么:版本契约门只看 `--- PASS: X` 两行,rc1 取到却没用。同一进程里别的测试 +失败时 go test 仍会打印这两个 PASS 行、退出码非 0——那种"绿"证明不了这一轮测试 +成功,负构建因编译/网络错误非 0 也会被当成"断言还活着"。审计 F19 的原始触发即此。 + +改了什么:判据抽成 `judge_contract_positive` / `judge_contract_negative`,正向要求 +rc=0 + 每个必需测试真 PASS + 无 FAIL 事件 + 未跳过;负例要求非 0 且失败在预期断言上, +命中编译/网络/工具链标记即判红。判据的反例自检 `contract_judgement_problems()` 同时在 +`make verify` 的 contracts 步骤与 `--self-test` 里跑,判据被改坏在本地就红。 +POLICY_REVISION 提到 ci-checks/4。 + +怎么验:`python3 scripts/ci_checks.py --self-test` rc=0(10 汇总分支 + 10 契约反例); +`--internal-contracts $(command -v go)` rc=0;反例探针(假 go 打印两个 PASS 后 exit 1) +现在 rc=1,修复前同一输入 rc=0。 + +改动范围:`scripts/ci_checks.py` +统计:1 个文件,+104/-21。 + +## 开发快照 snapshot/v0.1.237 - 2026-10-30 +目标提交:c2ab658033ffaa2ae8001134528214fe14f25c07 + +### Docs +- **docs: 记录写集合证据被整份覆盖的陷阱** +新增 trap 20:复用预备份时重新造一份证据,会让已登记的写集合锚点被整份 +抹掉(现场 backup_bytes:0 + writeset_* 全丢)。写明症状、根因、负例优先的 +判据与修法,含预备份版本行「一条只属于首次登记的作业」这一归属语义。 +AGENTS.md 索引表那一行受写入保护、需主人批准,本次未改(见交接单待批准项)。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/agents/traps.md` +统计:1 个文件,+43/-0。 + +## 开发快照 snapshot/v0.1.236 - 2026-10-30 +目标提交:d0310761b6a266722cbe772ab997727c69454183 + +### Fixed +- **fix(worker): 接管复用预备份不再抹掉写集合证据** +- **崩溃接管复用预备份时,已经登记的写集合证据被整份覆盖,恢复链断在第二次中断**: + `BackupPrepared` 原先每一轮都新造一份证据,而版本登记是整份替换 + (`evidence = EXCLUDED.evidence`)。接管路径上复用声明只带快照 id(没有字节数), + 写集合预检又只在首轮执行,于是 `writeset_digest`/`writeset_rows` 被抹掉、 + `backup_bytes` 记成 0;同一作业再中断一次就再也取不回写集合,只能在 + `verify_effective` 上失败(2026-10-30T00:58Z 演练实例 `…-1793321916382871758-retry`, + 摘要 `fddd98cf70…` → 空)。现在证据按"同一作业 + 同一份预备份"合并进已持久化那一行, + 身份不符一律拒绝;接管复用从首次登记的证据取回真实字节(缺失即拒), + 生效版本证据统一构造。同一作业的写集合只允许落定一次,摘要冲突即失败。 + +改动范围:`cmd/worker/library_handlers.go`、`cmd/worker/library_writeset.go`、`scripts/test-scope.json`、`CHANGELOG.md`、`cmd/worker/library_writeset_resume_integration_test.go`、`cmd/worker/library_writeset_test.go` +统计:6 个文件,+643/-17。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_writeset_resume_integration_test.go`、`cmd/worker/library_writeset_test.go` + +## 开发快照 snapshot/v0.1.235 - 2026-10-30 +目标提交:780ab988c4676fab1816415fa35d15288343063a + +### Fixed +- **fix(worker): 历史快照恢复接管按作业身份与新授权判定** +真实现场 2026-10-30T00:19Z:新恢复作业恢复历史快照 fc595511(已被 0d982f76 +顶替),写入 database 后被 SIGKILL;重启接管时 classifyTakeover 只要看到 +该快照有 SupersededAt 就判 superseded,没有判这行历史版本属于哪个作业, +把历史那次发布被顶替当成这次作业过期,作业 failed/prebackup,而恢复文案 +又写"无需恢复",目标半写且维护锁未释放。 + +修法:被顶替分支先分清归属——本作业 finalize 成功或版本行属于本作业 ⇒ 仍 +拒绝;历史行属于别的作业时,仅当本次是 restore、授权签发于顶替之后、scope +与 instance 两把锁仍由本作业独占且指纹一致、预备份登记属于本作业且清单字节 +仍等于摘要,才按 fresh 继续重跑整条链路。任一证据缺失/读不到仍拒绝。 + +同时把续作早退统一走 failLibraryJobOrTakeover:有持久化预备份时保留 +needs_restore 并点名 backup,不再写"无需恢复"。 + +验证: +- 先写失败回归(历史行+新授权 ⇒ 期望 fresh,实得 superseded),修后绿; +- 真实 PostgreSQL 正负例:授权撤销/实例锁释放/预备份归属被改/清单字节被改 + 均回到 superseded;续作早退保留备份与 needs_restore; +- 本地 make verify 16 项必需检查全绿(identity 本地档案跳过)。 + +改动范围:`cmd/worker/library_finish.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_takeover_resume.go`、`scripts/test-scope.json`、`cmd/worker/library_finish_test.go`、`cmd/worker/library_takeover_historical_integration_test.go` 等 8 个 +统计:8 个文件,+518/-30。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_finish_test.go`、`cmd/worker/library_takeover_historical_integration_test.go`、`cmd/worker/library_takeover_historical_test.go`、`cmd/worker/library_takeover_integration_test.go` + +## 开发快照 snapshot/v0.1.234 - 2026-10-29 +目标提交:c57c22c65e7e9f9a9a739b80597c65c34760e7b5 + +### Docs +- **docs: 记录接管证据陷阱与判据变化** +- traps §19:汇总日志与阶段文案都不是接管证据;认领/决策行必须带作业 id 且晚于 + 杀点;prebackup 允许 succeeded,但要证明复用同一份而不是重做; +- traps 索引第 19 行待主人批准(AGENTS.md 受写入保护),草稿在 + docs/agents/traps-index-pending.md; +- 验收矩阵:S04-b 记"写链路已实测、脚本级验收未成立",并补一节 + "这一轮到底验到了什么/还没成立什么"。旧 FAIL 证据不改写。 + +verify: make verify overall success(16 项)。文档不含会漂移的统计数字。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/agents/traps-index-pending.md`、`docs/agents/traps.md`、`docs/library-acceptance-matrix.md` +统计:3 个文件,+77/-2。 + +## 开发快照 snapshot/v0.1.233 - 2026-10-29 +目标提交:8a3aa800a3e0ecd59a4878557f3ec47ee99f891c + +### Fixed +- **fix(scripts): 演练判据改用认领与决策行并校验预备份复用** +v4 判据(都带作业身份,且时间戳必须晚于杀点): + +- `scripts/takeover_log_contract.py` 是唯一判据:认领行 + 决策行都要有本作业 id、 + target/backup 一致;只有汇总行、别的作业的认领行、杀之前的旧日志三种一律红; + `--self-test` 11 条(正例 2 / 负例 9)进 `make verify`(新增第 16 项必需检查); +- `prebackup` 不再强制 `skipped`:真实接管是复用后重跑整条链路,阶段记 succeeded。 + 但**不取消备份校验**,改为证明复用同一份——快照 id、清单字节与 mtime、 + 版本行首次登记时刻都不变,且证据里有 `backup_reused=true`; +- 杀之前把预备份清单 sha256/mtime 与版本行登记时刻拍进 evidence; +- summary.json 增加 takeover_decision / claim_at / backup_registered_at。 + +verify: 判据自检 11 条全过;用真实 Go 输出行形状的正例日志 rc=0;旧形状(只有 +汇总行)rc=2 且理由点名"汇总";`--check` 前置体检 13 项全 pass(含新增 +preflight_log_contract);make verify overall success。 + +改动范围:`scripts/ci_checks.py`、`scripts/library-kill-takeover.sh`、`scripts/takeover_log_contract.py` +统计:3 个文件,+404/-17。 + +## 开发快照 snapshot/v0.1.232 - 2026-10-29 +目标提交:85b3596e0ef5c9fc54f35b691b92721bd80b3b25 + +### Fixed +- **fix(postgres): 复用预备份时保留首次登记时刻** +崩溃接管会复用崩溃前那份预备份;BackupPrepared 会再登记一次版本行,而 +`created_at = EXCLUDED.created_at` 把"备份什么时候拍的"洗成了接管时刻 —— +事后无法区分"复用"和"崩溃后重做了备份",而后者正好把半写状态当成可回滚基线。 + +- 只对 `production_prebackup` 取 LEAST(首次登记时刻只早不晚); +- 生效版本行仍写当前时刻(重新激活一个旧快照后,页面要显示最近一次生效); +- 真实 PG 用例两条负例:撤掉保留规则 ⇒ 红;规则漏到所有 kind ⇒ 红。 + +verify: 一次性库 kg_takeover_reuse_test 上 PASS; +负例 1(撤掉 CASE)→ "复用后登记时刻被改写";负例 2(CASE 去掉 kind 条件)→ +"生效版本重新激活后时刻";make verify overall success。 + +改动范围:`internal/platform/postgres/library_jobs.go`、`scripts/test-scope.json`、`cmd/worker/library_backup_reuse_test.go` +统计:3 个文件,+115/-2。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_backup_reuse_test.go` + +## 开发快照 snapshot/v0.1.231 - 2026-10-29 +目标提交:6bdc17474c344fd8f343363515fa6ee67bd936c2 + +### Changed +- **feat(worker): 接管认领与决策落结构化日志** +2026-10-29T19:56Z 的 after:database 演练里,worker 只留下汇总行 +`library job takeover sweep: 1 resumed, 0 failed without backup`:既不说哪个 +作业,也不说它是否真被本进程认领(被别的 worker 抢走、attach 失败都只影响 +计数)。演练脚本要的老文案只在"新建队列行"那条路径打印,真实走的是"队列行 +已存在"那条 ⇒ 判据与实现各说一套,演练 exit 5。 + +- 新增 `library job takeover claimed at=… kind=… scope=… target=… + backup=… queue=… path=…`:claim + attach 都成功之后才写,两条认领路径共用 + (path=enqueue / existing-queue); +- 新增 `library job takeover decision=…`:分类后、动手之前写,含 + finalize_only。只留阶段表的话,同快照收尾能把它伪造成完整续作; +- resume 的 store 参数抽成接口,单测才能证明"没认领/attach 失败时一行都不写" + (变异验证:把认领行提到 attach 之前 ⇒ 红;删掉 existing-queue 那行 ⇒ 红); +- 接管复用的预备份在证据里写 `backup_reused=true`:分不清"复用"与"崩溃后重做 + 备份",后者会把半写状态当成可回滚基线。 + +verify: go test ./cmd/worker -run 'TestTakeover|TestLedgerBackupStore' -count=1 全绿; +make verify overall success(16 项必需全绿)。 + +改动范围:`cmd/worker/library_handlers.go`、`cmd/worker/library_takeover_log.go`、`cmd/worker/library_writeset.go`、`internal/libraryrelease/release.go`、`cmd/worker/library_takeover_log_test.go` +统计:5 个文件,+342/-6。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_takeover_log_test.go` + +## 开发快照 snapshot/v0.1.230 - 2026-10-29 +目标提交:d5447280018614224e902f34595b57df35b258e7 + +### Tests +- **test(worker): 真实PG断言拒绝接管的落库效果** +拒绝接管不只要"分类对",还要三处落库都对:library_jobs 终态 failed + 保留预备份 +基线 + 恢复指引里带得上那个基线;library_maintenance 的 released_at 仍为 NULL、 +state=needs_restore(目标可能半写,释放等于谎称已恢复)。 + +用一次性库 kg_takeover_foreign_test 实跑: +- TestFailLibraryTakeoverKeepsMaintenanceAndNamesBackup PASS (1.35s) +- 负例:把恢复指引改成"无需恢复" ⇒ 同一用例红(library_takeover_integration_test.go:117) +- TestTakeoverRefusesSameSnapshotRegisteredByAnotherJob / 超出历史窗口那条仍 PASS + +改动范围:`scripts/test-scope.json`、`cmd/worker/library_takeover_integration_test.go` +统计:2 个文件,+71/-0。 + +## 开发快照 snapshot/v0.1.229 - 2026-10-29 +目标提交:4a70c2a848f687ed94dbd841a6ed10f3e5243219 + +### Fixed +- **fix(scripts): 杀之前等 docker events 监听就位** +SIGKILL 与事件监听抢在同一秒时,die 事件可能早于 attach 被错过,症状是误报 +"没有 exitCode=137 证据"(假红)。加 1s 等待,并用注释写清它只会假红、不会假绿。 + +改动范围:`scripts/library-kill-takeover.sh` +统计:1 个文件,+3/-0。 + +## 开发快照 snapshot/v0.1.228 - 2026-10-29 +目标提交:d0fe257531b7412c60b238e44c4d25f6f82a5cb7 + +### Docs +- **docs: 记录接管身份陷阱与演练判据变化** +- **同一个快照由别的作业登记成生效版本时,接管会把它当成本作业"只差收尾"**: + `classifyTakeover` 原先只看"当前生效版本的目标快照是否等于我的目标快照",而版本行 + 主键由 `(kind, scope, 快照)` 决定、写入是 upsert(会改写 `source_job_id`), + 所以"生产上有这个快照"被误当成"本作业写完了"。2026-10-29T19:16Z 的真实后果: + 作业只写完了 `database` 阶段(`resources/index/wiki/verify` 仍 pending), + 人工拉起后被判 `succeeded`,并把生效版本归属改写成自己。现在分类带作业身份 + (`effectiveOwnedBy`):归属别的作业 ⇒ `foreign_effective`,走拒绝接管的失败出口 + (不写目标、不释放维护、终态失败并指明预备份),不再按同快照收尾。 + 同一份身份判定与基线共用,快照相等不再单独构成"完成"证据。 + +- **中断演练脚本改用"进程崩溃"语义,并把期望内容按快照推导**: + `scripts/library-kill-takeover.sh` 不再 `docker kill`(那是 Docker 手动停止, + `unless-stopped` 也不拉起,上一轮就因此空等 420s、最后靠人工 `docker start`)。 + 现在向容器 PID1 从宿主机发 SIGKILL,用 `docker events` 的 `exitCode=137` 作证据, + 限期等 restart policy 拉起;策略没起来才显式 `docker start`,并在证据里记成 + `restart_source=manual_start`,绝不当自动恢复。期望内容按目标快照的 manifest 推导 + (`knowledges/chunks/wiki_pages`),`resources` 不进默认期望(同租户其它知识库的 + 资源会保留)。新增:`--kind sync|restore`、`--snapshot` 强校验、目标快照等于中断前 + 生效版本时**杀之前就拒绝**、五个写入阶段全部 `succeeded` 才算完整续作、 + 独立写集合校验器缺失即失败、首屏证据读回用 `owner_scope`。 + +改动范围:`CHANGELOG.md`、`docs/agents/traps-index-pending.md`、`docs/agents/traps.md` +统计:3 个文件,+72/-0。 + +## 开发快照 snapshot/v0.1.227 - 2026-10-29 +目标提交:1d70059d328977fcae01589992d16f5d407dbe5f + +### Fixed +- **fix(scripts): 中断演练改用进程崩溃语义并按快照推导期望** +上一轮为什么空等 420s:docker kill 走 Docker API 的"手动停止",unless-stopped +也不拉起,容器一直躺着,最后由人工 docker start 才接管 —— 那不是崩溃自恢复。 + +改法: +- 命中后从宿主机向容器 PID1 发 SIGKILL(同 uid 才允许,先证明能杀);退出码证据取 + docker events 的 die exitCode=137 —— restart 后 State.ExitCode 会被重置成 0, + 事后 inspect 读不到 137。 +- 限期等 restart policy 拉起(同容器/同镜像才算);策略没起来才显式 docker start, + 并记 restart_source=manual_start,绝不当自动恢复。 +- 期望内容按目标快照 manifest 推导(knowledges/chunks/wiki_pages),resources 不进 + 默认期望(同租户其它知识库资源会保留,trap-16)。 +- --kind sync|restore + --snapshot 强校验;目标快照等于中断前生效版本时**杀之前 + 就拒绝**(同快照收尾不能当完整续作验收)。 +- 新增 verify_stages_complete:database/resources/index/wiki/verify 全部 succeeded + 才算完整续作(上一轮这四个还是 pending,却被判成功)。 +- 独立写集合校验器缺失即 fail(旧版记 canonical=not_run 还 pass)。 +- save_evidence 读实例维护用 owner_scope(旧版读 scope 列,SQL 报错被吞)。 + +验证(已跑): +- bash -n 通过;--check 全绿(READY_FOR_PARENT,含 preflight_verifier) +- 负例:WRITESET_VERIFIER=/nonexistent → preflight_verifier fail / exit 2 +- 期望推导:fc5955→4/38/31、0d982→1/2/9、0fea→4/38/31;不存在的快照 → exit 1 +- 宿主 SIGKILL 能力实测(scratch 容器,非本栈):kill -9 PID1 → 策略自动重启, + RestartCount 0→1,docker events 记 exitCode=137 + +改动范围:`scripts/library-kill-takeover.sh` +统计:1 个文件,+246/-47。 + +## 开发快照 snapshot/v0.1.226 - 2026-10-29 +目标提交:ba852f3dc20119cf9a18aebde73d217acbe6f63d + +### Fixed +- **fix(worker): 接管判据绑作业身份,同快照别作业登记不算完成** +2026-10-29T19:16Z 真实现场:作业只写完 database 阶段(resources/index/wiki/verify +仍 pending),worker 被杀、人工拉起后被判 succeeded,阶段写"已登记生效版本(仅收尾, +未重写生产)",并把生效版本归属改写成这个作业。 + +根因:classifyTakeover 只看"当前生效版本的目标快照是不是我的目标快照"。版本行主键 +由 (kind, scope, 快照) 决定(LibraryVersionID),登记是 ON CONFLICT (id) DO UPDATE、 +会改写 source_job_id —— 快照相等这一维里没有作业身份。 + +改法:effectiveOwnedBy(version, jobID, snapshotID) 一份实现,接管与基线共用; +归属别的作业 ⇒ 新的 takeoverForeignEffective,走 failLibraryTakeover:不写目标、 +不释放维护、终态失败并指明预备份(目标可能半写,释放等于谎称已恢复)。 +本作业自己的 finalize 阶段成功仍是独立证据,不被归属改写推翻。 + +验证(已跑): +- go test ./cmd/worker -run TestClassifyTakeover → PASS(含 4 条新用例) +- 负例:撤掉身份判定后同两条用例红(classify="pending_final", want "foreign_effective") +- 真实 PG(一次性库 kg_takeover_foreign_test): + TestTakeoverRefusesSameSnapshotRegisteredByAnotherJob PASS(1.41s), + 负例同一用例红(library_takeover_integration_test.go:53) +- 同一库 TestTakeoverClassificationUsesExactCurrentVersionBeyondHistoryWindow PASS +- make verify:overall success(15 项必需全绿) + +改动范围:`cmd/worker/library_baseline.go`、`cmd/worker/library_finish.go`、`cmd/worker/library_handlers.go`、`scripts/test-scope.json`、`cmd/worker/library_finish_test.go`、`cmd/worker/library_takeover_integration_test.go` +统计:6 个文件,+136/-9。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_finish_test.go`、`cmd/worker/library_takeover_integration_test.go` + +## 开发快照 snapshot/v0.1.225 - 2026-10-29 +目标提交:a19cf819fc4284e722129c52701fbd3ae45b355d + +### Fixed +- **fix(scripts): 修演练脚本的撤注入与 restore 自锁** +两处实测出来的缺陷: + +- --restore 也走完整前置体检,而体检里"不许已经带注入"这一条会把它自己锁死 + (上一轮没收尾时它就永远跑不了)。restore 只校验 docker/worker/归档根。 +- 注入用的 overlay 被 compose 记进容器的 config_files 标签,restore 时原样重放 + 等于把注入又加回去(实测 KG_TEST_BARRIER_DIR 撤不掉)。按文件名排除演练 overlay。 + +另外演练中断(not_run/接管失败)时明确提示"屏障仍在注入,先 --restore", +不让父以为栈已经干净。 + +改动范围:`scripts/library-kill-takeover.sh` +统计:1 个文件,+19/-1。 + +## 开发快照 snapshot/v0.1.224 - 2026-10-29 +目标提交:465cae80bd00a70d054036e6bef68862a3ff8818 + +### Docs +- **docs: 记录"窗口当索引"陷阱与本次改动** +- **"当前生效版本"靠最近 50 条找,历史一长就把已生效读成没有**:接管分类 + (`classifyTakeover`)、基线判定(`classifyBaselineVersions`)与"已知索引映射" + 都把分页窗口当索引;窗口之外的生效版本被读成"不存在"之后,接管会把已经上线的 + 目标重写一遍,基线入口会为已有权威版本的目标再建一次基线。现在统一走两条精确 + 查询:`LibraryCurrentVersion`(`kind='production_effective' AND superseded_at IS NULL`, + 每 scope 至多一行)与 `LibraryVersionOfSnapshot`(按快照身份取回"已顶替"证据)。 + 同一含义只保留一份实现:同步与恢复共用 `knownIndexMapping`。 +- **同一判断在接口侧也要改,不是"只是展示"**:整库页的生产版本、生产同步闸口 + (这是**创建**判据:读错会放行一次不必要的覆盖)、建立基线入口(读错会覆盖 + 别人的版本)、归档保留里"生产生效版本"的保护标记,全部改用精确查询;查询失败 + 一律 fail closed(500/拒绝),不猜。历史列表仍是分页展示,`LibraryVersions` + 的 1..100 上限没动。 + +- **真实 worker 中断演练的固定同步屏障**(`internal/testbarrier`,默认关闭): + 只有 `KG_TEST_BARRIER_DIR` 与 `KG_TEST_BARRIER_POINTS` 同时在场才生效,且只在 + 本机测试栈通过 compose overlay 注入。worker 每个阶段写完后写现场文件并停在固定 + 点位,演练方看到它再 SIGKILL——命中是确定的,不是靠 sleep 猜时间。进程被杀后 + 重启的 worker 看到同一份现场文件直接通过,不会把接管再拦住。 +- `scripts/library-kill-takeover.sh`:前置体检(目标拓扑、无在飞作业、无未释放 + 维护窗口、镜像真的带屏障代码)→ 注入屏障 → 等命中 → 锁住这一个作业 → 读回写 + 集合台账并独立校验摘要 → SIGKILL 容器 → 等同一作业被接管 → 校对目标内容、 + 维护释放与服务恢复 → 撤掉注入。只有整条链路成立才 exit 0;missed / 超时 / + 接管失败分别用不同退出码,**"没做"与"做成"分开**。 + +改动范围:`scripts/test-scope.json`、`AGENTS.md`、`CHANGELOG.md`、`docs/agents/traps.md` +统计:4 个文件,+68/-0。 + +## 开发快照 snapshot/v0.1.223 - 2026-10-29 +目标提交:ed307f3c2014f5896c2580795402e32db1af5453 + +### Changed +- **feat(scripts): 真中断演练脚本改成父可直接执行** +旧 kill-takeover.sh 的判据自相矛盾:要求"作业已 running 且 ledger 齐"才启动, +可它又要先启动再等作业;维护窗口里要求业务 health 200(那时 app 是被有意停掉 +的);没杀到任何进程也 exit 0。 + +这一版把"做成"定义清楚:真 SIGKILL 真容器 → 同一作业被接管 → 目标按期望内容 +恢复 → 服务/入口恢复,四条全成立才 exit 0;missed/超时/接管失败各有非零退出码 +并写成 not_run。流程:前置体检(目标拓扑、无在飞作业、无未释放维护窗口、镜像 +里真的带屏障代码、只允许本机栈)→ 注入屏障 → ARMED 后由人在页面发起作业 → +看到 .hit 锁住这一个作业 → 读回写集合台账(文件名/自述摘要/作业绑定,可选独立 +校验器)→ SIGKILL → 等同一作业接管 → 核对 prebackup:skipped、生效版本、写集合 +摘要不变、目标计数、维护释放与容器恢复 → 撤掉注入。每一步有界,不做后台 sleep +轮询假装工作。 + +改动范围:`scripts/library-kill-takeover.sh` +统计:1 个文件,+544/-0。 + +## 开发快照 snapshot/v0.1.222 - 2026-10-29 +目标提交:0d3a016a9e06657088a82c591f3ba60238cafee1 + +### Changed +- **feat(worker): 加真实中断演练的固定同步屏障** +真杀 worker 只有在"写了一半"那一刻才有意义,靠 sleep 猜时间会错过阶段 —— +上一版演练脚本就是这样永远 exit 0 的。这里把"进程确实停在固定点"变成文件事实: +worker 到达点位后写 /.hit 再等放行,演练方看到它再 SIGKILL,命中 +是确定的。 + +安全边界:只有 KG_TEST_BARRIER_DIR 与 KG_TEST_BARRIER_POINTS 同时在场才生效 +(默认关闭),只由本机 compose overlay 注入;单次等待有硬超时,没人放行就自己 +继续;同一进程被杀后重启看到同一份 .hit 直接通过,不会把接管再拦住。屏障挂在 +contentTrackedTarget(阶段之间),发布链路不需要知道演练的存在。 + +验证:屏障包 4 条用例(默认关闭无副作用 / 命中与放行握手 / 超时自行继续并留 +.hit+.timeout / 目录不可建报错但不阻塞)与包装层接线用例全绿(后者证明真实 +Apply 路径真的走到点位,漏接线会红)。 + +改动范围:`internal/testbarrier/barrier.go`、`cmd/worker/library_barrier_test.go`、`internal/testbarrier/barrier_test.go` +统计:3 个文件,+366/-0。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_barrier_test.go`、`internal/testbarrier/barrier_test.go` + +## 开发快照 snapshot/v0.1.221 - 2026-10-29 +目标提交:0088004cd6cec924092a39de63b95c0b570d7045 + +### Fixed +- **fix(library): 当前生效版本改按精确查询** +接管分类、基线判定、已知索引映射、同步闸口的创建判据与归档保留的保护标记, +原来都用 LibraryVersions(scope, 50/100) 这个分页窗口再在内存里筛。生效版本每 +scope 只有一行、可能很久以前登记,历史一长就被挤出窗口 —— 于是"已生效"被读成 +"没有生效":接管会把已经上线的目标重写一遍,基线入口会给已有权威版本的目标 +再建一次基线。 + +现在统一走两条精确查询:LibraryCurrentVersion(kind='production_effective' AND +superseded_at IS NULL,每 scope 至多一行)与 LibraryVersionOfSnapshot(按快照 +身份取回"已顶替"证据)。多行、自相矛盾、读不到一律 fail closed;同一含义只留 +一份实现(knownIndexMapping 同步与恢复共用)。LibraryVersions 仍是 1..100 的 +展示窗口,只用于列表。 + +验证:真实 PG 上先复现(窗口实现 ⇒ found=false),改后 7 条 store 契约用例与 +worker 端到端判定用例全绿;本机 make verify 15 项 success(用例 1264 通过 / +0 失败 / 93 已声明可选跳过)。 + +改动范围:`cmd/worker/library_baseline.go`、`cmd/worker/library_finish.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_recovery.go`、`cmd/worker/library_versions.go`、`internal/httpapi/library_baseline.go` 等 15 个 +统计:15 个文件,+655/-130。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_baseline_test.go`、`cmd/worker/library_finish_test.go`、`cmd/worker/library_takeover_integration_test.go`、`internal/httpapi/library_baseline_test.go` 等 6 个 + +## 开发快照 snapshot/v0.1.220 - 2026-10-29 +目标提交:67743f22854d4bc378be7030ac30aa72f196e07b + +### Tests +- **test(library): 真实PG验证超出历史窗口仍能取回写集合** +fake 版本库不实现 Store 的 1..100 上限,正是它让"限 out of range"一路绿到线上。 +这组用例跑真实 PostgreSQL:真实 Run → contentTrackedTarget → 真实 +libraryStageRecorder.WriteSetPlanned → 真实 store,断言台账在第一笔写入之前可读、 +原备份证据字段与 writeset_digest 原子共存,并把记录推到 250 条更新版本之后 +(窗口里已看不到它)仍能按身份取回。 + +store 级契约用例覆盖:命中、真缺失 found=false、别的作业=冲突、同身份两行=拒绝挑选、 +跨 scope/跨 kind 不命中、不完整身份拒绝。变异成"列最近 N 条再筛"时四条全红。 +隔离 schema 逻辑收敛到 pgtest 一份,postgres 侧改为委托。 + +改动范围:`internal/platform/postgres/pgtest/isolated.go`、`scripts/test-scope.json`、`cmd/worker/library_writeset_integration_test.go`、`cmd/worker/library_writeset_test.go`、`internal/platform/postgres/integration_isolation_test.go`、`internal/platform/postgres/library_version_lookup_integration_test.go` +统计:6 个文件,+461/-37。 + +## 开发快照 snapshot/v0.1.219 - 2026-10-29 +目标提交:f0bd6fb0d250aa713767638a973c3916c530008f + +### Fixed +- **fix(library): 版本台账改按身份精确查询** +写集合台账的取回走的是"按 scope 列最近 N 条再筛",而真实 Store 只接受 1..100, +于是真作业在预备份已落盘之后登记失败(library version limit out of range), +写集合引用没能持久化。假版本库没有这个上限,单测因此一路绿。 + +只把 200 改成 100 不够:历史超过窗口后,存在会被读成不存在(本机实测:把记录推到 +250 条更新版本之后,接管/恢复就找不到它)。改为 Store.LibraryVersionByRef: +scope+kind+作业+快照 一条 SQL 精确命中;命中多行拒绝挑选,命中别的作业拒绝借用, +真的没有才返回 found=false。登记/接管/恢复三处共用它,公开分页上限保持 1..100 不变。 +版本行解码抽成 scanLibraryVersions,窗口列表与精确查询共用一份。 + +改动范围:`cmd/worker/library_writeset.go`、`internal/platform/postgres/library_jobs.go` +统计:2 个文件,+91/-34。 + +## 开发快照 snapshot/v0.1.218 - 2026-10-29 +目标提交:27828ff21e7c66846ba41ed50894814915fdf36f + +### Tests +- **test(worker): 编排链路里包装层必须真的触发写集合预检** +只测“包装体转发”还不够:Run 是按可选接口断言决定要不要预检的。补一条走 +libraryrelease.Run + contentTrackedTarget 的用例,断言预检被调用一次、结果 +带回编排层、四类写入照常执行。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`cmd/worker/library_writeset_test.go` +统计:1 个文件,+59/-0。 + +## 开发快照 snapshot/v0.1.217 - 2026-10-29 +目标提交:18683ca63ca10dc8238d230eeb677608e911dd81 + +### Docs +- **docs(agents): 记录资源范围冲突与可审计复用判据** +trap-16:resources 是多知识库共享表,“不在预备份范围”不等于“属于别的 +知识库”;恢复保留下来的行是本目标上次成功同步的结果。判据、修法与反例 +写进全文,索引表加一行。 + +仅文档变更,不改变运行时行为。 + +改动范围:`AGENTS.md`、`docs/agents/traps.md` +统计:2 个文件,+28/-0。 + +## 开发快照 snapshot/v0.1.216 - 2026-10-29 +目标提交:0252492e53b76c48c2deca86f5c497c055ba73ac + +### Fixed +- **fix(library): 恢复保留下来的资源凭可审计证据复用** +同步 A 成功后手工恢复 B,resources 表既不删行也不删对象;再同步 A 时, +resources 里那 21 行以“同租户但不在预备份范围”被判成别人的知识库,整次 +同步在写第一笔之前被拒。 + +“目标里没人引用”不是归属证据:历史孤儿、其它知识库暂未绑定的资源都满足 +它。改成唯一放行路径——可审计复用(v071/library_reuse.go): +1. 持久来源:这个目标成功同步过且登记过生效版本的快照,或它自己的预备份, + 且同一资源行在来源里内容一致; +2. 整行内容(除易变时间戳)与本次写入将要落地的行完全一致; +3. 该资源的对象字节与本次快照归档摘要一致。 + +三条同时成立才允许复用:写入阶段跳过它(不重写行、不重传对象),写集合里 +记 existing+reused,恢复不清理;证据单独落盘 reuse/.json,摘要写进 +写集合行,不冒充历史台账。内容不同、来源范围不同、或没有持久来源一律继续 +拒绝,且拒绝发生在写入之前。 + +为什么把预备份也算来源:恢复作业的写集合同样会把“本目标历史状态里已有的 +资源”判成跨范围冲突,而它们本来就出自这个目标自己的快照。 + +验证:隔离 PG+ES+MinIO 真服务下新增 5 个场景用例(复用成功且 xmin 不变、 +无来源拒绝、内容不同拒绝、同内容不同来源拒绝、wiki 半写回滚只清本次新建); +v071 整包与全仓 go test 通过;make verify 15 项全绿。 + +改动范围:`cmd/worker/library_handlers.go`、`cmd/worker/library_writeset.go`、`internal/libraryrelease/release.go`、`internal/libraryrelease/writeset.go`、`internal/platform/postgres/library_jobs.go`、`internal/releaseadapter/v071/library_production_target.go` 等 12 个 +统计:12 个文件,+1034/-18。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_writeset_test.go`、`internal/libraryrelease/writeset_test.go`、`internal/releaseadapter/v071/library_reuse_integration_test.go`、`internal/releaseadapter/v071/library_writeset_integration_test.go` + +## 开发快照 snapshot/v0.1.215 - 2026-10-29 +目标提交:cf3f4662ccb88d6b6bf640749e628ec16017ccab + +### Docs +- **docs: 记录写集合与定位符陷阱并归档真作业证据** +- **写集合台账在真作业里根本没生成**:worker 把目标包成 `contentTrackedTarget` + 以标记"内容可能半写",但包装层没转发 `PlanWriteSet`,而 orchestrator 是用 + **类型断言** `target.(WriteSetPlanner)` 决定要不要算写集合的 —— 断言恒为假, + 台账既不落盘也不登记。真实后果:10-29 两次真作业的预备份证据里都没有 + `writeset_digest`,归档根下没有 `writesets/`,一旦 worker 崩在写入中间接管必然 + 失败。现在包装层显式转发;内层不支持预检时返回硬错误,不退回"没有台账也照写"。 +- **`S3ObjectStore.Stat`/`Delete`/`Copy` 与 `Open`/`Put` 吃不同的定位符**:真实资源 + 路径是 `storage:///:///`,前三个用只认单层的 + `validObjectLocator` 并把整串当对象键,于是"对象在桶里但校验读不到"。现在四个 + 入口共用 `validObjectKey` + `providerPathFromLocator`。集成用例改成喂真实定位符, + 负例覆盖键不存在 / provider 不符 / 路径穿越 / 复制源不存在;写集合集成用例里 + 那条"读不到也当通过"的容忍断言改为真断言。 +- **已成功/已失败的作业在页面上仍写"尚未启动""此时尚未运行"**:生产版本行与作业条 + 的文案原来写死,阶段条只认 `kind=sync`。现在按作业类型与终态显示,恢复/基线也 + 用同一串阶段读自己的阶段行(不再一律"本次作业尚未开始")。 +- **预备份已登记却显示"尚未创建/无记录"**:`overview.prebackup` 原来只认"与拟发布 + 快照同内容的那一份",而恢复作业登记的是**恢复前**的备份,两者必然不同。现在显示 + 最近一次已登记预备份,并给出所属作业与"是否为当前拟发布目标";闸口判定不变。 +- **所有归档都被标成"测试封存"**:归档根下同时有目标基线与每次预备份。overview 新增 + 轻量版本清单(不含 evidence),抽屉按登记过的 kind 标注每份快照,未登记的归档 + 如实写"未登记(归档文件,不作为发布候选)"。 +- **基线与恢复被写成"生产同步"/"封存进行中"**:作业类型改成逐类映射 + (测试封存 / 生产同步 / 按版本恢复 / 建立目标基线),页签徽标、作业头、明细表同步。 +- **轮询只覆盖封存队列**:点了同步/恢复/建立基线之后页面根本不刷新,看上去像"还没 + 启动",而失败作业又可能被无限轮询。现在轮询覆盖"投递 → 终态读回":投递中的动作、 + 封存队列作业、任一 scope 的在飞持久作业都算在跑;读到终态(成功/失败/取消)再读 + 回一次就停。 +- **维护窗口的起始时间永远是第一次建立基线那一刻**:`acquired_at` 没进 + `ON CONFLICT DO UPDATE`,新作业接管已释放的窗口时不会换时间。库级与实例级两份 + SQL 都改成"同一作业重入才保留旧值,新作业接管用本次时间"。 + +- `docs/agents/traps.md` trap-14(包装层丢掉可选接口 ⇒ 台账静默跳过)、 + trap-15(对象存储各入口定位符形状不一致)。 +- 真实 PostgreSQL 用例:维护窗口起始时间只属于当前这次占用。 +- 真实 MinIO 用例:正例用 `storage://` 定位符走 Put/Open/Stat/Copy/Delete,负例四种。 + +改动范围:`AGENTS.md`、`CHANGELOG.md`、`docs/agents/traps.md`、`docs/evidence/2026-10-30-real-sync-restore/README.md`、`docs/evidence/2026-10-30-real-sync-restore/archive-integrity.txt`、`docs/evidence/2026-10-30-real-sync-restore/jobs.txt` 等 11 个 +统计:11 个文件,+480/-1。 + +## 开发快照 snapshot/v0.1.214 - 2026-10-29 +目标提交:74fb04b2d1e50b1f227a19d0c0582394beff4f4f + +### Fixed +- **fix(web): 整库页按作业类型与终态显示并补全轮询** +- 成功的作业不再写"尚未启动/此时尚未运行",阶段条对恢复/基线也读自己的阶段行; +- 基线/恢复不再被写成"生产同步""封存进行中",改为逐类映射; +- 抽屉按版本登记标注每份归档,未登记的不冒充候选; +- 轮询覆盖投递→终态读回:投递中动作、封存队列、任一 scope 在飞作业都算在跑, + 读到终态再读回一次就停,失败作业不会被无限轮询。 + +改动范围:`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx`、`web/src/librarySnapshots.ts` +统计:3 个文件,+498/-51。 + +## 开发快照 snapshot/v0.1.213 - 2026-10-29 +目标提交:402173263ecc2e18c2f216ead0b397b7c79f5d6e + +### Fixed +- **fix(library): 预备份与归档类型按版本登记显示** +两处契约错:prebackup 只认"与拟发布快照同内容的那一份",而恢复作业登记的是 +恢复前备份(必然不同),于是刚备份完就显示"尚未创建";归档里同时有目标基线与 +每次预备份,overview 不给登记类型,页面只能把每份都写成"测试封存"。 + +现在 prebackup 取最近一次已登记的那份,并给出所属作业与 bound_to_target; +overview 新增不含 evidence 的轻量版本清单供页面标注每份快照。闸口判定不变。 + +改动范围:`internal/httpapi/library_flow.go`、`internal/httpapi/library_flow_test.go` +统计:2 个文件,+105/-14。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_flow_test.go` + +## 开发快照 snapshot/v0.1.212 - 2026-10-29 +目标提交:72ea9726e7073d5c4cbb8b459cfef0cd1c48e38d + +### Fixed +- **fix(library): 维护窗口起始时间只属于本次占用** +acquired_at 没进 ON CONFLICT DO UPDATE,于是第一次建立基线写下的时间再也不会变: +恢复作业 16:59 才开窗口,页面却显示 13:37。库级与实例级是两份 SQL,都要改成 +"同一作业重入(崩溃接管)保留旧值,新作业接管用本次时间"。 + +真实 PostgreSQL 用例覆盖两者:首开、同作业重入、释放后新作业接管、持有期间他人被拒。 + +改动范围:`internal/platform/postgres/library_instance_maintenance.go`、`internal/platform/postgres/library_maintenance.go`、`internal/platform/postgres/library_maintenance_window_integration_test.go` +统计:3 个文件,+121/-0。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/library_maintenance_window_integration_test.go` + +## 开发快照 snapshot/v0.1.211 - 2026-10-29 +目标提交:168fc2ecb7427140233825460c3a9897b4677ed3 + +### Fixed +- **fix(release): 对象存储四个入口共用同一定位符解析** +真实资源路径是 storage:///:///。Open/Put 用 +validObjectKey 并拆出裸 key,而 Stat/Delete/Copy 用只认单层的 validObjectLocator +且把整串当对象键——对象在桶里却校验读不到。集成用例只喂裸 key,把这条不一致 +藏了过去;写集合用例里那句"读不到也算通过"同样把断言关掉了。 + +现在四个入口共用 validObjectKey + providerPathFromLocator;集成用例喂真实定位符, +负例覆盖键不存在 / provider 不符 / 路径穿越 / 复制源不存在,并验证 Delete 后再读必失败。 + +改动范围:`internal/releaseadapter/v071/s3_object_store.go`、`internal/releaseadapter/v071/library_writeset_integration_test.go`、`internal/releaseadapter/v071/s3_object_store_integration_test.go` +统计:3 个文件,+108/-28。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/library_writeset_integration_test.go`、`internal/releaseadapter/v071/s3_object_store_integration_test.go` + +## 开发快照 snapshot/v0.1.210 - 2026-10-29 +目标提交:f0f5571518bd644429da4fa3148219da2e0e1042 + +### Fixed +- **fix(worker): 写集合预检经包装层转发,缺失即拒写** +orchestrator 用 target.(WriteSetPlanner) 决定要不要在写第一笔之前算写集合, +而 contentTrackedTarget 只转发了 Current/Apply/Verify/Restore,断言恒为假, +台账既不落盘也不登记。真实现场:10-29 两次真作业的预备份证据里没有 +writeset_digest,归档根下没有 writesets/,崩溃接管必然无台账可读。 + +现在包装层显式转发;内层不支持预检时返回硬错误,不退回"没有台账也照写"。 +用例断言包装后仍实现 WriteSetPlanner,并覆盖"内层不支持"的硬错误。 + +改动范围:`cmd/worker/library_handlers.go`、`cmd/worker/library_writeset_test.go` +统计:2 个文件,+65/-0。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_writeset_test.go` + +## 开发快照 snapshot/v0.1.209 - 2026-10-29 +目标提交:a0a7a266394557e338860eb8b272349ee44bfc4c + +### Tests +- **test(library): 写集合锚点与接管加载的单测** +治理侧的摘要登记与取回原先只能连真实治理库验证,等于没有负例。这里把"列版本" +抽成一个最小接口(真实 store 原样满足),并为三个判据补单测:预备份原有证据必须 +保留、摘要必须按"作业+目标+预备份"三者匹配才能取回、接管时没有写集合必须失败。 + +本地验证:go test ./cmd/worker/ -run 'WriteSet|LedgerBackup' 4 项通过; +go vet ./cmd/worker/ 无输出。 + +改动范围:`cmd/worker/library_writeset.go`、`cmd/worker/library_writeset_test.go` +统计:2 个文件,+177/-17。 + +## 开发快照 snapshot/v0.1.208 - 2026-10-29 +目标提交:e0768f2caadb3359b680586b9355157f20987062 + +### Fixed +- **fix(library): 写集合台账与跨范围冲突预检** +失败恢复会在写完之后按"目标租户里没人引用"清理资源行,于是历史孤儿、同租户其它 +知识库暂未绑定的资源、被共享的资源都可能被删掉;而预备份里没有这些行,删了不可 +恢复,随后整实例指纹才发现不一致,只能停在 rollback_failed。恢复校验依赖的整实例 +证据又只存在内存里,worker 重启后只按快照 id 恢复,等于静默跳过比对。 + +改法:写第一笔之前把"本次明确写集合 + 写前存在状态 + 预备份时刻整实例内容证据" +算出来并按内容寻址落盘(文件名与治理库里的引用都是 sha256),摘要登记在预备份 +版本证据里;恢复只删"写前不存在 ∧ 由本次写入 ∧ 不在恢复内容里"的精确 ID,并对 +资源额外要求仍无绑定/正文引用;缺记录、记录被改、绑定对不上都直接失败、维护保持。 +resources 的 upsert 补租户限定,跨范围同 ID 在写入之前就被预检拒绝。 +整实例指纹从"身份集合"改成"逐行内容摘要",别的知识库同 ID 行被覆盖写坏也会暴露。 + +本地验证(已跑): +- make verify 15 项全 success(identity 因本地档案 skipped) +- go test ./internal/releaseadapter/v071/ -run Isolated(真实 PG + 真实 ES + + 真实 MinIO 对象存储,写失败按定位符注入):目标非空/同租户其它知识库/共享资源/ + 历史孤儿/跨租户数据在失败恢复后逐行字节不变、本次残留 0;缺写集合拒绝恢复; + 跨范围 ID 冲突在写入前拒绝;wiki 阶段半写回滚干净 +- SIGKILL 子进程后按盘上写集合接管恢复,目标原有数据逐行不变 +- go test ./internal/libraryrelease/:写集合先于第一笔、规划失败/登记失败都不写目标、 + 接管不重新规划 + +改动范围:`cmd/librarydrill/main.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_recovery.go`、`cmd/worker/library_writeset.go`、`internal/libraryrelease/release.go`、`internal/libraryrelease/writeset.go` 等 16 个 +统计:16 个文件,+2103/-99。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryrelease/release_test.go`、`internal/libraryrelease/writeset_test.go`、`internal/releaseadapter/v071/library_export_integration_test.go`、`internal/releaseadapter/v071/library_production_target_integration_test.go` 等 6 个 + +## 开发快照 snapshot/v0.1.207 - 2026-10-29 +目标提交:034c0b3a1c0b9fc5884750cc0d9929c0df4ac314 + +### Changed +- **Merge pull request #13:跨源同步按目标范围改写并校验残留** +第一父 `0ef79846…` → 本合并 `034c0b3a…`:108 个文件,+10643/-548。第二父 +`5defe238…` 是功能提交;本合并的真实边界是集成该分支,不把分支历史重复算作新开发。 + +功能变化:跨源同步不再把归档行按来源 tenant/KB 原样写入目标,而是按目标范围改写 +身份并在写入后校验残留;范围覆盖 library 同步/恢复写入、HTTP 入口、CLI 诊断与集成测试。 +改动范围:`cmd/worker/library_baseline.go`、`cmd/worker/library_capture_identity.go`、 +`cmd/worker/library_finish.go`、`internal/httpapi/library_restore.go`、 +`cmd/libraryresidue/main.go`、`docs/library-capture.md` 等 108 个文件。 +统计:108 个文件,+10643/-548。 + +## 开发快照 snapshot/v0.1.206 - 2026-10-29 +目标提交:5defe238e0b992ab4d0037f63d04606d9e16cd2c + +### Fixed +- **fix(library): 跨范围同步按目标范围改写并校验残留** +真实事故:源 KB(10000/0c84a098) 同步到目标 KB(10001/e64e82b5) 时,归档行被原样 +插入目标库,落在来源租户/知识库;资源阶段随即报"生产缺少资源 ... 的存储路径" +(资源查询按目标租户过滤,看不见刚写进去的行)。回滚只按目标范围回放,于是页面 +报"已恢复到预备份",目标却多出 4 文件/38 分块/21 资源/4 绑定。 + +改: +- 写入与校验共用 retargetRow:tenant_id / knowledge_base_id / 资源定位符(后端、 + provider、桶、租户前缀) / storage_backend_id / provider / embedding_model_id + 统一映射到目标范围;行里的来源身份对不上就失败,宁可不写。 +- Verify 增加"本次写集合仍以来源身份残留"判定;Restore 增加整库指纹比对(预备份 + 时刻 vs 恢复后)与孤儿资源清理,回滚后用 Verify 复核,恢复工具退出 0 不再等于 + 恢复完成。 +- 新增 cmd/libraryresidue:按归档身份精确、可备份、可复核地清理已知的范围外残留。 + +验证:make verify 全绿;真实 PG+ES 用例复现"源目标 KB 不同 + 目标非空 + 资源阶段 +失败",断言回滚后无来源范围残留、其它租户行未动、恢复后内容=预备份;正向用例断言 +行落在目标范围且资源定位符指向目标存储。 + +改动范围:`cmd/libraryresidue/main.go`、`internal/libraryrelease/release.go`、`internal/releaseadapter/v071/library_backup_store.go`、`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/library_residue.go`、`internal/releaseadapter/v071/library_scope_remap.go` 等 11 个 +统计:11 个文件,+1588/-70。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryrelease/release_test.go`、`internal/releaseadapter/v071/library_production_target_integration_test.go`、`internal/releaseadapter/v071/library_scope_remap_test.go`、`internal/releaseadapter/v071/resource_locator_test.go` + +## 开发快照 snapshot/v0.1.205 - 2026-10-29 +目标提交:c27a0c14cc0a2a34f61b80e4a2d40994ba44ae2e + +### Fixed +- **fix(library): 基线契约读目标真实 schema/模型,演练标内容风险** +- **基线契约按"能验证的来源"填充**:归档要求完整的兼容性契约(v0.7.1 / schema 74 / + elasticsearch_v8 / 1024 维 / 映射摘要)。原先只填了 embedding 与映射,捕获会被 + `unsupported snapshot compatibility contract` 拒绝。现在 schema 版本**读目标库** + `schema_migrations`(dirty 或版本不符直接拒绝),embedding 优先读目标库模型绑定、 + 读不到才回落部署声明,映射取目标当前值,版本/引擎用受支持栈常量。 + +改动范围:`cmd/librarydrill/main.go`、`internal/librarystack/stack.go`、`CHANGELOG.md` +统计:3 个文件,+109/-14。 + +## 开发快照 snapshot/v0.1.204 - 2026-10-29 +目标提交:a42b101a7b50cadd70b9e369c32aaeb0311712ae + +### Fixed +- **fix(library): 基线崩溃续作与维护原状态保留** +- **基线作业"登记成功但没来得及收尾"不再被判死**:原来崩溃重入会在 + "已有生效版本"检查处直接失败,把目标留在维护里、占用也不释放。 + 现在按「本作业 + 同一快照」识别为**自己的**版本:只做收尾(恢复服务、开入口、 + 释放两把占用),不重新捕获、不重写版本;别人登记的生效版本仍然一律拒绝。 + 捕获完成但登记失败的作业会明确失败并写"未对目标写入",不会假装成功。 +- **同一作业重入不再覆盖第一次记下的原运行状态**:崩溃接管时目标已被停住, + 再读一次只会读到 `stopped`,写回去会让恢复阶段以为写入者本来就没跑、 + 永远不启动它。现在 `AcquireInstanceMaintenance` / `AcquireLibraryMaintenance` + 在 owner 相同的重入时保留已持久化的原状态;新作业接管已释放窗口仍用自己读到的值。 + (真实 PostgreSQL 集成用例覆盖,非内存假实现。) +- **基线的版本登记移进维护窗口**:捕获、校验、登记三件事要么一起成立、要么目标 + 原样恢复;记录失败时窗口已按原状态开放,治理记录同步释放,**不再出现 + "显示保持维护、实际入口已开"**。 +- **索引映射读不到时拒绝登记**:不再 `_` 忽略错误后用空摘要写进基线证据。 +- 基线窗口的统一收尾抽成 `settleBaselineWindow`:版本已登记走与同步相同的成功边界; + 窗口仍 held 才标 `needs_restore`;窗口已恢复则释放占用并失败。 + +- **`cmd/librarydrill`:目标实例真实恢复演练**(维护隔离 → 整库预备份 → 一致性校验 + → canary 漂移检测 → 按预备份恢复 → 逐类复核 → 按原状态恢复服务)。它使用与 + worker 完全相同的 `LIBRARY_*` 配置与维护协调器,绝不触碰封存源;任一步失败都 + 保持维护并写报告,不伪造通过。 +- `internal/librarystack`:目标/预备份/维护栈的唯一装配点(同步、恢复、基线、演练共用)。 + +- 基线作业的"已有生效版本"判定改为三种状态(own / foreign / none),并在 + 阶段里写明是否走"只收尾"续作。 + +改动范围:`cmd/librarydrill/main.go`、`cmd/worker/library_baseline.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_wiring.go`、`internal/httpapi/library_baseline.go`、`internal/httpapi/server.go` 等 15 个 +统计:15 个文件,+1103/-302。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_baseline_test.go`、`cmd/worker/library_finish_test.go`、`internal/httpapi/library_baseline_mutex_test.go`、`internal/platform/postgres/library_job_mutex_integration_test.go` 等 5 个 + +## 开发快照 snapshot/v0.1.203 - 2026-10-29 +目标提交:3284658eb1d5d64de8693f83732fb4ed3030293f + +### Changed +- **feat(web): 发布页接上签发同步授权与建立基线入口** +- **管理员在发布页签发同步授权(`POST /api/v1/library/authorizations`,`action=sync`)**: + 授权把「范围 + 目标快照 + 参数摘要 + 有效期」钉死,仍与执行分成两步 —— + 页面只提供入口,不会替你签发,也不会自动重试执行。工程师看得到缺项原因, + 但拿不到签发按钮(接口本来就只认管理员)。 +- **目标权威基线(迁移 075,作业类型 `baseline`)**:目标非空、又没有生效版本时, + 首次发布的真实解法是「维护隔离 → 整库捕获 → 逐类校验 → 登记基线」。 + `POST /api/v1/library/baselines` 只建作业;worker 用与同步同一套维护窗口 + (关入口、停写入者、证明排空)把目标整库捕获成归档快照,再用同一套 `Verify` + 证明目标与这份快照一致,最后登记 `production_effective`(证据写明 + `origin=target_baseline`、快照 ID、逐表行数、目标索引映射)。 + 它**不写目标内容、不清空目标、不手写版本**:没有捕获与校验证据就没有基线。 + 基线作业与 sync/restore 共用同一把写互斥(同一 scope 只允许一个在飞写作业), + worker 被杀时同一作业 id 会接管那个窗口继续,而不是把目标留在停机状态。 +- **维护能力(`GET /api/v1/library/maintenance` 的 `capability`)**:页面区分 + 「此刻没有维护窗口」与「维护能力没接线」,逐项列出缺少的 + `LIBRARY_TARGET_*`;接口没给能力信息时显示"未知",不再用一句 + "也没有维护能力配置"糊过去。 + +- **`productionScopeEmpty` 改成整库口径**:原来只数 `knowledges`,"文档删了但 + 分块/Wiki/资源还在"的目标会被判成空库,从而绕过基线初始化。现在用适配层 + 同一份表清单与范围过滤(`v071.ScopeContentEmpty`)逐表计数,并把逐表行数 + 交回接口,"空"只有一份定义。 +- **拟发布的测试封存只认版本登记(`kind=test_sealed`)**:归档里同时存在生产 + 预备份与目标基线快照,按"这个 scope 最新一份"挑会把目标自己的内容显示成 + 测试候选。现在候选来自登记、再用归档确认它还在本机;不在就说明原因。 +- **发布页不再说"生产同步执行链尚未接线"**:同步按钮按真实闸口启用, + 点击走 `POST /api/v1/library/syncs`;被拒时逐条显示接口返回的缺项。 +- 缺项文案从"生产当前权威版本未知,不能启动写入"改为指向真实入口: + 「目标非空且没有生效版本记录:先建立目标权威基线…或确认目标确实是空库」。 + +- 维护卡片把"没有窗口记录"错误地写成"没有维护能力配置",与实际接线不符。 +- 首次发布时 `POST /library/baselines` 在目标读不到时**不建作业、不登记版本** + (拒绝用建基线掩盖连接/配置故障)。 + +改动范围:`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx`、`web/src/librarySnapshots.ts`、`web/src/librarySyncAuth.test.ts`、`CHANGELOG.md` +统计:5 个文件,+460/-13。 + +## 开发快照 snapshot/v0.1.202 - 2026-10-29 +目标提交:517d5f862df92230c494ae3bdeddd06021810a9e + +### Changed +- **feat(library): 首次发布接上目标权威基线与整库空判定** +目标非空又没有生效版本时,首次发布以前只能停在"权威版本未知"。现在有了 +真实入口:管理员发起 baseline 作业,worker 在维护隔离下把目标整库捕获成 +归档快照,再用同一套 Verify 证明目标与快照逐类一致,最后登记 +production_effective(证据写明 origin=target_baseline、快照 ID、逐表行数、 +目标索引映射)。不写目标内容、不清空目标、不手写版本。 + +同时修两处会误导人的判定: +- productionScopeEmpty 原来只数 knowledges,"文档删了但分块/Wiki/资源还在" + 的目标会被当成空库;改用适配层同一份表清单与范围过滤逐表计数。 +- 概览里的"测试封存候选"原来取该 scope 最新一份归档,而归档里还有生产 + 预备份与目标基线快照;改为只认版本登记里 kind=test_sealed 的那一份。 + +迁移 075 放开 kind='baseline' 并把它并入 sync/restore 的写互斥索引; +worker 重启时用同一作业 id 接管未完成的基线窗口。维护接口补 capability, +页面才能区分"未运行维护"与"维护能力没接线"。 + +验证:go build ./... / go vet ./... 通过;新增用例覆盖管理员校验、已有生效 +版本拒绝、目标读不到时零作业零版本、候选来自登记、缺项文案指向基线入口、 +capability 逐项缺失;反向自检(把候选改回按最新归档取、把文案改回旧句、 +去掉管理员判断)三项均按预期变红后复原。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`cmd/worker/library_baseline.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_wiring.go`、`cmd/worker/main.go` 等 16 个 +统计:16 个文件,+903/-59。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_baseline_test.go`、`internal/platform/postgres/migrations_test.go` + +## 开发快照 snapshot/v0.1.201 - 2026-10-29 +目标提交:f9c15a8f14353865258fd1c4bba19c9df5f621df + +### Fixed +- **fix(web): 存储提示改为实际能力** +页面仍写"保留策略与清理在系统设置→存储管理,均未接线",但存储与备份已有只读 +去重/保护范围/预览。改为说明可查看什么、什么尚未开放。 + +改动范围:`web/src/ReleaseTargets.tsx` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.200 - 2026-10-29 +目标提交:271f9f5f0992d03e409affe0f1fd91326fa33f5e + +### Docs +- **docs: 台账补记 0.1.198–0.1.199** +记录接管分类与维护释放幂等的真实 SHA、CI run(236)与候选栈身份注入后 +/api/v1/build-info 的读回结果。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+2/-0。 + +## 开发快照 snapshot/v0.1.199 - 2026-10-29 +目标提交:24d2546cbb99e2d5d1d8e126a1bf5d06af9ee457 + +### Fixed +- **fix(library): 接管不再把版本查询失败当成没有收尾证据** +- **接管在版本查询失败时 fail-open**:`resumed` 后版本查询出错被忽略、`FinalizeOnly` 仍为 + false,于是"已成功登记并释放窗口、只差终态"的作业会被**重新写一遍目标**。现在接管先按 + 证据分类:`finalize` 阶段成功是独立证据(不受版本查询影响);查询失败且无阶段证据 ⇒ + **未知**,零写入、作业失败可重试;本快照的生效版本已被别的快照顶替 ⇒ **拒绝覆盖**; + 只有真正没有收尾证据时才按正常流程。 +- **维护释放部分成功后的重试不再永久卡死**:`Update*/Release*` 对"已由本作业释放"的行 + 返回可判别的 `ErrMaintenanceReleased`,收尾重试视其为已完成;别的作业来释放仍是 + "未持有"错误。真 PG 负例:同作业重复 Update/Release 得到已释放,跨作业得到未持有。 + +改动范围:`cmd/worker/library_finish.go`、`cmd/worker/library_handlers.go`、`internal/platform/postgres/library_instance_maintenance.go`、`internal/platform/postgres/library_maintenance.go`、`CHANGELOG.md`、`cmd/worker/library_finish_test.go` +统计:6 个文件,+186/-41。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_finish_test.go` + +## 开发快照 snapshot/v0.1.198 - 2026-10-29 +目标提交:691e4e0225b8b2b861be80a58a134158c81603ee + +### Docs +- **docs: 台账补记 0.1.195–0.1.197** +记录 R1 身份契约、封存资源诊断与 R4 成功边界三个提交的真实 SHA 与 CI run, +标明候选栈 clean 构建(vcs.modified=false)与真实验收覆盖范围。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+4/-0。 + +## 开发快照 snapshot/v0.1.197 - 2026-10-29 +目标提交:8d2ed8ebe61fcf5ef9a5e1b25923e6456c52c5c8 + +### Fixed +- **fix(library): 维护释放与服务恢复完成之后才暴露作业成功** +- **作业成功暴露早于维护结束**:原来 `execute` 里写完生效版本就 `AdvanceLibraryJob(succeeded)`, + 而服务恢复、入口开放与维护锁释放要在窗口返回后才做。任何一步失败时外部已经看到 + `succeeded`,重启接管又只认非终态,锁就永远挂着。现在内容校验/版本登记之后只记 + "待收尾",`finishLibrarySuccess` 依次确认目标写入者与入口健康、按 **scope → instance** + 顺序释放两把锁(每一步错误都上抛,不再丢弃),最后才写 `succeeded`;任一步失败都把 + 作业落成失败、维护保持 `needs_restore`。释放与终态写入用 `context.WithoutCancel` + 包住,停机不会留下半成品。接管判定改为按证据(finalize 阶段成功或存在未顶掉的生效 + 版本)转 finalize-only,只复核与登记,不重写生产。 + +改动范围:`cmd/worker/library_finish.go`、`cmd/worker/library_handlers.go`、`CHANGELOG.md`、`cmd/worker/library_finish_test.go` +统计:4 个文件,+308/-25。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_finish_test.go` + +## 开发快照 snapshot/v0.1.196 - 2026-10-29 +目标提交:c14dd01f08ca1d7a5fccbe5ffdc0b69ed3463962 + +### Fixed +- **fix(library): 封存读资源失败带上资源行与底层原因** +- **封存读资源失败只剩一句 `read library resource`**:对象缺失、桶错、端点解析不到 + 都会走到同一个字符串,真实封存直接卡在这里无法判断方向。现在带上资源行 id 与底层 + 原因(`read library resource : `),不含凭据。 + +改动范围:`internal/releaseadapter/v071/library_archive.go`、`CHANGELOG.md` +统计:2 个文件,+7/-1。 + +## 开发快照 snapshot/v0.1.195 - 2026-10-29 +目标提交:6ed06357f9a0fa7787796beb149d053407a6b3eb + +### Fixed +- **fix(library): 期望执行器身份随 capture 请求送达并在执行前核对** +- **封存身份核对移进请求本身(TOCTOU)**:原来 worker 先 `health` 再 `capture`,两次 + 拨号之间 socket 可能被换成另一个 agent——错的执行器已经把写入者停了才被拒登记。 + 现在 `capture` 请求携带治理侧配置生成的期望身份(`project` 必填,`source_app`/ + `archive_root` 配了就一起绑定)与稳定指纹(`sha256:`,覆盖三项);接收方在**操作 + 互斥内、执行任何源操作之前**比对,缺失或被改过一律拒绝,错的执行器一次 `capture` + 都不跑。封存结果回显该指纹,worker 事后复核只作为证据防线,不能替代请求内核对。 + 恢复路径不受期望约束(它只把写入者恢复回来)。 + +改动范围:`cmd/worker/library_capture_identity.go`、`cmd/worker/main.go`、`internal/appconfig/config.go`、`internal/libraryagent/agent.go`、`internal/libraryagent/client.go`、`internal/libraryagent/expectation.go` 等 12 个 +统计:12 个文件,+382/-161。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_capture_identity_test.go`、`internal/libraryagent/agent_test.go`、`internal/libraryagent/health_test.go`、`internal/libraryagent/swap_test.go` + +## 开发快照 snapshot/v0.1.194 - 2026-10-29 +目标提交:5d42cba6c628fa32dc41caa05d3580e4d1924c45 + +### Docs +- **docs: 执行器证据绑定到确切代码 SHA 而不是版本号** +矩阵里写"0.1.187 构建"会与台账的版本号漂移;改成代码 SHA 4c79052(0.1.192 工作树), +与候选二进制来源一致。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/library-acceptance-matrix.md` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.193 - 2026-10-29 +目标提交:a47f9323e060074d90eb1a3db53d826711e81ba5 + +### Docs +- **docs: 台账补记执行器可用性与还原入口(0.1.188–0.1.192)** +记录真实 SHA、CI run 229(head 4c79052,必需 context success)、候选栈二进制来源与 +回退目录。代码 SHA 与已部署候选产物分开写,不把文档提交当成部署证据。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+11/-0。 + +## 开发快照 snapshot/v0.1.192 - 2026-10-29 +目标提交:4c79052a189ad2be3892498905774d77fc40a67e + +### Tests +- **test(release-worker): 测试 DSN 改为拼接构造避免密钥扫描误报** +完整带口令的 URL 出现在源码里会被 security-secrets 判红(测试值也一样)。 +按既有做法把连接串拆开拼接,语义不变。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`cmd/release-worker/diagnosis_test.go` +统计:1 个文件,+5/-4。 + +## 开发快照 snapshot/v0.1.191 - 2026-10-29 +目标提交:18276d0839ce44b4fbf36675ced45884ab379cae + +### Docs +- **docs: 按用户决定收窄整库还原范围并记录执行器证据** +- **封存执行器的运行时可用性(迁移 074 `library_executor_status`)**:页面上的 + "可以发起封存"不再等于 `LIBRARY_AGENT_SOCKET` 非空。主机侧 agent 新增 + `health` 动作(不占封存操作锁、不跑子进程),worker 每 30 秒探测一次并把 + "指向哪个实例、归档在哪、是否降级/正在跑、观测时间"落库;API 只读这份观测。 + socket 只挂在 worker 容器里,所以由 worker 观测、页面读结果,而不是让 API + 假装能 dial。观测过期、不可达、实例不符、降级、正忙时页面与 + `POST /library/captures` 用同一份判定拒绝,并逐条给出原因。 +- **封存执行前后的身份复核**:封存结果由 agent 附上自报身份(`agent_identity`)。 + worker 在停写入者之前再探测一次,执行后再用结果里的身份复核;不一致时作业失败 + 且**不登记**为测试封存——心跳只能证明"刚才",从心跳到停写入者之间 socket + 可能被换掉。 +- **按版本恢复的页面入口**:`GET /api/v1/library/restore-availability` 说明 + "这份快照现在能不能恢复"(双闸、该快照的恢复授权、目标实例是否在维护)。 + 页面据此启用"恢复至该版本",管理员可签发 30 分钟有效期的 restore 授权; + 工程师只看到条件,不获得入口。 +- 可选 `LIBRARY_SOURCE_PROJECT`:声明封存执行器应指向的实例名(默认等于 + `LIBRARY_SOURCE_INSTANCE`)。它描述封存源,与同步目标 `LIBRARY_TARGET_*` 分开。 + +- `LIBRARY_EXECUTOR_STATUS_MAX_AGE`(默认 120 秒)控制执行器观测的有效期; + 未设置不等于"永不过期",过期即"无法确认"。 +- 页面/接口不再出现写死的"封存通道未接线""生产恢复未接线":不能发起时给出真实原因、 + 执行器身份与观测时间。 + +- **正式 release-worker 启动失败无法定位**:配置里的目标库指向不存在的主机时, + 日志只有一句 `connect release target database`。现在错误里带库端点 + (`host:port/db`,去口令)与路由标识,并保留底层原因;原因文本先经 + `pgdsn.Redact` 抹掉口令(pgx 的解析错误可能原样回显连接串),可诊断不等于泄露。 + 共享的 `internal/pgdsn` 替换了 cmd/worker 里只留库名的旧实现。 +- `libraryctl` 用法文本补上 `dead-letters` 子命令。 + +改动范围:`CHANGELOG.md`、`docs/library-acceptance-matrix.md` +统计:2 个文件,+65/-5。 + +## 开发快照 snapshot/v0.1.189 - 2026-10-29 +目标提交:c40696145b43a47ea0cef6d83ae2fbe00bb3677f + +### Changed +- **feat(library-web): 恢复入口按真实条件启用并支持签发恢复授权** +原来"恢复至该版本"写死 disabled,标题还写"生产恢复未接线"——而 POST /library/restores +与授权接口早已可用,等于把整库还原的唯一入口藏起来。 + +现在页面按 GET /library/restore-availability 启用:缺授权时管理员可签发 30 分钟 +有效期的 restore 授权(固定期限,没有"永久授权"),条件满足才可点恢复;工程师只看到 +条件与"仅管理员可发起"。封存不可发起时也不再写死"通道未接线",而是显示接口原因、 +执行器身份与观测时间。 + +改动范围:`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx`、`web/src/libraryRestore.test.ts`、`web/src/librarySnapshots.ts` +统计:4 个文件,+433/-14。 + +## 开发快照 snapshot/v0.1.190 - 2026-10-29 +目标提交:cfad0034995de0fdd4a437de336502dc574fb0b3 + +### Fixed +- **fix(release-worker): 启动失败带端点与脱敏原因** +正式 release-worker 崩溃重启时日志只有一句 connect release target database, +主机名、库名和底层原因都不在里面。现在错误里带 host:port/db、路由标识与原因。 + +端点去口令不等于整条日志安全:pgx 的解析错误可能原样回显连接串。新增 +internal/pgdsn.Redact(按已知口令精确替换 + 按 URL/keyword 形状兜底), +错误保留 Unwrap 以便 errors.Is/As,技术原因不丢。cmd/worker 里只留库名的旧实现 +换成同一个包,避免两份脱敏逻辑。libraryctl 用法补上 dead-letters。 + +改动范围:`cmd/libraryctl/main.go`、`cmd/release-worker/runtime.go`、`cmd/worker/library_handlers.go`、`internal/pgdsn/dsn.go`、`cmd/release-worker/diagnosis_test.go`、`internal/pgdsn/dsn_test.go` +统计:6 个文件,+267/-4。 + +### Tests +本次提交包含测试/夹具变更:`cmd/release-worker/diagnosis_test.go`、`internal/pgdsn/dsn_test.go` + +## 开发快照 snapshot/v0.1.188 - 2026-10-29 +目标提交:47eb23cf6873e3c3487ef3b07cbfd547e43dd5f9 + +### Changed +- **feat(library): 封存执行器可用性与还原条件来自真实观测** +页面上的"可发起封存"原来只判 LIBRARY_AGENT_SOCKET 非空:正式栈的 API 根本没挂 +那个 socket,而 agent 曾顶着正式单元名冻结候选实例——配置非空、页面可点、真发起 +却封错库。 + +现在:agent 新增 health 动作(不占封存操作锁、不跑子进程,只回答身份/降级/忙), +worker 每 30 秒探测并写入迁移 074 的 library_executor_status;overview、快照列表与 +POST /library/captures 共用同一份判定(过期、不可达、实例不符、降级、正忙都拒绝并 +给原因)。封存结果由 agent 附上自报身份,worker 在停写入者之前再探测一次、执行后 +用结果复核,不一致就不登记测试封存——心跳只能证明"刚才"。 + +期望身份用 LIBRARY_SOURCE_*(封存源),不是 LIBRARY_TARGET_*(同步目标),否则 +正确的执行器会被判成不匹配。另加 GET /library/restore-availability:恢复能否执行由 +双闸、该快照的恢复授权与实例维护状态决定,页面不再写死 disabled。 + +真跑(候选隔离栈,两处 socket 隔离不变):overview 返回 executor +{kgmaint-weknora/kgmaint-app};停 agent 后转不可达并 503 带原因;重启后恢复。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`cmd/worker/library_capture_identity.go`、`cmd/worker/library_executor_status.go`、`cmd/worker/main.go`、`internal/appconfig/config.go` 等 26 个 +统计:26 个文件,+1350/-112。 + +### Tests +本次提交包含测试/夹具变更:`cmd/worker/library_capture_identity_test.go`、`internal/httpapi/library_capture_test.go`、`internal/httpapi/library_executor_test.go`、`internal/httpapi/server_test.go` 等 8 个 + +## 开发快照 snapshot/v0.1.187 - 2026-10-28 +目标提交:a06945516fe8de5a41c0bc7ae765627d536fb02d + +### Docs +- **docs(acceptance): V03 撤销语义不通过,补 B02/V05/死信实测** +按父审后重跑的真实结果改写验收矩阵:V03-a 单列"失败/不通过"(共享页正文仍带 +撤销方独有事实);V05 并发阻断、B02 删源对象后目标应用读回、死信精确解除的 +"已做/未演练"分开放;记 R03 实测耗时与正式栈 socket 风险;台账补 0.1.181–0.1.186 +与 run 222–227。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/library-acceptance-matrix.md`、`docs/release-ledger.md` +统计:2 个文件,+46/-10。 + +## 开发快照 snapshot/v0.1.186 - 2026-10-28 +目标提交:e508abd958834d93515e86add2fa2e89a5b09e4c + +### Fixed +- **fix(library): 死信解除绑定封存源实例而不是同步目标** +- 死信解除绑定 `LIBRARY_SOURCE_INSTANCE`(封存源),留空回落到 `LIBRARY_TARGET_INSTANCE`: + 同步目标与封存源常常不是同一个实例,用目标名去绑来源死信会让真实观测永远对不上 + (拒绝而不是误放行)。worker 取指纹、API 写记录用同一个来源实例名。 + +改动范围:`cmd/api/main.go`、`cmd/worker/main.go`、`internal/appconfig/config.go`、`internal/httpapi/library_deadletters.go`、`internal/httpapi/server.go`、`CHANGELOG.md` +统计:6 个文件,+31/-3。 + +## 开发快照 snapshot/v0.1.185 - 2026-10-28 +目标提交:c542a1333a869cfe1c8ef855c8e22640a9607419 + +### Fixed +- **fix(library): 资源行的存储后端列也改到目标实例** +- **同步过去的资源行指向来源实例的存储后端 id(定位符与独立列两处)**:`storage:///minio:///` + `resources.storage_backend_id` 这一列同样要换(应用先按它找文件服务)。 + +改动范围:`internal/releaseadapter/v071/library_production_target.go`、`CHANGELOG.md`、`internal/releaseadapter/v071/resource_locator_test.go` +统计:3 个文件,+38/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/resource_locator_test.go` + +## 开发快照 snapshot/v0.1.184 - 2026-10-28 +目标提交:1aecd9d6af0e2f7e8da6710f9bc73711ecb76e81 + +### Fixed +- **fix(library): 资源定位符同时改到目标存储后端** +- **同步过去的资源行指向来源实例的存储后端 id**:`storage:///minio:///` + 里的 `` 是来源 `storage_backends` 的主键,目标实例没有这条行。只换桶不改 id 时, + 原版应用落回默认存储服务并拒绝整条路径(真实下载 500 `code 1007 + invalid MinIO file path`)。现在写入前按"租户 + 目标桶名"在目标库解析后端 id, + 写入与校验共用同一份行变换;解析不到就拒绝写入,不产出目标读不出来的定位符。 + +改动范围:`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/object_import.go`、`CHANGELOG.md`、`internal/releaseadapter/v071/resource_locator_test.go` +统计:4 个文件,+103/-5。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/resource_locator_test.go` + +## 开发快照 snapshot/v0.1.183 - 2026-10-28 +目标提交:c2402947a96e19b26279c8f93168d7b67c87d3eb + +### Changed +- **feat(library): 死信按精确指纹解除,保留上游记录** +- **死信解除契约(治理侧)**:上游 `task_dead_letters` 没有"已解决"标记, + purge/DELETE 都会销毁"这条任务失败过"的唯一证据。新增 + `library_dead_letter_releases`(迁移 073)记录**一条精确死信**的解除:绑定实时行 + 逐字节指纹(`sha256(to_jsonb(row))`,先压紧空白)、重放引用(队列/任务号/时间/ + 证据引用)、源侧观测摘要、操作人与时间。上游行一个字节都不动。 +- `GET/POST /api/v1/library/dead-letter-releases`:POST 需工程师及以上 + + `X-Governance-Action: dead-letter-release`,拒绝条件全部显式——观测摘要不符(被 + 改写/格式化)、源侧未结清、观测里没有这条死信(已被删除)、重放早于失败时间、 + 重放之后同一任务键又出现新死信(说明重放没成功)、实例不一致。 +- `libraryctl dead-letters`(只读):打印整库死信原始行 + 结算计数 + 观测摘要, + 供治理平台绑定;平台自己不连源库、不复制"自报成功"。 + +- 结算/封存不再"死信存在即阻断",而是"每条实时死信都要被精确解除命中": + `checkLibrarySourceSettlementReleased` / `ExportLibraryWithReleases` 对每条行 + 重算指纹,未命中、行被改过、出现新行都继续阻断并点名。 +- 解除指纹经 worker → agent → `libraryctl -released-dead-letters` 逐段校验 + (`sha256:<64 hex>`,最多 64 条,不接受通配),agent 的固定命令形态不变。 + +- 指纹对空白敏感会让"同一份内容"两边算不出同一个值(PostgreSQL `to_jsonb::text` + 带空格、Go `json.Marshal` 不带);指纹改为先 `json.Compact` 再摘要。 + +改动范围:`api/openapi.yaml`、`cmd/libraryctl/main.go`、`cmd/worker/main.go`、`internal/governance/library_flow.go`、`internal/httpapi/library_deadletters.go`、`internal/httpapi/server.go` 等 22 个 +统计:22 个文件,+1267/-23。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_deadletters_test.go`、`internal/libraryagent/agent_test.go`、`internal/librarydeadletter/deadletter_test.go`、`internal/platform/postgres/migrations_test.go` 等 5 个 + +## 开发快照 snapshot/v0.1.182 - 2026-10-28 +目标提交:958292d1ff2246b39c43bfe7d93e2b15e407bf6f + +### Docs +- **docs(ledger): 按实际运行的二进制记封存闭环时序** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+3/-2。 + +## 开发快照 snapshot/v0.1.181 - 2026-10-28 +目标提交:bc49b85b5627b5947b87d96df2089b444fd4df75 + +### Docs +- **docs(acceptance): 封存闭环进"已完成",补死信最小外部契约** +- 矩阵:新增 S06/S06-a/S06-b/V03-c/Neo4j 拒绝行(都有真跑证据);把"封存入口未接线"、 + "CLI 库级窗口"从缺口里移走;排空时序旧结论保留但标注被确定性做法取代。 +- 死信解除仍缺产品路径,写出最小外部治理契约(保留原始行、审计、验证真实处理成功后 + 按精确项解除、未解除继续阻断)。 +- 台账补 0.1.169–0.1.180 的 SHA 与 run(含 211/215 failure、218 cancelled,不涂改)。 +- library-capture / 8088 部署方案同步成本轮真实结果。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/formal-8088-deployment-plan.md`、`docs/library-acceptance-matrix.md`、`docs/library-capture.md`、`docs/release-ledger.md` +统计:4 个文件,+43/-11。 + +## 开发快照 snapshot/v0.1.180 - 2026-10-28 +目标提交:a6406209bd2a4a037ba5804bdaae8f78d255bbbb + +### Fixed +- **fix(httpapi): 恢复作业 id 改成维护窗口可接受的形状** +- **恢复作业 id 让维护窗口拒绝**:`librestore--<时间戳.微秒>` 带 `.`,而冻结协调器 + 只接受 `[A-Za-z0-9_-]`,每次恢复都在开窗口时被拒(`invalid freeze request`),作业随后被 + 接管扫成失败。改用纳秒整数,并加测试锁住"id 必须是维护窗口可接受的标识"。 + +- `internal/httpapi/library_restore_test.go`:恢复作业 id 必须能被维护窗口接受。 + +改动范围:`internal/httpapi/library_restore.go`、`CHANGELOG.md`、`internal/httpapi/library_restore_test.go` +统计:3 个文件,+39/-2。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_restore_test.go` + +## 开发快照 snapshot/v0.1.179 - 2026-10-28 +目标提交:b061a9686c636bb8d92419907f68fd3703baf678 + +### Fixed +- **fix(v071): 资源换桶的变换在校验时同用** +只改写入侧会让"行内容摘要"对不上:校验拿变换前的归档行与目标里的变换后行比较, +真实同步在 verify 阶段报"生产 resources 内容与快照不一致"并回滚。 +把行变换抽成 rowTransform,写入与校验共用同一份。 + +试过:make verify 15 项全绿;真实同步复现该失败后修复(下一轮重跑验证)。 + +改动范围:`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/library_verify_content.go` +统计:2 个文件,+47/-22。 + +## 开发快照 snapshot/v0.1.178 - 2026-10-28 +目标提交:2e39e495694a4d7f69273a4704ea1eb2ad9675fc + +### Changed +- **chore: 移出一次性核对小工具(不留在仓库里)** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`_s3get/main.go` +统计:1 个文件,+0/-45。 + +## 开发快照 snapshot/v0.1.177 - 2026-10-28 +目标提交:cb0090802b51dba5de2b72af8c9c348e18d80369 + +### Fixed +- **fix(v071): 同步资源行时把定位符的桶换成目标桶** +- **资源定位符的桶没有跟着换**:同步把字节写进目标桶,但 `resources.physical_path` + 是从快照原样搬的,里面仍写着来源桶(`storage://…/minio://kgmaint-1028a/…`)。 + 目标实例之后取图/附件会指向测试环境的桶,或直接取不到。现在写入前把定位符里的桶 + 换成本次目标桶(键不变),解析不出来就报错而不是写一行指向别处的资源。 + +- `internal/releaseadapter/v071/resource_locator_test.go`:嵌套/单层两种定位符换桶、裸键原样、 + 非法形状拒绝。 + +改动范围:`_s3get/main.go`、`cmd/worker/library_wiring.go`、`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/object_import.go`、`CHANGELOG.md`、`internal/releaseadapter/v071/resource_locator_test.go` +统计:6 个文件,+161/-2。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/resource_locator_test.go` + +## 开发快照 snapshot/v0.1.176 - 2026-10-28 +目标提交:7d4ffdbfe5feb2d36f8ea5aa92009b57891086e2 + +### Fixed +- **fix(v071): 全新目标实例的空索引按空基线处理** +- **空目标索引不能当成"索引被改坏"**:全新 WeKnora 实例先用空映射建索引(`{}`), + 字段等第一次写入才动态生成;首次同步因此在读取目标状态时就失败。现在"没有范围字段 + + 确实 0 篇文档"按空基线处理,有文档却看不出归属仍然报错。 + +- `internal/releaseadapter/v071/search_empty_index_test.go`:空索引=空基线、有文档无范围字段必须报错。 + +改动范围:`internal/releaseadapter/v071/library_search.go`、`internal/releaseadapter/v071/search.go`、`internal/releaseadapter/v071/search_write.go`、`CHANGELOG.md`、`internal/releaseadapter/v071/search_empty_index_test.go` +统计:5 个文件,+109/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/search_empty_index_test.go` + +## 开发快照 snapshot/v0.1.175 - 2026-10-28 +目标提交:84e8a0dfdcaf4fe42e650ebbb00b839e97f9b83c + +### Changed +- **style(libraryagent): gofmt** +上一个提交漏跑 gofmt,本地门禁 format 失败;只改空白。 + +改动范围:`internal/libraryagent/agent.go` +统计:1 个文件,+8/-8。 + +## 开发快照 snapshot/v0.1.174 - 2026-10-28 +目标提交:faaf003707d17dd8550d3be5c98f4cf3c2420e82 + +### Fixed +- **fix(libraryagent): 把宿主侧对象存储端点纳入固定命令形态** +上一提交只给 libraryctl 加了 -source-s3-endpoint,agent 却不知道这个 flag, +systemd 起不来(exit 2)。端点属于"这台主机怎么访问这个源的存储",必须由 agent +自己钉住并随固定声明传给 libraryctl;请求仍然不能改。没配置时不凭空加 flag。 + +试过:make verify 15 项全绿;新增 agent 声明用例(有端点必传、无端点不多传)。 + +改动范围:`cmd/libraryagent/main.go`、`internal/libraryagent/agent.go`、`internal/libraryagent/agent_test.go` +统计:3 个文件,+55/-2。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryagent/agent_test.go` + +## 开发快照 snapshot/v0.1.173 - 2026-10-28 +目标提交:4d6ecda3102e9f3d93d828a2ca8aa99d29669750 + +### Changed +- **feat(libraryctl): 源对象存储端点可按宿主机地址覆盖** +- 主机侧封存新增 `-source-s3-endpoint`:容器里的对象存储端点常常只是服务名 + (`langfuse-minio:9000`),宿主机解析不到,资源导出会失败(真跑报 `read library resource`)。 + 覆盖只换访问入口,桶/对象键不变;`status` 如实打印实际 endpoint。 +- **封存 API 的队列作业 id 超列宽**:`library-capture--` 是 45 字符,而 + `jobs.id` 是 `varchar(36)`,真实请求一律 500(`value too long`)。此前页面停在"未接线" + 从未走到这里;改为 `libcap--` 并用测试锁住列宽。 +- **索引范围过滤漏掉 app 写入的正文**:v0.7.1 的 app 自己写索引不带 `tenant_id`, + 治理侧同步才补齐;只按 `term tenant_id` 过滤会把整库正文漏掉(真跑:索引有 2 条、 + 导出 0 条、候选校验报 legacy coverage)。改为"本租户 或 未写租户",写了别的租户仍排除。 + +- `internal/httpapi/library_capture_test.go`:队列作业 id 必须放得进 `varchar(36)` 且形状固定。 +- `internal/releaseadapter/v071/search_tenant_filter_test.go`:接受未写租户、排除他租户、 + 无租户字段时不造条件、整库过滤仍带知识库身份。 +- `cmd/libraryctl/discover_test.go`:端点覆盖生效且必须带 scheme。 + +改动范围:`cmd/libraryctl/main.go`、`CHANGELOG.md`、`docs/library-capture.md`、`cmd/libraryctl/discover_test.go` +统计:4 个文件,+83/-25。 + +### Tests +本次提交包含测试/夹具变更:`cmd/libraryctl/discover_test.go` + +## 开发快照 snapshot/v0.1.172 - 2026-10-28 +目标提交:f2d6f3f64682680173ac8e697cb27e0f7bb73a24 + +### Fixed +- **fix(httpapi): 封存队列作业 id 按 jobs.id 列宽拼短** +真实请求 POST /api/v1/library/captures 一律 500:拼出来的 +"library-capture--" 是 45 个字符,而 jobs.id 是 varchar(36), +PG 直接拒绝(value too long)。此前页面一直停在"未接线",这条路径从没被 +真实请求覆盖过,所以只有接上 agent 之后才暴露。 + +改为 libcap--(35 字符),并用测试锁住列宽与形状。 + +试过:go test ./internal/httpapi -run LibraryCapture 全绿;修复前用真实 +DATABASE_URL 复现 enqueue error: value too long for type character varying(36)。 + +改动范围:`internal/httpapi/library_capture.go`、`internal/httpapi/library_capture_test.go` +统计:2 个文件,+25/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_capture_test.go` + +## 开发快照 snapshot/v0.1.171 - 2026-10-28 +目标提交:37a8370f7be519f327334adb913173bd9d41abed + +### Fixed +- **fix(v071): 索引范围过滤接受未写 tenant_id 的文档** +真实 v0.7.1 的 app 自己写索引时不带 tenant_id,治理侧同步写入时才补齐。 +原来只按 term tenant_id 过滤,等于把 app 写入的正文整库漏掉:真跑时索引里有 +2 条文档,导出 0 条,候选校验报 legacy coverage,封存被拒。 + +改为"显式本租户 或 完全没写租户字段"(写了别的租户仍然排除),知识库身份 +仍是独立 term,范围没有放宽。Count/PruneScope/整库导出共用同一写法。 + +试过:make verify 15 项全绿;新增 3 个过滤条件用例;真实 preflight 由 +candidate-invalid(0 条) 变为 candidate-valid(2 条)。 + +改动范围:`internal/librarymaintenance/env.go`、`internal/releaseadapter/v071/library_search.go`、`internal/releaseadapter/v071/search.go`、`internal/releaseadapter/v071/search_write.go`、`internal/librarymaintenance/env_test.go`、`internal/releaseadapter/v071/search_tenant_filter_test.go` +统计:6 个文件,+102/-17。 + +### Tests +本次提交包含测试/夹具变更:`internal/librarymaintenance/env_test.go`、`internal/releaseadapter/v071/search_tenant_filter_test.go` + +## 开发快照 snapshot/v0.1.170 - 2026-10-28 +目标提交:11c52ad81b425355205221666aae1b1561b71ef3 + +### Fixed +- **fix(libraryctl): 封存窗口接上实例级入口闸门与后台静默** +- **主机侧封存不再用"库级窗口"跑实例**:`libraryctl capture` / `recover` 改由 + `librarymaintenance.Manager` 装配——入口闸门、后台静默检查、目标指纹、入口探针与发布链路 + 是同一套实现。实例级维护里"写入者 exit=1"不再等于"在途请求被截断":被代理的 WeKnora 收到 + SIGTERM 就 `exit(1)` 是已知上游行为,排空证据来自闸门(`active_at_close` / `drained`), + 校验没有放松,而是补上了缺的那一层证据。 +- 缺少 `LIBRARY_TARGET_INGRESS_*` / `LIBRARY_TARGET_REDIS_*` 时 `capture` 在**开窗口前拒绝** + 并点名缺哪个变量;不再退回一个没有排空证据的窗口(那样的"成功"无法复核)。 +- 维护接线解析收敛到 `internal/librarymaintenance/env.go`:agent 与 worker 讲同一组变量名, + 空白值算缺失、队列库号必须是非负整数、口令不 Trim(前后空格也是口令)。 +- `libraryagent` 启动时如实打印维护目标是否接好(缺了就直说"封存会拒绝")。 +- `scripts/library-agent-install.sh` 强制 `agent.env`(0600,`EnvironmentFile=`),并把源容器/ + 项目/写入者声明做成可覆盖变量;没有 env 文件直接 `AGENT_ENV_MISSING` 退出。 + +- `internal/librarymaintenance/env_test.go`:整份声明解析、逐项点名缺失、空白拒绝、 + 口令空格保留、非法队列库号。 +- `cmd/libraryctl/maintenance_test.go`:入口/队列/源身份绑到同一份配置、数据库身份不泄漏口令、 + 写入者声明透传、缺闸门拒绝。 + +改动范围:`cmd/libraryagent/main.go`、`cmd/libraryctl/main.go`、`internal/librarymaintenance/env.go`、`scripts/library-agent-install.sh`、`CHANGELOG.md`、`docs/library-capture.md` 等 8 个 +统计:8 个文件,+426/-12。 + +### Tests +本次提交包含测试/夹具变更:`cmd/libraryctl/maintenance_test.go`、`internal/librarymaintenance/env_test.go` + +## 开发快照 snapshot/v0.1.169 - 2026-10-28 +目标提交:ee7688f24eb5a5b9f6dcd18afc6bb672fdaf0f6d + +### Docs +- **docs(matrix): Wiki 撤销检查实际 13 项,改正计数** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/library-acceptance-matrix.md` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.168 - 2026-10-28 +目标提交:9d0fe33c130fe95ffffd105251d5f9d1c7491139 + +### Docs +- **docs(ledger): 补记 0.1.162–0.1.167 与验收代码 SHA** +0.1.166(1faf513)是本轮验收代码 SHA;f82eb07 起的文档提交不改代码。 +0.1.165 因后续提交被 CI 取消,按事实记为 cancelled,不改写成成功。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+12/-0。 + +## 开发快照 snapshot/v0.1.167 - 2026-10-28 +目标提交:f82eb0735f4cae339c542ac52c953256d3a7126b + +### Docs +- **docs(acceptance): 矩阵按四段重排,补封存链路缺口与 8088 部署方案** +- `docs/library-acceptance-matrix.md` 按「已完成 / 缺代码 / 已实现未跑 / 需授权」 + 四段重排(不再在顶部叠报告):补上本轮 Wiki 撤销真实验收、贡献级差异、维护面板; + 新增封存链路缺口(CLI 无入口排空证明、API 封存未接线)与死信契约缺口。 +- 新增 `docs/formal-8088-deployment-plan.md`:版本清单、迁移 067–072、运行配置、 + fail-closed 规则、回滚、正式账号与数据保留、部署风险。**只准备,未执行**。 + +改动范围:`CHANGELOG.md`、`docs/formal-8088-deployment-plan.md`、`docs/library-acceptance-matrix.md` +统计:3 个文件,+171/-73。 + +## 开发快照 snapshot/v0.1.166 - 2026-10-28 +目标提交:1faf5137ea53adee61e7c0aac4940a39ec832139 + +### Fixed +- **fix(libraryctl): 用完整容器 ID 判定写入者归属** +`docker ps -q` 默认输出 12 位短 ID,与 declared 里的 64 位 ID 永不相等, +结果连已声明的写入者都被判成"未声明的并发写入者",封存永远开不了窗。 +改用 --no-trunc 并按前缀双向匹配。 + +改动范围:`cmd/libraryctl/main.go` +统计:1 个文件,+18/-2。 + +## 开发快照 snapshot/v0.1.165 - 2026-10-28 +目标提交:fd71ea349e81694c8a9b4892379a1d49f24dd273 + +### Fixed +- **fix(libraryctl): 同镜像不等于同一个写入者** +共享业务栈与专用验收实例共用同一个 WeKnora 镜像,原来只按镜像判"未声明写入者", +任何一台开着共享栈的机器都永远开不了窗。判据改为:同项目或无项目标签即冲突; +另一个项目只有数据库/队列目标与源相同才算冲突。单测覆盖六种组合。 + +改动范围:`cmd/libraryctl/main.go`、`cmd/libraryctl/writer_check_test.go` +统计:2 个文件,+100/-4。 + +### Tests +本次提交包含测试/夹具变更:`cmd/libraryctl/writer_check_test.go` + +## 开发快照 snapshot/v0.1.164 - 2026-10-28 +目标提交:906c282986c2fa3576616bd52fd1e4024f12b022 + +### Fixed +- **fix(libraryctl): 捕获/预检也走同一份 scope 映射** +上一提交只改了 status;capture/preflight 仍直接读 routing bindings, +所以 CLI 封存的还是 bindings 里的库,而不是 API 的目标——契约读取直接失败。 + +改动范围:`cmd/libraryctl/main.go` +统计:1 个文件,+2/-2。 + +## 开发快照 snapshot/v0.1.163 - 2026-10-28 +目标提交:23cc6c0afe08de3110aae4beaf3bb0caaf5815da + +### Fixed +- **fix(libraryctl): 支持 MinIO 源,并与 API 共用同一份 scope 映射** +- **`libraryctl` 只认 OSS 源**:`STORAGE_TYPE=minio` 的目标在发现阶段就被拒 + (`unsupported source storage type "minio"`),S3 兼容的专用验收实例无法封存。 + 现在按 `MINIO_ENDPOINT / MINIO_USE_SSL / MINIO_ACCESS_KEY_ID / MINIO_SECRET_ACCESS_KEY / + MINIO_BUCKET_NAME` 映射成 `provider=minio` + path-style;读不到端点/桶就明确报错, + 不退回默认值。 +- **CLI 与 API 的 scope→知识库 映射不一致**:API 用 `LIBRARY_PRODUCTION_KB_*`,CLI 只读 + routing bindings,同一台机器上会封存"配置里那个库"而不是 API 的验收目标。现在环境变量 + 优先、读不到才退回 bindings。 + +改动范围:`cmd/libraryctl/main.go`、`CHANGELOG.md`、`cmd/libraryctl/discover_test.go` +统计:3 个文件,+166/-14。 + +### Tests +本次提交包含测试/夹具变更:`cmd/libraryctl/discover_test.go` + +## 开发快照 snapshot/v0.1.162 - 2026-10-28 +目标提交:1f482e4b49b24ca30150d66ce2400059310b4fbd + +### Changed +- **feat(library): Wiki 撤销按贡献比对,维护窗口在页面如实呈现** +- **Wiki 贡献级差异**(`internal/librarydiff/wiki.go`):以 slug 为身份,把每页拆成 + 正文 / 来源文档 / 引用分块 / 出边 / 入边 / 目录/状态 分别取集合比较,输出 + `sources_added` / `sources_removed` / `citations_before→after` / `changed`。 + 删除一篇与别人共同贡献同一页的文档后,页面通常仍是「更新」,只看页面级增删改会显示成 + 「无变化」——现在能指出这份贡献是从哪一页、哪几类语义上被摘掉的。两端同时接受 JSON 数组 + 与字符串化数组,读不出来直接报错,不把「读不到」当成「没有来源」。 +- **接口 `GET /api/v1/library/overview` 的 `diff.wiki` 增加逐页明细**:`pages`(最多 50 页, + 超出置 `pages_truncated`)、`sources_added/removed`、`base_count/target_count`;页面级计数 + 保留,说明文字明确「重算发生在源侧,本平台只如实比对与保留结果」。 +- **发布管理页面:目标维护面板**(`MaintenanceCard`):显示维护级别(实例级/库级)、持有 + scope+作业、阶段、入口开/关、服务、开始/释放时间、作业进度(阶段名中文化,未映射原样显示)、 + 恢复错误与处理记录;只有窗口仍持有且作业失败时才出现「按预备份恢复」,动作走 + `POST /api/v1/library/maintenance/recover`。没有维护记录时明确写「未接入 + fail closed」, + 不画成已就绪。 +- **变更页展示逐页贡献差异**:每条页面一行,直接写「更新 发布闸门 · 正文/来源文档/引用分块 · + 来源 -1 · 引用 2→1」。 + +- `LibraryJobRecord.kind` 之前只有 `seal | sync`,恢复作业(restore)在类型上不存在; + 补上后页面不再把恢复作业当成未知类型。 + +- 本次真实验收(kgmaint 专用实例 + 原版 WeKnora API)与本快照之外的部署计划见 + `docs/library-acceptance-matrix.md` 与交付报告;矩阵按「已完成 / 缺代码 / 未跑 / 需授权」 + 重排,不再在顶部叠报告。 + +改动范围:`internal/httpapi/library_flow.go`、`internal/librarydiff/wiki.go`、`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx`、`web/src/librarySnapshots.ts`、`web/src/releaseTargets.css` 等 10 个 +统计:10 个文件,+1006/-37。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_wiki_diff_test.go`、`internal/librarydiff/wiki_test.go` + +## 开发快照 snapshot/v0.1.161 - 2026-10-28 +目标提交:0ef79846e83bff0469b47a5dd20366e04498592c + +### Fixed +- **fix(library): 后台静默必须在关入口之后证明,并在停写者后复核** +- **顺序缺口**:原顺序是「先证明后台静默 → 关入口排空 → 停写者」。排空期间还在服务的 + 在途请求随时会派生新的异步任务,那个"空"到停写者时早就失效;而 app 收到 SIGTERM 会 + exit(1),正在跑的任务被腰斩。现在固定为「关入口并排空 → 证明后台静默 → 停写者 → + 停完再复核」,并且在**入口关闭之前禁止取样**(`awaitBackgroundQuiet` 要求 + `Gate.Closed && Gate.Drained`)。 +- **单次瞬时 0 不算证明**:新证据 `QuiesceProof` 要求连续取样为空、跨过稳定窗口 + (默认 1.5s)、任务集合指纹一致;只有 `Idle` 没有指纹的检查器在实例级直接拒绝。 +- **停写者后复核**:`verifyBackgroundAfterStop` 再取一次样,队列非空或指纹变化即判 + `background_truncated`,按"有任务被截断"失败,绝不继续写目标。 +- **scheduled/retry 自行产生任务**:队列长时间没有进展(默认 30s)就直接失败 + (`background_busy`),不拿等待时间冒充排空。 +- **旧 journal 的 `background_idle` 布尔不再当证明**:只保留为历史字段,恢复流程一律 + 重新取样(`RecoverWindow` 不读它);只有布尔、没有证明的旧窗口按"未证明"处理。 +- **恢复路径同样要求先停任务再停写者**:写入者已停但队列还有任务时立即失败并写清 + 外部处理方式(先起服务、入口保持关闭让任务跑完,再重试恢复),不再拿"服务没跑" + 冒充"后台已静默"。 +- **入口关到一半失败会把入口留在关闭状态**:`restore` 现在对实例级维护总是重新打开 + 入口(不再只看"是否成功关闭过"),放弃窗口时还要用 `ingressReady` 确认入口真的回来了, + 否则保持维护不释放——避免"维护已释放、服务在跑、入口却是关的"。 +- **zset 队列读取**:对 `scheduled`/`retry` 先 `TYPE` 再 `ZRANGE`,此前直接 `LRANGE` + 会报 WRONGTYPE,任何自带重试/定时任务的实例都开不了窗口。 + +- `QuiesceSnapshot` / `QuiesceProof` 与 `StableQuiescer`:后台静默从"一次布尔"变成 + 可复核证据(样本数、稳定窗口、任务指纹、停写后复核时间)。 +- `SetQuiesceStability(stable, stall)`:调整稳定窗口与"任务无进展"判定。 +- 回归测试:取样必须晚于关入口、排空期间产生的任务要等它结束、队列一直有任务要 + fail closed、停写后冒出新任务要判截断、旧布尔不算证明、只有 Idle 的检查器被拒。 + +改动范围:`internal/libraryfreeze/freeze.go`、`internal/libraryfreeze/recovery.go`、`internal/libraryfreeze/window.go`、`internal/librarymaintenance/quiesce.go`、`CHANGELOG.md`、`internal/libraryfreeze/quiesce_order_test.go` 等 7 个 +统计:7 个文件,+791/-65。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryfreeze/quiesce_order_test.go`、`internal/libraryfreeze/window_test.go` + +## 开发快照 snapshot/v0.1.160 - 2026-10-28 +目标提交:c7dafe987e8267cf65bc9904099c74858d748116 + +### Fixed +- **fix(library): 恢复校验按归档身份核对共享资源表** +- **`resources` 校验改用归档身份集合**:resources 是多知识库共享表,采集口径看 + knowledges/chunks/wiki 正文里的 `resource://`,校验却只看 chunks 并重新推导 + "本库可见",两边口径不一致——恢复得一字不差也会被判"行数 15/19"而拒绝开放。 + 现在按归档列出的 id 逐个核对存在性与逐行内容摘要;少一行、改一个字节都算失败。 + +改动范围:`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/library_verify_content.go`、`CHANGELOG.md` +统计:3 个文件,+110/-1。 + +## 开发快照 snapshot/v0.1.159 - 2026-10-28 +目标提交:f055fc174dc40d0dfbee35ed262144abe13c303c + +### Changed +- **style(library): gofmt 恢复重排文件** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`internal/platform/postgres/library_recovery_retry.go` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.158 - 2026-10-28 +目标提交:b007acd4437d269778b2033dcf57e66e8f007490 + +### Changed +- **feat(library): 恢复失败后可以重新排队,不必手工改库** +失败作业的幂等键把恢复入口锁死,运维修好故障也点不动第二次。 +现在按窗口重排失败作业(同窗口有活作业则拒绝并发),CLI/API 都能真恢复。 + +改动范围:`internal/httpapi/library_flow.go`、`internal/platform/postgres/library_recovery_retry.go` +统计:2 个文件,+68/-0。 + +## 开发快照 snapshot/v0.1.157 - 2026-10-28 +目标提交:7e4900b51b809b10f08efb91801d28cd6d1f07b0 + +### Fixed +- **fix(library): 恢复前按实际运行状态重新停写入者** +- **Docker inspect 反序列化**:`containerState` 把 `Config` 映射成 `map[string]string`, + 真实返回是对象,于是每次拓扑校验都报 `invalid docker response`——所有维护窗口被误拒。 +- **后台静默检查没接线**:`openLibraryMaintenance` 漏传目标库/队列,实例级窗口永远报 + "缺少后台静默检查"。防线代码在仓库里、运行时却没生效。 +- **恢复作业队列 id 超列宽**:`"librecover-"+窗口作业 id` 超过 `varchar(36)`, + 恢复入口投递即失败(409 enqueue failed),等价于没有恢复入口。 +- **恢复不再信任上一次窗口的 StopRequested**:写入者在窗口后被人工拉起来时, + `stopAll` 要按"现在是否真的在跑"再停一次;否则校验会跑在半开的目标上。 + +改动范围:`internal/libraryfreeze/window.go`、`CHANGELOG.md`、`internal/libraryfreeze/window_test.go` +统计:3 个文件,+59/-4。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryfreeze/window_test.go` + +## 开发快照 snapshot/v0.1.156 - 2026-10-28 +目标提交:1a04dfb4faf2e0ac4e76a63c89c9e32d384c3fa1 + +### Fixed +- **fix(library): 恢复作业的队列 id 不能超过列宽** +"librecover-"+窗口作业 id 超过 varchar(36),投递直接失败——恢复入口等于打不开。 +按窗口摘要取 33 字符的确定性 id。 + +改动范围:`internal/httpapi/library_flow.go` +统计:1 个文件,+6/-1。 + +## 开发快照 snapshot/v0.1.155 - 2026-10-28 +目标提交:5afe151c7d9648e23b5c8c341af98f81629aaa46 + +### Fixed +- **fix(library): 维护目标把后台静默检查的依赖接上** +openLibraryMaintenance 漏传了目标库/队列,导致实例级窗口永远报 +"缺少后台静默检查"——接线漏了,防线却看起来像在工作。 + +改动范围:`cmd/worker/library_handlers.go` +统计:1 个文件,+5/-0。 + +## 开发快照 snapshot/v0.1.154 - 2026-10-28 +目标提交:faf8027890463be00fdfecaf3d9899f8d431edd5 + +### Fixed +- **fix(library): 修 Docker inspect 反序列化,拓扑校验才读得到端口** +containerState 里把 Config 映射成 map[string]string,真实返回是对象, +于是每次拓扑校验都报 invalid docker response——所有窗口都被误拒。 + +改动范围:`internal/librarymaintenance/dockerapi.go` +统计:1 个文件,+2/-3。 + +## 开发快照 snapshot/v0.1.153 - 2026-10-28 +目标提交:3643e9bf82f01ce1b78ecc0a52b67a6ef2f77d12 + +### Fixed +- **fix(library): 维护收尾必须按预备份恢复并校验** +- **删除 `FinalizeAfterOperatorRecovery`**:它自称"不启动服务",实际会 `gate.OpenIngress`, + 而且只看服务健康与入口 200——健康不等于恢复成功,这条路径能把半写内容重新开放。 +- 新的唯一收尾入口 `Coordinator.RecoverWindow`:绑定「原作业 + 目标指纹 + journal 里持久化的预备份身份」, + 在**维护关闭**状态下(入口关、写入者停、排空确认)执行 `Restore` 与**逐类校验** + (行数/身份集合/逐行内容摘要 + 索引文档 + 对象资源),校验通过才恢复服务、开入口; + 校验或恢复失败则保持维护(服务停、入口关、journal 非终态)。 +- 预备份身份与「内容风险」在**第一笔写入之前一起落盘**(`Window.SetBackupSnapshot` + + `MarkContentRisk`)。没有预备份身份的窗口之后既不能自动恢复,也不许被任何收尾路径开放。 +- 低层恢复接口不再接受任何"已恢复/已验证"的入参:`Restorer`/`Verifier` 由协调器在窗口内调用, + `Verifier` 必须返回校验摘要并被持久化。 + +- 真实恢复入口 `POST /api/v1/library/maintenance/recover`:只建 `library.recover` 作业, + 由 worker 按预备份恢复 + 校验后释放占用;`libraryctl finalize` 删除(不再有"手工收尾"旁路)。 +- 实例级互斥:迁移 `000072_library_instance_maintenance`,维护占用按**实例**建键, + internal 持有期间 external 也进不来(旧实现按 scope 建行,两个 scope 会同时停/起同一实例)。 +- 后台静默检查(`targetQuiescer`):窗口关闭入口之前,必须证明目标库 `task_pending_ops=0`、 + 无未完成解析、asynq 队列(pending/active/scheduled/retry)为空;否则拒绝开窗口。 + HTTP 排空不等于后台任务排空——app 内的 asynq worker 会被上游 SIGTERM 的 exit(1) 切断。 +- 唯一入口拓扑校验(`Manager.VerifyTopology`):写入者**不许发布任何宿主机端口**, + 入口必须是独立声明的闸门且发布的端口与入口 URL 一致;不满足就拒绝开窗口。 + +- 拓扑校验只看"声明的写入者组":新增容器必须显式声明,平台不会自动猜测。 +- 后台静默检查依赖目标库表 `task_pending_ops/knowledges` 与 asynq 键名(v0.7.1 现状); + 上游改队列实现时需要同步调整。 +- 页面只透传新增字段(实例占用/入口状态),专门文案与浏览器验收仍未做。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`cmd/libraryctl/main.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_recovery.go`、`cmd/worker/main.go` 等 26 个 +统计:26 个文件,+1731/-226。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryfreeze/recover_window_test.go`、`internal/libraryfreeze/window_test.go`、`internal/librarymaintenance/target_test.go`、`internal/platform/postgres/library_maintenance_integration_test.go` 等 5 个 + +## 开发快照 snapshot/v0.1.152 - 2026-10-28 +目标提交:ec737a9a65822b2a9d5bf893bce6a54d0fbe5c7b + +### Fixed +- **fix(library): 排空证据要读闸门记录的 active_at_close** +闸门写的是 active_at_close / drain_ms,Go 侧却去读 active(排空后必然 0) +与 waited_ms(已改名),于是证据里恒显示"关闭时无在途连接"。改为读真实字段。 + +改动范围:`internal/librarymaintenance/gate.go` +统计:1 个文件,+11/-6。 + +## 开发快照 snapshot/v0.1.151 - 2026-10-28 +目标提交:96fffb5081142a843103637b54963f1e384abc01 + +### Fixed +- **fix(library): 排空证据必须由本次关闭产生** +- 排空证据不能被历史文件冒充:关入口前先删掉上一次的 `drain.json` 并确认真的不存在, + 关闭后还要求记录 mtime 不早于本次关闭时刻;闸门当时没在跑就直接失败,而不是读旧记录。 + +改动范围:`internal/librarymaintenance/gate.go`、`CHANGELOG.md` +统计:2 个文件,+15/-0。 + +## 开发快照 snapshot/v0.1.150 - 2026-10-28 +目标提交:962bed8f53236925b188f603547c3c3236878f8e + +### Changed +- **feat(library): 人工恢复后按证据收尾维护窗口** +- `libraryctl finalize -job `:回滚失败被保持维护之后,人工把目标恢复到可服务状态时的 + 收尾入口。它不启动任何服务、不释放治理占用,只核对「原本在跑的服务现在在跑且健康 + 入口在服务」, + 通过才把 journal 标成 `operator_recovered`。 + +改动范围:`cmd/libraryctl/main.go`、`internal/libraryfreeze/window.go`、`CHANGELOG.md`、`internal/libraryfreeze/window_test.go` +统计:4 个文件,+123/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryfreeze/window_test.go` + +## 开发快照 snapshot/v0.1.149 - 2026-10-28 +目标提交:38d04488de00455b29e3d62d3d34de7271d05eaf + +### Changed +- **feat(library): 入口闸门排空 + 维护占用可再接管** +- 入口闸门(`LIBRARY_TARGET_INGRESS_SERVICE` + `INGRESS_DRAIN_FILE`):被代理的 WeKnora 收到 SIGTERM + 会先关监听再因 `use of closed network connection` 直接 exit(1),在途请求会被切断。 + 因此排空放在真正的连接入口上做:闸门先停止接受新连接、等在途连接归零、写 `drain.json` + 并 exit 0;协调器只认「闸门 exit 0 + phase=drained」这一条证据,写者的退出码只作为记录。 +- 维护占用释放后可被新作业接管(此前 `ON CONFLICT ... WHERE owner_job_id = ...` 会让 + "第一次同步之后谁也再进不去");仍在持有的窗口依然只允许原作业重入。 + +改动范围:`cmd/worker/library_handlers.go`、`internal/appconfig/config.go`、`internal/libraryfreeze/freeze.go`、`internal/libraryfreeze/window.go`、`internal/librarymaintenance/gate.go`、`internal/librarymaintenance/target.go` 等 10 个 +统计:10 个文件,+533/-67。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryfreeze/window_test.go`、`internal/platform/postgres/library_maintenance_integration_test.go` + +## 开发快照 snapshot/v0.1.148 - 2026-10-28 +目标提交:6fe98c9a30a68282598afa4a25961b2fff1a17ce + +### Changed +- **feat(library): 同步/恢复改为实例级维护窗口** +- 同步/恢复不再只锁治理库 scope:`runLibraryRelease` 现在先开**实例级维护窗口** + (`internal/librarymaintenance` + `internal/libraryfreeze` 复用)—— + 持久化 owner / 目标精确身份(实例、写入者容器、入口、库/索引/桶 + 指纹)/ 原服务状态, + 关闭目标入口(SIGTERM 后监听立即关闭)、停下全部声明写入者, + 并验证「写入者真的停了」「在途请求真的排空了」「入口真的连不上」之后才允许写目标。 +- `libraryfreeze.RunWindow`:一个窗口里跑调用方的写阶段。第一次写目标前必须 + `MarkContentRisk`(fsync 落盘);写完先恢复原运行状态与入口,再释放维护占用。 +- 入口探针(`internal/librarymaintenance`):关闭 = 连不上(代理还回 502 不算关闭), + 恢复 = HTTP 200;只有原本在跑的服务会被重启。 +- 迁移 `000071_library_maintenance_level`:维护记录新增 `level`(instance/library)、 + `target_fingerprint`、`services`、`ingress_state`,页面/审计能看清这次到底动的是实例还是只锁了一个库。 + +- 进程被杀/授权过期不再误放行半写目标:journal 里的 `content_risk` 一旦置位, + 重启恢复只收尾确定性的事,**不会**自动把写入者启动回来;原作业接管后才继续。 +- 回滚失败(`rollback_failed`)或校验失败(`finalize` 不一致)时,服务保持停止、 + 维护占用保持持有(`needs_restore`),入口不重新开放。 +- 接管场景(已有预备份)一律按「内容可能半写」处理,任何早退都不重新开放目标。 + +- 维护层级判定是「配置里声明的写入者组」:多实例/多写入者拓扑变更需要重新声明, + 不会自动猜测新容器。 +- 前端只透传新增字段,页面尚未为 `level/ingress_state` 做专门的文案与布局; + Wiki 语义重算与浏览器整体验收仍未完成。 +- 本机专用候选实例(kgmaint-*)仅承载验收数据,不代表远程生产已验证。 + +改动范围:`cmd/worker/library_handlers.go`、`internal/appconfig/config.go`、`internal/libraryfreeze/docker.go`、`internal/libraryfreeze/freeze.go`、`internal/libraryfreeze/project.go`、`internal/libraryfreeze/window.go` 等 14 个 +统计:14 个文件,+1523/-236。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryfreeze/window_test.go`、`internal/librarymaintenance/target_test.go`、`internal/platform/postgres/migrations_test.go` + +## 开发快照 snapshot/v0.1.147 - 2026-10-28 +目标提交:fe6e218d9cd5b600e90ed2986204337869225a29 + +### Fixed +- **fix(library): 整库只读接口改清单级读取,修掉真实超时** +- 整库只读接口不再按版本重读全部 blob:`overview`(internal/external)、`storage`、`snapshots` + 从 10s 超时 503 变为真实返回完整数据(候选归档 79 版,本机实测 <1s)。 + 根因是列举路径用 `Archive.Usage()`(逐版 `Load` 校验全部部件), + 外加 `library_storage.go` 每版两次 `Load`、`snapshots` 每版一次 `Load`。 +- 新增 `Archive.UsageFromManifests` 给只读列举用:与 `Usage` 共用同一份去重实现, + 只把"读清单"换成清单级校验。`Usage`(逐版复核字节)保持不变,仍供同步/恢复与运维 CLI 使用。 +- `LoadManifest` 收紧到与 `Load` 相同的清单校验(严格解码 + 重新编码校验,含必需部件与兼容性契约), + `Load` 改为 `LoadManifest` + 逐部件验字节——同一套清单判据只有一份。 +- wiki 与文档差异只读所需部件(`wiki_pages` / `knowledges`),被读取的那个部件仍由 + `OpenPart` 复核摘要;不再为两页 Wiki 重算整版字节。 +- `libraryWithDeadline` 去掉了"另起 goroutine 到点先回 503"的写法:候选环境实测它会在超时后 + 继续写已结束的响应(日志 `http: superfluous response.WriteHeader call`),并留下仍在扫盘的 goroutine。 + 改为请求期限交给 ctx,读取在版本之间检查期限,响应只有一个写入者。 + +- 列举口径必须看得见:`snapshots`/`storage` 响应新增 `verification=manifest` 与说明, + 每份版本带 `verified=false`;单版详情因为整版复核字节,返回 `verification=content`、`verified=true`。 + 这样"清单可读"不会被读成"完整性已验证/可发布"。 + +- 运维 CLI `libraryctl` 仍走逐版复核(`Usage`/`Load`):它是执行前的操作入口,慢但真校验,本轮不动。 +- 归档规模到上万版本时仍未分页/增量盘点;只保证请求可被期限中止,不承诺增速。 +- 维护协议、Wiki 语义重算、最终部署仍未完成,见后续工作。 + +- ~~`GET /library/overview`、`GET /library/storage` 仍 **503**(10s 超时)。~~ + 已在上面「读接口超时:真实修复」一节修好:剩余调用点是 `Usage()`、`library_storage.go` 的 + 双 `Load` 与 `snapshots` 的每版 `Load`。 +⚠️ 上面的端口与容器名前缀是**本机运行栈**的实测值;换环境要按那边的运行栈改,别无脑照抄。 + +改动范围:`internal/httpapi/library_flow.go`、`internal/httpapi/library_snapshots.go`、`internal/httpapi/library_storage.go`、`internal/httpapi/server.go`、`internal/librarysnapshot/archive.go`、`internal/librarysnapshot/usage.go` 等 12 个 +统计:12 个文件,+602/-96。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_read_paths_test.go`、`internal/httpapi/library_snapshots_test.go`、`internal/librarysnapshot/usage_listing_test.go` + +## 开发快照 snapshot/v0.1.146 - 2026-10-28 +目标提交:1609a0c9be5d5192df5bfa9414473346d179ac61 + +### Changed +- **perf(librarysnapshot): 盘点改用 LoadManifest,去掉按版本重算 blob** +| 步骤 | 耗时 | +|---|---| +| Open(仅目录校验,无 flock) | 0 ms | +| Load 单个清单(含逐部件验字节) | 252 ms | +| OpenPart + 读 knowledges | 0 ms(4 行) | +| 遍历全部版本(当时用 Load) | **13833 ms**(79 版 / 2.77 GB 声明字节) | + +结论:接口超时不是锁、不是连接池,而是**按版本重复校验全部部件**导致的 O(全部版本字节)。 +79 个版本来自历次真实同步的预备份/派生快照,全部留在同一个归档根。 + +- 新增 `Archive.LoadManifest`:只校验清单自身(文件名摘要 == 内容摘要 + 结构), + 用于盘点/统计/列版本;`Load` 仍逐部件校验字节,同步/恢复路径不变。 +- `ContentUsage` 改用 `LoadManifest`(原先每个版本都 `Load`)。 + +- `GET /library/overview`、`GET /library/storage` 仍 **503**(10s 超时)。 + 说明还有别的调用点在枚举版本时用 `Load`(候选:最新封存选择、wiki 差异基线解析、保留策略扫描)。 + 需要继续把这些调用点逐个切到 `LoadManifest`,并用同样的分段计时验证。 + +改动范围:`internal/librarysnapshot/archive.go`、`internal/librarysnapshot/usage.go`、`CHANGELOG.md` +统计:3 个文件,+58/-1。 + +## 开发快照 snapshot/v0.1.145 - 2026-10-28 +目标提交:d1dbb2b9454836ce9d382981d25eccfa0c6cc152 + +### Changed +- **style: gofmt library_maintenance.go** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`internal/platform/postgres/library_maintenance.go` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.144 - 2026-10-28 +目标提交:288e01a01aef1b3fe5c895b0fe9dc06b4b84d7f4 + +### Changed +- **feat(library): 目标维护窗口(持久所有权/独占/release-on-verify)+ known-broken 记录** +- 迁移 000070 `library_maintenance`:一个 scope 一个持有者,记录作业/目标身份/服务原状态/阶段/释放时间。 +- `AcquireLibraryMaintenance`(异主占用直接拒绝)、`UpdateLibraryMaintenanceState`、 + `ReleaseLibraryMaintenance`、`LibraryMaintenanceOf`。 +- worker:写目标前 acquire,写前置 `applying`,只有"验证通过 + 版本登记成功"才 release; + 回滚失败/回滚后未验证 → `needs_restore` 且保持持有(不会被 finally 释放)。 +- API:`GET /api/v1/library/maintenance`;同步入口在目标被他人持有时返回 409。 + +- 候选环境实测 `GET /api/v1/library/maintenance` 返回 **404**:路由已注册在 server.go:451, + 但运行实例没匹配上,根因未定位。 +- 维护窗口的真实 kill/接管取证未成功:取证脚本在 kill 之前作业已跑完(竞态), + 三项断言(持有中、kill 后仍持有、维护期间拒绝新写入)全部 false。 + 因此维护协议**没有真实证据**,不得声称已实现。 + +改动范围:`api/openapi.yaml`、`cmd/worker/library_handlers.go`、`cmd/worker/main.go`、`internal/httpapi/library_flow.go`、`internal/httpapi/server.go`、`internal/platform/postgres/library_maintenance.go` 等 10 个 +统计:10 个文件,+250/-6。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/migrations_test.go` + +## 开发快照 snapshot/v0.1.143 - 2026-10-28 +目标提交:b76a433574b17c27607ca3146724652f73330264 + +### Fixed +- **fix(httpapi): 整库只读接口加请求级超时,避免归档大时请求挂死** +为什么:候选前端联调时 /library/overview 与 /library/storage 会挂到连接被重置, +浏览器无法渲染。加 10s 超时并返回明确降级原因,同时差异计算放进看门狗。 + +改动范围:`internal/httpapi/library_flow.go`、`internal/httpapi/server.go` +统计:2 个文件,+49/-3。 + +## 开发快照 snapshot/v0.1.142 - 2026-10-28 +目标提交:def6022048e9bf3273d99d8a2eddfc1178048421 + +### Docs +- **docs(ledger): 补记 0.1.137/0.1.138 并把进度文件更新到最终真实版本** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+5/-1。 + +## 开发快照 snapshot/v0.1.141 - 2026-10-28 +目标提交:e7ba2057aca11a5b56bff96156e1af1360a8b02a + +### Docs +- **docs(matrix): V03 标注架构阻塞、P02 真实计数、R01 恢复已验证** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/library-acceptance-matrix.md` +统计:1 个文件,+3/-3。 + +## 开发快照 snapshot/v0.1.140 - 2026-10-28 +目标提交:cef25d92a62ace37c5ecdeed07ba270dbe50c6cc + +### Changed +- **feat(worker): 四类进度用 manifest 真实总量,未知保持 NULL** +为什么:P02 要求分项计数/字节来自真实清单,不能永远 NULL 或写 0。 + +改动范围:`cmd/worker/library_handlers.go`、`cmd/worker/main.go` +统计:2 个文件,+49/-4。 + +## 开发快照 snapshot/v0.1.139 - 2026-10-28 +目标提交:f722ea87271a9d8d5bec465ee07f75bba4861d54 + +### Docs +- **docs(ledger): 补记 0.1.135 cancelled 与 0.1.136 success** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+5/-1。 + +## 开发快照 snapshot/v0.1.138 - 2026-10-28 +目标提交:e47e6d825dd21d883ae529e705dbc6306c411d7a + +### Docs +- **docs(matrix): 追加入口级 8 场景真实验收对照** +为什么:矩阵要与固定 SHA 的证据文件对应。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/library-acceptance-matrix.md` +统计:1 个文件,+16/-0。 + +## 开发快照 snapshot/v0.1.137 - 2026-10-28 +目标提交:7a2188a0ee7cd17c93142f25450128781c37a856 + +### Docs +- **docs(release): 入口级 8 场景真实验收证据与台账** +为什么:证据必须对应固定 SHA;旧证据与报告冲突的部分保留但不再引用。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+6/-1。 + +## 开发快照 snapshot/v0.1.136 - 2026-10-28 +目标提交:ea4cffbcaa54c0055ddcaeb812cb93a8ededbce3 + +### Changed +- **style: gofmt release_gate_test.go** +该提交未附正文,以下范围由真实 diff 归纳。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/libraryrelease/release_gate_test.go` +统计:1 个文件,+1/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryrelease/release_gate_test.go` + +## 开发快照 snapshot/v0.1.135 - 2026-10-28 +目标提交:c72b71d78afd1d72cefdc6ced301001172ccc968 + +### Fixed +- **fix(library): 预备份硬门禁 + 崩溃接管 + 五项入口验收** +- **预备份持久化成为硬门禁**:`BackupObserver.BackupPrepared` 现在返回 error, + 引用/版本登记失败时 `Run` 直接返回失败且**一个字节都不写目标**(此前只写日志继续写)。 +- 预备份同时登记成 `production_prebackup` 版本,失败与成功路径都留证据。 +- 中断接管按**队列租约**判定(原来只看 state=running,worker 刚被杀而租约未过期时会漏掉); + 运行期每 30 秒扫一次,不再只在启动时扫一次。 +- 接管用一次条件更新原子抢占(`running→pending` 只有一个 worker 成功),队列作业 ID/幂等键固定, + 并发接管只会得到同一条队列作业;重复接管时把 attempt 归零,否则 `attempt-queue` 会超长)。 +- 生产版本记录 ID 用稳定短摘要(`library_versions.id` 是 varchar(64),拼接完整快照 ID 会超长)。 +- 对象路径:真实 `resources.physical_path` 是 `storage:///oss:///`, + 写入/读取都先拆成裸 key;对象存储 provider 改为可配置(默认 s3),必须与生产 `resources.provider` 一致。 +- 生产索引不存在/为空时按"空基线"处理(Current/Export/Backup/Archive 全链路一致), + 非空时仍然严格比对映射,避免把索引丢失当成正常。 +- 索引校验按写入时的规范化比较(写入会补齐 tenant_id/knowledge_base_id), + 不一致时给出首个差异文档与字段。 + +- 收尾阶段 `finalize`:版本登记失败不再报成功,作业标失败并保留预备份,修好后可续作。 +- 崩溃接管:worker 启动时接管"running 但队列已无任务"的写作业,复用已持久化的预备份, + 绝不重新备份覆盖;没有预备份的判失败。 +- 跨 kind 互斥:迁移 000069 把唯一索引从 `(scope,kind)` 改成 `scope`(sync/restore 共用)。 +- 按版本恢复 `POST /library/restores`(管理员 + 该快照恢复授权)与续作 `POST /library/jobs/{id}/resume` + (管理员 + 闸口 + 授权,幂等键按源作业固定)。 +- 首次发布放行:生产可读且为空视为合法空基线;预备份不再作为启动前门禁(它由作业自身生成)。 + +- 环境:候选 API :18089 + 候选 worker + 独立治理库 `kg_candidate_1028165117` + + 真实 WeKnora 表结构的生产库 `kg_prod_1028165117` + 独立 ES 索引 + 独立 MinIO 桶。 +- 首次发布:生产为空 → 预备份 → 四类写入 → 校验 → 登记 `production_effective` 成功; + 真实落库 4 文档 / 38 分块 / 21 资源 / 31 Wiki 页 / 122 索引文档。 +- 同请求重复:返回同一作业且 `reused=true`,不重复写生产。 +- 未授权快照:503 并写明"没有与目标快照匹配的有效发布授权",不建作业。 +- 更新版本:第二份快照同步成功(真实改标题)。 +- 失败自动恢复:索引内容不一致、资源绑定行数不一致、对象上传失败等场景均被拒绝并回滚, + 回滚后生产回到上一版本(多次真实复现)。 +- 收尾失败不报成功:版本登记因 ID 超长失败时作业标 failed、生产写入保留并记录恢复责任。 + +改动范围:`cmd/api/main.go`、`cmd/library-e2e-seed/main.go`、`cmd/worker/library_handlers.go`、`cmd/worker/library_wiring.go`、`cmd/worker/main.go`、`internal/appconfig/config.go` 等 28 个 +统计:28 个文件,+878/-104。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_flow_test.go`、`internal/httpapi/library_restore_test.go`、`internal/platform/postgres/migrations_test.go`、`internal/releaseadapter/v071/library_production_isolation_test.go` + +## 开发快照 snapshot/v0.1.131 - 2026-10-28 +目标提交:8a68ea2da240134f5ac484d74412468048261473 + +### Docs +- **docs(release): 台账补记 0.1.129–0.1.130** +为什么:候选 SHA、CI 结论与真实服务验收事实要落台账。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+5/-1。 + +## 开发快照 snapshot/v0.1.130 - 2026-10-28 +目标提交:a2d051f6b3e7e0895eb4aaafdb941093536d82f5 + +### Changed +- **feat(library): 按版本恢复入口与失败作业续作** +- 迁移 000068:`library_jobs.kind` 允许 `restore`,与封存/同步分开。 +- `POST /api/v1/library/restores`:管理员按指定整库快照恢复;要求**针对该快照的恢复授权** + (同步授权不能顶替),闸口与恢复演练证据同样适用,缺项逐条拒绝且不建作业。 +- `POST /api/v1/library/jobs/{id}/resume`:失败/取消的同步或恢复作业按原参数重新排队, + 旧作业保留为审计记录;封存作业不走续作(由封存入口重发)。 +- worker 新增 `library.restore` 处理器,与同步共用"闸口 → 授权 → 预备份 → 四类写入 → 校验"链路; + 成功后登记 `production_effective` 版本(带预备份快照与字节数证据),失败/回滚失败分别留痕。 + +改动范围:`api/openapi.yaml`、`cmd/worker/library_handlers.go`、`cmd/worker/main.go`、`internal/governance/library_flow.go`、`internal/httpapi/library_restore.go`、`internal/httpapi/server.go` 等 11 个 +统计:11 个文件,+548/-91。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_restore_test.go`、`internal/platform/postgres/migrations_test.go` + +## 开发快照 snapshot/v0.1.129 - 2026-10-28 +目标提交:0b9dbe12cfbb30584b2dd3dc1a726822cd5c7f4e + +### Fixed +- **fix(library): 资源范围精确关联 + 内容级校验 + 真实对象存储验收** +- 资源范围:`scopeWhere(resources)` 与 `resourcePaths` 现在用 `resource_bindings.resource_id = resources.id` + 精确关联,覆盖知识库绑定与分块绑定,并限制绑定租户;此前只按 owner_id 判断会命中整张资源表。 + 归档资源部件名与资源 ID 对齐(此前按 handle 查路径,导入会找不到对象)。 +- 资源路径查询补上 `provider`,对象读写按资源真实 provider 执行。 + +- `Verify` 由"行数 + ID 集合"升级为内容级:逐行规范化摘要(仅豁免 created_at/updated_at/processed_at/expires_at)、 + 归档索引文档与生产索引文档的规范摘要、以及每个资源对象的实际字节 SHA256。 + 同 ID 改正文、改 Wiki、改向量、损坏对象都会被拒绝。 +- 预备份一致性由行数升级为内容指纹:导出前后逐表比对"数量 + 内容摘要",同数量改写也会失败。 +- 本机真实对象存储(MinIO)纳入验收:`TestLibraryProductionIsolationRealServices` 用真实桶与对象, + 覆盖跨租户/跨库资源隔离、chunk-only 绑定、对象损坏、以及"源对象被改后仍能用预备份恢复"。 + +- 三条真实服务用例同时通过:隔离资源+内容校验(`kg_library_test_*` 库、随机 ES 索引、唯一 MinIO 桶)、 + 单阶段导入/撤销/恢复、完整编排 e2e。跑完删库、删索引、删对象。 + +改动范围:`internal/releaseadapter/v071/library_backup_store.go`、`internal/releaseadapter/v071/library_production_target.go`、`internal/releaseadapter/v071/library_verify_content.go`、`internal/releaseadapter/v071/s3_object_store.go`、`CHANGELOG.md`、`internal/releaseadapter/v071/library_production_isolation_test.go` 等 7 个 +统计:7 个文件,+677/-31。 + +### Tests +本次提交包含测试/夹具变更:`internal/releaseadapter/v071/library_production_isolation_test.go`、`internal/releaseadapter/v071/library_production_target_integration_test.go` + +## 开发快照 snapshot/v0.1.128 - 2026-10-28 +目标提交:6ca8481e8e8c22f401d3ef1cbea9e9b9dbe2de6f + +### Docs +- **docs(release): 台账补记 0.1.126 与真实服务验收结论** +为什么:候选 SHA 与 CI/验收结论要落在台账里,便于父审独立核对。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+3/-1。 + +## 开发快照 snapshot/v0.1.127 - 2026-10-28 +目标提交:8da4666e76f8b46cad29e41d2fdd0b98663c53bc + +### Tests +- **test(library): 端到端编排在本机真实 PG/ES 上跑通** +→ 独立预备份(626 字节)→ 注入故障(删行)→ 校验失败 → 恢复后校验通过。 +- `TestLibraryReleaseRunIsolated`:同一环境上跑完整编排(授权 → 预备份 → 数据库/资源/索引/Wiki → + 校验),返回 succeeded,预备份快照 8e4ed5ba…(1074 字节)。 + +改动范围:`scripts/test-scope.json`、`CHANGELOG.md`、`docs/release-ledger.md`、`internal/releaseadapter/v071/library_production_target_integration_test.go` +统计:4 个文件,+120/-5。 + +## 开发快照 snapshot/v0.1.126 - 2026-10-28 +目标提交:281699a43104af6ce5344b17375ac7102f3e563d + +### Changed +- **feat(library): 生产整库真实读写/校验/恢复与本机真实服务验收** +- `internal/releaseadapter/v071/library_production_target.go` 由占位改为真实实现: + `Current` 读生产每张知识域表的行数与「身份集合摘要」+ 索引条数;`Apply` 按阶段真实写入 + (database/wiki 同事务先删本库再插、resources 上传对象、index 批量索引原始文档与向量); + `Verify` 用身份摘要与索引条数比对;`Restore` 按预备份快照回放整条链路。 + 只触碰知识域表,不写 users/sessions/api_keys;不做解析或 Embedding。 +- 撤销真正落地:索引阶段在写入后用 `PruneScope` 删除"快照里没有"的文档,避免只增不减。 +- `library_backup_store.go`:写前独立完整预备份——生产 PG(RepeatableRead)+ ES 整库导出 + + 资源对象密封成归档版本,导出前后比对行数做静默检查;映射契约不符直接拒绝。 +- `search_write.go`:`Count`/`BulkIndex`/`PruneScope`,范围过滤统一按「租户 + 知识库」。 +- `cmd/worker/library_wiring.go`:用部署注入的配置装配生产目标与预备份;缺项时把缺的 + 环境变量名写进阶段并失败,不再使用空占位对象。 +- 配置:`LIBRARY_PRODUCTION_DATABASE_URL`、`LIBRARY_PRODUCTION_ELASTIC_URL/INDEX`、 + `LIBRARY_PRODUCTION_TENANT_ID`、`LIBRARY_PRODUCTION_KB_INTERNAL/EXTERNAL`、 + `LIBRARY_PRODUCTION_S3_*`、`LIBRARY_EMBEDDING_MODEL/DIMENSION`。 + +- `libraryretention.CheckCapacity` 用安全加法:int64 溢出直接拒绝,不再绕回负数通过门禁。 +- 保留策略组合语义写明为「每个已设维度都超限才成为候选」并提供 `policy_note`; + 锁定/备份恢复依赖通过 `ProtectedBy` 进入保护集合,永不候选。 + +- `TestLibraryProductionTargetIsolated` 在本机 WeKnora 测试栈真实 PG(一次性 `kg_library_test_*` 库) + 与真实 ES(随机索引)跑通:首次导入 → 校验 → 撤销传播(PG 行与 ES 文档都消失、跨租户不受影响) + → 独立预备份(3111e823…,626 字节)→ 注入故障(删行)→ 校验失败 → 恢复后校验通过。 + +改动范围:`cmd/worker/library_wiring.go`、`cmd/worker/main.go`、`internal/appconfig/config.go`、`internal/libraryrelease/release.go`、`internal/libraryretention/capacity.go`、`internal/libraryretention/retention.go` 等 16 个 +统计:16 个文件,+1521/-71。 + +### Tests +本次提交包含测试/夹具变更:`internal/libraryretention/retention_test.go`、`internal/releaseadapter/v071/library_production_target_integration_test.go`、`internal/releaseadapter/v071/library_production_target_test.go` + +## 开发快照 snapshot/v0.1.125 - 2026-10-28 +目标提交:444b8202108adc4309d6cc77da77eefe089fad71 + +### Docs +- **docs(release): 台账补记 0.1.123 与 run164 失败说明** +为什么:run164 的失败原因与修复要留在台账里,不能让失败消失。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+5/-1。 + +## 开发快照 snapshot/v0.1.124 - 2026-10-28 +目标提交:67a48faf23996b7cf55d2ed589e4235f9b4d4754 + +### Tests +- **test(qawemail): 去掉单测对外部 DNS 的依赖** +- `internal/qawemail` 单测把 `smtp.example.com` 当成可解析主机,构建机没有外网 DNS 时必红; + 改用 `localhost` 并新增"RFC 6761 保留域 .invalid 必须判非法"的确定性断言(不放宽校验)。 + +改动范围:`CHANGELOG.md`、`internal/qawemail/store_test.go` +统计:2 个文件,+18/-7。 + +## 开发快照 snapshot/v0.1.123 - 2026-10-28 +目标提交:7e3075f0fc77c51821925d7c7194c6c759678b87 + +### Docs +- **docs(release): 台账补记 0.1.121–0.1.122 与候选说明** +为什么:每个开发版本的 SHA 与 CI 结论要能独立审计,不留在交付报告里。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+4/-1。 + +## 开发快照 snapshot/v0.1.122 - 2026-10-28 +目标提交:2038462dbbd09b4bee00ea8d647c2bb0e94f538d + +### Changed +- **feat(library): Wiki 页面级差异与页面展示** +- `GET /library/overview` 的差异结果新增 `wiki`:两份快照 `wiki_pages` 的新增/更新/撤销页数与样例, + 明确标注页面级、不代表实体/边/引用重算;缺部件时如实 unknown。 + +改动范围:`internal/httpapi/library_flow.go`、`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx`、`web/src/librarySnapshots.ts`、`CHANGELOG.md`、`docs/library-acceptance-matrix.md` +统计:6 个文件,+113/-1。 + +## 开发快照 snapshot/v0.1.121 - 2026-10-28 +目标提交:7b8cc0384b9160d488be6ed308b2007d9d6ef91f + +### Changed +- **feat(library): 生产发布授权与同步/恢复编排,worker 接线** +- `internal/libraryretention`:保留策略、依赖保护(生产生效/最近封存/预备份/在飞作业)与清理预览; + 预算未设置即不放行的容量门禁;已并入启动同步的缺项列表。 +- `GET /api/v1/library/storage`:真实归档用量 + 三类版本保护依据 + 策略 + 预览 + 容量,只读。 +- 发布授权:`library_release_authorizations`(目标+快照+参数摘要+有效期,可撤销), + `POST/GET /api/v1/library/authorizations`、`POST /{id}/revoke`,仅管理员签发,有效期 5–1440 分钟。 +- `internal/libraryrelease`:预备份 → 数据库/资源/索引/Wiki → 验证 → 失败恢复的编排, + 授权过期/目标不符/快照不符/参数变化一律在动生产前拒绝;恢复失败作为独立结论上报。 +- worker `library.sync` 接执行编排:先闸口、再授权,写入阶段落库;生产目标适配器未配置时明确失败。 +- 页面"生产保护与恢复"显示发布授权状态与有效期;系统设置→存储管理显示容量门禁、受保护版本与清理预览。 + +- 启动同步的缺项包含"没有与目标快照匹配的有效发布授权"与容量预算;作业只有在编排返回成功时才标成功。 + +改动范围:`api/openapi.yaml`、`cmd/worker/main.go`、`internal/governance/library_flow.go`、`internal/httpapi/library_authorization.go`、`internal/httpapi/library_flow.go`、`internal/httpapi/server.go` 等 22 个 +统计:22 个文件,+1289/-47。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_authorization_test.go`、`internal/httpapi/library_flow_test.go`、`internal/libraryrelease/release_test.go`、`internal/platform/postgres/migrations_test.go` 等 5 个 + +## 开发快照 snapshot/v0.1.120 - 2026-10-28 +目标提交:f91359f881077d1fad17fca021973c6beb54553f + +### Changed +- **feat(library): 存储管理真实化——容量门禁、依赖保护与清理预览** +为什么:存储页原来只有占用数字,保留/依赖保护/清理预览写"未接线";这些都不需要生产写权限, +按"未设置就不做决定"的口径实现成只读计算。 + +- internal/libraryretention:按保留数量/天数生成预览;生产生效、每库最近封存、每次生产预备份、 + 在飞作业引用一律受保护;回收预览只算独占字节,共享 blob 不计。 +- internal/libraryretention.CheckCapacity:预算未设置即不放行(无法证明装得下),超预算阻断; + 已并入 POST /library/syncs 的 gate 缺项。 +- 新增 GET /api/v1/library/storage:真实归档用量 + 三类版本保护依据 + 策略 + 预览 + 容量,只读。 +- 系统设置→存储管理改为读该接口:策略未设置时明确"全部保留、不生成候选",自动清理恒关闭。 +- 配置项 LIBRARY_CAPACITY_BUDGET_BYTES / LIBRARY_RETENTION_VERSIONS / LIBRARY_RETENTION_DAYS(未设=0)。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`internal/appconfig/config.go`、`internal/httpapi/library_flow.go`、`internal/httpapi/library_storage.go`、`internal/httpapi/server.go` 等 13 个 +统计:13 个文件,+756/-49。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/library_flow_test.go`、`internal/libraryretention/retention_test.go` + +## 开发快照 snapshot/v0.1.119 - 2026-10-28 +目标提交:12bb839d8a2cc138d3e4034d4dae559a52c3d094 + +### Docs +- **docs(release): 台账补记 0.1.116–0.1.118 的 CI 结论** +为什么:版本台账要能独立审计每个版本的 SHA 与 CI 结论,不能只留在交付报告里。 + +仅文档变更,不改变运行时行为。 + +改动范围:`docs/release-ledger.md` +统计:1 个文件,+5/-0。 + +## 开发快照 snapshot/v0.1.118 - 2026-10-28 +目标提交:3ad48ff32cf301b70555e93409d8593b3b571be0 + +### Changed +- **feat(web): 版本抽屉分列三类版本,不再只写"生产未接入"** +为什么:抽屉原来把所有记录都当测试封存,生产生效与本次预备份的真实状态读不到; +overview 已有三类版本,抽屉直接展示,缺的写"无记录",不互相顶替。 + +改动范围:`web/src/ReleaseTargets.tsx`、`web/src/releaseTargets.css` +统计:2 个文件,+49/-1。 + +## 开发快照 snapshot/v0.1.117 - 2026-10-28 +目标提交:e313ae12f29bd5579f779122cf6a26a87a98a87d + +### Changed +- **feat(library): 真实差异比对 + 孤儿作业回收 + 验收矩阵与台账** +- `internal/librarydiff`:按稳定文档 ID 与"排除 updated_at/updated_by 的整行摘要"比较两份归档快照的 `knowledges`, + 输出新增/更新/撤销;`GET /api/v1/library/overview` 在生产权威版本与测试封存都存在时给出真实差异, + 并标注 `base_snapshot`/`target_snapshot`,缺任一侧仍为 unknown 且说明原因。 +- 发布管理"本次变更"按文档身份列出增改撤销,并显示比对的两个版本前缀。 +- `ReconcileLibraryJobs`:worker 启动时把"队列里已无对应作业"的孤儿业务作业标失败并写明恢复责任, + 避免永久占用 (scope,kind) 互斥索引。 +- `docs/library-acceptance-matrix.md`:30 个验收项逐条对应代码/证据/状态(已实现已验证、已实现未验证、阻塞、未实现)。 +- `docs/release-ledger.md`:版本→完整 SHA→CI run 与结果→是否部署 的台账。 + +- 格式问题(CI run149–156 在 format 步骤连续失败):按仓库既有 prettier 配置格式化四个文件,不放宽检查。 +- `TestEmbeddedMigrationsAreVersionSorted` 仍写死 65 条迁移,新增 000066 后必红;改为 66 并补 000066 内容断言。 + +改动范围:`cmd/worker/main.go`、`internal/httpapi/library_flow.go`、`internal/librarydiff/diff.go`、`internal/platform/postgres/library_jobs.go`、`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx` 等 12 个 +统计:12 个文件,+490/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/librarydiff/diff_test.go` + +## 开发快照 snapshot/v0.1.116 - 2026-10-28 +目标提交:e3db157ba8d78f6046114055a24f7812e224e576 + +### Tests +- **test(postgres): 迁移清单跟随 000066 更新** +为什么:新增 000066 整库作业迁移后,清单测试仍写死 65 条,CI tests-go 因此红。 +不只改计数,同时断言 66 建出 library_versions 与 library_jobs_active 互斥索引。 + +仅测试/夹具变更,不新增产品或运行时功能。 + +改动范围:`internal/platform/postgres/migrations_test.go` +统计:1 个文件,+7/-2。 + +## 开发快照 snapshot/v0.1.115 - 2026-10-28 +目标提交:7e1610da44387c1cd86af2605311997e8249c47a + +### Changed +- **style(web): 格式化发布管理相关文件** +为什么:远端 CI run149–155 连续在 format 步骤失败,报的就是这四个新文件; +不做格式白名单、不跳过检查,直接按仓库既有 prettier 配置格式化。 + +改动范围:`web/src/LibraryStorageSection.tsx`、`web/src/ReleaseTargets.test.tsx`、`web/src/ReleaseTargets.tsx`、`web/src/releaseTargets.css` +统计:4 个文件,+55/-29。 + +## 开发快照 snapshot/v0.1.106 - 2026-10-28 +目标提交:9f990158b97c0f6d0ec010b01a80f540042d5945 + +### Tests +- **test(snapshot): 联合验证真实隔离存储与暂停恢复链** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`scripts/test-scope.json`、`docs/library-sync-acceptance.md`、`internal/releaseadapter/v071/library_capture_integration_test.go` +统计:3 个文件,+258/-0。 + +## 开发快照 snapshot/v0.1.95 - 2026-10-27 +目标提交:74aef1e373513ec605750313b7002528575bf50e + +### Fixed +- **fix(fetch): 修复钉钉来源身份与取件失败监控** +- 修复钉钉新登记来源仍按旧离线目录身份取件的问题:从当前来源配置读取空间坐标,实时枚举所在目录并严格匹配节点身份;同名文件不替代、目录不完整不误报删除。修复解析监控遗漏 `version_id` 取件任务及缺少业务元数据的失败记录,正确显示失败原因、重试入口与历史。 + +改动范围:`internal/platform/postgres/artifact_fetch_store.go`、`internal/platform/postgres/monitor_tasks.go`、`internal/workflows/artifactfetch/handler.go`、`scripts/artifact_fetch.py`、`scripts/artifact_fetch_test.py`、`CHANGELOG.md` 等 8 个 +统计:8 个文件,+211/-9。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/artifact_fetch_manifest_integration_test.go`、`internal/platform/postgres/monitor_tasks_integration_test.go` + +## 开发快照 snapshot/v0.1.94 - 2026-10-27 +目标提交:1b09f7d35bcb7a4b2a79417996933b1b45a31c95 + +### Changed +- **feat(monitor): 卡片概况与统一文件处理表** +- 新增解析监控统一工作台:顶部运行指标与依赖卡片、下方单一文件处理表;来源文件与目标测试库归并最新版本,动作、阶段、状态分列,后端统一筛选、计数及分页。支持单条/跨页勾选重试和版本、失败、重试详情;测试库移除重试独立核验治理规则,不误走上传流程。取消六分页和手动开始入口,生产授权仍在发布管理;本次不改变后台自动调度策略,自动处理闭环需另行端到端验收。 + +改动范围:`api/openapi.yaml`、`internal/httpapi/monitor_tasks.go`、`internal/httpapi/server.go`、`internal/platform/postgres/monitor_removal_retry.go`、`internal/platform/postgres/monitor_tasks.go`、`web/src/WeKnoraMonitor.test.tsx` 等 13 个 +统计:13 个文件,+2224/-545。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/monitor_tasks_test.go`、`internal/platform/postgres/monitor_tasks_integration_test.go` + +## 开发快照 snapshot/v0.1.93 - 2026-10-27 +目标提交:d8d143eca004b83cbd9226f088ddf8ad79f2317f + +### Changed +- **style(catalog): 移除冗余策略说明和大小展示** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`web/src/SourceCatalogBrowser.test.tsx`、`web/src/SourceCatalogBrowser.tsx`、`web/src/sourceCatalogBrowser.css` +统计:3 个文件,+6/-7。 + +## 开发快照 snapshot/v0.1.92 - 2026-10-27 +目标提交:52f411783581f3aa586ff86838ca99ba69b1b251 + +### Changed +- **style(catalog): 文件格式筛选默认折叠** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`web/src/SourceCatalogBrowser.test.tsx`、`web/src/SourceCatalogBrowser.tsx`、`web/src/sourceCatalogBrowser.css` +统计:3 个文件,+7/-0。 + +## 开发快照 snapshot/v0.1.91 - 2026-10-27 +目标提交:7448d130ec71cbfd4f31b9a2eff4bc8ef7b57f2e + +### Changed +- **feat(settings): 汇总全部数据源配置操作审计** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`api/openapi.yaml`、`internal/httpapi/auth.go`、`internal/httpapi/dingtalk_session.go`、`internal/httpapi/server.go`、`internal/httpapi/source_audit.go`、`internal/platform/postgres/dingtalk_space.go` 等 17 个 +统计:17 个文件,+453/-56。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/source_audit_test.go`、`internal/platform/postgres/migrations_test.go`、`internal/platform/postgres/source_audit_integration_test.go` + +## 开发快照 snapshot/v0.1.90 - 2026-10-27 +目标提交:f0b12412a1fa6cd7251692cc485369c3dd789f1c + +### Fixed +- **fix(settings): 仅展示只读DWS凭证状态** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`internal/dingtalkdiscovery/credentials.go`、`internal/httpapi/dws_credentials.go`、`internal/httpapi/server.go`、`web/src/SourceManagement.tsx` 等 8 个 +统计:8 个文件,+149/-32。 + +### Tests +本次提交包含测试/夹具变更:`internal/dingtalkdiscovery/credentials_test.go` + +## 开发快照 snapshot/v0.1.89 - 2026-10-27 +目标提交:5b6e154459d510a26e8434ad521f5009b803a0a1 + +### Changed +- **feat(settings): 增加连接移除确认并收拢数据源设置** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`web/src/SourceManagement.css`、`web/src/SourceManagement.tsx`、`web/src/SystemSettings.tsx` +统计:3 个文件,+112/-16。 + +## 开发快照 snapshot/v0.1.88 - 2026-10-27 +目标提交:8930ef29cdfd091dfb0897c195799fba002e12bd + +### Changed +- **feat(settings): 集中刷新策略与账号授权并独立设置审计** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`web/src/DingtalkSessionControl.tsx`、`web/src/SourceManagement.css`、`web/src/SourceManagement.test.tsx`、`web/src/SourceManagement.tsx`、`web/src/SystemSettings.test.tsx`、`web/src/SystemSettings.tsx` 等 8 个 +统计:8 个文件,+520/-214。 + +## 开发快照 snapshot/v0.1.87 - 2026-10-26 +目标提交:a55d7f454e74f3a123b62180adad90a7ab16868b + +### Changed +- **style(settings): 精简数据源列表并收起低频管理操作** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`web/src/SystemSettings.test.tsx`、`web/src/SystemSettings.tsx`、`web/src/systemSettings.css` +统计:3 个文件,+119/-78。 + +## 开发快照 snapshot/v0.1.86 - 2026-10-26 +目标提交:b55292bba16666fd2a7b20c1f06fd3a440781bc0 + +### Fixed +- **fix(catalog): 重复点击当前来源时保留已加载目录** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`web/src/SourceCatalogBrowser.tsx` +统计:1 个文件,+1/-1。 + +## 开发快照 snapshot/v0.1.85 - 2026-10-26 +目标提交:02ee5da231d8f761a756db06aad4ab4b3a225767 + +### Fixed +- **fix(catalog): 保留首次扫描零进度避免来源列表解析失败** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`internal/governance/source_catalog.go`、`internal/governance/source_catalog_json_test.go` +统计:2 个文件,+22/-1。 + +### Tests +本次提交包含测试/夹具变更:`internal/governance/source_catalog_json_test.go` + +## 开发快照 snapshot/v0.1.84 - 2026-10-26 +目标提交:e744114ff438cbbf15d98dd46a5e74f900d0b1be + +### Fixed +- **fix(catalog): 打通共享授权扫描与统一来源清单显示** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`internal/httpapi/dingtalk_session.go`、`internal/workflows/catalogrefresh/handler.go`、`web/src/SystemSettings.test.tsx`、`web/src/SystemSettings.tsx`、`scripts/dws_dingtalk_scan.py`、`scripts/live_catalog_refresh.py` 等 10 个 +统计:10 个文件,+276/-50。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/dingtalk_register_dws_test.go`、`internal/workflows/catalogrefresh/handler_test.go` + +## 开发快照 snapshot/v0.1.83 - 2026-10-26 +目标提交:c8f05ee46f61ee2ec6a8f20a31fea5783a61b283 + +### Fixed +- **fix(qa): 数据源登记改走 dws,不再要求扫码** +侧车扫码会话只用于解析空间;dws 已有有效凭据且能给出空间 id 与根节点, +登记直接用 dws 结果生成确定性键,同名来源回 200 already_present,认不出的空间才回落侧车。 + +改动范围:`internal/httpapi/dingtalk_session.go`、`internal/httpapi/dingtalk_register_dws_test.go` +统计:2 个文件,+123/-0。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/dingtalk_register_dws_test.go` + +## 开发快照 snapshot/v0.1.82 - 2026-10-26 +目标提交:1e8d8e3cdf30d94fad4b99ce1e5ede3da5d402fd + +### Fixed +- **fix(qa): 数据源配置去掉页面噪声** +去掉页头副标题与刷新状态按钮、工程师/管理员权限条、活动版本横幅、 +与向导重复的模块说明,以及「去掉来源」按钮(保留停用来源与修订历史)。 + +改动范围:`web/src/SourceWizard.tsx`、`web/src/SystemSettings.test.tsx`、`web/src/SystemSettings.tsx` +统计:3 个文件,+14/-98。 + +## 开发快照 snapshot/v0.1.81 - 2026-10-26 +目标提交:842bfccc1b92613212589b66db39a24ad29975ed + +### Changed +- **feat(qa): 向导补上 Partner Portal 卡片** +PP 一个门户一条来源:已接入时只做说明不重复登记,未接入时提示需服务端放置只读凭据。 + +改动范围:`web/src/SourceWizard.tsx`、`web/src/SystemSettings.tsx` +统计:2 个文件,+15/-4。 + +## 开发快照 snapshot/v0.1.80 - 2026-10-26 +目标提交:740f0e69baf33f64b9dec7b5689f56cd3159baa6 + +### Changed +- **feat(qa): 数据源配置改为统一添加向导** +一个「+ 添加数据源」入口、五步固定(类型→授权→范围→校验→保存),类型只换候选来源与授权说明, +版式与动作词一致;对内/对外不在此配置,仍只在来源与目录标注。钉钉两类复用既有登记与扫码会话路径。 + +改动范围:`web/src/SourceWizard.tsx`、`web/src/SystemSettings.test.tsx`、`web/src/SystemSettings.tsx`、`web/src/sourceWizard.css` +统计:4 个文件,+468/-7。 + +## 开发快照 snapshot/v0.1.79 - 2026-10-26 +目标提交:020cae1228d2c5a30808baadf42444fdd91a3236 + +### Changed +- **style: gofmt 新增的发现与路由文件** +该提交未附正文,以下范围由真实 diff 归纳。 + +改动范围:`internal/dingtalkdiscovery/docs.go`、`internal/dingtalkdiscovery/docs_test.go`、`internal/httpapi/source_available_test.go` +统计:3 个文件,+4/-4。 + +### Tests +本次提交包含测试/夹具变更:`internal/dingtalkdiscovery/docs_test.go`、`internal/httpapi/source_available_test.go` + +## 开发快照 snapshot/v0.1.78 - 2026-10-26 +目标提交:017cbcb851901c1ad0a7571aaea211fafae0ace7 + +### Changed +- **feat(api): 数据源统一列举与添加前校验** +GET /source-catalog/available 四类同一形状(wiki/drive/doc/pp),类型差异只放在 content_type; +POST /source-catalog/validate 真读一次:文档表格校验可读、知识库钉盘校验账号仍可见,失败不让添加。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`internal/httpapi/server.go`、`internal/httpapi/source_available.go`、`internal/httpapi/source_available_test.go` +统计:5 个文件,+423/-2。 + +### Tests +本次提交包含测试/夹具变更:`internal/httpapi/source_available_test.go` + +## 开发快照 snapshot/v0.1.77 - 2026-10-26 +目标提交:b3992bfa0f5c61cdb102393d8fba12b9cae58308 + +### Changed +- **feat(discovery): 钉钉在线文档与表格的发现与可读校验** +数据源统一改造第一块:drive +recent/+search-docs 列文档与表格,doc info / sheet list 真读一次 +校验可读;表格按 contentType 分流,读不到返回 ErrUnavailable 而不是空列表。 + +改动范围:`internal/dingtalkdiscovery/docs.go`、`internal/dingtalkdiscovery/docs_test.go` +统计:2 个文件,+267/-0。 + +### Tests +本次提交包含测试/夹具变更:`internal/dingtalkdiscovery/docs_test.go` + +## 开发快照 snapshot/v0.1.76 - 2026-10-26 +目标提交:2902ba0af2dbb01bbab49dee5662f23833d74d56 + +### Changed +- **feat(qa): 周报页移除下载 MD 与下载明细 CSV 按钮** +保留复制排版内容与自动保存;列表页的完整明细导出不受影响。 + +改动范围:`web/src/QAWeekly.tsx`、`web/src/QAWeeklyEditor.test.tsx` +统计:2 个文件,+4/-40。 + +## 开发快照 snapshot/v0.1.75 - 2026-10-26 +目标提交:555bc6ff5614a672d82ff5c103f92da04b86bb93 + +### Changed +- **feat(qa): 确认周报时自动附上统计看板图片** +看板图只能由浏览器渲染,改为确认动作内自动生成并上传,不再要求另点按钮;只在已附图时提供重新生成。 + +改动范围:`web/src/QAWeeklyMail.tsx` +统计:1 个文件,+12/-3。 + +## 开发快照 snapshot/v0.1.74 - 2026-10-26 +目标提交:1dda055e4c5ea2b0556141ee5efac7de2ba2e526 + +### Fixed +- **fix(qa): 授权码加密不再绑定设置版本** +AAD 只含租户,避免任何设置变更使已存密码失效;旧行在解密时按历史版本回退,无需重填授权码。 + +改动范围:`internal/qawemail/store.go` +统计:1 个文件,+15/-5。 + +## 开发快照 snapshot/v0.1.73 - 2026-10-26 +目标提交:f87d3fad9be11f1164137d1e28f2599dccab43fd + +### Fixed +- **fix(qa): 授权码按写入版本解密,改其它设置不再失效** +只调整收件人或时间也会递增设置版本,导致已保存的授权码无法解密、测试发送报存储不可用。 +新增 password_revision 记录加密时的版本,迁移回填现有行。 + +改动范围:`internal/platform/postgres/migrations/000064_weekly_mail_password_revision.down.sql`、`internal/platform/postgres/migrations/000064_weekly_mail_password_revision.up.sql`、`internal/qawemail/store.go`、`internal/platform/postgres/migrations_test.go` +统计:4 个文件,+20/-10。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/migrations_test.go` + +## 开发快照 snapshot/v0.1.72 - 2026-10-26 +目标提交:23b19350cce09a18a52ccfa9d0e66e9b2c2539a6 + +### Changed +- **feat(qa): 周报邮件新增测试/审核邮箱** +测试发送只投递到该地址,不打扰主送与抄送名单;未填时退回主送首位。 + +改动范围:`api/openapi.yaml`、`internal/platform/postgres/migrations/000063_weekly_mail_review_address.down.sql`、`internal/platform/postgres/migrations/000063_weekly_mail_review_address.up.sql`、`internal/qawemail/store.go`、`web/src/QAWeeklyMail.tsx`、`web/src/qaWeeklyMail.test.tsx` 等 9 个 +统计:9 个文件,+49/-10。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/migrations_test.go`、`internal/qawemail/store_test.go` + +## 开发快照 snapshot/v0.1.71 - 2026-10-26 +目标提交:1a9d1fff8391e531b0af6b6b32f0ae0ee86e057a + +### Fixed +- **fix(qa): 看板附图上传改用大请求体解码** +附图 base64 远超 64KiB 的质量编辑上限,被误判为无效设置并报“发送设置无效”。 +改为 12MB 上限的通用解码,并返回明确的图片错误文案。 + +改动范围:`internal/httpapi/qa_weekly_mail.go` +统计:1 个文件,+3/-2。 + +## 开发快照 snapshot/v0.1.70 - 2026-10-26 +目标提交:822fb652ffaea9088e31f87ad1abf5a8b4fdc3ff + +### Changed +- **feat(qa): 周报邮件区分主送抄送并附统计看板图片** +设置新增抄送列表,MIME 增加 Cc 头、envelope 同时投递主送与抄送,同一地址不得同时出现在两边。 +确认后可保存统计看板 PNG(multipart/related + cid),发送时放在正文末尾内联显示;正文改动使确认失效后不再使用旧图。 + +改动范围:`api/openapi.yaml`、`internal/httpapi/qa_weekly_mail.go`、`internal/httpapi/server.go`、`internal/platform/postgres/migrations/000061_weekly_mail_cc.down.sql`、`internal/platform/postgres/migrations/000061_weekly_mail_cc.up.sql`、`internal/platform/postgres/migrations/000062_weekly_mail_dashboard_image.down.sql` 等 13 个 +统计:13 个文件,+325/-25。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/migrations_test.go`、`internal/qawemail/store_test.go` + +## 开发快照 snapshot/v0.1.69 - 2026-10-26 +目标提交:600e9a2dc2464d0013f40375d71ab3937ce4e401 + +### Changed +- **feat(qa): 周报邮件支持立即发送测试** +管理员可在周报页先发一封测试邮件验证邮箱配置;测试不写入发送记录、不改变确认状态,也不会把该周标记为已发送。 + +改动范围:`api/openapi.yaml`、`internal/httpapi/qa_weekly_mail.go`、`internal/httpapi/server.go`、`internal/qawemail/store.go`、`web/src/QAWeeklyMail.tsx`、`web/src/qaWeeklyMail.ts` +统计:6 个文件,+106/-3。 + +## 开发快照 snapshot/v0.1.68 - 2026-10-26 +目标提交:eed83039ab08c7ed88a6bf2c01c3d1f0ad299bdb + +### Fixed +- **fix(qa): 邮件设置未配置时返回空收件人数组** +未初始化设置时 recipients 为 null,前端严格解析判为无效,导致周报页显示“响应无效”。 +后端统一返回空数组,前端同时兼容历史的 null。 + +改动范围:`internal/qawemail/store.go`、`web/src/qaWeeklyMail.ts` +统计:2 个文件,+7/-3。 + +## 开发快照 snapshot/v0.1.67 - 2026-10-26 +目标提交:43b1e423fec01a3534dac4dfba9b6152d4bab36c + +### Fixed +- **fix(qa): 规范化邮件调度测试并声明其外部依赖** +gofmt 修正;该集成测试需要一次性库与测试密钥,按仓库约定在 test-scope.json 声明为可选未运行。 + +改动范围:`scripts/test-scope.json`、`internal/qawemail/scheduling_integration_test.go` +统计:2 个文件,+15/-3。 + +### Tests +本次提交包含测试/夹具变更:`internal/qawemail/scheduling_integration_test.go` + +## 开发快照 snapshot/v0.1.66 - 2026-10-26 +目标提交:5aa32492de54c9ac32841e8fef96489697611d10 + +### Fixed +- **fix(qa): 周报邮件读取鉴权与测试隔离** +只读查询不再要求同源操作意图,写操作仍需;前端改为直接消费已解包的 data。 +调度集成测试按租户清理并要求一次性测试库,避免误清正式数据。 + +改动范围:`internal/httpapi/qa_weekly_mail.go`、`web/src/qaWeeklyMail.ts`、`internal/qawemail/scheduling_integration_test.go` +统计:3 个文件,+139/-8。 + +### Tests +本次提交包含测试/夹具变更:`internal/qawemail/scheduling_integration_test.go` + +## 开发快照 snapshot/v0.1.65 - 2026-10-26 +目标提交:68162895528ef3a1f42be18693d32915fc3abfde + +### Changed +- **feat(qa): 周报确认后按设定时段自动发邮件** +周报页新增自动发送区:管理员配置 SMTP/收件人/发送星期与小时,授权码用主密钥加密保存。 +确认绑定当前草稿版本与正文哈希,正文再改则确认失效;worker 每分钟仅在启用、到点、周已结束且未发送过时发一次。 +邮件同时提供渲染后的 HTML 与可读纯文本;SMTP 仅允许 TLS,拒绝明文。 +迁移 000060 新增设置、确认与发送记录三张表,唯一键防重复发送。 + +改动范围:`api/openapi.yaml`、`cmd/api/main.go`、`cmd/worker/main.go`、`cmd/worker/qa_weekly_mail.go`、`internal/httpapi/qa_weekly_mail.go`、`internal/httpapi/server.go` 等 18 个 +统计:18 个文件,+1550/-2。 + +### Tests +本次提交包含测试/夹具变更:`internal/platform/postgres/migrations_test.go`、`internal/qawemail/store_test.go` + +## 开发快照 snapshot/v0.1.64 - 2026-10-25 +目标提交:1d33ff697632c8ab81ce2ae305ed200ef1fd2da6 + +### Fixed +- **fix(qa): 无法判定的判错结论不再计入正确率分母** +根因为“结果不清”或未归因的判错记录移出正确率分母,并以 unjudged 单独返回,覆盖率口径不变。 +统计规则版本升到 calendar-month-strict-yes-over-yes-no-v2,前端严格解析同步接受该字段。 + +改动范围:`api/openapi.yaml`、`internal/qaopsmirror/dashboard_monthly.go`、`web/src/qaDashboardData.ts`、`internal/qaopsmirror/dashboard_monthly_test.go`、`web/src/qaDashboardMonthly.fixture.ts` +统计:5 个文件,+74/-11。 + +### Tests +本次提交包含测试/夹具变更:`internal/qaopsmirror/dashboard_monthly_test.go`、`web/src/qaDashboardMonthly.fixture.ts` + +## 开发快照 snapshot/v0.1.35 - 2026-10-19 +目标提交:330fd12b3f30376c3aee757ba2a9f4ba3f8bcf27 + +### Changed +- **Merge pull request #9:问答运营查询与镜像** +第一父 `f33730ed…` → 本合并 `330fd12b…`:121 个文件,+9065/-376。第二父 +`f5e0f8d2…` 是功能分支;以下按第一父真实 diff 描述本次集成,不把分支历史重复算作新开发。 + +功能变化:新增问答运营看板/镜像与质量范围读取,接入独立问答副本同步、HTTP 路由和 +worker 任务;覆盖 `cmd/worker/qa_dashboard.go`、`cmd/worker/qa_mirror.go`、 +`internal/dobotaiops/mirror.go`、`internal/httpapi/qa_mirror_sync.go`、 +`internal/httpapi/qa_dashboard.go` 及对应测试;未声称已部署或验收。 +统计:121 个文件,+9065/-376。 + diff --git a/Dockerfile b/Dockerfile index acf3933..40e3af1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -21,6 +21,7 @@ RUN LDFLAGS="-X knowledge-governance/internal/version.Number=${VERSION} -X knowl && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "$LDFLAGS" -o /out/api ./cmd/api \ && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "$LDFLAGS" -o /out/worker ./cmd/worker \ && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "$LDFLAGS" -o /out/release-worker ./cmd/release-worker \ + && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "$LDFLAGS" -o /out/libraryctl ./cmd/libraryctl \ && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "$LDFLAGS" -o /out/test-publication-seed ./cmd/test-publication-seed \ && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "$LDFLAGS" -o /out/test-weknora-e2e-report ./cmd/test-weknora-e2e-report \ && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags "$LDFLAGS" -o /out/test-weknora-probe ./cmd/test-weknora-probe @@ -49,7 +50,8 @@ RUN set -eux; \ dws version WORKDIR /app COPY --from=build /out/ /app/ -COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/artifact_fetch.py \ - scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/ +COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/dws_dingtalk_scan.py \ + scripts/pp_client.py scripts/artifact_fetch.py scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/ +RUN chmod 0644 /app/scripts/*.py USER 65532:65532 CMD ["/app/api"] diff --git a/README.md b/README.md index b524e4b..2c92023 100644 --- a/README.md +++ b/README.md @@ -52,9 +52,9 @@ Knowledge Adapter / DobotAI 网关 | 来源 | 当前接入方式 | 参考文档 | | --- | --- | --- | -| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) | +| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [登录授权](docs/DWS_LOGIN.md) · [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) | | AList | 来源目录与资料获取,依赖指定连接和凭据 | [用户操作流程](docs/OPERATIONS_RUNBOOK.md) | -| PP(资料门户) | 本地清单、历史账本接管与只读扫描 | [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) | +| PP(资料门户) | 页面管理 API 与认证配置;真实校验、只读扫描及取件 | [认证配置](docs/SOURCE_AUTH_CONFIGURATION.md) · [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) | IT、行政等是待扩展的业务资料范围,不是已经完成的新连接器。接入敏感资料前,需要先确认 Owner、有效版本、可见范围与知识库路由。 @@ -122,7 +122,7 @@ make list # 查看检查清单与适用范围 ## 问答运营模型配置 -管理员在「系统设置 → 服务配置 → 问答评估模型」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。 +管理员在「系统设置 → AI 模型连接」填写 OpenAI 兼容基础地址、模型和 API Key。测试连接发送最小非业务请求;保存不会启动历史全量任务,自动分析/翻译默认关闭。密钥不回显,保留、更换和清除分别选择;录入只允许有效 HTTPS 或本机回环连接,不允许跳过证书校验。 API 和普通 worker 须只读挂载同一个独立的 **32 字节、0600 普通文件**,以 `QA_AI_MASTER_KEY_FILE` 指向容器内路径。文件属主应为实际运行 UID;不要复用 Agent 会话存储或把主密钥写进 Compose/Git。治理库只保存加密后的服务密钥;恢复时必须同时恢复治理库和这份独立主密钥。未配置主密钥时如实显示安全存储未就绪。 diff --git a/api/openapi.yaml b/api/openapi.yaml index b5d9f3e..009e603 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -52,6 +52,7 @@ "/api/v1/qa-ops/master/weekly-mail/confirmations/{week}": {"get":{"operationId":"getQAWeeklyMailConfirmation","tags":["QA operations"],"summary":"读取该周是否已确认自动发送;current=false表示确认后正文已被修改,需要重新确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"post":{"operationId":"confirmQAWeeklyMail","tags":["QA operations"],"summary":"确认本周周报可自动发送,绑定当前草稿版本与正文哈希;后续改动使确认失效,不发送改动后的正文","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"delete":{"operationId":"unconfirmQAWeeklyMail","tags":["QA operations"],"summary":"取消该周的自动发送确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}}, "/api/v1/qa-ops/master/weekly-mail/sends": {"get":{"operationId":"listQAWeeklyMailSends","tags":["QA operations"],"summary":"读取周报邮件发送记录:周次、草稿版本、发送中/已发送/失败及错误摘要,不返回正文或收件人","parameters":[{"name":"week","in":"query","required":false,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}}, "/api/v1/qa-ops/master/weekly-mail/test": {"post":{"operationId":"sendQAWeeklyMailTest","tags":["QA operations"],"summary":"管理员用当前已保存的邮件设置立即发送一封测试邮件,正文取该周已保存草稿;不写入发送记录、不改变确认状态、不把该周标记为已发送","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["week"],"properties":{"week":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可测试发送"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因"},"503":{"description":"邮件设置存储不可用"}}}}, + "/api/v1/qa-ops/master/weekly-mail/send/{week}": {"get":{"operationId":"previewQAWeeklyMailSend","tags":["QA operations"],"summary":"管理员补发前核对:按周、已确认版本与正文hash返回真实主送/抄送人数、版本与是否已发送;不投递、不写记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"revision","in":"query","required":true,"schema":{"type":"integer","minimum":1}},{"name":"body_sha256","in":"query","required":true,"schema":{"type":"string","pattern":"^[0-9a-f]{64}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"邮件设置存储不可用"}}},"post":{"operationId":"sendQAWeeklyMailFormal","tags":["QA operations"],"summary":"管理员正式补发周报:精确指定周、已确认版本与正文hash;已结束周可发、当前周须到设定时点、未来周拒绝;正文/看板图片/主送/抄送与自动发送共用,写入正式发送记录并返回真实message_id;已发送幂等、结果未知不重发","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["revision","body_sha256"],"properties":{"revision":{"type":"integer","minimum":1},"body_sha256":{"type":"string","pattern":"^[0-9a-f]{64}$"}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且需同源操作意图"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知/授权码缺失"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因且不写已发送"},"503":{"description":"邮件设置存储不可用"}}}}, "/api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image": {"post":{"operationId":"saveQAWeeklyMailImage","tags":["QA operations"],"summary":"管理员保存该周确认对应的统计看板 PNG;发送时作为内嵌图片(cid)放在正文末尾,正文改动使确认失效后不再使用旧图","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["png_base64"],"properties":{"png_base64":{"type":"string","maxLength":12000000}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可上传"},"429":{"description":"请求过快"},"503":{"description":"邮件设置存储不可用"}}}}, "/api/v1/qa-ops/departments/statistics": { "post": { @@ -832,6 +833,62 @@ } } }, + "/api/v1/library/source-associations": { + "post": { + "tags": [ + "Runtime" + ], + "operationId": "associateLegacyLibrarySource", + "summary": "管理员核验原捕获证据并关联旧封存来源;不修改快照、不发布内容", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": false, + "required": [ + "scope", + "snapshot_id" + ], + "properties": { + "scope": { + "type": "string", + "enum": [ + "internal", + "external" + ] + }, + "snapshot_id": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "已持久关联并读回;associated=true,published=false,返回准确snapshot_id/source_id/source_identity" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "403": { + "description": "需要管理员登录身份" + }, + "409": { + "description": "原捕获证据缺失、来源/指纹/清单不符或已有不可变关联冲突" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "description": "来源配置或关联存储不可用" + } + } + } + }, "/api/v1/library/captures": { "get": { "tags": [ @@ -1312,6 +1369,45 @@ } } }, + "/api/v1/library/jobs/{id}/reconcile-capture": { + "post": { + "tags": [ + "Runtime" + ], + "operationId": "reconcileLibraryCapture", + "summary": "仅在 completed capture queue、精确 test_sealed 版本与归档复核一致时,修复该封存作业终态;不重新封存", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "已修复或已成功(幂等)" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "403": { + "description": "需要管理员权限" + }, + "404": { + "description": "作业不存在" + }, + "409": { + "description": "队列/阶段/版本/归档证据不一致,拒绝修复" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + } + } + }, "/api/v1/library/restore-availability": { "get": { "tags": [ @@ -1599,6 +1695,93 @@ } } }, + "/api/v1/library/verifications": { + "get": { + "tags": [ + "Runtime" + ], + "operationId": "getLibraryRestoreVerification", + "summary": "当前整库目标的恢复验证证据:verified 只由真实演练记录回答(按 target_id 绑定,换目标自动失效),并返回完整目标与失败原因", + "parameters": [ + { + "name": "scope", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": [ + "internal", + "external" + ] + } + } + ], + "responses": { + "200": { + "description": "目标与证据:verified/reason/latest/history/target" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "description": "恢复验证存储不可用或证据读取失败" + } + } + }, + "post": { + "tags": [ + "Runtime" + ], + "operationId": "startLibraryRestoreVerification", + "summary": "发起一次真实恢复验证(管理员):维护隔离下捕获目标 → 校验基线 → 写 canary 证明校验有效 → 按预备份恢复 → 复核,通过后才产生同步闸口认的证据", + "responses": { + "202": { + "description": "已创建 verify 作业(worker 在维护窗口内真实执行)" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "403": { + "description": "不是管理员" + }, + "409": { + "description": "目标正在维护或已有在飞写作业(同步/恢复/基线/验证互斥)" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "description": "生产写入闸口关闭或恢复验证存储不可用" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": false, + "required": [ + "scope" + ], + "properties": { + "scope": { + "type": "string", + "enum": [ + "internal", + "external" + ] + } + } + } + } + } + } + } + }, "/api/v1/library/snapshots/{id}": { "get": { "tags": [ @@ -2499,6 +2682,211 @@ } } }, + "/api/v1/pp-connection": { + "get": { + "operationId": "getPPConnection", + "summary": "管理员读取 PP 配置元数据及最近检查结果", + "responses": { + "200": { + "description": "请求完成", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/PPConnectionView" + } + } + } + } + } + }, + "400": { + "description": "输入格式错误" + }, + "401": { + "description": "需要登录或重新授权" + }, + "403": { + "description": "需要管理员权限或缺少目录权限" + }, + "409": { + "description": "配置或账号已变化" + }, + "422": { + "description": "明确拒绝本次配置,原配置保留" + }, + "500": { + "description": "内部错误" + }, + "503": { + "description": "依赖服务暂不可用" + } + } + }, + "put": { + "operationId": "savePPConnection", + "summary": "管理员保存并真实校验 PP 配置", + "responses": { + "200": { + "description": "请求完成", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/PPConnectionView" + } + } + } + } + } + }, + "400": { + "description": "输入格式错误" + }, + "401": { + "description": "需要登录或重新授权" + }, + "403": { + "description": "需要管理员权限或缺少目录权限" + }, + "409": { + "description": "配置或账号已变化" + }, + "422": { + "description": "明确拒绝本次配置,原配置保留" + }, + "500": { + "description": "内部错误" + }, + "503": { + "description": "依赖服务暂不可用" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PPConnectionDraft" + } + } + } + } + } + }, + "/api/v1/pp-connection/test": { + "post": { + "operationId": "testPPConnection", + "summary": "管理员使用草稿真实登录并读取最小目录,不登记来源", + "responses": { + "200": { + "description": "请求完成", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/PPObservation" + } + } + } + } + } + }, + "400": { + "description": "输入格式错误" + }, + "401": { + "description": "需要登录或重新授权" + }, + "403": { + "description": "需要管理员权限或缺少目录权限" + }, + "409": { + "description": "配置或账号已变化" + }, + "422": { + "description": "明确拒绝本次配置,原配置保留" + }, + "500": { + "description": "内部错误" + }, + "503": { + "description": "依赖服务暂不可用" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PPConnectionDraft" + } + } + } + } + } + }, + "/api/v1/dingtalk-spaces/validate": { + "post": { + "operationId": "validateDingtalkSourceSpaces", + "summary": "管理员用共享 DWS 身份真实检查所选空间可见性", + "responses": { + "200": { + "description": "请求完成" + }, + "400": { + "description": "输入格式错误" + }, + "401": { + "description": "需要登录或重新授权" + }, + "403": { + "description": "需要管理员权限或缺少目录权限" + }, + "409": { + "description": "配置或账号已变化" + }, + "422": { + "description": "明确拒绝本次配置,原配置保留" + }, + "500": { + "description": "内部错误" + }, + "503": { + "description": "依赖服务暂不可用" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "urls" + ], + "properties": { + "urls": { + "type": "array", + "minItems": 1, + "maxItems": 100, + "items": { + "type": "string" + } + } + } + } + } + } + } + } + }, "/api/v1/dingtalk-spaces": { "post": { "tags": [ @@ -3251,6 +3639,26 @@ } } }, + "/api/v1/system/worker-capabilities": { + "get": { + "tags": [ + "Settings" + ], + "operationId": "getWorkerCapabilities", + "summary": "读取 worker 能力心跳(执行器是否注册上传/解析链)", + "responses": { + "200": { + "$ref": "#/components/responses/Envelope" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + } + } + }, "/api/v1/routing-bindings": { "get": { "tags": [ @@ -5676,6 +6084,140 @@ } }, "schemas": { + "PPConnectionDraft": { + "type": "object", + "required": [ + "base_url", + "username", + "revision" + ], + "additionalProperties": false, + "properties": { + "base_url": { + "type": "string", + "format": "uri", + "description": "HTTPS API 根地址" + }, + "username": { + "type": "string", + "maxLength": 255 + }, + "password": { + "type": "string", + "writeOnly": true, + "maxLength": 8192, + "description": "省略或空值保留已存密码" + }, + "revision": { + "type": "integer", + "minimum": 0 + }, + "pending_id": { + "type": "string", + "description": "继续校验已保存的待验证修改" + } + } + }, + "PPSafeMetadata": { + "type": "object", + "required": [ + "id", + "base_url", + "username", + "password_configured" + ], + "properties": { + "id": { + "type": "string" + }, + "base_url": { + "type": "string", + "format": "uri" + }, + "username": { + "type": "string" + }, + "password_configured": { + "type": "boolean" + } + } + }, + "PPObservation": { + "type": "object", + "required": [ + "state", + "message", + "checked_at" + ], + "properties": { + "state": { + "type": "string", + "enum": [ + "valid", + "auth_failed", + "permission_denied", + "incomplete", + "unavailable", + "invalid_response" + ] + }, + "message": { + "type": "string" + }, + "checked_at": { + "type": "string", + "format": "date-time" + } + } + }, + "PPConnectionView": { + "type": "object", + "properties": { + "revision": { + "type": "integer" + }, + "active": { + "anyOf": [ + { + "$ref": "#/components/schemas/PPSafeMetadata" + }, + { + "type": "null" + } + ] + }, + "pending": { + "anyOf": [ + { + "$ref": "#/components/schemas/PPSafeMetadata" + }, + { + "type": "null" + } + ] + }, + "observation": { + "anyOf": [ + { + "$ref": "#/components/schemas/PPObservation" + }, + { + "type": "null" + } + ] + }, + "pending_observation": { + "anyOf": [ + { + "$ref": "#/components/schemas/PPObservation" + }, + { + "type": "null" + } + ] + } + } + }, "QAReportedHistoricalRate": { "type": "object", "additionalProperties": false, diff --git a/cmd/api/main.go b/cmd/api/main.go index 163a637..e41b7f8 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -3,11 +3,11 @@ package main import ( "context" "errors" + "fmt" "log" "net/http" "os" "os/signal" - "strings" "syscall" "time" @@ -17,13 +17,16 @@ import ( "knowledge-governance/internal/backuphost" "knowledge-governance/internal/dingtalkdiscovery" "knowledge-governance/internal/httpapi" + "knowledge-governance/internal/libraryhandoff" "knowledge-governance/internal/monitoring" postgresstore "knowledge-governance/internal/platform/postgres" "knowledge-governance/internal/platform/weknora" + "knowledge-governance/internal/ppauth" "knowledge-governance/internal/qaopsai" "knowledge-governance/internal/qaopsorg" "knowledge-governance/internal/qaopsquality" "knowledge-governance/internal/qawemail" + "knowledge-governance/internal/readiness" "knowledge-governance/internal/serviceverify" "knowledge-governance/internal/version" ) @@ -88,30 +91,10 @@ func run(ctx context.Context, getenv func(string) string) error { return errors.New("read production release authorization token") } } - // P10: with a mounted API key the probe verifies a real knowledge-base read - // (readiness); without one it degrades to the liveness-only HTTP check. - var weknoraReadiness func(context.Context) error - var knowledgeBaseLister httpapi.KnowledgeBaseLister - if strings.TrimSpace(config.TestWeKnoraBaseURL) != "" { - if apiKey, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); keyErr == nil { - probeTimeout := config.TestWeKnoraHTTPTimeout - if probeTimeout > 10*time.Second || probeTimeout <= 0 { - probeTimeout = 10 * time.Second - } - if probeClient, clientErr := weknora.NewClient(weknora.ClientConfig{BaseURL: config.TestWeKnoraBaseURL, APIKey: apiKey, Timeout: probeTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}); clientErr == nil { - knowledgeBaseLister = probeClient - routingKB := config.InternalRoutingKnowledgeBaseID - weknoraReadiness = func(probeCtx context.Context) error { - _, _, err := probeClient.ListKnowledge(probeCtx, routingKB, 1, 1) - return err - } - } - } - } // Production WeKnora is probed for liveness only: the console must show the // real state of that endpoint, while credentials and the publish target stay // in the release runtime config (RELEASE_CONFIG_FILE). - // 生产 WeKnora 端点:配置入口在网页「系统设置 → 服务配置」,管理员保存的值是 + // 生产 WeKnora 端点:配置入口在网页「系统设置 → 知识库映射」,管理员保存的值是 // 这里的真源;容器 env 只作为未在网页配置时的兜底。凭据与发布目标仍留在 // release 运行时配置(RELEASE_CONFIG_FILE)里,不经网页也不落明文。 actionStore := postgresstore.NewStore(pool) @@ -129,7 +112,43 @@ func run(ctx context.Context, getenv func(string) string) error { } return settings.TestWeKnoraBaseURL } - monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter}) + // P10 readiness 与执行链看同一目标:网页保存的端点、当前持久化绑定、同一份 + // API Key。启动时只捕获 resolver,不捕获任何一项的值(F13:旧 env 绑定 404)。 + readinessResolver := newWeKnoraReadinessResolver( + func(resolveCtx context.Context) string { + if saved := testEndpointResolver(resolveCtx); saved != "" { + return saved + } + return config.TestWeKnoraBaseURL + }, + config.InternalRoutingKnowledgeBaseID, + func(resolveCtx context.Context) (string, error) { + internal, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx) + return internal, err + }, + func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) }, + ) + readinessProber := readiness.Prober{ + Resolve: readinessResolver, + Timeout: config.TestWeKnoraHTTPTimeout, + AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP, + } + weknoraProbe := func(probeCtx context.Context) (string, error) { + result := readinessProber.Check(probeCtx) + return result.Target, result.Err + } + knowledgeBaseLister := &weKnoraLister{ + endpoint: func(resolveCtx context.Context) string { + if saved := testEndpointResolver(resolveCtx); saved != "" { + return saved + } + return config.TestWeKnoraBaseURL + }, + readKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) }, + timeout: config.TestWeKnoraHTTPTimeout, + allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP, + } + monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter}) if err != nil { return err } @@ -168,7 +187,28 @@ func run(ctx context.Context, getenv func(string) string) error { if getenv("DOBOTAI_OPS_TENANT_KEY") != "" { qaSyncStore = qaOrganizationStore } + // 快照搬运是否接线:只用于决定"发布/恢复作业先入哪个队列"。 + // 配置不完整即启动失败(半接线会让作业以"快照不在执行器"失败)。 + _, handoffConfigured, handoffErr := libraryhandoff.FromEnv(getenv) + if handoffErr != nil { + return fmt.Errorf("快照搬运接线无效: %w", handoffErr) + } + log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity()) + ppStateFile := getenv("PP_AUTH_STATE_FILE") + if ppStateFile == "" { + ppStateFile = "/data/source-auth/pp/settings.json" + } + ppPython := getenv("PP_AUTH_PYTHON") + if ppPython == "" { + ppPython = "/usr/bin/python3" + } + ppScript := getenv("PP_AUTH_CHECK_SCRIPT") + if ppScript == "" { + ppScript = "/app/scripts/pp_client.py" + } handler, err := httpapi.NewHandler(httpapi.Config{ + PPConnection: &ppauth.Manager{Path: ppStateFile, LegacyPath: getenv("PP_LEGACY_CREDENTIALS_FILE"), Probe: ppauth.CommandProbe(ppPython, ppScript)}, + LibraryHandoffEnabled: handoffConfigured, QAAI: qaopsai.NewFromEnvironment(pool, getenv, config.DatabaseURL), QAWeeklyMail: qawemail.NewStore(pool, qaSettings.TenantKey, getenv("QA_AI_MASTER_KEY_FILE"), nil), QAAITrustTLSProxy: getenv("QA_AI_TRUST_TLS_PROXY") == "true", @@ -180,7 +220,7 @@ func run(ctx context.Context, getenv func(string) string) error { QAOpsTenantKey: qaSettings.TenantKey, QAOpsEnabled: qaSettings.Enabled, QAOpsProblem: qaSettings.Problem, - Store: postgresstore.NewStore(pool), + Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID), Monitor: monitorProvider, InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID, ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID, @@ -197,6 +237,7 @@ func run(ctx context.Context, getenv func(string) string) error { ProductionReleaseAuthorizationToken: releaseAuthorizationToken, // 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。 DingtalkSources: dingtalkSourceLister{}, + DWSLogin: dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{}), DingtalkDocuments: dingtalkSourceLister{}, BackupSchedule: postgresstore.NewStore(pool), VersionHistory: versionHistoryStore, @@ -207,10 +248,16 @@ func run(ctx context.Context, getenv func(string) string) error { LibraryTargetWriters: config.LibraryTargetWriters, LibraryTargetIngressURL: config.LibraryTargetIngressURL, LibraryTargetIngressService: config.LibraryTargetIngressService, + LibraryTargetIngressMode: config.LibraryTargetIngressMode, + LibraryTargetHealthURL: config.LibraryTargetHealthURL, LibraryTargetDockerSocket: config.LibraryTargetDockerSocket, LibraryTargetJournalRoot: config.LibraryTargetJournalRoot, LibrarySourceInstance: config.SourceInstance(), LibrarySourceProject: config.SourceProject(), + LibrarySourceApp: config.LibrarySourceApp, + LibrarySourceTenantID: config.LibrarySourceTenantID, + LibrarySourceInternalKB: config.LibrarySourceInternalKB, + LibrarySourceExternalKB: config.LibrarySourceExternalKB, LibraryAgentSocket: config.LibraryAgentSocket, LibraryExecutorStatusMaxAge: config.LibraryExecutorStatusMaxAge, LibraryCapacityBudgetBytes: config.LibraryCapacityBudgetBytes, @@ -218,6 +265,8 @@ func run(ctx context.Context, getenv func(string) string) error { LibraryProductionInternalKB: config.LibraryProductionInternalKB, LibraryProductionExternalKB: config.LibraryProductionExternalKB, LibraryProductionTenantID: config.LibraryProductionTenantID, + LibraryProductionIndex: config.LibraryProductionIndex, + LibraryProductionS3Bucket: config.LibraryProductionS3Bucket, LibraryRetentionVersions: config.LibraryRetentionVersions, LibraryRetentionDays: config.LibraryRetentionDays, BackupHost: backuphost.New(backuphost.Config{ diff --git a/cmd/api/readiness.go b/cmd/api/readiness.go new file mode 100644 index 0000000..42abb29 --- /dev/null +++ b/cmd/api/readiness.go @@ -0,0 +1,81 @@ +package main + +import ( + "context" + "fmt" + "log" + "strings" + "time" + + "knowledge-governance/internal/platform/weknora" + "knowledge-governance/internal/readiness" +) + +// newWeKnoraReadinessResolver 把「探测目标」收敛到与业务同一组真源: +// 端点来自网页「知识库映射」保存的连接配置(endpoint 内部已做 env 兜底),知识库来自 +// 当前持久化绑定(未绑定才用 env 引导值),凭据每次重新读同一份 key 文件。 +// 任何一项读取失败都必须显式报错——静默退回旧值正是 F13 的成因。 +func newWeKnoraReadinessResolver( + endpoint func(context.Context) string, + envKnowledgeBaseID string, + loadBinding func(context.Context) (string, error), + readKey func() (string, error), +) func(context.Context) (readiness.Target, error) { + resolver := readiness.Resolver{ + Endpoint: endpoint, + DefaultKB: envKnowledgeBaseID, + LoadBinding: func(resolveCtx context.Context) (string, error) { + if loadBinding == nil { + return "", nil + } + stored, err := loadBinding(resolveCtx) + if err != nil { + log.Printf("readiness: load routing bindings: %v", err) + } + return stored, err + }, + ReadKey: func() (string, error) { + if readKey == nil { + return "", nil + } + value, err := readKey() + if err != nil { + log.Printf("readiness: read WeKnora API key: %v", err) + } + return value, err + }, + } + return resolver.Resolve +} + +// weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据, +// 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。 +type weKnoraLister struct { + endpoint func(context.Context) string + readKey func() (string, error) + timeout time.Duration + allowDockerHTTP bool +} + +func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) { + baseURL := "" + if lister.endpoint != nil { + baseURL = strings.TrimSpace(lister.endpoint(ctx)) + } + if baseURL == "" { + return nil, fmt.Errorf("WeKnora 端点未配置") + } + apiKey, err := lister.readKey() + if err != nil { + return nil, err + } + timeout := lister.timeout + if timeout <= 0 || timeout > 10*time.Second { + timeout = 10 * time.Second + } + client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP}) + if err != nil { + return nil, err + } + return client.ListKnowledgeBases(ctx) +} diff --git a/cmd/api/readiness_test.go b/cmd/api/readiness_test.go new file mode 100644 index 0000000..8a9f1c4 --- /dev/null +++ b/cmd/api/readiness_test.go @@ -0,0 +1,112 @@ +package main + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "knowledge-governance/internal/readiness" +) + +// F13 的接线回归:探测目标必须来自「网页保存的端点 + 当前持久化绑定」, +// env 只能是未绑定时的引导兜底;任何一项都不许在启动时固化。 +func TestReadinessResolverUsesPersistedBindingOverEnv(t *testing.T) { + const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c" + const storedKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8" + resolve := newWeKnoraReadinessResolver( + func(context.Context) string { return "https://weknora.test" }, + envKB, + func(context.Context) (string, error) { return storedKB, nil }, + func() (string, error) { return "key-1", nil }, + ) + target, err := resolve(context.Background()) + if err != nil { + t.Fatal(err) + } + if target.KnowledgeBaseID != storedKB || target.BaseURL != "https://weknora.test" || target.APIKey != "key-1" { + t.Fatalf("resolved target = %#v", target) + } +} + +func TestReadinessResolverFallsBackToEnvOnlyWhenUnbound(t *testing.T) { + const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c" + resolve := newWeKnoraReadinessResolver( + func(context.Context) string { return "https://weknora.test" }, + envKB, + func(context.Context) (string, error) { return "", nil }, + func() (string, error) { return "key-1", nil }, + ) + target, err := resolve(context.Background()) + if err != nil || target.KnowledgeBaseID != envKB { + t.Fatalf("unbound fallback = %#v, %v", target, err) + } +} + +func TestReadinessResolverReportsBindingAndCredentialFailures(t *testing.T) { + bindingDown := newWeKnoraReadinessResolver( + func(context.Context) string { return "https://weknora.test" }, + "env-kb", + func(context.Context) (string, error) { return "", errors.New("db unavailable") }, + func() (string, error) { return "key-1", nil }, + ) + target, err := bindingDown(context.Background()) + if err == nil { + t.Fatalf("binding read failure must not silently probe env: %#v", target) + } + keyDown := newWeKnoraReadinessResolver( + func(context.Context) string { return "https://weknora.test" }, + "env-kb", + func(context.Context) (string, error) { return "", nil }, + func() (string, error) { return "", errors.New("key file missing") }, + ) + if _, err := keyDown(context.Background()); err == nil { + t.Fatal("missing API key must surface, not degrade to liveness-only") + } +} + +func TestReadinessResolverMarksUnconfiguredEndpoint(t *testing.T) { + resolve := newWeKnoraReadinessResolver( + func(context.Context) string { return "" }, + "env-kb", + func(context.Context) (string, error) { return "", nil }, + func() (string, error) { return "key-1", nil }, + ) + // 端点缺失时归类为「未配置」,不是「服务不可用」。 + result := readiness.Prober{Resolve: resolve}.Check(context.Background()) + if !errors.Is(result.Err, readiness.ErrNotConfigured) { + t.Fatalf("blank endpoint probe = %v, want ErrNotConfigured", result.Err) + } +} + +func TestKnowledgeBaseListerFollowsTheCurrentEndpoint(t *testing.T) { + base := func(name string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path != "/api/v1/knowledge-bases" { + writer.WriteHeader(http.StatusNotFound) + return + } + _, _ = writer.Write([]byte(`{"success":true,"data":[{"id":"` + name + `","name":"` + name + `"}]}`)) + })) + } + first, second := base("kb-a"), base("kb-b") + defer first.Close() + defer second.Close() + endpoint := first.URL + lister := &weKnoraLister{ + endpoint: func(context.Context) string { return endpoint }, + readKey: func() (string, error) { return "key-1", nil }, + timeout: time.Second, + } + bases, err := lister.ListKnowledgeBases(context.Background()) + if err != nil || len(bases) != 1 || bases[0].ID != "kb-a" { + t.Fatalf("initial endpoint bases = %#v, %v", bases, err) + } + endpoint = second.URL + bases, err = lister.ListKnowledgeBases(context.Background()) + if err != nil || len(bases) != 1 || bases[0].ID != "kb-b" { + t.Fatalf("rotated endpoint bases = %#v, %v", bases, err) + } +} diff --git a/cmd/libraryagent/main.go b/cmd/libraryagent/main.go index 81fe64e..d401add 100644 --- a/cmd/libraryagent/main.go +++ b/cmd/libraryagent/main.go @@ -10,10 +10,13 @@ import ( "os" "os/signal" "path/filepath" + "strconv" + "strings" "syscall" "time" "knowledge-governance/internal/libraryagent" + "knowledge-governance/internal/librarydsn" "knowledge-governance/internal/librarymaintenance" ) @@ -25,22 +28,43 @@ func main() { flag.StringVar(&config.ArchiveRoot, "archive", filepath.Join(home, ".local/share/knowledge-governance/library"), "sealed artifact root") flag.StringVar(&config.JournalRoot, "journal", filepath.Join(home, ".local/share/knowledge-governance/freeze"), "freeze journal root") flag.StringVar(&config.SourceApp, "source-app", "WKNFull-app", "source container describing the stack") - flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container") + flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container; empty = the source DB lives on a managed instance and is reached with the source app env (DB_HOST/...)") flag.StringVar(&config.SourceES, "source-es", "WKNFull-elasticsearch", "source Elasticsearch container") flag.StringVar(&config.SourceS3Endpoint, "source-s3-endpoint", "", "host-reachable source object-store endpoint (overrides the container-internal one)") - flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container") + flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE") flag.StringVar(&config.Project, "project", "weknora071full", "Compose project owning the writers") flag.StringVar(&config.Writers, "writers", "app", "declared writer services") nonWriters := flag.String("non-writers", defaultNonWriters, "service=reason for every other project service") + allowUIDs := flag.String("allow-peer-uid", "", "extra peer uids allowed to connect (comma separated; default: same uid only)") flag.DurationVar(&config.MaxDuration, "max-duration", 10*time.Minute, "upper bound for one operation") describe := flag.Bool("describe", false, "print the fixed configuration and exit") flag.Parse() + if strings.TrimSpace(*allowUIDs) != "" { + for _, raw := range strings.Split(*allowUIDs, ",") { + raw = strings.TrimSpace(raw) + if raw == "" { + continue + } + uid, err := strconv.ParseUint(raw, 10, 32) + if err != nil { + log.Fatalf("--allow-peer-uid 需要十进制 uid:%q", raw) + } + config.AllowedPeerUIDs = append(config.AllowedPeerUIDs, uint32(uid)) + } + } config.NonWriters = *nonWriters agent, err := libraryagent.New(config) if err != nil { log.Fatal(err) } + if *describe { + // describe 只回答"这两个库从哪来"。地址与凭据一律不出现:这段输出会被贴进 + // 工单与日志,而 RDS 的连接串里带口令。 + log.Printf("source_db=%s governance_db=%s", + librarydsn.SourceMode(config.SourcePG), librarydsn.GovernanceMode(config.GovernancePG)) + return + } // 实例级维护接线(入口闸门 + 后台队列)不在 agent 的 Config 里:它由同一份 // 环境声明提供给子进程。启动时先说清楚有没有——缺了封存会在开窗口前被拒, // 不允许"以为接好了"跑到一半才发现没有排空证据。 @@ -49,10 +73,6 @@ func main() { } else { log.Printf("library agent: 实例级维护目标 %s 入口 %s 闸门 %s", target.Instance, target.IngressURL, target.IngressService) } - if *describe { - log.Printf("library agent config: %+v", agent.Describe()) - return - } ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() log.Printf("library agent listening on %s (project %s, writers %s)", config.Socket, config.Project, config.Writers) diff --git a/cmd/libraryctl/governance_dsn_test.go b/cmd/libraryctl/governance_dsn_test.go new file mode 100644 index 0000000..d5bff4e --- /dev/null +++ b/cmd/libraryctl/governance_dsn_test.go @@ -0,0 +1,44 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +// 文件模式没配置:必须失败关闭并点名缺的那个变量——"静默退回容器模式"会让 +// 操作员以为在读 RDS,实际在读本机容器(或者干脆读到不存在的容器)。 +func TestGovernanceFileModeFailsClosedWithoutDSNFile(t *testing.T) { + t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", "") + _, err := readRoutingBindings(context.Background(), options{governancePG: ""}) + if err == nil { + t.Fatal("没有 DSN 文件却读成功了") + } + if !strings.Contains(err.Error(), "LIBRARY_GOVERNANCE_DSN_FILE") { + t.Fatalf("错误没有点名缺哪一项:%v", err) + } +} + +// 外部 DSN 连不上/写错时,错误必须是固定说法:pgx 的错误里带的是连接串(主机、 +// 用户名,口令它自己打码),直接透传就等于把地址写进日志与工单。 +func TestGovernanceFileModeNeverLeaksPasswordInErrors(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "governance.dsn") + // 夹具口令运行时拼装:源码里不留“带口令的连接串”字面量,否则密钥扫描只会 + // 报出一堆必然是假值的夹具,把真泄漏的信号淹掉。 + password := strings.Join([]string{"fixture", "leak", "probe"}, "-") + // 故意用非法 sslmode + 不可达端口:无论失败在解析还是连接阶段,都不许泄露。 + if err := os.WriteFile(path, []byte("postgres://gov:"+password+"@127.0.0.1:1/gov?sslmode=bogus&connect_timeout=1\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", path) + _, err := readRoutingBindings(context.Background(), options{governancePG: ""}) + if err == nil { + t.Fatal("坏 DSN 竟然读成功了") + } + if strings.Contains(err.Error(), password) { + t.Fatalf("错误里漏了口令:%v", err) + } +} diff --git a/cmd/libraryctl/main.go b/cmd/libraryctl/main.go index 7b2206b..71d5ca9 100644 --- a/cmd/libraryctl/main.go +++ b/cmd/libraryctl/main.go @@ -30,10 +30,13 @@ import ( "syscall" "time" + "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "knowledge-governance/internal/librarydeadletter" + "knowledge-governance/internal/librarydsn" "knowledge-governance/internal/libraryfreeze" + "knowledge-governance/internal/libraryhandoff" "knowledge-governance/internal/librarymaintenance" "knowledge-governance/internal/librarysnapshot" v071 "knowledge-governance/internal/releaseadapter/v071" @@ -60,6 +63,11 @@ type options struct { job string dryRun bool snapshot string + // kb/tenant 是 snapshot-push 要核对的期望身份(来自治理库作业,不是 bundle 自报)。 + kb string + tenant uint64 + // bundle 是快照跨主机包路径(snapshot-pack 输出 / snapshot-unpack 输入)。 + bundle string // releasedDeadLetters 是治理平台审计过的精确解除指纹(逗号分隔)。它只让这些 // 确切的行不再阻断;实时行必须逐字节命中,否则照旧拒绝。 releasedDeadLetters string @@ -100,6 +108,16 @@ func main() { runErr = runRecover(ctx, opts) case "dead-letters": runErr = runDeadLetters(ctx, opts) + case "snapshot-pack": + runErr = runSnapshotPack(opts) + case "snapshot-unpack": + runErr = runSnapshotUnpack(opts) + case "snapshot-push": + runErr = runSnapshotPush(opts) + case "snapshot-fetch": + runErr = runSnapshotFetch(opts) + case "snapshot-verify": + runErr = runSnapshotVerify(opts) default: usage() os.Exit(2) @@ -111,7 +129,7 @@ func main() { } func usage() { - fmt.Fprint(os.Stderr, `libraryctl [flags] + fmt.Fprint(os.Stderr, `libraryctl [flags] status probe the real source and print what is configured / blocked preflight read the source, run settlement + candidate validation (no writes, no stop) @@ -121,12 +139,22 @@ func usage() { recover restore writers from an interrupted freeze journal dead-letters print the source's live dead letters (read-only) with a digest the governance platform binds a precise release to + snapshot-pack export one sealed snapshot into a single verifiable bundle file + snapshot-unpack verify a bundle and install it into this archive (content-addressed, + version manifest is the commit point; repeated import is idempotent) + snapshot-push send one sealed snapshot to the cloud release executor (verify on both sides) + snapshot-fetch bring a cloud-held snapshot back into this archive (verified) + snapshot-verify re-hash every part of one snapshot (used before reusing a remote copy) Flags (defaults target the local WKNFull test stack): -source-app WKNFull-app container whose env describes the source - -source-pg WKNFull-postgres source PostgreSQL container (address resolution) + -source-pg WKNFull-postgres source PostgreSQL container; empty = the source DB is a + managed instance: connect with the source app env + (DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD), TLS mode from + LIBRARY_SOURCE_DB_SSLMODE (default require) -source-es WKNFull-elasticsearch - -governance-pg knowledge-governance-p1-postgres-1 routing bindings read here + -governance-pg knowledge-governance-p1-postgres-1 routing bindings read here; empty = read + the DSN from LIBRARY_GOVERNANCE_DSN_FILE (0600 file) -project weknora071full Compose project owning the writer group -writers WKNFull-app declared writer services (comma separated) -non-writers WKNFull-frontend=reason,... every other project service @@ -160,9 +188,9 @@ func parseFlags(command string, args []string) (options, []string, error) { set := flag.NewFlagSet(command, flag.ContinueOnError) set.SetOutput(os.Stderr) set.StringVar(&opts.sourceApp, "source-app", opts.sourceApp, "source container describing the stack") - set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container") + set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container; empty = connect to the source app's external (managed) database") set.StringVar(&opts.sourceES, "source-es", opts.sourceES, "source Elasticsearch container") - set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container") + set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE") set.StringVar(&opts.project, "project", opts.project, "Compose project owning the writers") set.StringVar(&opts.writers, "writers", opts.writers, "declared writer services") set.StringVar(&opts.nonWriters, "non-writers", "", "service=reason for every other project service") @@ -177,6 +205,9 @@ func parseFlags(command string, args []string) (options, []string, error) { set.BoolVar(&opts.dryRun, "dry-run", false, "export and validate without archiving or stopping") set.StringVar(&opts.snapshot, "snapshot", "", "snapshot id for verify") set.StringVar(&opts.releasedDeadLetters, "released-dead-letters", "", "audited dead-letter fingerprints (comma separated)") + set.StringVar(&opts.bundle, "bundle", "", "snapshot bundle path (snapshot-pack / snapshot-unpack)") + set.StringVar(&opts.kb, "kb", "", "expected knowledge base id (snapshot-push)") + set.Uint64Var(&opts.tenant, "tenant", 0, "expected tenant id (snapshot-push)") if err := set.Parse(args); err != nil { return opts, nil, err } @@ -260,15 +291,25 @@ func discoverSource(ctx context.Context, opts options, binding map[string]string if app["DB_DRIVER"] != "postgres" { return config, errors.New("source database driver is not postgres") } - address, err := containerAddress(ctx, opts.sourcePG) - if err != nil { - return config, err + // 两种来源:给了 -source-pg 就按容器地址拼(0.7.1 栈);没给说明库是托管 + // 实例(RDS 型 0.9.0 栈没有源库容器),用源应用容器 env 里的 DB_* 直连。 + if librarydsn.SourceMode(opts.sourcePG) == librarydsn.SourceExternal { + dsn, dsnErr := librarydsn.SourceURL(app, os.Getenv) + if dsnErr != nil { + return config, dsnErr + } + config.DatabaseURL = dsn + } else { + address, addressErr := containerAddress(ctx, opts.sourcePG) + if addressErr != nil { + return config, addressErr + } + dsn, dsnErr := librarydsn.ContainerURL(address, app) + if dsnErr != nil { + return config, dsnErr + } + config.DatabaseURL = dsn } - dsn := strings.Join([]string{ - "postgres://" + urlEscape(app["DB_USER"]) + ":" + urlEscape(app["DB_PASSWORD"]) + - "@" + address + ":" + app["DB_PORT"] + "/" + urlEscape(app["DB_NAME"]) + "?sslmode=disable", - }, "") - config.DatabaseURL = dsn config.AppImageID, err = containerImageID(ctx, opts.sourceApp) if err != nil { return config, err @@ -363,17 +404,12 @@ func parseBool(value string) bool { return false } -func urlEscape(value string) string { - replacer := strings.NewReplacer("%", "%25", ":", "%3A", "@", "%40", "/", "%2F", "?", "%3F", "#", "%23", "&", "%26", " ", "%20") - return replacer.Replace(value) -} - // scopeBindings 返回 scope→知识库 映射。治理 API 用的是 LIBRARY_PRODUCTION_KB_*, // CLI 读的是治理库里的 routing bindings;同一台机器上两份不一致时, // CLI 抓到的会是"配置里那个库"而不是 API 认为的目标——所以环境变量优先, // 读不到才退回 bindings。两边讲同一份身份,验收才可比。 -func scopeBindings(ctx context.Context, container string) (map[string]string, error) { - binding, err := readRoutingBindings(ctx, container) +func scopeBindings(ctx context.Context, opts options) (map[string]string, error) { + binding, err := readRoutingBindings(ctx, opts) if err != nil { return nil, err } @@ -385,17 +421,105 @@ func scopeBindings(ctx context.Context, container string) (map[string]string, er return binding, nil } -func readRoutingBindings(ctx context.Context, container string) (map[string]string, error) { - raw, err := dockerOutput(ctx, "exec", container, "psql", "-U", "governance", "-d", "governance", "-tAc", - "SELECT internal_kb_id||'|'||external_kb_id FROM routing_kb_bindings WHERE id='active'") +// readRoutingBindings 读治理库里生效的 scope 绑定。两种来源: +// - 给了 -governance-pg:docker exec 进治理库容器跑 psql(0.7.1 本机栈); +// - 没给:治理库是托管实例(RDS 型 0.9.0 栈没有 governance 容器),DSN 来自 +// LIBRARY_GOVERNANCE_DSN_FILE 指向的 0600 文件。 +// +// 两条路径只共用行解析,不共用连接方式:容器里没有网络到 RDS 的凭据,宿主机也不该 +// 为了读两列去 docker exec 一个不存在的容器。 +func readRoutingBindings(ctx context.Context, opts options) (map[string]string, error) { + if librarydsn.GovernanceMode(opts.governancePG) == librarydsn.GovernanceFile { + dsn, err := librarydsn.GovernanceURL(os.Getenv) + if err != nil { + return nil, err + } + return readRoutingBindingsFromDSN(ctx, dsn) + } + raw, err := dockerOutput(ctx, "exec", opts.governancePG, "psql", "-U", "governance", "-d", "governance", "-tAc", + routingBindingsQuery) if err != nil { return nil, errors.New("read routing bindings failed") } - internal, external, ok := strings.Cut(strings.TrimSpace(raw), "|") - if !ok || internal == "" || external == "" { - return nil, errors.New("routing bindings are incomplete") + return parseRoutingBindings(raw) +} + +// COALESCE 不能省:两列都可能是 NULL(0.9.0 迁移把\"旧知识库绑定已解除\"落成 NULL, +// 平台约定\"对外库没有对应目标时留空\")。裸拼接遇 NULL 得到整行 NULL,文件模式 +// 会在 Scan 成 string 时直接失败,报出的还是一句\"read routing bindings failed\"—— +// 真正的原因(哪一列没绑)被吞掉。这里先拼成固定形状,由 parseRoutingBindings 判。 +const routingBindingsQuery = "SELECT COALESCE(internal_kb_id,'')||'|'||COALESCE(external_kb_id,'') FROM routing_kb_bindings WHERE id='active'" + +// readRoutingBindingsFromDSN 用外部 DSN 读同一份绑定。 +// +// 只读会话是刻意的:这条路径只是读两列,出了问题必须是"读不到",而不是在治理库上 +// 留下一次写入。错误一律收敛成固定说法:pgx 的错误里会带连接串(口令它自己打了码, +// 但主机与用户名照旧出去),而这里连那份地址都不该出现在日志或工单里。 +func readRoutingBindingsFromDSN(ctx context.Context, dsn string) (map[string]string, error) { + parsed, err := pgxpool.ParseConfig(dsn) + if err != nil { + return nil, errors.New("governance database url is invalid") } - return map[string]string{"internal": internal, "external": external}, nil + parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on" + parsed.ConnConfig.RuntimeParams["statement_timeout"] = "30000" + parsed.MaxConns = 2 + pool, err := pgxpool.NewWithConfig(ctx, parsed) + if err != nil { + return nil, errors.New("open governance database failed") + } + defer pool.Close() + var raw string + if err = pool.QueryRow(ctx, routingBindingsQuery).Scan(&raw); err != nil { + return nil, errors.New("read routing bindings failed") + } + return parseRoutingBindings(raw) +} + +// parseRoutingBindings 解一行 `|`。两条来源(psql -tAc 与 pgx +// 只读会话)拼的是同一句 SQL,所以只有这一份解析语义。 +// +// 对内库必填:没有对内库就没有\"整库\"可言,此时必须点名是哪一列没绑,而不是退化成 +// 泛化的读失败。对外库可空:平台侧约定\"对外库没有对应目标时留空\",绑定本身仍然 +// 有效(`status`、internal scope 照常可跑);只有真去用 external scope 时才拒绝, +// 且绝不回退到对内库——那会把对内库的内容当成对外库封存出去。 +func parseRoutingBindings(raw string) (map[string]string, error) { + trimmed := strings.TrimSpace(raw) + // 空输出 = 没有生效绑定行,等于对内库没绑:这跟"读失败"是两件事, + // 必须说成前者,否则现场又会退回一句泛化错误。 + if trimmed == "" { + return nil, errInternalKBMissing + } + internal, external, ok := strings.Cut(trimmed, "|") + if !ok { + return nil, errors.New("read routing bindings failed") + } + internal = strings.TrimSpace(internal) + external = strings.TrimSpace(external) + if internal == "" { + return nil, errInternalKBMissing + } + binding := map[string]string{"internal": internal} + if external != "" { + binding["external"] = external + } + return binding, nil +} + +var ( + errInternalKBMissing = errors.New("对内知识库未绑定(routing_kb_bindings.internal_kb_id 为空)") + errExternalKBMissing = errors.New("对外知识库未配置(routing_kb_bindings.external_kb_id 为空)") +) + +// scopeKnowledgeBase 取本次 scope 的目标库。空值必须在这里就拒绝:往下走会变成 +// \"knowledge base not found in source\"——那是拿空 UUID 查源库得到的假原因。 +func scopeKnowledgeBase(binding map[string]string, scope string) (string, error) { + if kb := strings.TrimSpace(binding[scope]); kb != "" { + return kb, nil + } + if scope == "external" { + return "", errExternalKBMissing + } + return "", errInternalKBMissing } func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool, error) { @@ -407,11 +531,25 @@ func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool // that a database-enforced property rather than a convention. parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on" parsed.ConnConfig.RuntimeParams["statement_timeout"] = "120000" + // 启动参数不足以保证只读:角色级/库级设置会在启动参数之后生效,托管实例 + // (RDS)上实测就是这样——SHOW 回来是 off。而池里每条连接是独立的会话, + // 对单条连接 SET 管不到其他连接,所以放在 AfterConnect:每条新连接都显式 + // 置只读,池里就没有能写的会话。下面的 SHOW 只是对任意一条连接再核一次。 + parsed.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error { + _, err := conn.Exec(ctx, "SET SESSION default_transaction_read_only = on") + return err + } pool, err := pgxpool.NewWithConfig(ctx, parsed) if err != nil { return nil, errors.New("open source database failed") } var readOnly string + // 连接失败与"能连上但会话可写"必须分开报:把两者压成同一句,现场只能看到 + // 一句无信息量的失败,反而会去怀疑权限或只读设置。 + if err = pool.Ping(ctx); err != nil { + pool.Close() + return nil, errors.New("source database connection failed") + } if err = pool.QueryRow(ctx, "SHOW default_transaction_read_only").Scan(&readOnly); err != nil || readOnly != "on" { pool.Close() return nil, errors.New("source session is not read-only") @@ -485,6 +623,11 @@ func openFreeze(ctx context.Context, opts options) (*libraryfreeze.Coordinator, // // 入口/队列的声明与容器内 worker 共用同一组 LIBRARY_TARGET_* 名称, // 数据库/索引/桶则取自本次真实发现的源,避免"关的是 A 的门、读的是 B 的队列"。 +// +// LIBRARY_TARGET_INGRESS_MODE=none 只给整栈没有闸门的测试环境(0.9.0 测试栈): +// 必须同时给 LIBRARY_NO_INGRESS_ACK=test-only,窗口里一笔闸门动作都不做, +// 排空证据降为"写者全停 + 队列静默",恢复由 LIBRARY_TARGET_HEALTH_URL 的 200 证明。 +// 缺省仍是 gate:没有显式确认就照旧要求闸门。 func captureMaintenanceConfig(opts options, source sourceConfig, get func(string) string) (librarymaintenance.Config, error) { target, err := librarymaintenance.TargetFromEnv(get) if err != nil { @@ -504,9 +647,12 @@ func captureMaintenanceConfig(opts options, source sourceConfig, get func(string Writers: writers, NonWriters: nonWriters, DockerSocket: opts.dockerSocket, + IngressMode: target.Mode, + IngressAck: target.Ack, IngressURL: target.IngressURL, IngressService: target.IngressService, IngressDrainFile: target.IngressDrainFile, + HealthURL: target.HealthURL, Database: identity, Index: source.SearchIndex, Bucket: source.Object.Bucket, @@ -562,7 +708,12 @@ func openArchive(opts options) (*librarysnapshot.Archive, error) { func runStatus(ctx context.Context, opts options) error { report := map[string]any{} - binding, bindingErr := scopeBindings(ctx, opts.governancePG) + // 只报来源模式:地址与凭据连 describe/status 都不出现,日志自然也不会带出去。 + report["databases"] = map[string]string{ + "source_db": librarydsn.SourceMode(opts.sourcePG), + "governance_db": librarydsn.GovernanceMode(opts.governancePG), + } + binding, bindingErr := scopeBindings(ctx, opts) var config sourceConfig var err error if bindingErr != nil { @@ -655,7 +806,12 @@ func runPreflight(ctx context.Context, opts options) error { if opts.scope != "internal" && opts.scope != "external" { return errors.New("-scope must be internal or external") } - binding, err := scopeBindings(ctx, opts.governancePG) + binding, err := scopeBindings(ctx, opts) + if err != nil { + return err + } + // 绑定缺哪一半在连源库之前就要说清楚:external 未配置不是"源库里没这个库"。 + kb, err := scopeKnowledgeBase(binding, opts.scope) if err != nil { return err } @@ -668,7 +824,6 @@ func runPreflight(ctx context.Context, opts options) error { return err } defer pool.Close() - kb := config.Scopes[opts.scope] tenant, err := tenantAndKnowledgeBase(ctx, pool, kb) if err != nil { return err @@ -748,7 +903,13 @@ func runCapture(ctx context.Context, opts options) error { return err } defer archive.Close() - binding, err := scopeBindings(ctx, opts.governancePG) + binding, err := scopeBindings(ctx, opts) + if err != nil { + return err + } + // 先定住本次 scope 的库:external 没配置时,封存必须在开维护窗口之前就停, + // 不能先停写者再发现目标为空。 + kb, err := scopeKnowledgeBase(binding, opts.scope) if err != nil { return err } @@ -776,7 +937,7 @@ func runCapture(ctx context.Context, opts options) error { if err != nil { return err } - scopedKB := binding[opts.scope] + scopedKB := kb if found { manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive) if err != nil { @@ -789,7 +950,6 @@ func runCapture(ctx context.Context, opts options) error { return err } defer pool.Close() - kb := config.Scopes[opts.scope] tenant, err := tenantAndKnowledgeBase(ctx, pool, kb) if err != nil { return err @@ -1125,7 +1285,12 @@ func runDeadLetters(ctx context.Context, opts options) error { if opts.scope != "internal" && opts.scope != "external" { return errors.New("-scope must be internal or external") } - binding, err := scopeBindings(ctx, opts.governancePG) + binding, err := scopeBindings(ctx, opts) + if err != nil { + return err + } + // external 未配置时,死信观测同样要明说"没配置",而不是拿空库去查源库。 + kb, err := scopeKnowledgeBase(binding, opts.scope) if err != nil { return err } @@ -1138,7 +1303,6 @@ func runDeadLetters(ctx context.Context, opts options) error { return err } defer pool.Close() - kb := config.Scopes[opts.scope] tenant, err := tenantAndKnowledgeBase(ctx, pool, kb) if err != nil { return err @@ -1151,3 +1315,121 @@ func runDeadLetters(ctx context.Context, opts options) error { printJSON(map[string]any{"observation": json.RawMessage(payload), "observation_digest": digest}) return nil } + +// runSnapshotPack 导出一份已封存版本,供另一台主机(发布执行器所在机)导入。 +// 只读本机归档:不碰来源、不碰目标、不改任何版本。 +func runSnapshotPack(opts options) error { + if opts.snapshot == "" || opts.bundle == "" { + return errors.New("snapshot-pack 需要 -snapshot 与 -bundle ") + } + archive, err := openArchive(opts) + if err != nil { + return err + } + defer archive.Close() + info, err := archive.Pack(opts.snapshot, opts.bundle) + if err != nil { + return err + } + printJSON(info) + return nil +} + +// runSnapshotUnpack 校验并装入快照包。装入是内容寻址 + 版本清单提交: +// 校验不通过就什么都不留下,重复导入是幂等成功。 +func runSnapshotUnpack(opts options) error { + if opts.bundle == "" { + return errors.New("snapshot-unpack 需要 -bundle (-snapshot 可选,用于核对身份)") + } + archive, err := openArchive(opts) + if err != nil { + return err + } + defer archive.Close() + manifest, err := archive.Unpack(opts.bundle, opts.snapshot) + if err != nil { + return err + } + printJSON(map[string]any{ + "format": librarysnapshot.Format, + "scope": manifest.Scope, + "tenant_id": manifest.TenantID, + "knowledge_base_id": manifest.KnowledgeBaseID, + "parts": len(manifest.Parts), + "created_at": manifest.CreatedAt, + }) + return nil +} + +// runSnapshotPush 把一份本机封存快照送到云端发布执行器(先校验字节,再校验身份)。 +// 只读本机归档;远端只写暂存目录与目标归档,不做任何目标库动作。 +func runSnapshotPush(opts options) error { + if opts.snapshot == "" || opts.scope == "" || opts.kb == "" || opts.tenant == 0 { + return errors.New("snapshot-push 需要 -snapshot -scope internal|external -tenant -kb ") + } + handoff, err := openHandoff(opts) + if err != nil { + return err + } + evidence, err := handoff.Push(context.Background(), libraryhandoff.Identity{ + SnapshotID: opts.snapshot, Scope: opts.scope, TenantID: opts.tenant, KnowledgeBaseID: opts.kb}) + if err != nil { + return err + } + printJSON(evidence) + return nil +} + +// runSnapshotFetch 把云端的快照取回本机归档(预备份/云端版本的读回)。 +func runSnapshotFetch(opts options) error { + if opts.snapshot == "" { + return errors.New("snapshot-fetch 需要 -snapshot ") + } + handoff, err := openHandoff(opts) + if err != nil { + return err + } + evidence, err := handoff.Fetch(context.Background(), opts.snapshot) + if err != nil { + return err + } + printJSON(evidence) + return nil +} + +// openHandoff 只认部署注入的配置:CLI 不接受调用方指定远端路径/容器/上游地址。 +func openHandoff(opts options) (*libraryhandoff.Handoff, error) { + config, configured, err := libraryhandoff.FromEnv(os.Getenv) + if err != nil { + return nil, err + } + if !configured { + return nil, errors.New("快照搬运未接线(缺少 LIBRARY_HANDOFF_*)") + } + if opts.archiveRoot != "" && config.LocalArchive == "" { + config.LocalArchive = opts.archiveRoot + } + return libraryhandoff.New(config, nil) +} + +// runSnapshotVerify 对一份快照做整版校验(逐部件重算字节),用于"复用前先证明字节还在"。 +func runSnapshotVerify(opts options) error { + if opts.snapshot == "" { + return errors.New("snapshot-verify 需要 -snapshot ") + } + archive, err := openArchive(opts) + if err != nil { + return err + } + defer archive.Close() + manifest, err := archive.Load(opts.snapshot) + if err != nil { + return fmt.Errorf("快照校验失败:%w", err) + } + printJSON(map[string]any{ + "verified": true, "snapshot": opts.snapshot, "scope": manifest.Scope, + "tenant_id": manifest.TenantID, "knowledge_base_id": manifest.KnowledgeBaseID, + "parts": len(manifest.Parts), + }) + return nil +} diff --git a/cmd/libraryctl/no_gate_maintenance_test.go b/cmd/libraryctl/no_gate_maintenance_test.go new file mode 100644 index 0000000..7dbbe8b --- /dev/null +++ b/cmd/libraryctl/no_gate_maintenance_test.go @@ -0,0 +1,59 @@ +package main + +import ( + "strings" + "testing" + + "knowledge-governance/internal/libraryfreeze" +) + +// noGateMaintenanceEnv 是 0.9.0 测试栈:没有闸门,用显式确认 + 健康探针代替。 +func noGateMaintenanceEnv() map[string]string { + env := maintenanceEnv() + delete(env, "LIBRARY_TARGET_INGRESS_URL") + delete(env, "LIBRARY_TARGET_INGRESS_SERVICE") + delete(env, "LIBRARY_TARGET_INGRESS_DRAIN_FILE") + env["LIBRARY_TARGET_INGRESS_MODE"] = libraryfreeze.IngressModeNone + env["LIBRARY_NO_INGRESS_ACK"] = libraryfreeze.NoIngressAck + env["LIBRARY_TARGET_HEALTH_URL"] = "http://127.0.0.1:18081/health" + return env +} + +func TestCaptureMaintenanceConfigNoGateWithAck(t *testing.T) { + env := noGateMaintenanceEnv() + config, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] }) + if err != nil { + t.Fatalf("no-gate 声明被拒:%v", err) + } + if config.IngressMode != libraryfreeze.IngressModeNone || config.IngressAck != libraryfreeze.NoIngressAck { + t.Fatalf("入口形态没透传:%+v", config) + } + if config.IngressURL != "" || config.IngressService != "" || config.IngressDrainFile != "" { + t.Fatalf("no-gate 配置里出现了闸门项:%+v", config) + } + if config.HealthURL != "http://127.0.0.1:18081/health" || config.RedisAddr != "127.0.0.1:26379" { + t.Fatalf("健康探针/队列没透传:%+v", config) + } + // 目标身份仍取自本次真实发现的源:no-gate 只改证据形态,不改动的是谁。 + if config.Database != "127.0.0.1:25432/kgmaint_target" || config.Index != "kgmaint_1028a_chunks" { + t.Fatalf("目标身份不对:%+v", config) + } +} + +func TestCaptureMaintenanceConfigNoGateWithoutAckIsRefused(t *testing.T) { + env := noGateMaintenanceEnv() + delete(env, "LIBRARY_NO_INGRESS_ACK") + _, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] }) + if err == nil || !strings.Contains(err.Error(), "LIBRARY_NO_INGRESS_ACK") { + t.Fatalf("没有显式确认却放过了 no-gate:%v", err) + } +} + +// no-gate 不得悄悄接受半套闸门声明:要么有闸门,要么明确没有。 +func TestCaptureMaintenanceConfigNoGateRejectsPartialGate(t *testing.T) { + env := noGateMaintenanceEnv() + env["LIBRARY_TARGET_INGRESS_SERVICE"] = "ingress" + if _, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] }); err == nil { + t.Fatal("no-gate 与闸门服务同时存在却没有拒绝") + } +} diff --git a/cmd/libraryctl/routing_bindings_test.go b/cmd/libraryctl/routing_bindings_test.go new file mode 100644 index 0000000..3c4a05c --- /dev/null +++ b/cmd/libraryctl/routing_bindings_test.go @@ -0,0 +1,103 @@ +package main + +import ( + "strings" + "testing" +) + +// internal 为空必须拒绝并点名。实测到的现场就是这一行:0.9.0 迁移后 +// internal_kb_id 与 external_kb_id 都是 NULL,旧解析退化成 +// "read routing bindings failed",操作员无法判断是连不上还是没绑定。 +// NULL 与空串在 SQL 侧由 routingBindingsQuery 的 COALESCE 收敛成同一形状, +// 解析侧两者都必须落到同一条错误上。 +func TestParseRoutingBindingsRejectsEmptyInternal(t *testing.T) { + for _, raw := range []string{"|", "|ext-kb", " \n| \n", "\n|\n", ""} { + binding, err := parseRoutingBindings(raw) + if err == nil { + t.Fatalf("internal 为空却解析成功:%q → %v", raw, binding) + } + if binding != nil { + t.Fatalf("internal 为空仍返回了映射:%q → %v", raw, binding) + } + if !strings.Contains(err.Error(), "对内知识库未绑定") || !strings.Contains(err.Error(), "internal_kb_id") { + t.Fatalf("错误没有点名 internal 未绑定:%q → %v", raw, err) + } + } +} + +// 0.9.0 测试实例的真实形状:只有对内库(wiki-demo),平台约定对外库没有对应 +// 目标时留空。绑定仍然有效,internal scope 能解析;external scope 必须失败、 +// 点名 external_kb_id,并且绝不回退到对内库。 +func TestParseRoutingBindingsAllowsEmptyExternal(t *testing.T) { + binding, err := parseRoutingBindings("0da9b571-6f13-46a1-85fa-e63d2ef5666e|") + if err != nil { + t.Fatalf("对外库为空不该让整份绑定失效:%v", err) + } + if got := binding["internal"]; got != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" { + t.Fatalf("对内库解析错误:%q", got) + } + if value, present := binding["external"]; present { + t.Fatalf("对外库没配置却写进了映射:%q", value) + } + + kb, err := scopeKnowledgeBase(binding, "internal") + if err != nil || kb != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" { + t.Fatalf("internal scope 不该被 external 为空牵连:kb=%q err=%v", kb, err) + } + + kb, err = scopeKnowledgeBase(binding, "external") + if err == nil { + t.Fatalf("对外库未配置却解析出了目标库:%q", kb) + } + if kb != "" { + t.Fatalf("external scope 回退到了别的库:%q", kb) + } + if !strings.Contains(err.Error(), "对外知识库未配置") || !strings.Contains(err.Error(), "external_kb_id") { + t.Fatalf("错误没有点名 external 未配置:%v", err) + } +} + +// 两个库都绑定时行为不变:这是 0.7.1 栈与对外库已配置的 0.9.0 栈的常态路径。 +func TestParseRoutingBindingsBothScopesUnchanged(t *testing.T) { + // psql -tAc 输出带行尾换行,pgx 那边不带——两边都必须是同一个结果。 + for _, raw := range []string{"kb-internal|kb-external", "kb-internal|kb-external\n", " kb-internal | kb-external \n"} { + binding, err := parseRoutingBindings(raw) + if err != nil { + t.Fatalf("两个库都绑定却解析失败:%q → %v", raw, err) + } + if len(binding) != 2 || binding["internal"] != "kb-internal" || binding["external"] != "kb-external" { + t.Fatalf("解析结果与原行为不一致:%q → %v", raw, binding) + } + for _, scope := range []string{"internal", "external"} { + if _, err := scopeKnowledgeBase(binding, scope); err != nil { + t.Fatalf("%s scope 不该失败:%v", scope, err) + } + } + } +} + +// 没有分隔符说明拿到的不是那一行(空结果集、psql 报错文本等),只能是读失败。 +func TestParseRoutingBindingsRejectsMalformedRow(t *testing.T) { + for _, raw := range []string{"kb-without-separator", "ERROR: relation \"routing_kb_bindings\" does not exist"} { + if _, err := parseRoutingBindings(raw); err == nil { + t.Fatalf("没有分隔符却解析成功:%q", raw) + } + } +} + +// 不连库的语法/形状校验:裸拼接遇 NULL 会得到整行 NULL,文件模式在 Scan 成 +// string 时就会失败并丢掉真实原因。两句来源共用这一条 SQL,因此只查这一处。 +func TestRoutingBindingsQueryCoalescesBothColumns(t *testing.T) { + query := routingBindingsQuery + for _, column := range []string{"internal_kb_id", "external_kb_id"} { + if !strings.Contains(query, "COALESCE("+column+",'')") { + t.Fatalf("查询没有把 %s 的 NULL 收敛成空串:%s", column, query) + } + } + if !strings.Contains(query, "||'|'||") { + t.Fatalf("查询不再产出 '|' 形状:%s", query) + } + if !strings.Contains(query, "WHERE id='active'") { + t.Fatalf("查询没有锁定生效绑定行:%s", query) + } +} diff --git a/cmd/libraryctl/v090_capture_script_test.go b/cmd/libraryctl/v090_capture_script_test.go new file mode 100644 index 0000000..9bd1eb9 --- /dev/null +++ b/cmd/libraryctl/v090_capture_script_test.go @@ -0,0 +1,59 @@ +package main + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// v090 采集脚本是本轮新增的唯一入口。为什么用 bash -n 而不是"跑一遍":跑一遍要 +// 停写入者、连 RDS——那是真实采集,不是单元测试。语法与声明在这里钉住,能让 +// "标志写错一个字母"在 CI 里就红,而不是等到开维护窗口时才发现。 +func TestV090CaptureScriptIsSyntacticallyValid(t *testing.T) { + bash, err := exec.LookPath("bash") + if err != nil { + t.Fatalf("需要 bash 才能检查脚本语法(CI 与测试机都有):%v", err) + } + path := filepath.Join("..", "..", "scripts", "library-capture-v090.sh") + out, err := exec.Command(bash, "-n", path).CombinedOutput() + if err != nil { + t.Fatalf("bash -n %s 失败:%v\n%s", path, err, out) + } +} + +// 脚本内容断言:外部库模式(两个 -pg 传空)、写者声明、容器名、归档根、 +// LIBRARYCTL_BIN 缺失即失败——这些一旦漂移,真跑时会封错栈或读错库。 +func TestV090CaptureScriptDeclaresExternalDatabases(t *testing.T) { + body, err := os.ReadFile(filepath.Join("..", "..", "scripts", "library-capture-v090.sh")) + if err != nil { + t.Fatalf("读脚本:%v", err) + } + for _, want := range []string{ + "set -euo pipefail", + "LIBRARYCTL_MISSING", + "-project weknora-v090", + "-writers app", + "-source-app weknora-v090-app", + "-source-es weknora-v090-elasticsearch", + `-source-pg ""`, + `-governance-pg ""`, + "frontend=UI only; no knowledge writes", + "docreader=parse RPC service; app persists parse output", + "elasticsearch=search store; not an initiator", + "redis=queue/cache store; not an initiator", + "/var/lib/knowledge-governance/library", + "/var/lib/knowledge-governance/freeze", + } { + if !strings.Contains(string(body), want) { + t.Fatalf("脚本缺少 %q", want) + } + } + // 0.7.1 的服务名绝不能出现在 v090 入口里:那会让封存停错栈。 + for _, forbidden := range []string{"WKNFull", "weknora071full"} { + if strings.Contains(string(body), forbidden) { + t.Fatalf("v090 脚本里出现了 0.7.1 的 %q", forbidden) + } + } +} diff --git a/cmd/librarydrill/main.go b/cmd/librarydrill/main.go index da6e78c..fe4a5a5 100644 --- a/cmd/librarydrill/main.go +++ b/cmd/librarydrill/main.go @@ -1,4 +1,4 @@ -// command librarydrill 在目标实例上做一次**真实**的恢复演练: +// command librarydrill 是恢复演练的**命令行入口**,实现在 internal/libraryverify: // // 维护隔离(关入口/停写入者/证明排空) // → 捕获目标整库(真预备份,落归档) @@ -8,15 +8,14 @@ // → 逐表/索引/资源/Wiki 再校验一次,必须完全一致 // → 关窗口(按原运行状态恢复服务、开入口、验证健康) // -// 它只读/写**被测目标自己**,绝不触碰封存源;所有凭据来自进程环境 -// (与 worker 同一份 LIBRARY_* 配置),不进命令行、不打印。 -// 任一步失败都不伪装成功:窗口保持维护、报告写明失败阶段。 +// 为什么只剩薄封装:页面要能点一次"恢复验证",worker 必须在进程内跑同一份实现。 +// 两份实现意味着"CLI 通过、页面失败"或反过来,演练结论就不可信了。 +// 它只读/写**被测目标自己**,绝不触碰封存源;所有凭据来自进程环境。 package main import ( "context" "encoding/json" - "errors" "flag" "fmt" "log" @@ -25,35 +24,12 @@ import ( "time" "knowledge-governance/internal/appconfig" - "knowledge-governance/internal/libraryfreeze" - "knowledge-governance/internal/libraryrelease" - "knowledge-governance/internal/librarystack" + "knowledge-governance/internal/libraryverify" ) -type drillVerification struct { - SnapshotID string `json:"snapshot_id"` - Verified bool `json:"verified"` - Error string `json:"error,omitempty"` - At time.Time `json:"at"` -} - -type drillReport struct { - Status string `json:"status"` // passed | failed | maintenance_held - Scope string `json:"scope"` - Target string `json:"target"` - SnapshotID string `json:"snapshot_id"` - Project string `json:"project"` - Counts map[string]int64 `json:"counts"` - BaselineCheck *drillVerification `json:"baseline_check"` - DriftCheck *drillVerification `json:"drift_check"` // 必须失败:证明确实能发现差异 - RestoreCheck *drillVerification `json:"restore_check"` - Canary string `json:"canary"` - Failure string `json:"failure,omitempty"` - Stage string `json:"stage,omitempty"` - StartedAt time.Time `json:"started_at"` - FinishedAt time.Time `json:"finished_at"` - Until map[string]string `json:"until,omitempty"` -} +// 报告类型直接复用共享实现:命令行与页面/worker 的证据字段完全一致。 +type drillVerification = libraryverify.Verification +type drillReport = libraryverify.Report func main() { scope := flag.String("scope", "internal", "internal|external") @@ -87,18 +63,7 @@ func recoverWindows() error { if err != nil { return fmt.Errorf("load config: %w", err) } - manager, err := librarystack.OpenMaintenance(config) - if err != nil { - return err - } - defer manager.Close() - coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot) - if err != nil { - return err - } - defer control.Close() - defer coordinator.Close() - if err := coordinator.Recover(context.Background()); err != nil { + if err := libraryverify.RecoverWindows(config); err != nil { return err } log.Printf("maintenance windows recovered; target should be back to its original service state") @@ -106,155 +71,18 @@ func recoverWindows() error { } func run(scope, jobID string) (*drillReport, error) { - if scope != "internal" && scope != "external" { - return nil, errors.New("scope must be internal or external") - } config, err := appconfig.Load(os.Getenv) if err != nil { return nil, fmt.Errorf("load config: %w", err) } - ctx := context.Background() - report := &drillReport{Status: "failed", Scope: scope, Project: config.LibraryTargetProject, - Target: config.LibraryTargetInstance, StartedAt: time.Now().UTC()} - fail := func(stage string, cause error, held bool) (*drillReport, error) { - report.Stage = stage - report.Failure = cause.Error() - report.FinishedAt = time.Now().UTC() - if held { - report.Status = "maintenance_held" - } - return report, cause - } - - target, backups, err := librarystack.OpenBaselineStack(ctx, config, scope) - if err != nil { - return fail("open_target", err, false) - } - defer target.Close() - manager, err := librarystack.OpenMaintenance(config) - if err != nil { - return fail("open_maintenance", err, false) - } - defer manager.Close() - if err := manager.VerifyTopology(ctx); err != nil { - return fail("topology", err, false) - } - coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot) - if err != nil { - return fail("open_coordinator", err, false) - } - defer control.Close() - defer coordinator.Close() - if jobID == "" { - jobID = "drill-" + scope + "-" + time.Now().UTC().Format("20060102T150405") + jobID = fmt.Sprintf("drill-%s-%d", scope, time.Now().UTC().UnixNano()) } - var ( - snapshotID string - counts map[string]int64 - canary string - contentTouched bool - baseline drillVerification - drift drillVerification - restored drillVerification - ) - work := func(ctx context.Context, window *libraryfreeze.Window) (string, error) { - start := time.Now() - current, err := target.Current(ctx) - if err != nil { - return "", errors.New("读取目标当前整库状态失败:" + err.Error()) - } - counts = current.Counts - report.Counts = counts - // 1) 真预备份(落归档、内容寻址、导出后复核内容未变)。 - backup, err := backups.Prepare(ctx, "", current) - if err != nil { - return "", errors.New("捕获目标整库失败:" + err.Error()) - } - snapshotID = backup.SnapshotID - report.SnapshotID = snapshotID - if err := window.SetBackupSnapshot(ctx, snapshotID); err != nil { - return "", errors.New("记录预备份身份失败:" + err.Error()) - } - log.Printf("drill: snapshot captured snapshot=%s bytes=%d in=%s", snapshotID, backup.Bytes, time.Since(start)) - - // 2) 基线校验:预备份必须与目标完全一致。 - baseline = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()} - if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil { - baseline.Error = err.Error() - report.BaselineCheck = &baseline - return "", errors.New("预备份与目标不一致(预备份本身不可信):" + err.Error()) - } - baseline.Verified = true - report.BaselineCheck = &baseline - - // 3) canary:改一行真实内容,校验**必须**失败(否则"校验"是摆设)。 - canary = "drill-canary-" + time.Now().UTC().Format("20060102T150405") - identity := target.Identity() - tag, err := target.Pool().Exec(ctx, ` -UPDATE knowledges SET title = title || ' [' || $3 || ']' -WHERE id = (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND deleted_at IS NULL - ORDER BY id LIMIT 1)`, identity.TenantID, identity.KnowledgeBaseID, canary) - if err != nil { - return "", errors.New("写入 canary 失败:" + err.Error()) - } - if tag.RowsAffected() == 0 { - return "", errors.New("目标里没有可改写的文档,无法做漂移检测(目标不应为空)") - } - report.Canary = canary - // 从这一笔开始目标内容被改写过:窗口必须记录内容风险, - // 之后只有"恢复并校验通过"才允许重新开放(否则就是半写状态)。 - if err := window.MarkContentRisk(ctx); err != nil { - return "", errors.New("记录内容风险失败:" + err.Error()) - } - contentTouched = true - drift = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()} - if verifyErr := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); verifyErr == nil { - drift.Error = "写入 canary 后校验仍然通过:校验没有真正比对内容" - report.DriftCheck = &drift - return "", errors.New("写入 canary 后校验仍然通过:校验没有真正比对内容,拒绝把这次演练当成通过") - } else { - drift.Error = verifyErr.Error() - } - report.DriftCheck = &drift - log.Printf("drill: drift detected as expected (%s)", drift.Error) - - // 4) 按预备份恢复。 - if err := target.Restore(ctx, libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID}); err != nil { - return "", errors.New("按预备份恢复失败:" + err.Error()) - } - // 5) 恢复后逐类复核:必须与预备份完全一致。 - restored = drillVerification{SnapshotID: snapshotID, At: time.Now().UTC()} - if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil { - restored.Error = err.Error() - report.RestoreCheck = &restored - return "", errors.New("恢复后内容仍与预备份不一致:" + err.Error()) - } - restored.Verified = true - report.RestoreCheck = &restored - log.Printf("drill: restored and verified snapshot=%s", snapshotID) - return snapshotID, nil - } - - window, windowErr := coordinator.RunWindow(ctx, jobID, - func(ctx context.Context) error { return manager.VerifyRunning(ctx) }, work, - // 没写过目标内容 ⇒ 按原状态恢复永远安全;写过 canary ⇒ 只有恢复并校验通过才开放。 - func(error) bool { return !contentTouched || restored.Verified }) - - report.Until = map[string]string{"job": jobID, "window_state": window.State} - if windowErr != nil || window.State != "succeeded" { - cause := windowErr - if cause == nil { - cause = fmt.Errorf("维护窗口状态 %s(未成功)", window.State) - } - if window.State == "held" { - return fail("window", cause, true) - } - return fail("window", cause, false) - } - report.Status = "passed" - report.FinishedAt = time.Now().UTC() - return report, nil + // 主机侧 CLI 不持有治理库连接:维护记录由调用它的作业/运维流程负责。 + // 页面发起的验证走 worker,那里 Options 同时接治理生命周期与写集合登记。 + return libraryverify.Run(context.TODO(), config, scope, jobID, libraryverify.Options{ + Progress: func(stage, state, detail string) { log.Printf("stage=%s state=%s %s", stage, state, detail) }, + }) } func writeReport(path string, report *drillReport) error { diff --git a/cmd/libraryresidue/main.go b/cmd/libraryresidue/main.go index 164aaaa..0add89f 100644 --- a/cmd/libraryresidue/main.go +++ b/cmd/libraryresidue/main.go @@ -87,7 +87,7 @@ func run(ctx context.Context, config appconfig.Config, scope, snapshotID, backup if strings.TrimSpace(expectSource) != want { return nil, fmt.Errorf("来源范围与 -expect-source 不一致:归档为 %s,参数为 %s", want, expectSource) } - target, _, err := librarystack.OpenProductionStack(ctx, config, scope, backupSnapshotID, "") + target, _, err := librarystack.OpenProductionStack(ctx, config, scope, backupSnapshotID, "", nil) if err != nil { return nil, fmt.Errorf("装配目标失败: %w", err) } diff --git a/cmd/object-gateway-control/main.go b/cmd/object-gateway-control/main.go new file mode 100644 index 0000000..e56c152 --- /dev/null +++ b/cmd/object-gateway-control/main.go @@ -0,0 +1,61 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "time" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/objectgateway" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +// This command belongs to the separately authenticated controller. It must not +// be installed with control credentials in an ordinary data worker container. +func main() { + if e := run(); e != nil { + fmt.Fprintln(os.Stderr, e) + os.Exit(1) + } +} +func run() error { + path := flag.String("plan", "", "exact frozen write-set JSON") + directory := flag.String("grant-directory", "", "private durable grant output directory") + expected := flag.Int64("expected-epoch", -1, "previous epoch from the frozen controller intent; never guessed") + flag.Parse() + if *path == "" || *directory == "" || *expected < 0 || flag.NArg() != 0 { + return errors.New("exact plan, grant directory and expected epoch required") + } + f, e := os.Open(*path) + if e != nil { + return errors.New("frozen gateway plan unavailable") + } + defer f.Close() + var set libraryrelease.WriteSet + d := json.NewDecoder(io.LimitReader(f, 16<<20)) + d.DisallowUnknownFields() + if d.Decode(&set) != nil || d.Decode(&struct{}{}) != io.EOF { + return errors.New("frozen gateway plan invalid") + } + provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET") + if provider == "" || endpoint == "" || bucket == "" { + return errors.New("exact gateway target configuration required") + } + scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket)) + client, e := objectgateway.NewClient(os.Getenv("OBJECT_GATEWAY_URL"), os.Getenv("OBJECT_GATEWAY_CONTROL_TOKEN"), scope) + if e != nil { + return e + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + if e = v071.PrepareObjectGatewayGrant(ctx, client, set, *expected, provider, bucket, *directory); e != nil { + return e + } + fmt.Printf("gateway grant persisted: plan=%s epoch=%d\n", set.Digest, *expected+1) + return nil +} diff --git a/cmd/object-gateway/main.go b/cmd/object-gateway/main.go new file mode 100644 index 0000000..c65f212 --- /dev/null +++ b/cmd/object-gateway/main.go @@ -0,0 +1,79 @@ +package main + +import ( + "context" + "errors" + "log" + "net" + "net/http" + "os" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + "knowledge-governance/internal/objectgateway" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +func main() { + if err := run(); err != nil { + log.Print(err) + os.Exit(1) + } +} +func run() error { + ctx := context.Background() + addr := os.Getenv("OBJECT_GATEWAY_LISTEN") + host, _, e := net.SplitHostPort(addr) + // A reviewed TLS terminator may expose this loopback-only listener. Never bind + // authenticated plaintext to a LAN address by an accidental config default. + if e != nil || (host != "127.0.0.1" && host != "::1") { + return errors.New("gateway_requires_loopback_listener") + } + data, control := os.Getenv("OBJECT_GATEWAY_DATA_TOKEN"), os.Getenv("OBJECT_GATEWAY_CONTROL_TOKEN") + if len(data) < 32 || len(control) < 32 || data == control { + return errors.New("gateway_distinct_tokens_required") + } + provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET") + scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket)) + pool, e := pgxpool.New(ctx, os.Getenv("OBJECT_GATEWAY_DATABASE_URL")) + if e != nil { + return objectgateway.ErrPersistence + } + defer pool.Close() + backend, e := v071.NewGatewayBackend(v071.S3ObjectStoreConfig{Provider: provider, Endpoint: endpoint, Bucket: bucket, Region: os.Getenv("OBJECT_GATEWAY_REGION"), AccessKeyID: os.Getenv("OBJECT_GATEWAY_ACCESS_KEY"), SecretAccessKey: os.Getenv("OBJECT_GATEWAY_SECRET_KEY"), MaxObjectBytes: 256 * 1024 * 1024}) + if e != nil { + return errors.New("gateway_backend_configuration_invalid") + } + // The target bucket is shared with other writers. Admission is the journal + // plus backend capability; retired attestation env vars are deliberately + // ignored so an old deployment file cannot gate this path. + g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024} + if governanceURL := os.Getenv("OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL"); governanceURL != "" { + cfg, e := pgxpool.ParseConfig(governanceURL) + if e != nil { + return errors.New("gateway_control_authority_unavailable") + } + cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on" + cfg.MaxConns = 4 + governancePool, e := pgxpool.NewWithConfig(ctx, cfg) + if e != nil { + return errors.New("gateway_control_authority_unavailable") + } + defer governancePool.Close() + authority := &v071.GatewayGovernanceAuthority{Pool: governancePool, ArchiveRoot: os.Getenv("OBJECT_GATEWAY_ARCHIVE_ROOT"), TargetID: os.Getenv("OBJECT_GATEWAY_TARGET_ID"), Provider: provider, Bucket: bucket} + if e = authority.Ready(ctx); e != nil { + return e + } + g.Authority = authority + } + probe, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + if e = g.Ready(probe); e != nil { + return e + } + server := &http.Server{Addr: addr, Handler: objectgateway.HTTPServer{Gateway: g, DataToken: data, ControlToken: control}, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 3 * time.Minute, WriteTimeout: 3 * time.Minute, IdleTimeout: 30 * time.Second} + if server.ListenAndServe() != nil { + return errors.New("gateway_listener_stopped") + } + return nil +} diff --git a/cmd/object-gateway/main_test.go b/cmd/object-gateway/main_test.go new file mode 100644 index 0000000..b0e8f61 --- /dev/null +++ b/cmd/object-gateway/main_test.go @@ -0,0 +1,82 @@ +package main + +import ( + "context" + "encoding/base64" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// startErrorMessage builds the addressed binary and runs it long enough to +// observe why the real entry point refused to listen. +func startErrorMessage(t *testing.T, extra ...string) (string, int) { + t.Helper() + bin := filepath.Join(t.TempDir(), "object-gateway") + build := exec.Command("go", "build", "-o", bin, ".") + if out, err := build.CombinedOutput(); err != nil { + t.Fatalf("build gateway: %v\n%s", err, out) + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, bin) + cmd.Env = append([]string{ + "PATH=" + os.Getenv("PATH"), + "HOME=" + os.Getenv("HOME"), + "OBJECT_GATEWAY_LISTEN=127.0.0.1:0", + "OBJECT_GATEWAY_DATABASE_URL=postgres://gateway@127.0.0.1:1/gateway?sslmode=disable&connect_timeout=2", + "OBJECT_GATEWAY_PROVIDER=minio", + "OBJECT_GATEWAY_ENDPOINT=http://127.0.0.1:19100", + "OBJECT_GATEWAY_BUCKET=maintenance-fixture-bucket", + "OBJECT_GATEWAY_REGION=us-east-1", + "OBJECT_GATEWAY_ACCESS_KEY=fixture-access-key", + "OBJECT_GATEWAY_SECRET_KEY=fixture-secret-key", + "OBJECT_GATEWAY_DATA_TOKEN=" + strings.Repeat("d", 32), + "OBJECT_GATEWAY_CONTROL_TOKEN=" + strings.Repeat("c", 32), + }, extra...) + out, err := cmd.CombinedOutput() + if ctx.Err() != nil { + t.Fatalf("gateway did not terminate; output=%s", out) + } + code := 0 + if exit, ok := err.(*exec.ExitError); ok { + code = exit.ExitCode() + } else if err != nil { + t.Fatalf("run gateway: %v", err) + } + return string(out), code +} + +// The default shared-bucket path must not require a whole-bucket exclusive +// writer attestation. Only the journal/backend admission gate may refuse it, +// and a stale attestation file left behind by an older deployment must not +// gate the default path either. +func TestGatewayEntrypointDoesNotRequireBucketAttestation(t *testing.T) { + for _, tc := range []struct { + name string + env []string + }{ + {name: "no_audit_configured"}, + {name: "stale_audit_file_ignored", env: []string{ + "OBJECT_GATEWAY_ID=retired-gateway", + "OBJECT_GATEWAY_AUDIT_FILE=/nonexistent/expired-attestation.json", + "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY=" + base64.StdEncoding.EncodeToString(make([]byte, 32)), + }}, + } { + t.Run(tc.name, func(t *testing.T) { + out, code := startErrorMessage(t, tc.env...) + if code == 0 { + t.Fatalf("gateway exited 0 instead of reporting its admission state: %s", out) + } + if strings.Contains(out, "gateway_auditor_key_required") || strings.Contains(out, "gateway_exclusive_writer_evidence_unverified") { + t.Fatalf("shared-bucket admission still gated by whole-bucket attestation: %s", out) + } + if !strings.Contains(out, "gateway_persistence_unavailable") && !strings.Contains(out, "gateway_backend_not_ready") { + t.Fatalf("gateway did not reach journal/backend admission: %s", out) + } + }) + } +} diff --git a/cmd/release-channel-e2e/main.go b/cmd/release-channel-e2e/main.go index bdacf18..26f8f9d 100644 --- a/cmd/release-channel-e2e/main.go +++ b/cmd/release-channel-e2e/main.go @@ -81,6 +81,10 @@ func secret(path string) string { } func main() { + if err := v071.CheckLegacyObjectWrites(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } configPath := flag.String("config", "", "release config json") knowledgeID := flag.String("knowledge", "", "knowledge id to release") mode := flag.String("mode", "publish", "publish | withdraw | rollback") diff --git a/cmd/release-diag/main.go b/cmd/release-diag/main.go index 9147e39..3be4c0a 100644 --- a/cmd/release-diag/main.go +++ b/cmd/release-diag/main.go @@ -69,6 +69,10 @@ func secret(path string) string { } func main() { + if err := v071.CheckLegacyObjectWrites(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } configPath := flag.String("config", "", "release config json") knowledgeID := flag.String("knowledge", "", "knowledge id to diagnose") flag.Parse() diff --git a/cmd/release-worker/legacy_gate_test.go b/cmd/release-worker/legacy_gate_test.go new file mode 100644 index 0000000..8cd89c8 --- /dev/null +++ b/cmd/release-worker/legacy_gate_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "context" + v071 "knowledge-governance/internal/releaseadapter/v071" + "testing" +) + +func TestLegacyReleaseRuntimeRefusesBeforeCredentials(t *testing.T) { + // Empty credential paths would fail differently if route assembly were reached. + runtime, e := buildReleaseRuntime(context.Background(), releaseRuntimeConfig{}) + if runtime != nil || e == nil || e.Error() != v071.CheckLegacyObjectWrites().Error() { + t.Fatal("legacy runtime did not fail at the no-write gate", e) + } + route, pools, e := buildReleaseRoute(context.Background(), "", releaseTargetSnapshotConfig{}, releaseRouteConfig{}) + if route != nil || len(pools) != 0 || e == nil || e.Error() != v071.CheckLegacyObjectWrites().Error() { + t.Fatal("direct route bypassed the no-write gate", e) + } +} diff --git a/cmd/release-worker/runtime.go b/cmd/release-worker/runtime.go index 2b34acb..fe6a905 100644 --- a/cmd/release-worker/runtime.go +++ b/cmd/release-worker/runtime.go @@ -31,6 +31,9 @@ func (runtime *releaseRuntime) Close() { } func buildReleaseRuntime(ctx context.Context, config releaseRuntimeConfig) (*releaseRuntime, error) { + if err := v071.CheckLegacyObjectWrites(); err != nil { + return nil, err + } runtime := &releaseRuntime{} publishers := make(map[string]releaseworkflow.Publisher, len(config.Routes)) for _, route := range config.Routes { @@ -52,6 +55,9 @@ func buildReleaseRuntime(ctx context.Context, config releaseRuntimeConfig) (*rel } func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot releaseTargetSnapshotConfig, route releaseRouteConfig) (releaseworkflow.Publisher, []*pgxpool.Pool, error) { + if err := v071.CheckLegacyObjectWrites(); err != nil { + return nil, nil, err + } sourceDatabaseURL, err := readRestrictedValue(route.Source.DatabaseURLFile) if err != nil { return nil, nil, errors.New("read source database credential") diff --git a/cmd/worker/library_admission.go b/cmd/worker/library_admission.go new file mode 100644 index 0000000..44a6860 --- /dev/null +++ b/cmd/worker/library_admission.go @@ -0,0 +1,51 @@ +package main + +import ( + "context" + "errors" + "fmt" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// 准入:worker 在动维护/目标之前,必须自己证明"这个队列作业确实是这条业务作业"。 +// +// 为什么不能只靠"通用入口拒绝 library.*":那只堵住了一个入口。队列里仍可能因为历史 +// 残留、手工 SQL、别的服务投递而出现畸形作业;而 worker 拿到没有业务行的作业时会照常 +// 取维护锁、停写入者、开备份窗口(F14 的真实现场)。所以准入必须在**副作用之前**, +// 并且同时核三件事:业务行存在、kind/scope 与载荷一致、队列关联不可伪造。 +func admitLibraryJob(ctx context.Context, store *postgresstore.Store, queueJob jobs.Job, + libraryJobID, scope string, kind governance.LibraryJobKind, requireQueueMatch bool) (governance.LibraryJob, error) { + if libraryJobID == "" { + return governance.LibraryJob{}, errors.New("载荷缺少业务作业号:拒绝执行") + } + if scope != "internal" && scope != "external" { + return governance.LibraryJob{}, fmt.Errorf("载荷 scope 非法(%q):拒绝执行", scope) + } + business, err := store.LibraryJob(ctx, libraryJobID) + if err != nil { + // 没有业务行 ⇒ 这次执行没有准入依据(闸口/授权/维护归属都无从核对)。 + return governance.LibraryJob{}, fmt.Errorf("队列作业 %s 没有对应的业务作业 %s:拒绝在任何维护动作前继续", + queueJob.ID, libraryJobID) + } + if business.Scope != scope { + return governance.LibraryJob{}, fmt.Errorf("业务作业 %s 属于 scope=%s,载荷声称 %s:拒绝", libraryJobID, business.Scope, scope) + } + if kind != "" && business.Kind != kind { + return governance.LibraryJob{}, fmt.Errorf("业务作业 %s 的 kind=%s,与执行器 %s 不一致:拒绝", libraryJobID, business.Kind, kind) + } + if requireQueueMatch { + // 队列关联由 API 在建作业后写入;为空说明投递没有落定,不匹配说明这个队列作业 + // 不是为它准备的。两种情况都不能执行。 + if business.QueueJobID == "" { + return governance.LibraryJob{}, fmt.Errorf("业务作业 %s 没有队列关联:拒绝执行未落定的投递", libraryJobID) + } + if business.QueueJobID != queueJob.ID { + return governance.LibraryJob{}, fmt.Errorf("队列作业 %s 不是业务作业 %s 的关联作业(%s):拒绝", + queueJob.ID, libraryJobID, business.QueueJobID) + } + } + return business, nil +} diff --git a/cmd/worker/library_anchor_r13_integration_test.go b/cmd/worker/library_anchor_r13_integration_test.go new file mode 100644 index 0000000..0c73ad4 --- /dev/null +++ b/cmd/worker/library_anchor_r13_integration_test.go @@ -0,0 +1,124 @@ +package main + +import ( + "context" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" +) + +// r13CountingTarget 记录 Apply 次数:锚点写失败时它必须是 0。 +type r13CountingTarget struct { + ledgerTestTarget + applied int +} + +func (t *r13CountingTarget) Apply(ctx context.Context, stage libraryrelease.Stage, snapshot string) error { + t.applied++ + return t.ledgerTestTarget.Apply(ctx, stage, snapshot) +} + +// B25:写集合/预备份锚点写不进治理库时,必须在任何业务写入之前失败,目标零写入, +// 也不许留下"已有基线"的假象。故障来自真实 PG(版本表上的 CHECK 约束拒绝写入), +// 不是包一层必失败的假 store。 +func TestR13AnchorWriteFailureBlocksTargetIsolated(t *testing.T) { + store, pool := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const ( + scope = "internal" + jobID = "libsync-r13-anchor" + snapshot = "backup-snap-r13-anchor" + target = "target-snap-r13-anchor" + params = "params-r13-anchor" + ) + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope, + Kind: governance.LibraryJobSync, IdempotencyKey: "library.sync:internal:r13-anchor", + RequestDigest: params, Actor: "admin", TargetSnapshotID: target}, governance.SyncStages(), now); err != nil { + t.Fatalf("create job: %v", err) + } + var exists bool + // 隔离夹具把表建在每次运行专属 schema 里(search_path 指向它), + // 因此这里用非限定名,不能写死 public。 + if err := pool.QueryRow(ctx, `SELECT to_regclass('library_versions') IS NOT NULL`).Scan(&exists); err != nil { + t.Fatalf("locate version table: %v", err) + } + if !exists { + rows, err := pool.Query(ctx, `SELECT table_schema||'.'||table_name FROM information_schema.tables + WHERE table_name LIKE 'library%' ORDER BY 1`) + if err == nil { + var names []string + for rows.Next() { + var n string + rows.Scan(&n) + names = append(names, n) + } + rows.Close() + t.Logf("library tables visible: %v", names) + } + var ledger []string + if r2, err := pool.Query(ctx, `SELECT version::text FROM schema_migrations ORDER BY 1 DESC LIMIT 5`); err == nil { + for r2.Next() { + var v string + r2.Scan(&v) + ledger = append(ledger, v) + } + r2.Close() + } + t.Fatalf("版本表不存在:夹具/迁移不完整,本用例的前提不成立(最近迁移=%v)", ledger) + } + // NOT VALID:不动已有行,只让新的版本写入被真实 PG 拒绝。 + if _, err := pool.Exec(ctx, `ALTER TABLE library_versions ADD CONSTRAINT r13_anchor_reject CHECK (false) NOT VALID`); err != nil { + t.Fatalf("inject anchor constraint: %v", err) + } + dropConstraint := func() { + pool.Exec(context.Background(), `ALTER TABLE library_versions DROP CONSTRAINT IF EXISTS r13_anchor_reject`) + } + t.Cleanup(dropConstraint) + recorder := libraryStageRecorder{store: store, jobID: jobID, scope: scope} + // 写集合必须落在一次性目录,不能把测试产物写进仓库。 + inner := &r13CountingTarget{ledgerTestTarget: ledgerTestTarget{root: t.TempDir()}} + backups := ledgerTestBackups{ref: libraryrelease.BackupRef{ID: "backup-" + snapshot, SnapshotID: snapshot, + Bytes: 4096, Universe: map[string]libraryrelease.TableFingerprint{"resources": {Count: 1, Digest: "universe"}}}} + request := libraryrelease.Request{JobID: jobID, Target: scope, SnapshotID: target, ParamsDigest: params, + Now: now, Grant: libraryrelease.Grant{Target: scope, SnapshotID: target, ParamsDigest: params, + ExpiresAt: now.Add(time.Hour), AuthorizedBy: "tester"}} + outcome := libraryrelease.Run(ctx, request, inner, backups, recorder) + if outcome.State != "failed" { + t.Fatalf("锚点写失败却继续执行:%+v", outcome) + } + if outcome.FailedAt != "" { + t.Fatalf("锚点失败必须早于任何阶段写入,failed_at=%q", outcome.FailedAt) + } + if inner.applied != 0 { + t.Fatalf("锚点失败后仍写了目标 %d 个阶段", inner.applied) + } + shown := false + for _, sub := range []string{"写集合", "登记", "constraint", "check", "23514"} { + if strings.Contains(outcome.Error, sub) { + shown = true + } + } + if !shown { + t.Fatalf("失败原因没有指向锚点写入:%q", outcome.Error) + } + versions, err := store.LibraryVersionsBySnapshot(ctx, scope, snapshot) + if err != nil { + t.Fatalf("read versions: %v", err) + } + if len(versions) != 0 { + t.Fatalf("锚点失败却留下版本证据:%+v", versions) + } + // 去掉故障后同一请求能完成登记:证明失败来自注入的锚点故障,不是环境坏掉。 + dropConstraint() + retry := libraryrelease.Run(ctx, request, inner, backups, recorder) + if retry.State != "succeeded" { + t.Fatalf("去掉故障后应当能完成:%+v", retry) + } + if inner.applied != 4 { + t.Fatalf("去掉故障后应写满四个阶段,实际 %d", inner.applied) + } +} diff --git a/cmd/worker/library_attempt_timing.go b/cmd/worker/library_attempt_timing.go new file mode 100644 index 0000000..2fff5ea --- /dev/null +++ b/cmd/worker/library_attempt_timing.go @@ -0,0 +1,8 @@ +//go:build !kg_isolated_drill + +package main + +import "time" + +// Production timing is not controllable through test environment variables. +const libraryAttemptLease = 10 * time.Minute diff --git a/cmd/worker/library_attempt_timing_drill.go b/cmd/worker/library_attempt_timing_drill.go new file mode 100644 index 0000000..c1338f0 --- /dev/null +++ b/cmd/worker/library_attempt_timing_drill.go @@ -0,0 +1,26 @@ +//go:build kg_isolated_drill + +package main + +import ( + "net/url" + "os" + "strings" + "time" +) + +// Only an explicitly tagged executable can shorten the real lease clock. It +// refuses non-disposable DBs; no production binary recognizes this injection. +const libraryAttemptLease = 4 * time.Second + +func init() { + if os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + panic("isolated drill build requires explicit opt-in") + } + for _, name := range []string{"DATABASE_URL", "LIBRARY_PRODUCTION_DATABASE_URL"} { + u, e := url.Parse(os.Getenv(name)) + if e != nil || (u.Hostname() != "127.0.0.1" && u.Hostname() != "localhost") || !strings.HasPrefix(u.Path, "/kg_library_test_r8_") { + panic("isolated drill build refuses non-disposable database") + } + } +} diff --git a/cmd/worker/library_attempt_timing_test.go b/cmd/worker/library_attempt_timing_test.go new file mode 100644 index 0000000..661ea73 --- /dev/null +++ b/cmd/worker/library_attempt_timing_test.go @@ -0,0 +1,16 @@ +//go:build !kg_isolated_drill + +package main + +import ( + "testing" + "time" +) + +func TestProductionAttemptTimingIgnoresDrillEnvironment(t *testing.T) { + t.Setenv("KG_LIBRARY_TEST_ISOLATED", "1") + t.Setenv("WORKER_LEASE_DURATION", "1ms") + if libraryAttemptLease != 10*time.Minute { + t.Fatal("production lease shortened by drill injection") + } +} diff --git a/cmd/worker/library_backup_reuse_test.go b/cmd/worker/library_backup_reuse_test.go new file mode 100644 index 0000000..5644d94 --- /dev/null +++ b/cmd/worker/library_backup_reuse_test.go @@ -0,0 +1,114 @@ +package main + +import ( + "context" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" +) + +// 接管复用的预备份必须是"同一份、且登记时刻不被洗掉": +// 崩溃后又重做一次备份会把半写状态当成可回滚基线,而 created_at 被重写 +// 会让这两种情况在库里长得一模一样(演练脚本就判不出来了)。 +// +// 只能在真实 PostgreSQL 上证明:这条语义写在 RecordLibraryVersion 的 upsert 里。 +func TestPrebackupVersionKeepsFirstRegistrationTimeOnReuse(t *testing.T) { + store, _ := openLedgerStore(t) + ctx := context.Background() + const scope = "internal" + const snapshot = "snap-prebackup-reused" + + first := time.Now().UTC().Add(-30 * time.Minute).Truncate(time.Second) + record := func(at time.Time, evidence map[string]any) { + t.Helper() + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, snapshot), + Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: snapshot, + SourceJobID: "librestore-internal-resumed", CreatedBy: "worker", + Evidence: evidence, CreatedAt: at, + }); err != nil { + t.Fatalf("record prebackup at %s: %v", at, err) + } + } + record(first, map[string]any{"backup_snapshot": snapshot, "backup_bytes": 2048}) + + // 接管复用:BackupPrepared 会再登记一次(带 backup_reused),时刻是"现在"。 + record(time.Now().UTC(), map[string]any{"backup_snapshot": snapshot, "backup_bytes": 2048, + "backup_reused": true}) + + version, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionPrebackup, + "librestore-internal-resumed", snapshot) + if err != nil || !found { + t.Fatalf("read prebackup version: found=%t err=%v", found, err) + } + if !version.CreatedAt.UTC().Equal(first) { + t.Fatalf("复用后登记时刻被改写:%s, want %s(备份什么时候拍的被洗掉了)", + version.CreatedAt.UTC(), first) + } + if reused, _ := version.Evidence["backup_reused"].(bool); !reused { + t.Fatalf("复用的预览份没有 backup_reused=true:%v", version.Evidence) + } + + // 反例对照:真的"重新生效"是**新的意图**(新的作业/新的 operation), + // 它带自己的登记时刻;同一意图里的重复登记则只补证据、时刻不变。 + // 这条区分必须成立,否则页面会把"最近一次生效"显示成很早以前。 + const effectiveSnap = "snap-effective-reactivated" + effectiveAt := first.Add(time.Hour) + reactivatedAt := effectiveAt.Add(time.Hour) + opFirst := testLibraryOperation(t, store, scope, governance.LibraryJobSync, "activate-1", effectiveAt) + recordVersionEvent(t, store, scope, governance.LibraryVersionProductionEffective, effectiveSnap, + "librestore-internal-reactivate-1", opFirst, effectiveAt, map[string]any{"action": "restore"}) + // 同一意图内的重复登记:时刻不变(事件不可变)。 + recordVersionEvent(t, store, scope, governance.LibraryVersionProductionEffective, effectiveSnap, + "librestore-internal-reactivate-1", opFirst, reactivatedAt, map[string]any{"action": "restore"}) + effective, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionEffective, + "librestore-internal-reactivate-1", effectiveSnap) + if err != nil || !found { + t.Fatalf("read effective version: found=%t err=%v", found, err) + } + if !effective.CreatedAt.UTC().Equal(effectiveAt) { + t.Fatalf("同一意图的重复登记改写了时刻:%s, want %s", effective.CreatedAt.UTC(), effectiveAt) + } + // 新的意图(另一个作业)重新激活同一快照:新事件、新时刻、成为当前。 + opSecond := testLibraryOperation(t, store, scope, governance.LibraryJobSync, "activate-2", reactivatedAt) + recordVersionEvent(t, store, scope, governance.LibraryVersionProductionEffective, effectiveSnap, + "librestore-internal-reactivate-2", opSecond, reactivatedAt, map[string]any{"action": "restore"}) + reactivated, found, err := store.LibraryVersionByRef(ctx, scope, + governance.LibraryVersionProductionEffective, "librestore-internal-reactivate-2", effectiveSnap) + if err != nil || !found { + t.Fatalf("read reactivated version: found=%t err=%v", found, err) + } + if !reactivated.CreatedAt.UTC().Equal(reactivatedAt) { + t.Fatalf("重新激活的登记时刻 = %s, want %s", reactivated.CreatedAt.UTC(), reactivatedAt) + } + current, hasCurrent, err := store.LibraryCurrentVersion(ctx, scope) + if err != nil || !hasCurrent || current.ID != reactivated.ID { + t.Fatalf("当前生效版本应指向重新激活的事件:found=%v err=%v %+v", hasCurrent, err, current) + } +} + +// ledgerBackupStore 复用预备份时必须显式带上 Reused 与持久写集合: +// 少了 Reused,证据里就分不清"复用"和"重做备份";少了写集合,恢复只能按 +// 目标现状推断残渣(把历史/共享资源当残渣删掉的老缺陷)。 +func TestLedgerBackupStoreMarksReuseAndCarriesWriteSet(t *testing.T) { + write := &libraryrelease.WriteSet{JobID: "librestore-internal-1", Target: "internal"} + store := ledgerBackupStore{ + ref: libraryrelease.BackupRef{ID: "backup-snap-1", SnapshotID: "snap-1", Bytes: 4096}, + write: write, + } + ref, err := store.Prepare(context.Background(), "target-snap", libraryrelease.CurrentState{}) + if err != nil { + t.Fatalf("prepare: %v", err) + } + if !ref.Reused { + t.Fatal("复用预备份没有标 Reused:证据里分不清复用与重做备份") + } + if ref.SnapshotID != "snap-1" || ref.WriteSet != write { + t.Fatalf("复用的预备份身份/写集合被改:%+v", ref) + } + if _, err := (ledgerBackupStore{ref: ref}).Prepare(context.Background(), "t", libraryrelease.CurrentState{}); err == nil { + t.Fatal("没有写集合时必须失败(不许降级成按现状推断残渣)") + } +} diff --git a/cmd/worker/library_barrier_test.go b/cmd/worker/library_barrier_test.go new file mode 100644 index 0000000..3be37a8 --- /dev/null +++ b/cmd/worker/library_barrier_test.go @@ -0,0 +1,67 @@ +package main + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/testbarrier" +) + +// 包装层必须真的把"阶段写完"这个点位交给屏障:只测屏障包不够——真实演练命中的是 +// 这条路径(contentTrackedTarget → 真实目标 Apply → 屏障)。漏接线的症状是脚本永远 +// 等不到 .hit,只能靠 sleep 猜时间(旧脚本就是这样错过阶段的)。 +func TestContentTrackedTargetReachesFixedBarrierPoint(t *testing.T) { + dir := t.TempDir() + t.Setenv(testbarrier.EnvDir, dir) + t.Setenv(testbarrier.EnvPoints, "after:database") + t.Setenv(testbarrier.EnvTimeout, "1ms") // 只验证点位与现场文件,不在这里做长等待 + + inner := &plainTarget{} + wrapped := &contentTrackedTarget{inner: inner, jobID: "libsync-internal-barrier", onApply: func() {}} + if err := wrapped.Apply(context.Background(), libraryrelease.StageDatabase, "snap-1"); err != nil { + t.Fatalf("apply: %v", err) + } + if inner.applied != 1 { + t.Fatalf("inner target must really be applied: %d", inner.applied) + } + raw, err := os.ReadFile(filepath.Join(dir, "after-database.hit")) + if err != nil { + t.Fatalf("阶段完成后必须留下屏障现场文件:%v", err) + } + var record struct { + Point string `json:"point"` + Subject string `json:"subject"` + } + if err := json.Unmarshal(raw, &record); err != nil { + t.Fatalf("decode hit: %v", err) + } + if record.Point != "after:database" || record.Subject != "libsync-internal-barrier" { + t.Fatalf("现场文件必须带上点位与作业身份:%+v", record) + } + + // 没配置的点位不许停留(否则一次演练会把后面所有阶段都卡住)。 + if err := wrapped.Apply(context.Background(), libraryrelease.StageResources, "snap-1"); err != nil { + t.Fatalf("apply resources: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "after-resources.hit")); !os.IsNotExist(err) { + t.Fatal("未配置的点位不许写现场文件") + } +} + +// 屏障默认关闭:没有注入时包装层行为与以前完全一致(不多写文件、不多等待)。 +func TestContentTrackedTargetIsInertWithoutBarrierInjection(t *testing.T) { + t.Setenv(testbarrier.EnvDir, "") + t.Setenv(testbarrier.EnvPoints, "") + inner := &plainTarget{} + wrapped := &contentTrackedTarget{inner: inner, jobID: "job-plain", onApply: func() {}} + if err := wrapped.Apply(context.Background(), libraryrelease.StageDatabase, "snap-1"); err != nil { + t.Fatalf("apply: %v", err) + } + if inner.applied != 1 { + t.Fatalf("inner target must be applied: %d", inner.applied) + } +} diff --git a/cmd/worker/library_baseline.go b/cmd/worker/library_baseline.go index 41e27c4..2f9d0db 100644 --- a/cmd/worker/library_baseline.go +++ b/cmd/worker/library_baseline.go @@ -22,7 +22,10 @@ type libraryBaselinePayload struct { Scope string `json:"scope"` } -// baselineVersionState 回答"这个 scope 现在有没有生效版本、是不是本作业登记的"。 +// classifyBaselineVersions 回答"这个 scope 现在有没有生效版本、是不是本作业登记的"。 +// +// 输入是**当前生效版本**这一个精确查询的结果(每 scope 至多一行),不是"最近 N 条": +// 窗口一满,已登记过的基线会被读成"没有",于是重复捕获、覆盖别人的版本。 // // 三种情况必须分开,否则崩溃续作会被自己的版本挡住: // - own:本作业 + 同一快照已经登记过 → 只收尾,绝不重复捕获或重写版本; @@ -33,19 +36,15 @@ type baselineVersionState struct { Foreign *governance.LibraryVersion } -func classifyBaselineVersions(versions []governance.LibraryVersion, jobID, snapshotID string) baselineVersionState { - for index := range versions { - item := versions[index] - if item.Kind != governance.LibraryVersionProductionEffective || item.SupersededAt != nil { - continue - } - if jobID != "" && snapshotID != "" && item.SourceJobID == jobID && item.SnapshotID == snapshotID { - return baselineVersionState{Own: true} - } - foreign := item - return baselineVersionState{Foreign: &foreign} +func classifyBaselineVersions(current governance.LibraryVersion, hasCurrent bool, jobID, snapshotID string) baselineVersionState { + if !hasCurrent { + return baselineVersionState{} } - return baselineVersionState{} + if effectiveOwnedBy(current, jobID, snapshotID) { + return baselineVersionState{Own: true} + } + foreign := current + return baselineVersionState{Foreign: &foreign} } // settleBaselineWindow 是基线窗口的**唯一**收尾入口,负责让治理状态与实际入口一致: @@ -101,14 +100,27 @@ func settleBaselineWindow(ctx context.Context, store libraryMaintenanceStore, he // 复核这份快照再登记; // - 登记后、收尾前被杀:重入识别出"本作业+同一快照"已生效,只做收尾 // (恢复服务/开入口/释放占用),不重复捕获、不重写版本;别人的版本仍然拒绝。 -func runLibraryBaseline(ctx context.Context, store *postgresstore.Store, config appconfig.Config, job jobs.Job) error { +func runLibraryBaseline(ctx context.Context, base *postgresstore.Store, config appconfig.Config, job jobs.Job) error { var payload libraryBaselinePayload if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.LibraryJobID == "" || (payload.Scope != "internal" && payload.Scope != "external") { return errors.New("invalid library baseline payload") } + // 准入与代次:基线也会停写入者、取整库快照,同样是"动目标"的执行, + // 必须和 sync/restore 用同一套准入与 fencing(F14/F13)。 + if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope, governance.LibraryJobBaseline, true); admitErr != nil { + return admitErr + } + return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID, func(runCtx context.Context, writer *libraryAttemptWriter) error { + return runLibraryBaselineAttempt(runCtx, writer, config, payload) + }) +} + +func runLibraryBaselineAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config, payload libraryBaselinePayload) error { + store := writer now := time.Now().UTC() - recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope} + recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope, + operationID: writer.attempt.OperationID} fail := func(message, stage string) error { return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, message, stage) } @@ -122,11 +134,12 @@ func runLibraryBaseline(ctx context.Context, store *postgresstore.Store, config _ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "capture", "", "", "", "", now) // 版本判定:别人的生效版本一律拒绝;本作业已登记过的快照只收尾。 - versions, versionErr := store.LibraryVersions(ctx, payload.Scope, 50) + // 用精确查询(当前生效版本),不用"最近 N 条":窗口一满会把已登记读成没登记。 + current, hasCurrent, versionErr := store.LibraryCurrentVersion(ctx, payload.Scope) if versionErr != nil { - return fail("读不到版本记录,无法确认是否需要建立基线;未对目标执行任何操作", "capture") + return fail("读不到生效版本记录,无法确认是否需要建立基线;未对目标执行任何操作", "capture") } - state := classifyBaselineVersions(versions, payload.LibraryJobID, persistedSnapshot) + state := classifyBaselineVersions(current, hasCurrent, payload.LibraryJobID, persistedSnapshot) if state.Foreign != nil { return fail("该目标已有生效版本 "+shortSnapshotID(state.Foreign.SnapshotID)+ "(作业 "+state.Foreign.SourceJobID+"),不需要再建基线;换版本请走同步或恢复", "capture") @@ -254,7 +267,7 @@ func runLibraryBaseline(ctx context.Context, store *postgresstore.Store, config // 版本登记放在窗口内:捕获、校验、登记三件事要么一起成立,要么目标原样恢复。 recorder.Stage(ctx, "finalize", "running", "登记目标权威基线") if recordErr := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ - ID: governance.LibraryVersionID(governance.LibraryVersionProductionEffective, payload.Scope, baselineID), + ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionEffective, payload.Scope, baselineID, writer.attempt.OperationID), Scope: payload.Scope, Kind: governance.LibraryVersionProductionEffective, SnapshotID: baselineID, SourceJobID: payload.LibraryJobID, CreatedBy: actor, Evidence: map[string]any{ diff --git a/cmd/worker/library_baseline_test.go b/cmd/worker/library_baseline_test.go index bad8c27..45db832 100644 --- a/cmd/worker/library_baseline_test.go +++ b/cmd/worker/library_baseline_test.go @@ -11,38 +11,36 @@ import ( ) // 崩溃续作的版本判定:本作业+同一快照 = 只收尾;别人的生效版本 = 拒绝;都没有 = 正常建基线。 +// "已顶替"的旧版本由 Store 的精确查询过滤掉(LibraryCurrentVersion 只返回未顶替的那一行), +// 所以这里只需要一个事实:当前生效的是谁。 func TestClassifyBaselineVersions(t *testing.T) { const jobA, jobB, snap = "libbase-internal-1", "libbase-internal-2", "snap-abc" - effective := func(sourceJob, snapshot string, superseded bool) governance.LibraryVersion { - item := governance.LibraryVersion{ + effective := func(sourceJob, snapshot string) governance.LibraryVersion { + return governance.LibraryVersion{ Scope: "internal", Kind: governance.LibraryVersionProductionEffective, SnapshotID: snapshot, SourceJobID: sourceJob, CreatedAt: time.Now().UTC(), } - if superseded { - at := time.Now().UTC() - item.SupersededAt = &at - } - return item } - if state := classifyBaselineVersions(nil, jobA, snap); state.Own || state.Foreign != nil { - t.Fatalf("no versions must mean neither own nor foreign: %+v", state) + if state := classifyBaselineVersions(governance.LibraryVersion{}, false, jobA, snap); state.Own || state.Foreign != nil { + t.Fatalf("没有生效版本必须既不是 own 也不是 foreign: %+v", state) } - if state := classifyBaselineVersions([]governance.LibraryVersion{effective(jobA, snap, false)}, jobA, snap); !state.Own { + if state := classifyBaselineVersions(effective(jobA, snap), true, jobA, snap); !state.Own { t.Fatalf("same job + same snapshot must be recognized as own: %+v", state) } // 快照不同就不是"我登记的那份",不能当成可收尾。 - if state := classifyBaselineVersions([]governance.LibraryVersion{effective(jobA, "snap-other", false)}, jobA, snap); state.Own || state.Foreign == nil { + if state := classifyBaselineVersions(effective(jobA, "snap-other"), true, jobA, snap); state.Own || state.Foreign == nil { t.Fatalf("different snapshot of same job must not be own: %+v", state) } // 别人的生效版本:即使快照相同也必须拒绝。 - foreign := classifyBaselineVersions([]governance.LibraryVersion{effective(jobB, snap, false)}, jobA, snap) + foreign := classifyBaselineVersions(effective(jobB, snap), true, jobA, snap) if foreign.Own || foreign.Foreign == nil || foreign.Foreign.SourceJobID != jobB { t.Fatalf("foreign effective version must be reported: %+v", foreign) } - // 已被顶替的旧版本不算生效版本。 - if state := classifyBaselineVersions([]governance.LibraryVersion{effective(jobB, snap, true)}, jobA, snap); state.Own || state.Foreign != nil { - t.Fatalf("superseded version must not block a baseline: %+v", state) + // 作业行里还没有持久化快照(persistedSnapshot 为空)时,自己登记的版本也算 foreign: + // 没有绑定身份的证据不能被当成"我可以只收尾"。 + if state := classifyBaselineVersions(effective(jobA, snap), true, jobA, ""); state.Own || state.Foreign == nil { + t.Fatalf("no persisted snapshot must not be own: %+v", state) } } diff --git a/cmd/worker/library_capacity.go b/cmd/worker/library_capacity.go new file mode 100644 index 0000000..03b1a6c --- /dev/null +++ b/cmd/worker/library_capacity.go @@ -0,0 +1,67 @@ +package main + +import ( + "context" + "errors" + "fmt" + "math" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/libraryretention" + "knowledge-governance/internal/librarysnapshot" +) + +// libraryWriteFootprint 是本次写入的容量需求下界:内容字节 + 等量恢复余量。 +// +// 为什么要算两份:写入前必须留出"目标被写坏后按预备份恢复"的空间。只按本次内容算, +// 预算刚好够写、不够恢复,故障时就地无法回滚——那比不发布更糟。 +func libraryWriteFootprint(contentBytes int64) (int64, error) { + if contentBytes < 0 { + return 0, errors.New("内容字节为负:容量口径异常") + } + if contentBytes > math.MaxInt64/2 { + return 0, errors.New("内容字节过大:容量需求溢出,拒绝放行") + } + return contentBytes * 2, nil +} + +// checkLibraryCapacity 是**执行前**的容量门禁(F11)。 +// +// 旧实现只在存储页 GET 里调用 CheckCapacity:那个数字是给人看的,worker 从来不读它, +// 所以"预算为正但明显不够"照样会进入维护、拍备份、写目标。这里把它接到真正要写之前。 +// +// 读不到容量/预算时不放行:无法证明装得下就不该动生产。 +func checkLibraryCapacity(ctx context.Context, config appconfig.Config, snapshotID string) error { + if config.LibraryCapacityBudgetBytes <= 0 { + return errors.New("容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES):无法证明装得下,拒绝进入维护") + } + archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024) + if err != nil { + return fmt.Errorf("归档不可用,无法核算容量:%w", err) + } + defer archive.Close() + usage, usageErr := archive.ContentUsage() + if usageErr != nil { + return fmt.Errorf("读不到当前归档内容占用,拒绝放行:%w", usageErr) + } + manifest, loadErr := archive.Load(snapshotID) + if loadErr != nil { + return fmt.Errorf("读不到待写入快照的清单,无法核算容量:%w", loadErr) + } + var incoming int64 + for _, part := range manifest.Parts { + if part.Bytes < 0 || incoming > math.MaxInt64-part.Bytes { + return errors.New("快照分片字节异常:拒绝放行") + } + incoming += part.Bytes + } + required, footprintErr := libraryWriteFootprint(incoming) + if footprintErr != nil { + return footprintErr + } + capacity := libraryretention.CheckCapacity(usage.ContentBytes, required, config.LibraryCapacityBudgetBytes) + if !capacity.OK { + return fmt.Errorf("容量门禁拒绝,未打开维护窗口:%s", capacity.Reason) + } + return nil +} diff --git a/cmd/worker/library_capacity_test.go b/cmd/worker/library_capacity_test.go new file mode 100644 index 0000000..4b16215 --- /dev/null +++ b/cmd/worker/library_capacity_test.go @@ -0,0 +1,22 @@ +package main + +import ( + "math" + "testing" +) + +// F11:容量需求必须是"内容 + 等量恢复余量",且溢出/负值要拒绝而不是绕回。 +func TestLibraryWriteFootprint(t *testing.T) { + if got, err := libraryWriteFootprint(1000); err != nil || got != 2000 { + t.Fatalf("footprint = %d, %v(写入 + 恢复余量)", got, err) + } + if _, err := libraryWriteFootprint(-1); err == nil { + t.Fatal("负字节必须拒绝") + } + if _, err := libraryWriteFootprint(math.MaxInt64/2 + 1); err == nil { + t.Fatal("溢出必须拒绝,不能算出负数后放行") + } + if got, err := libraryWriteFootprint(0); err != nil || got != 0 { + t.Fatalf("空内容 = %d, %v", got, err) + } +} diff --git a/cmd/worker/library_capture_persistence_test.go b/cmd/worker/library_capture_persistence_test.go new file mode 100644 index 0000000..67aa202 --- /dev/null +++ b/cmd/worker/library_capture_persistence_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +type capturePersistenceFake struct { + failAdvance error + failStage error + advanced []governance.LibraryJobState + stages []string +} + +func (f *capturePersistenceFake) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState, + _, _, _, _, _ string, _ time.Time) error { + f.advanced = append(f.advanced, state) + return f.failAdvance +} + +func (f *capturePersistenceFake) UpdateLibraryStage(_ context.Context, _, stage, state string, + _, _, _, _ *int64, _ string, _ time.Time) error { + f.stages = append(f.stages, stage+"/"+state) + return f.failStage +} + +// The handler must stop before touching the source when the starting state +// cannot be persisted. This is the failure injection that the old log-and-ignore +// path hid behind a completed queue row. +func TestBeginLibraryCaptureStopsOnAdvanceFailure(t *testing.T) { + store := &capturePersistenceFake{failAdvance: errors.New("injected advance failure")} + err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now()) + if err == nil || !strings.Contains(err.Error(), "cannot be advanced") { + t.Fatalf("err=%v", err) + } + if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobRunning { + t.Fatalf("advance calls=%v", store.advanced) + } + if len(store.stages) != 0 { + t.Fatalf("stage was written before advance failure: %v", store.stages) + } +} + +func TestBeginLibraryCaptureStopsOnStageFailure(t *testing.T) { + store := &capturePersistenceFake{failStage: errors.New("injected stage failure")} + err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now()) + if err == nil || !strings.Contains(err.Error(), "stage cannot be advanced") { + t.Fatalf("err=%v", err) + } + if len(store.stages) != 1 || store.stages[0] != "export/running" { + t.Fatalf("stage calls=%v", store.stages) + } +} + +// Terminal persistence is two writes; either failure must be returned rather +// than turning the queue row into completed while the business job is pending. +func TestCompleteLibraryCaptureStopsOnStageFailure(t *testing.T) { + store := &capturePersistenceFake{failStage: errors.New("injected success stage failure")} + err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now()) + if err == nil || !strings.Contains(err.Error(), "success stage cannot be persisted") { + t.Fatalf("err=%v", err) + } + if len(store.advanced) != 0 { + t.Fatalf("advance must not run after stage failure: %v", store.advanced) + } +} + +func TestCompleteLibraryCaptureStopsOnAdvanceFailure(t *testing.T) { + store := &capturePersistenceFake{failAdvance: errors.New("injected success advance failure")} + err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now()) + if err == nil || !strings.Contains(err.Error(), "success terminal cannot be persisted") { + t.Fatalf("err=%v", err) + } + if len(store.stages) != 1 || store.stages[0] != "export/succeeded" { + t.Fatalf("stage calls=%v", store.stages) + } + if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded { + t.Fatalf("advance calls=%v", store.advanced) + } +} + +func TestCompleteLibraryCapturePersistsBothFacts(t *testing.T) { + store := &capturePersistenceFake{} + if err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now()); err != nil { + t.Fatal(err) + } + if len(store.stages) != 1 || store.stages[0] != "export/succeeded" || + len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded { + t.Fatalf("stages=%v advanced=%v", store.stages, store.advanced) + } +} diff --git a/cmd/worker/library_capture_terminal_test.go b/cmd/worker/library_capture_terminal_test.go new file mode 100644 index 0000000..e2704d0 --- /dev/null +++ b/cmd/worker/library_capture_terminal_test.go @@ -0,0 +1,65 @@ +package main + +import ( + "errors" + "strings" + "testing" + + "knowledge-governance/internal/jobs" +) + +// R3g: only retained deterministic capture failures become permanent after the +// agent has recovered the writer. Cancelled body-index coverage markers are +// deliberately absent. +func TestRetainedLibraryCaptureFailuresArePermanent(t *testing.T) { + for _, marker := range []string{ + "missing library generated question index", + "empty library index content", + } { + t.Run(marker, func(t *testing.T) { + original := errors.New("LIBRARYCTL_FAILED: " + marker + ";已执行 recover 并确认写入者恢复") + got := terminalLibraryCaptureError(original) + terminal, code := jobs.Terminal(got) + if !terminal || code != jobs.ErrCodeValidationFailed { + t.Fatalf("retained validation failure must park immediately: terminal=%v code=%q err=%v", terminal, code, got) + } + if got.Error() != original.Error() { + t.Fatalf("original message changed: got %q want %q", got.Error(), original.Error()) + } + }) + } +} + +func TestCancelledCoverageFailureStaysRetryable(t *testing.T) { + for _, marker := range []string{ + "unverified legacy library chunk index coverage", + "missing indexed library chunk", + } { + err := terminalLibraryCaptureError(errors.New(marker + ";已执行 recover 并确认写入者恢复")) + if terminal, code := jobs.Terminal(err); terminal { + t.Fatalf("cancelled marker %q must not be terminal; code=%q", marker, code) + } + } +} + +func TestTransientLibraryCaptureFailureStaysRetryable(t *testing.T) { + for _, message := range []string{ + "library agent is unreachable", + "context deadline exceeded", + `LIBRARYCTL_FAILED: job "lib-internal-x" already exists with state "failed";已执行 recover 并确认写入者恢复`, + "missing library generated question index; writer restore not confirmed", + } { + got := terminalLibraryCaptureError(errors.New(message)) + if terminal, code := jobs.Terminal(got); terminal { + t.Fatalf("%q must stay retryable, got terminal code=%q", message, code) + } + } +} + +func TestRetainedFailureDoesNotChangeMessage(t *testing.T) { + original := errors.New("LIBRARYCTL_FAILED: missing library generated question index;已执行 recover 并确认写入者恢复") + got := terminalLibraryCaptureError(original) + if !strings.Contains(got.Error(), "missing library generated question index") { + t.Fatalf("lost original cause: %v", got) + } +} diff --git a/cmd/worker/library_completion.go b/cmd/worker/library_completion.go new file mode 100644 index 0000000..ac01e4e --- /dev/null +++ b/cmd/worker/library_completion.go @@ -0,0 +1,155 @@ +package main + +import ( + "context" + "errors" + "fmt" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// libraryFailStore 是"失败出口"需要的写面:带代次守卫的失败收尾。 +// 抽成接口是因为 writer 与裸 Store 都要能传进来(测试里常用裸 Store)。 +type libraryFailStore interface { + AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error + UpdateLibraryMaintenanceState(ctx context.Context, scope, ownerJobID, state, note string, now time.Time) error +} + +// prebackupAnchors 读"这次操作第一次拍下的那份额度":字节数与写集合摘要。 +// +// 为什么必须读它而不是重新计算:接管/收尾续作都没有重新备份,手上只有已登记的事实; +// 重新用当前状态算一遍就等于把"这次用了多大一份基线、写了什么"换成猜的(F09 的现场 +// 就是 backup_bytes 变成 0、writeset_digest 变空)。 +func prebackupAnchors(ctx context.Context, store *postgresstore.Store, scope, jobID, backupSnapshot string) (map[string]any, error) { + version, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionPrebackup, jobID, backupSnapshot) + if err != nil { + return nil, fmt.Errorf("读不到预备份证据:%w", err) + } + if !found { + return nil, fmt.Errorf("预备份 %s 没有作业 %s 的证据行:拒绝用空锚点登记生效版本", backupSnapshot, jobID) + } + anchors := map[string]any{} + for _, key := range []string{"backup_bytes", "writeset_digest", "writeset_rows", "writeset_path", + "writeset_created_at", "backup_created_at", "index_mapping_sha256", "backup_reused"} { + if value, ok := version.Evidence[key]; ok && value != nil { + anchors[key] = value + } + } + return anchors, nil +} + +// finalizeEvidence 构造"生效/恢复"事件的证据:以持久化锚点为底,补上本次动作与映射。 +// 缺字节数或写集合摘要时返回错误——收尾可以补登记,但不能补出一份没有锚点的"成功"。 +func finalizeEvidence(ctx context.Context, store *postgresstore.Store, scope, jobID, backupSnapshot, + targetSnapshot, action, mappingDigest string) (map[string]any, error) { + anchors, err := prebackupAnchors(ctx, store, scope, jobID, backupSnapshot) + if err != nil { + return nil, err + } + if _, ok := anchors["backup_bytes"]; !ok { + return nil, fmt.Errorf("预备份 %s 的证据里没有真实字节数:拒绝登记生效版本(会把 backup_bytes 洗成空)", backupSnapshot) + } + if digest, _ := anchors["writeset_digest"].(string); digest == "" { + return nil, fmt.Errorf("预备份 %s 的证据里没有写集合摘要:拒绝登记生效版本(恢复将无从按计划清理)", backupSnapshot) + } + evidence := map[string]any{"backup_snapshot": backupSnapshot, "action": action, "target_snapshot": targetSnapshot} + for key, value := range anchors { + evidence[key] = value + } + if mappingDigest != "" { + evidence["index_mapping_sha256"] = mappingDigest + } + return evidence, nil +} + +// rebuildSuccessBoundary 从**持久事实**重建"内容已验证、只差收尾"的凭据。 +// +// 触发场景(F05 路径一):journal 已 saved succeeded,但进程在 finishLibrarySuccess 之前 +// 崩了。接管方再跑 RunWindow 会直接成功返回、不再执行 work;如果这里还依赖进程内 +// pending 指针,作业就永远收不了尾(锁挂着、队列已完成、页面一直显示维护中)。 +// +// 重建需要且只需要三件事: +// 1. 作业行里持久化的预备份身份(这次用的是哪份基线); +// 2. 那份预备份的证据行里有真实字节数与写集合摘要(首次锚点没被洗掉); +// 3. 生效事件存在,或可以被**幂等补登记**(不重写目标、不再 Apply)。 +func rebuildSuccessBoundary(ctx context.Context, store *libraryAttemptWriter, recorder libraryStageRecorder, + payload libraryReleasePayload, previous governance.LibraryJob, kind governance.LibraryJobKind, + grant governance.LibraryReleaseAuthorization) (successBoundary, error) { + backup := previous.SnapshotID + if backup == "" { + return successBoundary{}, errors.New("窗口已成功,但作业行没有持久化预备份身份:无法证明内容基线") + } + action := string(kind) + if payload.FinalizeOnly { + action = "finalize_only" + } + if _, err := prebackupAnchors(ctx, store.Store, payload.Scope, payload.LibraryJobID, backup); err != nil { + return successBoundary{}, err + } + _, found, err := store.LibraryVersionByRef(ctx, payload.Scope, governance.LibraryVersionProductionEffective, + payload.LibraryJobID, payload.TargetSnapshotID) + if err != nil { + return successBoundary{}, fmt.Errorf("读不到生效事件:%w", err) + } + if !found { + recorder.Stage(ctx, "finalize", "running", "窗口已成功:补登记生效版本(不重写生产)") + evidence, evidenceErr := finalizeEvidence(ctx, store.Store, payload.Scope, payload.LibraryJobID, backup, + payload.TargetSnapshotID, action, recorder.mappingDigest) + if evidenceErr != nil { + return successBoundary{}, evidenceErr + } + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionEffective, payload.Scope, payload.TargetSnapshotID, store.attempt.OperationID), + Scope: payload.Scope, Kind: governance.LibraryVersionProductionEffective, + SnapshotID: payload.TargetSnapshotID, SourceJobID: payload.LibraryJobID, CreatedBy: grant.AuthorizedBy, + Evidence: evidence, CreatedAt: time.Now().UTC(), + }); err != nil { + return successBoundary{}, fmt.Errorf("补登记生效版本失败:%w", err) + } + recorder.Stage(ctx, "finalize", "succeeded", "已补登记生效版本(未重写生产)") + } + return successBoundary{Ready: true, Backup: backup, Target: payload.TargetSnapshotID, + FinishedAt: time.Now().UTC()}, nil +} + +// recordRecoveryEvent 是"按预备份恢复成功"的持久事实(F06)。 +// +// 它必须回答两件事,缺一不可: +// - 恢复出来的内容身份是什么(backup 快照 + 校验摘要); +// - current 现在指向它——旧实现只释放维护锁,于是物理内容已经是旧版, +// overview/diff/provenance 仍然宣称失败的新版本生效,后续操作拿错误基线做判断。 +// +// 它是独立事件,不改写原来那条失败作业/失败版本;原失败事实保持不变。 +func recordRecoveryEvent(ctx context.Context, store *libraryAttemptWriter, operation governance.LibraryOperation, + scope, jobID, backupSnapshot, verifyDigest, note string) error { + if backupSnapshot == "" || verifyDigest == "" { + return errors.New("恢复事件缺少预备份身份或校验摘要:不能登记成恢复事实") + } + // 事件挂在**恢复意图**上(不是失败作业的旧意图):current 的次序按意图创建时间, + // 旧意图的迟到事实推不动当前状态。 + operationID := operation.ID + evidence := map[string]any{ + "backup_snapshot": backupSnapshot, "action": "recover", "verify_digest": verifyDigest, + "window_job": jobID, "note": note, "recovered_at": time.Now().UTC(), + } + // 首次锚点若存在,一并带上:恢复事件同样要能回答"这份基线多大、写集合是什么"。 + if anchors, err := prebackupAnchors(ctx, store.Store, scope, jobID, backupSnapshot); err == nil { + for key, value := range anchors { + if _, exists := evidence[key]; !exists { + evidence[key] = value + } + } + } + return store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionEventID(governance.LibraryVersionRecoveryVerified, scope, backupSnapshot, + operationID), + Scope: scope, Kind: governance.LibraryVersionRecoveryVerified, SnapshotID: backupSnapshot, + SourceJobID: jobID, OperationID: operationID, AttemptEpoch: store.attempt.Epoch, + CreatedBy: "worker", Evidence: evidence, CreatedAt: operation.CreatedAt, + }) +} + +var _ libraryrelease.Recorder = libraryStageRecorder{} diff --git a/cmd/worker/library_contract_adopter_test.go b/cmd/worker/library_contract_adopter_test.go new file mode 100644 index 0000000..c6f6c67 --- /dev/null +++ b/cmd/worker/library_contract_adopter_test.go @@ -0,0 +1,51 @@ +package main + +import ( + "context" + "errors" + "testing" + "time" + + "knowledge-governance/internal/libraryrelease" +) + +type contractAdoptingTarget struct { + plainTarget + adopted int + planned int + reject error +} + +func (t *contractAdoptingTarget) AdoptWriteSet(set libraryrelease.WriteSet) error { + t.adopted++ + return t.reject +} +func (t *contractAdoptingTarget) PlanWriteSet(context.Context, libraryrelease.WriteSetPlan) (libraryrelease.WriteSet, error) { + t.planned++ + return libraryrelease.WriteSet{}, errors.New("must not replan") +} + +func TestContractWorkerWrapperReplaysPersistedPlan(t *testing.T) { + for _, reject := range []bool{false, true} { + inner := &contractAdoptingTarget{} + if reject { + inner.reject = errors.New("binding mismatch") + } + wrapped := &contentTrackedTarget{inner: inner, jobID: "job-1", onApply: func() {}} + set := sealedLedger(t, "") + now := time.Now().UTC() + request := libraryrelease.Request{JobID: "job-1", Target: "internal", SnapshotID: "target-snap", ParamsDigest: "digest", Now: now, + Grant: libraryrelease.Grant{Target: "internal", SnapshotID: "target-snap", ParamsDigest: "digest", ExpiresAt: now.Add(time.Hour), AuthorizedBy: "test"}} + backup := ledgerBackupStore{ref: libraryrelease.BackupRef{ID: "backup-1", SnapshotID: "backup-snap", Bytes: 4096}, write: &set} + result := libraryrelease.Run(context.Background(), request, wrapped, backup, nil) + if inner.adopted != 1 || inner.planned != 0 { + t.Fatalf("real wrapper lost adoption: adopted=%d planned=%d result=%+v", inner.adopted, inner.planned, result) + } + if reject && (inner.applied != 0 || result.State == "succeeded") { + t.Fatal("adoption failure must be zero-write") + } + if !reject && result.State != "succeeded" { + t.Fatalf("replay: %+v", result) + } + } +} diff --git a/cmd/worker/library_domain.go b/cmd/worker/library_domain.go new file mode 100644 index 0000000..b5eddf1 --- /dev/null +++ b/cmd/worker/library_domain.go @@ -0,0 +1,104 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "strings" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/jobs" + "knowledge-governance/internal/libraryadmission" + postgresstore "knowledge-governance/internal/platform/postgres" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +// verifyLibraryExecutionDomain 在注册整库发布 handler 之前核对"这个进程能不能独占目标"。 +// +// 为什么不在 API 里做:真正的执行者是 worker,能写目标的是它。准入放在执行者起手, +// 才不会被"另一个进程的配置"绕过去。 +// +// 判定全部基于**读出来的事实**(目标实况 / 旧的 release 路由绑定 / 未释放的维护窗口), +// 任何一项读不到都按未知处理并拒绝;这里不停止、不修改任何既有服务(停旧 worker 是 +// 运维决定),只决定"本进程是否注册整库发布执行器"。 +func verifyLibraryExecutionDomain(ctx context.Context, config appconfig.Config, store *postgresstore.Store) error { + if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" { + return errors.New("整库目标未配置(LIBRARY_PRODUCTION_DATABASE_URL):不注册整库发布执行器") + } + instance := config.LibraryTargetInstance + if instance == "" { + return errors.New("目标实例身份未配置(LIBRARY_TARGET_INSTANCE):无法证明执行域唯一") + } + // 1) 目标实况:连上去读,而不是回声配置。 + live, liveErr := v071.ProbeTargetIdentity(ctx, config.LibraryProductionDatabaseURL, + config.LibraryProductionTenantID, config.LibraryProductionInternalKB) + facts := libraryadmission.Facts{LiveErr: liveErr} + if liveErr == nil { + facts.Live = libraryadmission.Target{ + DatabaseEndpoint: config.LibraryProductionDatabaseURL, Index: config.LibraryProductionIndex, + Bucket: config.LibraryProductionS3Bucket, KnowledgeBaseID: config.LibraryProductionInternalKB, + TenantID: config.LibraryProductionTenantID, SchemaVersion: live.SchemaVersion, + Instance: instance, + } + facts.LiveDirty = live.Dirty + if live.IndexName != "" { + facts.Live.Index = live.IndexName + } + } + // 2) 旧 release 路由写哪个知识库:production_kb_bindings 是它自己的持久事实。 + if internalKB, externalKB, _, bindErr := store.LoadProductionKBBindings(ctx); bindErr != nil { + facts.LegacyErr = bindErr + } else { + // 旧路由把"测试库"发布到 external;两个方向都算重叠。 + targetKB := strings.TrimSpace(config.LibraryProductionInternalKB) + for _, candidate := range []string{internalKB, externalKB} { + if candidate != "" && candidate == targetKB { + facts.LegacyReleaseKB = candidate + break + } + } + if facts.LegacyReleaseKB == "" && externalKB != "" { + facts.LegacyReleaseKB = externalKB + } + } + // 3) 未释放的维护窗口:谁此刻持有这个目标。 + held, heldErr := store.HeldInstanceMaintenance(ctx) + if heldErr != nil { + facts.HeldErr = heldErr + } else { + for _, row := range held { + if row.ReleasedAt != nil { + continue + } + facts.HeldInstance, facts.HeldJob = row.Instance, row.OwnerJobID + break + } + } + configured := libraryadmission.Target{ + DatabaseEndpoint: config.LibraryProductionDatabaseURL, Index: config.LibraryProductionIndex, + Bucket: config.LibraryProductionS3Bucket, KnowledgeBaseID: config.LibraryProductionInternalKB, + TenantID: config.LibraryProductionTenantID, SchemaVersion: 0, // 由目标实况回答;配置不再另声明一份容易过期的版本 + Instance: instance, + } + if err := libraryadmission.Verify(configured, facts); err != nil { + return err + } + log.Printf("library execution domain admitted: instance=%s kb=%s schema=%d index=%s", + instance, configured.KnowledgeBaseID, facts.Live.SchemaVersion, configured.Index) + return nil +} + +// admittanceGuarded 把一个 handler 包成"准入未通过就拒绝执行"。 +// +// 用错误返回而不是不注册:不注册会让作业以 no-handler 进死信、看不出原因; +// 这里让作业**明确失败**并带上准入原因,页面能直接读到,且任何维护动作都没发生。 +func admittanceGuarded(admissionErr error, handler func(context.Context, jobs.Job) error) func(context.Context, jobs.Job) error { + if admissionErr == nil { + return handler + } + reason := admissionErr.Error() + return func(context.Context, jobs.Job) error { + return fmt.Errorf("整库发布执行域准入未通过,未做任何维护动作:%s", reason) + } +} diff --git a/cmd/worker/library_finalize_r11_integration_test.go b/cmd/worker/library_finalize_r11_integration_test.go new file mode 100644 index 0000000..8e646e0 --- /dev/null +++ b/cmd/worker/library_finalize_r11_integration_test.go @@ -0,0 +1,197 @@ +package main + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "knowledge-governance/internal/governance" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// B28:内容已通过校验之后的两类收尾故障必须只补收尾、不重写目标,且绝不伪报成功。 +// +// 这里用真实治理 PG(维护行、作业行、版本事件行都是真表),故障只注入在 +// “释放 scope 维护占用”这一个步骤上;其余调用照旧打到真库。 +type r11FinishFaultStore struct { + *postgresstore.Store + applies *int + failOnRelease bool + releaseFailure error +} + +func (s *r11FinishFaultStore) ReleaseLibraryMaintenance(ctx context.Context, scope, ownerJobID string, now time.Time) error { + if s.failOnRelease { + return s.releaseFailure + } + return s.Store.ReleaseLibraryMaintenance(ctx, scope, ownerJobID, now) +} + +type r11HealthyTarget struct{ err error } + +func (h r11HealthyTarget) VerifyRunning(context.Context) error { return h.err } + +func TestR11FinalizeFailureAfterTerminalHoldsThenRepairsWithoutRewrite(t *testing.T) { + store, _ := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const ( + scope = "internal" + instance = "kgseal-r11-finalize" + jobID = "libsync-r11-finalize" + target = "target-snap-r11-finalize" + backup = "backup-snap-r11-finalize" + operation = "libop-r11-finalize" + ) + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope, + Kind: governance.LibraryJobSync, IdempotencyKey: "library.sync:internal:r11-finalize", + RequestDigest: "digest-r11-finalize", Actor: "admin", TargetSnapshotID: target}, + governance.SyncStages(), now); err != nil { + t.Fatalf("create library job: %v", err) + } + // 生效事件必须引用真实 operation:登记前先落这条执行意图(真表,不是夹具)。 + if _, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: operation, Scope: scope, + Kind: governance.LibraryJobSync, TargetSnapshotID: target, RequestDigest: "digest-r11-finalize", + OperationKey: "r11-finalize", Actor: "admin", CreatedAt: now}); err != nil { + t.Fatalf("ensure library operation: %v", err) + } + // 这次作业确实持有两把维护锁:收尾失败后必须仍然持有(页面显示维护中)。 + if _, err := store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{Scope: scope, + OwnerJobID: jobID, TargetIdentity: "scope=" + scope, Level: "library", State: "acquired", + IngressState: "closed", Services: []string{"app"}}, now); err != nil { + t.Fatalf("acquire library maintenance: %v", err) + } + if _, err := store.AcquireInstanceMaintenance(ctx, postgresstore.LibraryInstanceMaintenance{Instance: instance, + OwnerJobID: jobID, OwnerScope: scope, TargetFingerprint: "fingerprint-r11", + Level: "instance", Services: []string{"app"}, IngressState: "closed", State: "acquired"}, now); err != nil { + t.Fatalf("acquire instance maintenance: %v", err) + } + // 完整锚点:真实字节数与写集合摘要。缺任何一项,收尾都该拒绝登记而不是补一份空台账。 + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, backup), + Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: backup, + SourceJobID: jobID, CreatedBy: "tester", + Evidence: map[string]any{"backup_snapshot": backup, "backup_bytes": float64(4096), + "writeset_digest": "writeset-digest-r11", "writeset_rows": float64(7)}, + CreatedAt: now, + }); err != nil { + t.Fatalf("record prebackup version: %v", err) + } + + // 目标内容落盘且计数:任何“再来一次”的重写都会让计数增长。 + root := t.TempDir() + published := filepath.Join(root, "target-content.txt") + if err := os.WriteFile(published, []byte("published-v1"), 0o600); err != nil { + t.Fatal(err) + } + applies := 1 // 内容写入(含校验)已经发生过一次 + writer := &libraryAttemptWriter{Store: store, attempt: governance.LibraryAttempt{ + OperationID: operation, JobID: jobID, Owner: "queue-r11-finalize"}} + recorder := libraryStageRecorder{store: store, jobID: jobID, scope: scope, operationID: operation} + payload := libraryReleasePayload{LibraryJobID: jobID, Scope: scope, TargetSnapshotID: target, FinalizeOnly: true} + previous := governance.LibraryJob{ID: jobID, Scope: scope, Kind: governance.LibraryJobSync, + SnapshotID: backup, TargetSnapshotID: target} + grant := governance.LibraryReleaseAuthorization{AuthorizedBy: "admin", Scope: scope, SnapshotID: target} + + // 1) 事件登记失败(这里用真实数据缺口:锚点里没有写集合摘要)必须拒绝登记, + // 不写生效版本、不进入终态、不重写目标。 + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, backup+"-noanchor"), + Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: backup + "-noanchor", + SourceJobID: jobID + "-noanchor", CreatedBy: "tester", + Evidence: map[string]any{"backup_snapshot": backup + "-noanchor"}, + CreatedAt: now, + }); err != nil { + t.Fatalf("record anchorless prebackup: %v", err) + } + badBoundary := payload + badBoundary.TargetSnapshotID = target + "-noanchor" + badPrevious := previous + badPrevious.SnapshotID = backup + "-noanchor" + if _, err := rebuildSuccessBoundary(ctx, writer, recorder, badBoundary, badPrevious, + governance.LibraryJobSync, grant); err == nil { + t.Fatal("anchorless prebackup was accepted as a success boundary") + } + if _, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionEffective, + jobID, target+"-noanchor"); err != nil || found { + t.Fatalf("refused registration still wrote an effective version: found=%v err=%v", found, err) + } + if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State == governance.LibraryJobSucceeded { + t.Fatalf("refused registration reported success: state=%v err=%v", job.State, err) + } + + // 2) journal 终态之后、释放维护占用这一步失败:不许报成功,锁必须继续持有。 + failing := &r11FinishFaultStore{Store: store, applies: &applies, failOnRelease: true, + releaseFailure: errors.New("injected: scope maintenance release failed after terminal journal")} + boundary := successBoundary{Ready: true, Backup: backup, Target: target, FinishedAt: now} + if err := finishLibrarySuccess(ctx, failing, r11HealthyTarget{}, instance, scope, jobID, boundary); err == nil { + t.Fatal("finish reported success even though the maintenance release failed") + } + if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State != governance.LibraryJobFailed { + t.Fatalf("job must be failed after finalize failure: state=%v err=%v", job.State, err) + } + held, err := store.LibraryMaintenanceOf(ctx, scope) + if err != nil || held == nil || held.OwnerJobID != jobID || held.ReleasedAt != nil { + t.Fatalf("scope maintenance must stay held by this job: %+v err=%v", held, err) + } + if held.State != "needs_restore" { + t.Fatalf("held maintenance state = %q, want needs_restore", held.State) + } + if applies != 1 { + t.Fatalf("finalize failure rewrote target content: applies=%d", applies) + } + content, err := os.ReadFile(published) + if err != nil || string(content) != "published-v1" { + t.Fatalf("target bytes changed during finalize failure: %q err=%v", content, err) + } + + // 3) 修复只补收尾:同一个持久凭据再收尾一次即可成功,且仍然不重写。 + repaired := &r11FinishFaultStore{Store: store, applies: &applies} + if err := finishLibrarySuccess(ctx, repaired, r11HealthyTarget{}, instance, scope, jobID, boundary); err != nil { + t.Fatalf("finalize-only repair failed: %v", err) + } + if job, err := store.LibraryJob(ctx, jobID); err != nil || job.State != governance.LibraryJobSucceeded { + t.Fatalf("job not succeeded after repair: state=%v err=%v", job.State, err) + } + released, err := store.LibraryMaintenanceOf(ctx, scope) + if err != nil || released == nil || released.ReleasedAt == nil { + t.Fatalf("scope maintenance not released after repair: %+v err=%v", released, err) + } + if applies != 1 { + t.Fatalf("finalize-only repair rewrote target content: applies=%d", applies) + } + content, err = os.ReadFile(published) + if err != nil || string(content) != "published-v1" { + t.Fatalf("target bytes changed during repair: %q err=%v", content, err) + } + + // 4) current/event 与实际内容一致:补登记的生效版本恰好一条,重复收尾不再新增。 + if _, err := rebuildSuccessBoundary(ctx, writer, recorder, payload, previous, + governance.LibraryJobSync, grant); err != nil { + t.Fatalf("rebuild boundary after repair: %v", err) + } + if _, err := rebuildSuccessBoundary(ctx, writer, recorder, payload, previous, + governance.LibraryJobSync, grant); err != nil { + t.Fatalf("idempotent rebuild: %v", err) + } + current, found, err := store.LibraryCurrentVersion(ctx, scope) + if err != nil || !found || current.SnapshotID != target || current.SourceJobID != jobID { + t.Fatalf("current does not point at the repaired snapshot: %+v found=%v err=%v", current, found, err) + } + versions, err := store.LibraryVersionsBySnapshot(ctx, scope, target) + if err != nil { + t.Fatalf("read effective versions: %v", err) + } + same := 0 + for _, version := range versions { + if version.Kind == governance.LibraryVersionProductionEffective { + same++ + } + } + if same != 1 { + t.Fatalf("effective version rows for %s = %d, want exactly 1", target, same) + } +} diff --git a/cmd/worker/library_finish.go b/cmd/worker/library_finish.go index e8ba1eb..f29ad93 100644 --- a/cmd/worker/library_finish.go +++ b/cmd/worker/library_finish.go @@ -114,40 +114,114 @@ const ( takeoverPendingFinal takeoverKind = "pending_final" // takeoverSuperseded:本快照曾经生效、后来被别的快照顶替,不得自动覆盖。 takeoverSuperseded takeoverKind = "superseded" + // takeoverForeignEffective:当前生效的确实是本作业的目标快照,但那一行登记属于 + // **别的作业**。快照相同不等于本作业写过:2026-10-29 的真实现场就是这样—— + // 本作业只写完了第一个写入阶段(database),resources/index/wiki/verify 仍是 + // pending,却因为"当前生效快照 == 我的目标快照"被当成只差收尾,直接登记成功, + // 并把生效版本归属改写成自己(同一 (scope, 快照) 的版本行是 upsert)。 + takeoverForeignEffective takeoverKind = "foreign_effective" // takeoverUnknown:版本状态读不到且没有阶段证据,属"未知",不得写入。 takeoverUnknown takeoverKind = "unknown" ) +// effectiveOwnedBy 回答"这一行生效登记是不是本作业为这个快照登记的"。 +// +// 快照相等的判定共用于接管与基线两条链路(同一含义只准有一份实现):这两个 +// 调用方都必须绑作业身份,否则"别的作业把同一个快照发布上线"会被误认成 +// "本作业已经完成"。 +func effectiveOwnedBy(version governance.LibraryVersion, jobID, snapshotID string) bool { + return jobID != "" && snapshotID != "" && version.SourceJobID == jobID && version.SnapshotID == snapshotID +} + +// takeoverResumeFacts 是一次"接管继续"能否成立的外部约束。 +// +// 一行生效版本被顶替只说明"那个快照曾经上线、后来被更新版本替换",并不说明 +// **当前这个作业**已经过期。要把"新恢复历史快照"与"本作业完成后的旧版本"分开, +// 必须再证明三件事:授权是顶替之后新签的、维护窗口仍由本作业独占、预备份基线 +// 还是本作业登记的那一份且字节未被改动。 +type takeoverResumeFacts struct { + AuthorizedAt time.Time + MaintenanceOwned bool + BaselineRecorded bool + BaselineVerified bool +} + +// authorizedRestoreAfterSupersede 回答"这是不是一次在顶替之后才获授权的恢复"。 +// 只认恢复:同步没有"恢复历史版本"这个业务,不能借这条分支绕开覆盖保护。 +func (r takeoverResumeFacts) authorizedRestoreAfterSupersede(job governance.LibraryJob, supersededAt time.Time) bool { + return job.Kind == governance.LibraryJobRestore && job.TargetSnapshotID != "" && + !r.AuthorizedAt.IsZero() && r.AuthorizedAt.After(supersededAt) && + r.MaintenanceOwned && r.BaselineRecorded && r.BaselineVerified +} + // classifyTakeover 只按证据分类: // - finalize 阶段成功是独立证据(来自作业自己的阶段行),不因版本查询失败而丢弃; -// - 本快照存在 released/被顶替的版本 ⇒ superseded; -// - 本快照存在未被顶掉的生效版本 ⇒ pending_final; +// - 本快照存在 released/被顶替的版本 ⇒ superseded;例外是该行属于**别的作业**、 +// 且本次是顶替之后新授权的恢复并仍独占维护窗口、基线未变 ⇒ fresh(恢复历史 +// 快照是正常业务,历史那次发布被顶替不等于本作业过期); +// - 本快照存在未被顶掉的生效版本,且归属本作业 ⇒ pending_final;归属别的作业 ⇒ +// foreign_effective(同快照不算本作业的完成证据); // - 查询失败且无阶段证据 ⇒ unknown(可重试,不当成没有证据)。 -func classifyTakeover(job governance.LibraryJob, versions []governance.LibraryVersion, versionsErr error) takeoverKind { +// +// 事实来自两个精确查询(LibraryCurrentVersion / LibraryVersionOfSnapshot),**不是** +// "最近 N 条再在内存里筛":窗口一满,已生效的快照会被判成"没有证据",接管就会把 +// 已经上线的内容重写一遍。 +func classifyTakeover(job governance.LibraryJob, facts libraryVersionFacts, resume takeoverResumeFacts) takeoverKind { finalized := false for _, stage := range job.Stages { if stage.Stage == "finalize" && stage.State == "succeeded" { finalized = true } } - if versionsErr != nil && !finalized { + if facts.Err != nil && !finalized { return takeoverUnknown } - superseded, effective := false, false - for _, version := range versions { - if version.Kind != governance.LibraryVersionProductionEffective || version.SnapshotID != job.TargetSnapshotID { - continue + if facts.Err == nil { + // 本快照登记过生效版本:被顶替过就绝不能用它覆盖更新的生产版本。 + if facts.HasSnapshot && facts.Snapshot.SupersededAt != nil { + // 台账自相矛盾(这一行说已顶替,当前生效的却还是它):状态不可判定。 + if facts.HasCurrent && facts.Current.SnapshotID == job.TargetSnapshotID { + return takeoverUnknown + } + // 连"当前生效是哪一份"都读不到:无法证明生产上还有更新版本可保护, + // 也无法证明这次续写落在哪个基线上,一律拒绝。 + if !facts.HasCurrent { + return takeoverSuperseded + } + // 本作业自己完成过(finalize 阶段成功,或这一行生效登记就是本作业写的): + // 生产已被后续版本替换,再写回旧快照就是覆盖更新的生产,必须拒绝。 + if finalized || effectiveOwnedBy(facts.Snapshot, job.ID, job.TargetSnapshotID) { + return takeoverSuperseded + } + // 这一行属于**别的作业**:它说明的是那次历史发布被顶替,不是本作业过期。 + // 新恢复对该历史快照有顶替之后的独立授权、仍独占本次维护窗口、预备份 + // 基线未变时,恢复历史快照是正常业务,按 fresh 重跑整条写入链路 + // (不能按 pending_final:内容还没写完)。 + if resume.authorizedRestoreAfterSupersede(job, *facts.Snapshot.SupersededAt) { + return takeoverFresh + } + return takeoverSuperseded } - if version.SupersededAt != nil { - superseded = true - } else { - effective = true + if facts.HasSnapshot { + // 未顶替 ⇒ 必须就是当前生效的那一行;不是的话台账不一致,不许挑一条继续写。 + if !facts.HasCurrent || facts.Current.SnapshotID != job.TargetSnapshotID { + return takeoverUnknown + } + if !finalized && !effectiveOwnedBy(facts.Snapshot, job.ID, job.TargetSnapshotID) { + return takeoverForeignEffective + } + return takeoverPendingFinal + } + // 本快照没有自己的生效登记,但当前生效的正是它:内容确实已经在生产上。 + // 归属必须也是本作业,否则只能说明别的作业发布过同一快照。 + if facts.HasCurrent && facts.Current.SnapshotID == job.TargetSnapshotID { + if !finalized && !effectiveOwnedBy(facts.Current, job.ID, job.TargetSnapshotID) { + return takeoverForeignEffective + } + return takeoverPendingFinal } } - if superseded && !effective { - return takeoverSuperseded - } - if effective || finalized { + if finalized { return takeoverPendingFinal } return takeoverFresh diff --git a/cmd/worker/library_finish_test.go b/cmd/worker/library_finish_test.go index 8cb7b34..37576f2 100644 --- a/cmd/worker/library_finish_test.go +++ b/cmd/worker/library_finish_test.go @@ -152,38 +152,72 @@ func TestFinishLibrarySuccessReportsTerminalWriteFailure(t *testing.T) { } } -// 接管分类:阶段证据独立成立;查询失败=未知(不得写入);被顶替=不得覆盖。 +// 接管分类:阶段证据独立成立;查询失败=未知(不得写入);被顶替=不得覆盖; +// 台账自相矛盾(未顶替但不是当前生效 / 已顶替却是当前生效)=未知,fail closed。 func TestClassifyTakeoverSeparatesUnknownPendingSupersededAndFresh(t *testing.T) { - job := governance.LibraryJob{Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: "snap-1"} + job := governance.LibraryJob{ID: "job-own", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: "snap-1"} finalized := job finalized.Stages = []governance.LibraryStage{{Stage: "finalize", State: "succeeded"}} - effective := []governance.LibraryVersion{{Kind: governance.LibraryVersionProductionEffective, SnapshotID: "snap-1"}} - supersededVersion := []governance.LibraryVersion{{Kind: governance.LibraryVersionProductionEffective, - SnapshotID: "snap-1", SupersededAt: ptrTime(time.Now())}} - unrelated := []governance.LibraryVersion{{Kind: governance.LibraryVersionProductionEffective, SnapshotID: "snap-9"}} - queryErr := errors.New("version storage temporarily unavailable") + supersededAt := time.Now().UTC() + + // source 是"这一行生效登记属于哪个作业":快照相等不代表本作业写过。 + factsBy := func(source, current string, hasCurrent bool, snapshot string, hasSnapshot bool, superseded bool) libraryVersionFacts { + result := libraryVersionFacts{HasCurrent: hasCurrent, HasSnapshot: hasSnapshot} + if hasCurrent { + result.Current = governance.LibraryVersion{Kind: governance.LibraryVersionProductionEffective, + SnapshotID: current, SourceJobID: source} + } + if hasSnapshot { + result.Snapshot = governance.LibraryVersion{Kind: governance.LibraryVersionProductionEffective, + SnapshotID: snapshot, SourceJobID: source} + if superseded { + result.Snapshot.SupersededAt = &supersededAt + } + } + return result + } + facts := func(current string, hasCurrent bool, snapshot string, hasSnapshot bool, superseded bool) libraryVersionFacts { + return factsBy(job.ID, current, hasCurrent, snapshot, hasSnapshot, superseded) + } + queryErr := libraryVersionFacts{Err: errors.New("version storage temporarily unavailable")} cases := []struct { - name string - job governance.LibraryJob - versions []governance.LibraryVersion - err error - want takeoverKind + name string + job governance.LibraryJob + facts libraryVersionFacts + want takeoverKind }{ // 关键回归:查询失败 + 没有阶段证据 ⇒ 未知,不能当成"没有收尾证据"继续写。 - {"query fails without stage evidence", job, nil, queryErr, takeoverUnknown}, + {"query fails without stage evidence", job, queryErr, takeoverUnknown}, // 阶段证据先独立成立:查询失败不影响"只差收尾"的判定。 - {"query fails but finalize stage succeeded", finalized, nil, queryErr, takeoverPendingFinal}, - {"effective version for this snapshot", job, effective, nil, takeoverPendingFinal}, - {"finalize stage succeeded", finalized, nil, nil, takeoverPendingFinal}, - {"this snapshot was superseded", job, supersededVersion, nil, takeoverSuperseded}, - {"no evidence at all", job, nil, nil, takeoverFresh}, - {"another snapshot effective but this one has no row", job, unrelated, nil, takeoverFresh}, - {"empty target snapshot", governance.LibraryJob{Scope: "internal"}, nil, nil, takeoverFresh}, + {"query fails but finalize stage succeeded", finalized, queryErr, takeoverPendingFinal}, + {"effective version for this snapshot", job, facts("snap-1", true, "snap-1", true, false), takeoverPendingFinal}, + // 当前生效的就是本快照,但没有本作业的登记行:归属仍是本作业才算只差收尾。 + {"current is this snapshot without own row", job, facts("snap-1", true, "", false, false), takeoverPendingFinal}, + // 实测缺陷(2026-10-29):同一个快照由**别的作业**登记成生效版本时,本作业只写完了 + // database 阶段也被判成只差收尾 ⇒ 直接成功并改写版本归属。必须判 foreign。 + {"same snapshot registered by another job", job, + factsBy("libsync-internal-other", "snap-1", true, "snap-1", true, false), takeoverForeignEffective}, + {"current is this snapshot owned by another job", job, + factsBy("libsync-internal-other", "snap-1", true, "", false, false), takeoverForeignEffective}, + // 本作业自己的 finalize 阶段成功是独立证据:即使版本归属被别人改写,也不算未知。 + {"finalize stage succeeded even if ownership was rewritten", finalized, + factsBy("libsync-internal-other", "snap-1", true, "snap-1", true, false), takeoverPendingFinal}, + {"finalize stage succeeded", finalized, libraryVersionFacts{}, takeoverPendingFinal}, + {"this snapshot was superseded", job, facts("snap-9", true, "snap-1", true, true), takeoverSuperseded}, + {"no evidence at all", job, libraryVersionFacts{}, takeoverFresh}, + {"another snapshot effective but this one has no row", job, facts("snap-9", true, "", false, false), takeoverFresh}, + {"empty target snapshot", governance.LibraryJob{Scope: "internal"}, libraryVersionFacts{}, takeoverFresh}, + // 未顶替的登记行却不是当前生效版本:两个事实互相矛盾,不许挑一个继续写。 + {"own row not superseded but current differs", job, facts("snap-9", true, "snap-1", true, false), takeoverUnknown}, + // 已顶替却又是当前生效版本:同样是矛盾台账。 + {"own row superseded but current is it", job, facts("snap-1", true, "snap-1", true, true), takeoverUnknown}, + // 有登记行但读不到当前生效版本:无法确认它是不是生效版本。 + {"own row without current", job, facts("", false, "snap-1", true, false), takeoverUnknown}, } for _, test := range cases { t.Run(test.name, func(t *testing.T) { - if got := classifyTakeover(test.job, test.versions, test.err); got != test.want { + if got := classifyTakeover(test.job, test.facts, takeoverResumeFacts{}); got != test.want { t.Fatalf("classify = %q, want %q", got, test.want) } }) diff --git a/cmd/worker/library_grant_revoke_r11_integration_test.go b/cmd/worker/library_grant_revoke_r11_integration_test.go new file mode 100644 index 0000000..d8e2b2f --- /dev/null +++ b/cmd/worker/library_grant_revoke_r11_integration_test.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" +) + +// r11RevokingBackups 在真实预备份完成之后撤销授权:这正是"排空之后、首次写之前" +// 被撤销的那个窗口,不是凭空造一个失败。 +type r11RevokingBackups struct { + inner libraryrelease.BackupStore + after func() +} + +func (b r11RevokingBackups) Prepare(ctx context.Context, id string, current libraryrelease.CurrentState) (libraryrelease.BackupRef, error) { + ref, err := b.inner.Prepare(ctx, id, current) + if err == nil && b.after != nil { + b.after() + } + return ref, err +} + +// B30:授权在预备份之后被撤销,必须一笔目标写都不发生;同一链路在没有撤销时 +// 正常完成(正例对照,证明这条门不是靠"永远失败"通过的)。 +func TestR11RevokedAuthorizationStopsBeforeFirstWrite(t *testing.T) { + store, _ := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const ( + scope = "internal" + jobID = "libsync-r11-revoke" + snapshot = "control-snap-r11-revoke" + target = "target-snap-r11-revoke" + params = "params-r11-revoke" + operation = "libop-r11-revoke" + backup = "backup-snap-r11-revoke" + authID = "libauth-r11-revoke" + ) + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope, + Kind: governance.LibraryJobSync, IdempotencyKey: "library.sync:internal:r11-revoke", + RequestDigest: params, Actor: "admin", TargetSnapshotID: target}, governance.SyncStages(), now); err != nil { + t.Fatalf("create library job: %v", err) + } + if _, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: operation, Scope: scope, + Kind: governance.LibraryJobSync, TargetSnapshotID: target, RequestDigest: params, + OperationKey: "r11-revoke", Actor: "admin", CreatedAt: now}); err != nil { + t.Fatalf("ensure library operation: %v", err) + } + if err := store.CreateLibraryAuthorization(ctx, governance.LibraryReleaseAuthorization{ID: authID, Scope: scope, + SnapshotID: target, ParamsDigest: params, AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now}); err != nil { + t.Fatalf("create authorization: %v", err) + } + grant := libraryrelease.Grant{Target: scope, SnapshotID: target, ParamsDigest: params, + ExpiresAt: now.Add(time.Hour), AuthorizedBy: "admin"} + request := libraryrelease.Request{JobID: jobID, Target: scope, SnapshotID: target, + ParamsDigest: params, Now: now, Grant: grant} + backups := ledgerTestBackups{ref: libraryrelease.BackupRef{ID: "backup-" + backup, SnapshotID: backup, + Bytes: 4096, Universe: map[string]libraryrelease.TableFingerprint{"resources": {Count: 1, Digest: "universe"}}}} + + // 正例对照:授权有效时同一条链路写完四个阶段。 + control := &planningTarget{} + controlTarget := &contentTrackedTarget{inner: control, jobID: jobID, onApply: func() {}, + revalidateGrant: revalidateLibraryGrant(store)} + if out := libraryrelease.Run(ctx, request, controlTarget, backups, nil); out.State != "succeeded" { + t.Fatalf("control run did not succeed with a live authorization: %+v", out) + } + if control.applied != 4 { + t.Fatalf("control run applied %d stages, want 4", control.applied) + } + + // 撤销后:预备份成功、授权随即失效,写集合都不该被算出来(那会分配序列)。 + guarded := &planningTarget{} + guardedTarget := &contentTrackedTarget{inner: guarded, jobID: jobID, onApply: func() {}, + revalidateGrant: revalidateLibraryGrant(store)} + revoking := r11RevokingBackups{inner: backups, after: func() { + if err := store.RevokeLibraryAuthorization(ctx, authID, time.Now().UTC()); err != nil { + t.Fatalf("revoke authorization: %v", err) + } + }} + out := libraryrelease.Run(ctx, request, guardedTarget, revoking, nil) + if out.State != "failed" { + t.Fatalf("revoked authorization still produced state %q: %+v", out.State, out) + } + if !strings.Contains(out.Error, "持久授权") { + t.Fatalf("refusal reason does not name the persisted authorization: %q", out.Error) + } + if guarded.applied != 0 || guarded.planned != 0 { + t.Fatalf("revoked authorization wrote target: applied=%d planned=%d", guarded.applied, guarded.planned) + } + if out.Backup.SnapshotID != backup || !strings.Contains(out.Recovery, "预备份保留") { + t.Fatalf("prebackup must be preserved for a retry: backup=%+v recovery=%q", out.Backup, out.Recovery) + } + // 撤销是持久的:再读一次仍然查不到有效授权。 + if _, ok, err := store.ActiveLibraryAuthorization(ctx, scope, target, params, time.Now().UTC()); err != nil || ok { + t.Fatalf("revocation did not persist: ok=%v err=%v", ok, err) + } +} diff --git a/cmd/worker/library_handlers.go b/cmd/worker/library_handlers.go index 87ba6d8..65393ef 100644 --- a/cmd/worker/library_handlers.go +++ b/cmd/worker/library_handlers.go @@ -18,6 +18,7 @@ import ( "knowledge-governance/internal/librarysnapshot" "knowledge-governance/internal/pgdsn" postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/testbarrier" ) // 目标内容在窗口内的几种"已知状态",决定目标能否被重新开放: @@ -34,9 +35,48 @@ const ( // contentTrackedTarget 只做一件事:在第一次写目标时把"内容有风险"标出来。 // 这样"授权过期/进程被杀/校验失败"这些早退路径不会把半写目标当成没动过。 +// +// 另外它是本机中断演练的固定点位:每个阶段写完、下一个阶段还没开始时调用 +// testbarrier.Wait(默认关闭,两个环境变量同时在场才生效)。放在这一层而不是 +// 发布代码里,是因为"阶段之间"正是真实半写状态的边界,而发布链路本身不需要知道演练。 type contentTrackedTarget struct { inner libraryrelease.Target + jobID string onApply func() + // revalidateGrant 由 runLibraryRelease 无条件接线:每笔副作用前按治理库里的 + // 授权行重新判定(撤销/过期即停)。测试夹具可以显式传 nil 表示"这份夹具没有 + // 持久授权行",但真实发布路径不允许为空 —— 那里的空值等于回到只信内存快照。 + revalidateGrant func(context.Context, libraryrelease.Grant) error +} + +// revalidateLibraryGrant 是"授权没有被中途撤销/过期"的唯一判定实现: +// 真实发布链路与测试都走它,避免测试自己写一份看起来相同的查询。 +func revalidateLibraryGrant(store *postgresstore.Store) func(context.Context, libraryrelease.Grant) error { + return func(ctx context.Context, current libraryrelease.Grant) error { + // 权威来源是治理库里的授权行:参数摘要一变就查不到,撤销/过期立即消失。 + found, ok, err := store.ActiveLibraryAuthorization(ctx, current.Target, current.SnapshotID, + current.ParamsDigest, time.Now().UTC()) + if err != nil { + return fmt.Errorf("读取持久授权失败:%w", err) + } + if !ok { + return errors.New("当前授权已撤销或已过期") + } + if found.AuthorizedBy != current.AuthorizedBy { + return errors.New("持久授权与本次执行身份不一致") + } + return nil + } +} + +func (t *contentTrackedTarget) RevalidateGrant(ctx context.Context, grant libraryrelease.Grant) error { + if t.revalidateGrant != nil { + return t.revalidateGrant(ctx, grant) + } + if inner, ok := t.inner.(libraryrelease.GrantRevalidator); ok { + return inner.RevalidateGrant(ctx, grant) + } + return nil } func (t *contentTrackedTarget) Current(ctx context.Context) (libraryrelease.CurrentState, error) { @@ -45,7 +85,14 @@ func (t *contentTrackedTarget) Current(ctx context.Context) (libraryrelease.Curr func (t *contentTrackedTarget) Apply(ctx context.Context, stage libraryrelease.Stage, snapshotID string) error { t.onApply() - return t.inner.Apply(ctx, stage, snapshotID) + if err := t.inner.Apply(ctx, stage, snapshotID); err != nil { + return err + } + // 屏障错误只记日志:演练设施坏掉不许让一次真实发布失败。 + if barrierErr := testbarrier.Wait(ctx, "after:"+string(stage), t.jobID); barrierErr != nil { + log.Printf("library test barrier point=after:%s job=%s unavailable: %v", stage, t.jobID, barrierErr) + } + return nil } func (t *contentTrackedTarget) Verify(ctx context.Context, expect libraryrelease.Expectation) error { @@ -56,6 +103,42 @@ func (t *contentTrackedTarget) Restore(ctx context.Context, backup libraryreleas return t.inner.Restore(ctx, backup) } +// PlanWriteSet 必须显式转发:orchestrator 是按 `target.(WriteSetPlanner)` 这个 +// 类型断言决定要不要在写第一笔之前算写集合的,包一层之后断言就失败了——于是 +// 台账既不落盘也不登记,恢复/接管时根本没有"这次明确写了什么"可读。 +// 真实后果:2026-10-29 的两次真作业的预备份证据里都没有 writeset_digest, +// 归档根下也没有 writesets/;一旦 worker 崩在写入中间,接管必然失败。 +// +// 内层不支持预检时返回硬错误,不退回"没有台账也照写":那会让恢复只能按目标 +// 现状推断残渣,从而误删历史孤儿资源。 +func (t *contentTrackedTarget) PlanWriteSet(ctx context.Context, plan libraryrelease.WriteSetPlan) (libraryrelease.WriteSet, error) { + planner, ok := t.inner.(libraryrelease.WriteSetPlanner) + if !ok { + return libraryrelease.WriteSet{}, errors.New("目标实现不支持写集合预检:拒绝在没有可追溯写集合的情况下写生产") + } + set, err := planner.PlanWriteSet(ctx, plan) + if err == nil { + // 日志是"wrapper 路径真的执行了预检"的现场证据:接管排查先看这一行。 + log.Printf("library writeset planned job=%s target=%s digest=%s rows=%d reused=%d target_snapshot=%s", + set.JobID, set.Target, set.Digest, len(set.Rows), len(set.ReusedIDs("resources")), set.TargetSnapshotID) + } + return set, err +} + +func (t *contentTrackedTarget) AdoptWriteSet(set libraryrelease.WriteSet) error { + adopter, ok := t.inner.(libraryrelease.WriteSetAdopter) + if !ok { + return errors.New("目标实现不支持接管已持久化写集合,拒绝重建计划") + } + if set.JobID != t.jobID { + return errors.New("写集合与 worker 作业身份不符") + } + return adopter.AdoptWriteSet(set) +} + +var _ libraryrelease.WriteSetPlanner = (*contentTrackedTarget)(nil) +var _ libraryrelease.WriteSetAdopter = (*contentTrackedTarget)(nil) + // libraryReleasePayload 是同步与恢复共用的队列载荷形状。 type libraryReleasePayload struct { LibraryJobID string `json:"library_job_id"` @@ -72,15 +155,28 @@ type libraryReleasePayload struct { // runLibraryRelease 执行"闸口 → 授权 → 关闭目标入口并停止写入者 → 预备份 → // 四类写入 → 校验 → 登记权威版本 → 恢复原运行状态和入口"的完整链路。 // 同步与恢复只在作业类型、授权摘要与成功后登记的版本类型上不同。 -func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config appconfig.Config, - job jobs.Job, kind governance.LibraryJobKind) error { +func runLibraryRelease(ctx context.Context, base *postgresstore.Store, config appconfig.Config, + job jobs.Job, kind governance.LibraryJobKind) (err error) { var payload libraryReleasePayload if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.LibraryJobID == "" || payload.TargetSnapshotID == "" { return fmt.Errorf("invalid library %s payload", kind) } + // 准入必须在任何维护/目标动作之前:业务行存在、kind/scope 一致、队列关联不可伪造。 + if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope, kind, true); admitErr != nil { + return admitErr + } + return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID, func(runCtx context.Context, writer *libraryAttemptWriter) error { + return runLibraryReleaseAttempt(runCtx, writer, config, kind, payload) + }) +} + +func runLibraryReleaseAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config, + kind governance.LibraryJobKind, payload libraryReleasePayload) (err error) { + store := writer now := time.Now().UTC() _ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "prebackup", "", "", "", "", now) - recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope} + recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope, + operationID: store.attempt.OperationID} // 四类进度的真实总量来自快照清单(manifest):读不到就保持 NULL,不写 0。 if archive, openErr := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024); openErr == nil { if manifest, loadErr := archive.Load(payload.TargetSnapshotID); loadErr == nil { @@ -93,16 +189,37 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a // 绝不重新备份——重新备份会把"半写状态"当成新基线,覆盖真正可回滚的那份。 previous, err := store.LibraryJob(ctx, payload.LibraryJobID) resumed := err == nil && previous.SnapshotID != "" + // 续作失败时不能写"无需恢复":上一次尝试可能已经把目标写了一半。 + // 这一处按"有没有持久化预备份"统一选择失败出口,避免每个早退点各写一套文案。 + fail := func(message, stage string) error { + return failLibraryJobOrTakeover(ctx, store, recorder, payload.Scope, payload.LibraryJobID, + previous.SnapshotID, resumed, message, stage) + } if resumed { - versions, versionErr := store.LibraryVersions(ctx, payload.Scope, 50) - switch classifyTakeover(previous, versions, versionErr) { + facts := loadLibraryVersionFacts(ctx, store, payload.Scope, previous.TargetSnapshotID) + resume := loadTakeoverResumeFacts(ctx, store, config.LibraryArchiveRoot, previous, now) + decision := classifyTakeover(previous, facts, resume) + // 接管决策必须"动手之前"落日志,并带作业身份与复用的预备份: + // 只留阶段表的话,同快照收尾能把它伪造成"完整续作"(上一轮的假完成)。 + logTakeoverDecision(payload.LibraryJobID, decision, kind, payload.Scope, + payload.TargetSnapshotID, previous.SnapshotID, decision == takeoverPendingFinal, time.Now().UTC()) + switch decision { case takeoverUnknown: // 版本状态读不到、又没有阶段证据:不能当成"没有收尾证据"继续写目标。 - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, - "接管时读不到该目标的版本状态,无法判断是只差收尾还是要重做;未对目标执行任何写入,稍后重试", "prebackup") + return fail("接管时读不到该目标的版本状态,无法判断是只差收尾还是要重做;本作业未继续写目标,稍后重试", "prebackup") case takeoverSuperseded: - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, - "本快照的生效版本已被别的快照顶替,拒绝用旧快照覆盖当前生产版本", "prebackup") + return fail("本快照的生效版本已被别的快照顶替,且本作业没有新的恢复授权/独占维护窗口/未变基线,拒绝用旧快照覆盖当前生产版本", "prebackup") + case takeoverForeignEffective: + // 同一个快照由别的作业发布过:那只能证明生产上有这份内容,不能证明本作业 + // 写完过、更不能证明它只差收尾。按同快照收尾会把只写了第一个阶段的作业 + // 标成成功,并改写版本归属(实测过的假完成)。 + owner := facts.Current.SourceJobID + if facts.HasSnapshot { + owner = facts.Snapshot.SourceJobID + } + return failLibraryTakeover(ctx, store, recorder, payload.Scope, payload.LibraryJobID, previous.SnapshotID, + "接管时目标快照 "+shortSnapshotID(payload.TargetSnapshotID)+" 的生效版本由作业 "+owner+ + " 登记:本作业没有自己的完成证据,不按同快照收尾") case takeoverPendingFinal: // 上次可能死在"锁已放、终态没写"之间:只复核与登记,不重写生产。 payload.FinalizeOnly = true @@ -116,8 +233,8 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a if !config.ProductionReleaseRequestsEnabled { gateReasons = append(gateReasons, "生产写入闸口关闭") } - if !config.ProductionBackupRestoreVerified { - gateReasons = append(gateReasons, "没有已核验的生产恢复演练证据") + if ok, reason := libraryRestoreEvidenceSatisfied(ctx, store, config, payload.Scope); !ok { + gateReasons = append(gateReasons, reason) } if len(gateReasons) > 0 { message := "生产" + kindLabel(kind) + "被闸口拒绝:" + strings.Join(gateReasons, ";") @@ -135,62 +252,58 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a digest, err := governance.LibraryRequestDigest(payload.Scope, kind, map[string]any{digestKey(kind): payload.TargetSnapshotID}) if err != nil { - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, "无法计算请求摘要", "prebackup") + return fail("无法计算请求摘要", "prebackup") } grant, found, err := store.ActiveLibraryAuthorization(ctx, payload.Scope, payload.TargetSnapshotID, digest, now) if err != nil || !found { - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, "没有与目标快照匹配的有效发布授权", "prebackup") + return fail("没有与目标快照匹配的有效发布授权", "prebackup") } - // 生产索引映射基线:优先当前生效版本,其次任何一次成功预备份(它也记录了生产实际映射)。 - // 只认"生效版本"会在恢复把版本 supersede 掉之后误判"索引被改动"。 - knownMapping := "" - if versions, versionErr := store.LibraryVersions(ctx, payload.Scope, 50); versionErr == nil { - for _, item := range versions { - if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil { - if raw, ok := item.Evidence["index_mapping_sha256"].(string); ok && raw != "" { - knownMapping = raw - break - } - } - } - if knownMapping == "" { - for _, item := range versions { - if raw, ok := item.Evidence["index_mapping_sha256"].(string); ok && raw != "" { - knownMapping = raw - break - } - } + // 资源复用的来源证据:只认这个目标"成功同步过且登记过生效版本"的快照与它自己 + // 的预备份。读不到就按空处理——那只会让复用被拒绝,绝不会误放行覆盖。 + priorSnapshots := make([]libraryrelease.PriorSnapshot, 0, 8) + if sources, sourceErr := store.LibraryReuseSources(ctx, payload.Scope, 100); sourceErr != nil { + log.Printf("library %s prior reuse sources unavailable: %v", payload.LibraryJobID, sourceErr) + } else { + for _, source := range sources { + priorSnapshots = append(priorSnapshots, libraryrelease.PriorSnapshot{JobID: source.JobID, + SnapshotID: source.SnapshotID, Kind: source.Kind, FinishedAt: source.FinishedAt}) } } - target, backups, wireErr := buildLibraryProductionStack(ctx, config, payload.Scope, payload.TargetSnapshotID, knownMapping) + // 生产索引映射基线:权威来源是当前生效版本(精确查),其次任何一次成功记录的映射。 + // 只认"生效版本"会在恢复把版本顶替掉之后误判"索引被改动"。 + knownMapping := knownIndexMapping(ctx, store, payload.Scope) + target, backups, wireErr := buildLibraryProductionStack(ctx, config, restoreDispatchGate(config, store.Store), payload.Scope, payload.TargetSnapshotID, knownMapping) if wireErr == nil { if mapping, mapErr := target.Search().MappingSHA256(ctx); mapErr == nil { recorder.mappingDigest = mapping } } if wireErr != nil { - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, wireErr.Error(), "prebackup") + return fail(wireErr.Error(), "prebackup") } defer target.Close() + // 容量门禁必须在**任何副作用之前**(F11):预算不足就不该进维护、不该拍备份。 + // 旧实现只在存储页 GET 里算这个数,worker 从不读它,于是"预算为正但不够"照样写。 + if capErr := checkLibraryCapacity(ctx, config, payload.TargetSnapshotID); capErr != nil { + return fail(capErr.Error(), "prebackup") + } + // 维护目标必须在真正动目标之前确定:缺配置就拒绝写,不用"库级锁"顶替。 manager, managerErr := openLibraryMaintenance(config) if managerErr != nil { - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, - "目标维护未接线,拒绝在挡不住入口/后台写入的情况下写目标:"+managerErr.Error(), "prebackup") + return fail("目标维护未接线,拒绝在挡不住入口/后台写入的情况下写目标:"+managerErr.Error(), "prebackup") } defer manager.Close() // 拓扑必须先过关:写入者发布了端口 = 存在绕闸直连,窗口关的只是半扇门。 if topoErr := manager.VerifyTopology(ctx); topoErr != nil { - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, - "目标拓扑不满足唯一入口约束,拒绝开维护窗口:"+topoErr.Error(), "prebackup") + return fail("目标拓扑不满足唯一入口约束,拒绝开维护窗口:"+topoErr.Error(), "prebackup") } targetIdentity := fmt.Sprintf("scope=%s db=%s index=%s bucket=%s", payload.Scope, pgdsn.Endpoint(config.LibraryProductionDatabaseURL), config.LibraryProductionIndex, config.LibraryProductionS3Bucket) originalState, stateErr := manager.OriginalState(ctx) if stateErr != nil { - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, - "读不到目标写入者的原运行状态,不能开维护窗口:"+stateErr.Error(), "prebackup") + return fail("读不到目标写入者的原运行状态,不能开维护窗口:"+stateErr.Error(), "prebackup") } identity := manager.Target() // 实例级占用:internal/external 动的是同一批容器,必须按实例互斥。 @@ -202,8 +315,7 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a Note: "实例级维护:关闭目标入口并停止全部写入者,验证或回滚完成才开放", }, now) if instanceErr != nil { - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, - "目标实例正在维护中(跨对内/对外互斥):"+instanceErr.Error(), "prebackup") + return fail("目标实例正在维护中(跨对内/对外互斥):"+instanceErr.Error(), "prebackup") } _ = instanceLock maintenance, acquireErr := store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{ @@ -220,7 +332,7 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a if acquireErr != nil { _ = store.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.LibraryJobID, "needs_restore", "scope 占用申请失败,实例状态未确认:"+acquireErr.Error(), now) - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, "目标正在维护中:"+acquireErr.Error(), "prebackup") + return fail("目标正在维护中:"+acquireErr.Error(), "prebackup") } _ = maintenance @@ -237,7 +349,7 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a _ = releaseWindowLocks(ctx, store, identity.Instance, payload.Scope, payload.LibraryJobID, "未进入维护窗口(协调器不可用),目标未被停用", time.Now().UTC()) } - return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, "维护协调器不可用:"+openErr.Error(), "prebackup") + return fail("维护协调器不可用:"+openErr.Error(), "prebackup") } defer control.Close() defer coordinator.Close() @@ -249,7 +361,9 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a contentState = contentHalfWritten } pending := successBoundary{} - tracked := &contentTrackedTarget{inner: target, onApply: func() { contentState = contentHalfWritten }} + tracked := &contentTrackedTarget{inner: target, jobID: payload.LibraryJobID, + onApply: func() { contentState = contentHalfWritten }, + revalidateGrant: revalidateLibraryGrant(store.Store)} allowRestore := func(error) bool { return contentState == contentUntouched || contentState == contentSucceeded || contentState == contentRolledBack } @@ -268,12 +382,22 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a } contentState = contentSucceeded mappingDigest, _ := target.Search().MappingSHA256(ctx) + // 收尾续作只补登记,不允许把首次锚点洗掉:字节数与写集合摘要从已持久化的 + // 预备份证据合并进来(F09)。缺失即拒绝,不写一个"看起来完整"的空证据。 + evidence, evidenceErr := finalizeEvidence(ctx, store.Store, payload.Scope, payload.LibraryJobID, + previous.SnapshotID, payload.TargetSnapshotID, "finalize_only", mappingDigest) + if evidenceErr != nil { + message := "收尾续作缺少首次锚点,拒绝登记生效版本:" + evidenceErr.Error() + recorder.Stage(ctx, "finalize", "failed", message) + _ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "finalize", message, + "预备份 "+previous.SnapshotID+" 保留;补齐首次锚点证据后再续作", previous.SnapshotID, payload.TargetSnapshotID, time.Now().UTC()) + return errors.New(message) + } if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ - ID: governance.LibraryVersionID(governance.LibraryVersionProductionEffective, payload.Scope, payload.TargetSnapshotID), + ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionEffective, payload.Scope, payload.TargetSnapshotID, recorder.operationID), Scope: payload.Scope, Kind: governance.LibraryVersionProductionEffective, SnapshotID: payload.TargetSnapshotID, SourceJobID: payload.LibraryJobID, CreatedBy: "worker", - Evidence: map[string]any{"backup_snapshot": previous.SnapshotID, "action": "finalize_only", - "index_mapping_sha256": mappingDigest}, + Evidence: evidence, CreatedAt: time.Now().UTC(), }); err != nil { message := "收尾续作仍无法登记生效版本:" + err.Error() @@ -291,12 +415,35 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a var backupSource libraryrelease.BackupStore = backups if resumed { - backupSource = fixedBackupStore{ref: libraryrelease.BackupRef{ID: "backup-" + previous.SnapshotID, - SnapshotID: previous.SnapshotID}} + // 接管必须带着原来那份写集合:没有它,恢复只能按目标现状推断残渣, + // 而那时目标已经被写过(真实缺陷:历史孤儿资源被当成残渣删掉)。 + set, ledgerErr := loadWriteSetForJob(ctx, store, config.LibraryArchiveRoot, payload.Scope, + payload.LibraryJobID, previous.SnapshotID) + if ledgerErr != nil { + // 读不到就一笔都不许写:目标可能半写,恢复口径未知。 + message := "接管时读不回写集合记录,拒绝继续写目标:" + ledgerErr.Error() + _ = store.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.LibraryJobID, "needs_restore", message, time.Now().UTC()) + _ = store.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.LibraryJobID, "needs_restore", message, time.Now().UTC()) + recorder.Stage(ctx, "prebackup", "failed", message) + return errors.New(message) + } + // 复用不重做备份,真实字节只能从首次登记的证据里取:缺了就必须停, + // 否则生效版本证据会写成 backup_bytes:0(现场就是这样丢的)。 + backupBytes, bytesErr := prebackupBytesOf(ctx, store, payload.Scope, payload.LibraryJobID, previous.SnapshotID) + if bytesErr != nil { + message := "接管时读不回预备份的真实字节数,拒绝继续写目标:" + bytesErr.Error() + _ = store.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.LibraryJobID, "needs_restore", message, time.Now().UTC()) + _ = store.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.LibraryJobID, "needs_restore", message, time.Now().UTC()) + recorder.Stage(ctx, "prebackup", "failed", message) + return errors.New(message) + } + backupSource = ledgerBackupStore{ref: libraryrelease.BackupRef{ID: "backup-" + previous.SnapshotID, + SnapshotID: previous.SnapshotID, Bytes: backupBytes}, write: set} } - request := libraryrelease.Request{Target: payload.Scope, SnapshotID: payload.TargetSnapshotID, - ParamsDigest: digest, Now: now, + request := libraryrelease.Request{JobID: payload.LibraryJobID, Target: payload.Scope, + SnapshotID: payload.TargetSnapshotID, ParamsDigest: digest, Now: now, + PriorSnapshots: priorSnapshots, Grant: libraryrelease.Grant{Target: payload.Scope, SnapshotID: grant.SnapshotID, ParamsDigest: grant.ParamsDigest, ExpiresAt: grant.ExpiresAt, AuthorizedBy: grant.AuthorizedBy}} _ = store.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.LibraryJobID, "applying", "正在写目标", now) @@ -313,13 +460,11 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a // 登记失败必须让作业失败(可续作),否则"版本记录"和"作业状态"会分叉。 recorder.Stage(ctx, "finalize", "running", "登记生产生效版本") versionErr := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ - ID: governance.LibraryVersionID(governance.LibraryVersionProductionEffective, payload.Scope, payload.TargetSnapshotID), + ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionEffective, payload.Scope, payload.TargetSnapshotID, recorder.operationID), Scope: payload.Scope, Kind: governance.LibraryVersionProductionEffective, SnapshotID: payload.TargetSnapshotID, SourceJobID: payload.LibraryJobID, CreatedBy: grant.AuthorizedBy, - Evidence: map[string]any{"backup_snapshot": outcome.Backup.SnapshotID, - "backup_bytes": outcome.Backup.Bytes, "action": string(kind), - "index_mapping_sha256": mappingDigest}, + Evidence: effectiveEvidence(outcome.Backup, string(kind), mappingDigest), CreatedAt: finishedAt, }) if versionErr != nil { @@ -383,6 +528,21 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a } window, windowErr := coordinator.RunWindow(ctx, payload.LibraryJobID, prepare, windowWork, allowRestore) + // 终态重放(F05):journal 里已经 succeeded,本次没有再执行 work。内容/服务子协议 + // 已经完成,缺的只可能是"业务收尾"(版本登记、锁释放、终态)。这时必须从**持久事实** + // 重建收尾凭据,而不是靠进程内 pending——那个指针早就随崩溃没了。 + if windowErr == nil && window.State == "succeeded" && contentState != contentSucceeded { + rebuilt, rebuildErr := rebuildSuccessBoundary(ctx, store, recorder, payload, previous, kind, grant) + if rebuildErr != nil { + note := "窗口已成功但收尾凭据无法从持久事实重建,目标保持维护:" + rebuildErr.Error() + _ = store.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.LibraryJobID, "needs_restore", note, time.Now().UTC()) + _ = store.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.LibraryJobID, "needs_restore", note, time.Now().UTC()) + return errors.New(note) + } + pending = rebuilt + contentState = contentSucceeded + } + // 收尾:只有"内容已验证/已回滚"且服务与入口都恢复,才释放维护占用。 now2 := time.Now().UTC() switch { @@ -431,7 +591,12 @@ func runLibraryRelease(ctx context.Context, store *postgresstore.Store, config a // resumeInterruptedLibraryJobs 在 worker 启动时接管中断的写作业: // 已经持久化预备份的重新排队(同一个业务作业 id,阶段与备份都接着用), // 连预备份都没完成的才判失败——那种情况没有可回滚的基线,不能盲写。 -func resumeInterruptedLibraryJobs(ctx context.Context, store *postgresstore.Store, config appconfig.Config) (int, int, error) { +func resumeInterruptedLibraryJobs(ctx context.Context, store libraryResumeStore, config appconfig.Config) (int, int, error) { + if recoveries, ok := store.(interface{ ResumeExpiredLibraryRecoveryQueues(context.Context) error }); ok { + if err := recoveries.ResumeExpiredLibraryRecoveryQueues(ctx); err != nil { + return 0, 0, err + } + } interrupted, err := store.InterruptedLibraryJobs(ctx) if err != nil { return 0, 0, err @@ -463,6 +628,10 @@ func resumeInterruptedLibraryJobs(ctx context.Context, store *postgresstore.Stor // 基线作业被杀时窗口可能还停着目标:用同一个作业 id 接管那个窗口, // 继续捕获/校验,而不是留下一个 held 目标等人工处理。 queueType = libraryBaselineJobType + case governance.LibraryJobVerify: + // 恢复验证同样持有维护窗口:接管时必须用同一份作业 id 收掉那个窗口, + // 否则目标会一直停在维护里而作业显示失败。 + queueType = libraryVerifyJobType } payload, _ := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": job.Scope, "target_snapshot_id": job.TargetSnapshotID}) @@ -485,6 +654,7 @@ func resumeInterruptedLibraryJobs(ctx context.Context, store *postgresstore.Stor log.Printf("library job %s resume attach existing queue failed: %v", job.ID, attachErr) } else { resumed++ + logTakeoverClaim(job, queueID, takeoverPathExistingQueue, now) } continue } @@ -500,20 +670,26 @@ func resumeInterruptedLibraryJobs(ctx context.Context, store *postgresstore.Stor continue } resumed++ - log.Printf("library job %s resumed after worker restart (backup %s)", job.ID, job.SnapshotID) + // 只有 claim + attach 都成功才写这一行:它等于"这个作业归本 worker 继续跑", + // 外部用它判接管来源(汇总计数证明不了是哪个作业)。 + logTakeoverClaim(job, queueJob.ID, takeoverPathEnqueue, now) } return resumed, failed, nil } -// fixedBackupStore 在崩溃接管时返回已经存在的预备份,不再新建。 -type fixedBackupStore struct{ ref libraryrelease.BackupRef } - -func (s fixedBackupStore) Prepare(context.Context, string, libraryrelease.CurrentState) (libraryrelease.BackupRef, error) { - return s.ref, nil -} - // BackupPrepared 把预备份写进作业**并**登记成版本。任何一步失败都返回错误: // 上游据此在写目标前中止,保证"没有可恢复基线就不写"。 +// +// 接管时 BackupRef.Reused=true:复用上一次崩溃前登记的那一份。这时必须把 +// "复用"写进证据 —— 否则外部只能看到一条 created_at 很新的版本行, +// 分不清是复用还是重做了备份(重做备份正好把半写状态当成了基线)。 +// +// ⚠️ 证据必须**合并**进已有那一行,不能每次造一份新的:RecordLibraryVersion 是 +// `evidence = EXCLUDED.evidence`(整份覆盖)。2026-10-30 的演练里,接管复用时 +// 新造的证据只有 backup_* / job / index_mapping_sha256,把首次规划写入的 +// writeset_digest/writeset_rows… 整段抹掉,第二次中断再接管就再也读不回写集合 +// (verify_effective 因此从有摘要变成空)。合并只对**同一作业 + 同一份预备份** +// 成立:身份不符一律失败,绝不把别的作业的证据带进来。 func (r libraryStageRecorder) BackupPrepared(ctx context.Context, backup libraryrelease.BackupRef) error { now := time.Now().UTC() if r.onBackup != nil { @@ -521,16 +697,35 @@ func (r libraryStageRecorder) BackupPrepared(ctx context.Context, backup library return fmt.Errorf("落盘预备份身份/内容风险失败: %w", err) } } + // 先读既有证据:复用声称的那一份必须真的登记过,新造的也不许盖掉别人的行。 + existing, found, err := r.store.LibraryVersionByRef(ctx, r.scope, + governance.LibraryVersionProductionPrebackup, r.jobID, backup.SnapshotID) + if err != nil { + return fmt.Errorf("读不到现有预备份证据: %w", err) + } + if !found && backup.Reused { + return fmt.Errorf("预备份 %s 声称复用,但没有作业 %s 的版本证据:拒绝把复用登记成新备份", + backup.SnapshotID, r.jobID) + } + if found && !backup.Reused { + // 同一份预备份已经登记过,本轮却声称是新备份:那不是"重做备份", + // 而是用一份新证据替换已持久化的写集合锚点。 + return fmt.Errorf("预备份 %s 已登记为作业 %s 的版本证据,本轮却不是复用:拒绝覆盖已持久化证据", + backup.SnapshotID, r.jobID) + } + evidence, err := prebackupEvidence(existing.Evidence, backup, r.jobID, r.mappingDigest) + if err != nil { + return fmt.Errorf("合并预备份证据失败: %w", err) + } if err := r.store.AdvanceLibraryJob(ctx, r.jobID, governance.LibraryJobRunning, "", "", "", backup.SnapshotID, "", now); err != nil { return fmt.Errorf("持久化预备份引用失败: %w", err) } if err := r.store.RecordLibraryVersion(ctx, governance.LibraryVersion{ - ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, r.scope, backup.SnapshotID), + ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionPrebackup, r.scope, backup.SnapshotID, r.operationID), Scope: r.scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: backup.SnapshotID, SourceJobID: r.jobID, CreatedBy: "worker", - Evidence: map[string]any{"backup_snapshot": backup.SnapshotID, "backup_bytes": backup.Bytes, - "job": r.jobID, "index_mapping_sha256": r.mappingDigest}, + Evidence: evidence, CreatedAt: now, }); err != nil { return fmt.Errorf("登记预备份版本失败: %w", err) @@ -538,13 +733,43 @@ func (r libraryStageRecorder) BackupPrepared(ctx context.Context, backup library return nil } -func failLibraryJob(ctx context.Context, store *postgresstore.Store, recorder libraryStageRecorder, jobID, message, stage string) error { +func failLibraryJob(ctx context.Context, store libraryFailStore, recorder libraryStageRecorder, jobID, message, stage string) error { recorder.Stage(ctx, stage, "failed", message) _ = store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobFailed, stage, message, "未对生产执行任何写入,无需恢复", "", "", time.Now().UTC()) return errors.New(message) } +// failLibraryJobOrTakeover 按"这个作业有没有持久化预备份"选择失败出口。 +// +// 有预备份就说明上一次尝试可能已经写过目标:这时任何早退(授权过期、装配失败、 +// 维护被别人占用……)都必须保留 needs_restore 并点名基线,不能写"无需恢复"—— +// 那会让页面把半写目标当成完好,也让操作者手里没有可回滚的那一份。 +func failLibraryJobOrTakeover(ctx context.Context, store libraryFailStore, recorder libraryStageRecorder, + scope, jobID, backupSnapshotID string, resumed bool, message, stage string) error { + if resumed { + return failLibraryTakeover(ctx, store, recorder, scope, jobID, backupSnapshotID, message) + } + return failLibraryJob(ctx, store, recorder, jobID, message, stage) +} + +// failLibraryTakeover 是"拒绝接管"的失败出口:目标可能已被上一次尝试写过, +// 不能像 failLibraryJob 那样写"无需恢复"。维护占用保持现状(held/acquired 就是 +// 安全状态),scope 行显式标 needs_restore,作业终态失败并指明可回滚的预备份。 +// +// 为什么不在拒绝时释放维护:本作业没有自己的写入证据,目标是否半写未知; +// 释放就等于对页面和下一次作业谎称"目标已恢复原状"。实例行也不动——它的释放 +// 属于"按预备份恢复并核验"那条路径,这里连实例身份都还没查到。 +func failLibraryTakeover(ctx context.Context, store libraryFailStore, recorder libraryStageRecorder, + scope, jobID, backupSnapshotID, message string) error { + recorder.Stage(ctx, "prebackup", "failed", message) + recovery := "本作业未继续写目标;上一次尝试可能已半写,须按预备份 " + backupSnapshotID + " 恢复并核验后再处理" + _ = store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobFailed, "prebackup", message, recovery, + backupSnapshotID, "", time.Now().UTC()) + _ = store.UpdateLibraryMaintenanceState(ctx, scope, jobID, "needs_restore", message, time.Now().UTC()) + return errors.New(message) +} + func kindLabel(kind governance.LibraryJobKind) string { if kind == governance.LibraryJobRestore { return "恢复" diff --git a/cmd/worker/library_handoff.go b/cmd/worker/library_handoff.go new file mode 100644 index 0000000..7f13b73 --- /dev/null +++ b/cmd/worker/library_handoff.go @@ -0,0 +1,357 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "log" + "time" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "knowledge-governance/internal/libraryhandoff" + "knowledge-governance/internal/librarysnapshot" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// libraryHandoffJobType 与 API 侧常量同值:API 用它把"发布/恢复"拆成 +// "先搬运、后发布"。搬运作业由 capture 角色执行(只有本机有源归档与 SSH 凭据), +// release-executor 永不注册它——云端没有源归档,也没有回本机的通道。 +const libraryHandoffJobType = "library.snapshot.handoff" + +// 回传分页:每次 100 条、最多 20 页(单轮最多核对 2000 份引用), +// 游标按 (created_at, snapshot_id) 推进,下一轮从最新处重新开始。 +const ( + pullPageSize = 100 + // pullMaxPages 只是**单轮**工作量预算:一轮最多翻 20 页,避免一次扫描拖住 worker。 + // 游标跨轮保留,所以预算不会变成"永远只取前 2000 条"。 + pullMaxPages = 20 +) + +// pullCursor 是回传枚举的位置。跨轮保留:每轮结束把游标留在这一轮读到的最后一项, +// 下一轮从那里继续;读到不足一页说明这一圈走完了,游标回到起点(从最新处重新核对)。 +type pullCursor struct { + created time.Time + id string +} + +func (c pullCursor) advance(last postgresstore.SnapshotCandidate, count, pageSize int) pullCursor { + if count < pageSize { + return pullCursor{} + } + return pullCursor{created: last.CreatedAt, id: last.SnapshotID} +} + +// libraryHandoffStage 是搬运在作业阶段表里的名字(页面能看出卡在搬运还是发布)。 +const libraryHandoffStage = "handoff" + +type libraryHandoffPayload struct { + LibraryJobID string `json:"library_job_id"` + Scope string `json:"scope"` + TargetSnapshotID string `json:"target_snapshot_id"` + NextType string `json:"next_type"` +} + +// registerLibraryHandoffHandlers 注册"先把快照送到执行器"的作业。 +// +// 顺序是这条链的安全边界:push 成功(云端逐 blob 校验通过、清单摘要自证、身份一致) +// 之后才投递真正的发布作业。push 失败时发布作业根本不存在,executor 不会开维护窗口、 +// 不会写任何知识数据。 +func registerLibraryHandoffHandlers(handlers map[string]jobs.Handler, store *postgresstore.Store, + config appconfig.Config, handoff *libraryhandoff.Handoff) { + handlers[libraryHandoffJobType] = func(ctx context.Context, job jobs.Job) error { + var payload libraryHandoffPayload + if err := json.Unmarshal(job.Payload, &payload); err != nil || + payload.LibraryJobID == "" || payload.TargetSnapshotID == "" || + (payload.Scope != "internal" && payload.Scope != "external") { + return fmt.Errorf("invalid library handoff payload") + } + return runLibraryHandoffForQueue(ctx, store, config, handoff, payload, job.ID) + } +} + +// runLibraryHandoffForQueue 是 handoff 的唯一入口。queueJobID 是这次执行的**所有权凭据**: +// 业务作业的 queue_job_id 必须还是它,才允许写阶段/终态;交接给 release 之后, +// 迟到的旧 handoff 一次写入都不该落下去。 +func runLibraryHandoffForQueue(ctx context.Context, store *postgresstore.Store, config appconfig.Config, + handoff *libraryhandoff.Handoff, payload libraryHandoffPayload, queueJobID string) error { + now := time.Now().UTC() + // 作业身份必须与载荷逐项一致:载荷来自队列,业务作业才是治理库的事实。 + record, err := store.LibraryJob(ctx, payload.LibraryJobID) + if err != nil { + return fmt.Errorf("读不到业务作业 %s:%w", payload.LibraryJobID, err) + } + if record.Scope != payload.Scope || record.TargetSnapshotID != payload.TargetSnapshotID { + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, "队列载荷与业务作业不一致(scope/快照),拒绝搬运") + } + switch payload.NextType { + case librarySyncJobType: + if record.Kind != governance.LibraryJobSync { + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, "作业类型是恢复,但搬运要求投递同步,拒绝") + } + case libraryRestoreJobType: + if record.Kind != governance.LibraryJobRestore { + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, "作业类型是同步,但搬运要求投递恢复,拒绝") + } + default: + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, "未知的后续作业类型,拒绝搬运") + } + if record.State == governance.LibraryJobFailed || record.State == governance.LibraryJobCancelled || + record.State == governance.LibraryJobSucceeded { + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, "业务作业已终态,不再搬运") + } + + // 期望身份来自**独立注入的绑定** + 版本台账的登记类型,绝不来自快照自报: + // 封存快照的清单写的是源 tenant/KB,目标知识库本来就不是它(云测试验收用专用 KB)。 + want, identityErr := expectedSnapshotIdentity(ctx, store, config, payload.Scope, payload.TargetSnapshotID) + if identityErr != nil { + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, "无法确定快照的可信归属,拒绝搬运:"+identityErr.Error()) + } + + if record.QueueJobID == governance.QueueJobIDFor(payload.LibraryJobID) && + queueJobID == governance.LibraryHandoffQueueJobID(payload.LibraryJobID) { + log.Printf("library handoff replay job=%s: 已交接给 release,幂等跳过", payload.LibraryJobID) + return nil + } + // 阶段与所有权在同一事务里建立:不存在"先读 owner 再写 stage"的竞态窗口。 + // 阶段写一律只发生在 Begin/Complete/Fail 三个持有 job 行锁的事务方法里: + // 这里若再补一次无条件 UpdateLibraryStage,既重复事务里的写,又会在 + // Begin 返回与这次写之间被交接抢走——那正是上一轮退回的原因。 + started, beginErr := store.BeginLibraryHandoff(ctx, payload.LibraryJobID, queueJobID, + "正在把快照送到发布执行器并校验", now) + if beginErr != nil { + return fmt.Errorf("开始搬运阶段失败:%w", beginErr) + } + if !started { + return fmt.Errorf("业务作业 %s 当前不由本次 handoff 持有(%q),未做任何修改", + payload.LibraryJobID, record.QueueJobID) + } + evidence, err := handoff.Push(ctx, want) + if err != nil { + message := "快照未送到发布执行器:" + err.Error() + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, message) + } + + // 只有搬运校验通过后,发布作业才存在。 + payloadRaw, marshalErr := json.Marshal(map[string]string{ + "library_job_id": payload.LibraryJobID, "scope": payload.Scope, "target_snapshot_id": payload.TargetSnapshotID, + }) + if marshalErr != nil { + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, "无法构造发布作业载荷") + } + // 投递、交接、阶段成功三件事在同一个事务里完成:不会出现"作业已交给 release + // 但阶段还停在 running",也不会出现"阶段成功却没交接"。 + detail := fmt.Sprintf("快照已在校验后送达执行器(parts=%d bytes=%d reused=%t)", + evidence.Parts, evidence.Bytes, evidence.Reused) + handed, handErr := store.CompleteLibraryHandoff(ctx, payload.LibraryJobID, queueJobID, jobs.EnqueueRequest{ + ID: governance.QueueJobIDFor(payload.LibraryJobID), Type: payload.NextType, Payload: payloadRaw, + AvailableAt: time.Now().UTC(), MaxAttempts: 1, + IdempotencyKey: payload.NextType + ".queue:" + payload.LibraryJobID, + }, detail, time.Now().UTC()) + if handErr != nil { + // 事务已回滚:所有权仍在本 handoff 手里,失败文案可信。 + return failLibraryHandoffOwned(ctx, store, payload, queueJobID, + "发布作业投递或关联失败(同一事务,未产生半完成状态):"+handErr.Error()) + } + if !handed { + log.Printf("library handoff skip-handover job=%s: 所有权在搬运期间已转移,未做任何修改", payload.LibraryJobID) + return nil + } + log.Printf("library handoff completed job=%s scope=%s snapshot=%s parts=%d reused=%t", + payload.LibraryJobID, payload.Scope, payload.TargetSnapshotID, evidence.Parts, evidence.Reused) + return nil +} + +// handoffFailureBarrier 只给测试用:在失败出口写库之前被调用,让测试能把所有权 +// 确定地切给 release,从而复现"失败出口到来时所有权已交接"的竞态。生产恒为 nil。 +var handoffFailureBarrier func() + +func failLibraryHandoffOwned(ctx context.Context, store *postgresstore.Store, payload libraryHandoffPayload, + queueJobID, message string) error { + if handoffFailureBarrier != nil { + handoffFailureBarrier() + } + // 阶段失败与作业失败同一个事务:要么都写,要么都不写。 + changed, err := store.FailLibraryHandoff(ctx, payload.LibraryJobID, queueJobID, message, time.Now().UTC()) + if err != nil { + return fmt.Errorf("%s(写失败状态出错:%v)", message, err) + } + if !changed { + log.Printf("library handoff fail-skipped job=%s: 所有权已交接或作业已终态,未修改任何状态", payload.LibraryJobID) + } + return fmt.Errorf("%s", message) +} + +// runLibraryArchivePullLoop 把云端产生的快照(预备份等)取回本机归档。 +// +// 为什么要回传而不是"页面直接读云端":API 的所有归档消费点(列表/详情/差异/存储/ +// 容量/恢复寻址)都读本机 LIBRARY_ARCHIVE_ROOT,回传后它们读到的就是真实字节, +// 不需要给每条读路径加远端分支,也不会把两端路径当成全局身份(身份始终是 snapshot ID)。 +// +// 失败只记日志:本机没有这份版本时页面按"无此版本/不可读"展示,不会被误报成可恢复。 +func runLibraryArchivePullLoop(ctx context.Context, store *postgresstore.Store, handoff *libraryhandoff.Handoff, + archiveRoot string, interval time.Duration, report func(error)) { + if interval <= 0 { + interval = 5 * time.Minute + } + cursors := map[string]pullCursor{} + pull := func() { + for _, scope := range []string{"internal", "external"} { + next, fetched, err := pullRound(ctx, store, func(id string) bool { + archive, openErr := librarysnapshot.Open(archiveRoot, 256*1024*1024) + if openErr != nil { + return false + } + defer archive.Close() + _, loadErr := archive.Load(id) + return loadErr == nil + }, func(fetchCtx context.Context, id string) (libraryhandoff.Evidence, error) { + return handoff.Fetch(fetchCtx, id) + }, scope, cursors[scope]) + if err != nil { + report(err) + } + cursors[scope] = next + if fetched > 0 { + log.Printf("library archive pull round scope=%s fetched=%d", scope, fetched) + } + } + } + pull() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + pull() + } + } +} + +// expectedSnapshotIdentity 决定"这份快照的清单身份应该等于谁"。 +// +// 两类快照的身份来源不同,混用会把合法的跨 KB 发布判成非法(或反过来放行错数据): +// - 封存版本(test_sealed):清单里是**源**的 tenant/KB → 用部署注入的源绑定核对; +// - 目标状态版本(预备份/生效/恢复):清单里是**目标**的 tenant/KB → 用目标绑定核对。 +// +// 没有登记过版本、或两类同时出现,一律拒绝:来源不明的快照不允许进入发布链路。 +func expectedSnapshotIdentity(ctx context.Context, store *postgresstore.Store, config appconfig.Config, + scope, snapshotID string) (libraryhandoff.Identity, error) { + rows, err := store.LibraryVersionsBySnapshot(ctx, scope, snapshotID) + if err != nil { + return libraryhandoff.Identity{}, err + } + if len(rows) == 0 { + return libraryhandoff.Identity{}, fmt.Errorf("快照 %s 在该 scope 下没有登记过任何版本", snapshotID) + } + // 原产地只由**捕获**决定,且必须读证据: + // - test_sealed:源端封存 → 源绑定; + // - production_prebackup:目标端预备份 → 目标绑定; + // - production_effective 且证据 action=target_baseline_init / origin=target_baseline: + // 目标权威基线(library_baseline 的真实整库捕获)→ 目标绑定; + // - 普通 production_effective(发布成功后的引用)与 recovery_verified 不是捕获,不决定原产地。 + sourceOrigin, targetOrigin := false, false + for _, row := range rows { + switch row.Kind { + case governance.LibraryVersionTestSealed: + sourceOrigin = true + case governance.LibraryVersionProductionPrebackup: + targetOrigin = true + case governance.LibraryVersionProductionEffective: + if isTargetBaselineEvidence(row.Evidence) { + targetOrigin = true + } + } + } + if sourceOrigin && targetOrigin { + return libraryhandoff.Identity{}, fmt.Errorf("快照 %s 既由源封存、又由目标捕获(预备份/基线):原产地冲突", snapshotID) + } + if !sourceOrigin && !targetOrigin { + return libraryhandoff.Identity{}, fmt.Errorf("快照 %s 没有捕获证据(封存/预备份/目标基线),来源不明", snapshotID) + } + sealedState := sourceOrigin + tenant, knowledgeBase := config.LibrarySourceTenantID, config.LibrarySourceInternalKB + label := "源绑定" + if !sealedState { + tenant, knowledgeBase = config.LibraryProductionTenantID, config.LibraryProductionInternalKB + label = "目标绑定" + } + if scope == "external" { + if sealedState { + knowledgeBase = config.LibrarySourceExternalKB + } else { + knowledgeBase = config.LibraryProductionExternalKB + } + } + if tenant == 0 || knowledgeBase == "" { + return libraryhandoff.Identity{}, fmt.Errorf("未配置%s(tenant/知识库),无法核对快照身份", label) + } + return libraryhandoff.Identity{SnapshotID: snapshotID, Scope: scope, TenantID: tenant, KnowledgeBaseID: knowledgeBase}, nil +} + +// snapshotLister 是回传需要的存储面(便于用真实分页语义做单测)。 +type snapshotLister interface { + LibrarySnapshotCandidates(ctx context.Context, scope string, afterCreated time.Time, afterID string, + limit int) ([]postgresstore.SnapshotCandidate, error) +} + +// pullRound 是**单轮回传**:最多 pullMaxPages 页,返回下一轮的游标与取回条数。 +// +// 两个细节都是真实缺陷的教训: +// - 空页必须把游标**重置**(否则引用数正好是 pageSize 整数倍时,游标永远停在最老处, +// 下一轮还是空,之后新增的快照永远取不到); +// - 游标跨轮保留(单轮预算不等于总量上限)。 +func pullRound(ctx context.Context, source snapshotLister, isLocal func(string) bool, + fetch func(context.Context, string) (libraryhandoff.Evidence, error), scope string, + cursor pullCursor) (pullCursor, int, error) { + fetched := 0 + for page := 0; page < pullMaxPages; page++ { + items, err := source.LibrarySnapshotCandidates(ctx, scope, cursor.created, cursor.id, pullPageSize) + if err != nil { + return cursor, fetched, fmt.Errorf("读不到 %s 的快照引用:%w", scope, err) + } + if len(items) == 0 { + // 这一圈走完了:回到起点,下一轮从最新处重新核对(新增引用才会被看到)。 + return pullCursor{}, fetched, nil + } + for _, item := range items { + if err := ctx.Err(); err != nil { + return cursor, fetched, err + } + if isLocal(item.SnapshotID) { + continue + } + evidence, fetchErr := fetch(ctx, item.SnapshotID) + if fetchErr != nil { + // 单份失败不阻断整轮:下一轮会再试(游标仍推进,靠的是跨轮再核对)。 + continue + } + fetched++ + log.Printf("library archive pull snapshot=%s scope=%s parts=%d bytes=%d reused=%t", + evidence.Snapshot, evidence.Scope, evidence.Parts, evidence.Bytes, evidence.Reused) + } + cursor = cursor.advance(items[len(items)-1], len(items), pullPageSize) + if cursor == (pullCursor{}) { + return cursor, fetched, nil + } + } + return cursor, fetched, nil +} + +// isTargetBaselineEvidence 判定一条 production_effective 是不是"目标权威基线"的真实捕获。 +// 只认基线登记时写下的字段;普通发布成功的 effective 事件没有这些字段,不算原产地。 +func isTargetBaselineEvidence(evidence map[string]any) bool { + if len(evidence) == 0 { + return false + } + if action, _ := evidence["action"].(string); action == "target_baseline_init" { + return true + } + if origin, _ := evidence["origin"].(string); origin == "target_baseline" { + return true + } + return false +} diff --git a/cmd/worker/library_handoff_chain_test.go b/cmd/worker/library_handoff_chain_test.go new file mode 100644 index 0000000..0c4b74c --- /dev/null +++ b/cmd/worker/library_handoff_chain_test.go @@ -0,0 +1,340 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "sort" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "knowledge-governance/internal/libraryhandoff" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// bindHandoffQueue 复刻 API 的真实前驱:先入 handoff 队列作业,再把它关联到业务作业。 +// fixture 必须走这一步,否则测的是"没有前驱的理想顺序",会漏掉所有权检查的必现阻断。 +func bindHandoffQueue(t *testing.T, pool interface { + Exec(context.Context, string, ...any) (interface{ RowsAffected() int64 }, error) +}, store *postgresstore.Store, job governance.LibraryJob, scope, snapshot string) string { + t.Helper() + _ = pool + ctx := context.Background() + handoffQueueID := governance.LibraryHandoffQueueJobID(job.ID) + payload, err := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": scope, + "target_snapshot_id": snapshot, "next_type": librarySyncJobType}) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if _, err := store.Enqueue(ctx, jobs.EnqueueRequest{ID: handoffQueueID, Type: libraryHandoffJobType, + Payload: payload, AvailableAt: now, MaxAttempts: 1, IdempotencyKey: "handoff:" + job.ID}, now); err != nil { + t.Fatalf("enqueue handoff: %v", err) + } + if err := store.AttachLibraryQueueJob(ctx, job.ID, handoffQueueID, now); err != nil { + t.Fatalf("attach handoff: %v", err) + } + return handoffQueueID +} + +// R4a:从 API 真实前驱(handoff 队列作业已关联)开始,交接必须成功、且只能从真实前驱接管。 +func TestHandoffFromAPIBindingHandsOverToRelease(t *testing.T) { + pool, store := fixturePool(t) + ctx := context.Background() + resetFixtureJobs(t, pool) + fixture := newHandoffFixture(t) + config := appconfigFixture(fixture) + snapshot := fixture.seal(t) + recordSealedVersion(t, store, snapshot, "internal") + job := createFixtureJob(t, store, "internal", snapshot) + handoffQueueID := bindHandoffQueue(t, nil, store, job, "internal", snapshot) + + incoming := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal", + TargetSnapshotID: snapshot, NextType: librarySyncJobType} + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, incoming, handoffQueueID); err != nil { + t.Fatalf("正常交接被拒:%v", err) + } + after, err := store.LibraryJob(ctx, job.ID) + if err != nil { + t.Fatal(err) + } + releaseID := governance.QueueJobIDFor(job.ID) + if after.QueueJobID != releaseID { + t.Fatalf("交接后 queue_job_id = %q,期望 %q", after.QueueJobID, releaseID) + } + if after.State == governance.LibraryJobFailed { + t.Fatalf("交接成功却标失败:%s", after.Error) + } + var stageState, stageDetail string + if err := pool.QueryRow(ctx, `SELECT state, detail FROM library_job_stages +WHERE job_id=$1 AND stage='handoff'`, job.ID).Scan(&stageState, &stageDetail); err != nil { + t.Fatalf("交接后没有 handoff 阶段行(UI 看不到传输结果):%v", err) + } + if stageState != "succeeded" || stageDetail == "" { + t.Fatalf("handoff 阶段 = %q / %q,期望 succeeded 且有明细", stageState, stageDetail) + } + + var releaseType string + if err := pool.QueryRow(ctx, `SELECT type FROM jobs WHERE id=$1`, releaseID).Scan(&releaseType); err != nil { + t.Fatalf("release 队列作业不存在:%v", err) + } + if releaseType != librarySyncJobType { + t.Fatalf("release 队列类型 = %q", releaseType) + } + + // 错误前驱:拿别的所有权来接管必须拒绝。 + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, incoming, + "not-the-owner-"+snapshot[:8]); err == nil { + t.Fatal("错误前驱的所有权被接受了") + } + if after, err = store.LibraryJob(ctx, job.ID); err != nil || after.QueueJobID != releaseID { + t.Fatalf("错误前驱改动了所有权:%v / %q", err, after.QueueJobID) + } + + // 交接提交后重放:幂等(不重复投递、不改写),且不再写阶段。 + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, incoming, handoffQueueID); err != nil { + t.Logf("交接后的重放返回:%v(已交接时这必须是一个明确拒绝或幂等成功)", err) + } + for _, id := range []string{handoffQueueID, releaseID} { + var exists bool + if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM jobs WHERE id=$1)`, id).Scan(&exists); err != nil { + t.Fatal(err) + } + if !exists { + t.Fatalf("队列作业 %s 不存在", id) + } + } +} + +// R4b:迟到的 handoff 失败(真实 Push 出口)在所有权已交接后必须零修改。 +// 用 handoffFailureBarrier 在失败出口写库前把所有权切给 release,确定地复现竞态。 +func TestLateHandoffFailureLeavesHandedOverJobUntouched(t *testing.T) { + pool, store := fixturePool(t) + ctx := context.Background() + fixture := newHandoffFixture(t) + config := appconfigFixture(fixture) + for _, state := range []governance.LibraryJobState{governance.LibraryJobRunning, governance.LibraryJobSucceeded} { + t.Run(string(state), func(t *testing.T) { + resetFixtureJobs(t, pool) + snapshot := fixture.unknownSnapshotID() + job := createFixtureJob(t, store, "internal", snapshot) + recordSealedVersion(t, store, snapshot, "internal") + handoffQueueID := bindHandoffQueue(t, nil, store, job, "internal", snapshot) + releaseID := governance.QueueJobIDFor(job.ID) + if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages (job_id, stage, state, detail, updated_at) +VALUES ($1,'handoff','running','release 正在执行', now()) +ON CONFLICT (job_id, stage) DO UPDATE SET state='running', detail='release 正在执行'`, job.ID); err != nil { + t.Fatal(err) + } + // 失败出口到来之前,所有权已经交给 release(作业也在跑/已成功)。 + handoffFailureBarrier = func() { + handoffFailureBarrier = nil + if _, err := pool.Exec(ctx, `UPDATE library_jobs SET state=$2, queue_job_id=$3 WHERE id=$1`, + job.ID, string(state), releaseID); err != nil { + t.Errorf("flip ownership: %v", err) + } + } + incoming := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal", + TargetSnapshotID: snapshot, NextType: librarySyncJobType} + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, incoming, handoffQueueID); err == nil { + t.Fatal("期望这次迟到搬运失败") + } + after, err := store.LibraryJob(ctx, job.ID) + if err != nil { + t.Fatal(err) + } + if after.State != state { + t.Fatalf("迟到失败把状态 %s 改成 %s", state, after.State) + } + if after.Error != "" || after.Recovery != "" { + t.Fatalf("迟到失败写了 error/recovery:%q / %q", after.Error, after.Recovery) + } + var stageState, detail string + if err := pool.QueryRow(ctx, `SELECT state, detail FROM library_job_stages +WHERE job_id=$1 AND stage='handoff'`, job.ID).Scan(&stageState, &detail); err != nil { + t.Fatal(err) + } + // 阶段行必须真实存在(由 BeginLibraryHandoff 在事务里创建), + // 且迟到失败不能把它写成 failed、也不能写失败文案。 + if stageState != "running" { + t.Fatalf("handoff 阶段 = %q,期望仍为 running", stageState) + } + if containsAny(detail, "未进入维护窗口", "快照未送到") { + t.Fatalf("迟到失败在交接后改写了 stage 明细:%q", detail) + } + }) + } + handoffFailureBarrier = nil +} + +// R2:回传游标跨轮保留,且空页必须重置 —— 否则引用数正好是 pageSize 整数倍时, +// 游标永远停在最老处,新增引用再也取不到。 +func TestPullRoundsCoverAllReferencesAcrossRounds(t *testing.T) { + for _, total := range []int{100, 2000, 2100} { + t.Run(fmt.Sprintf("refs=%d", total), func(t *testing.T) { + source := newFakeSnapshotSource(total) + cursor := pullCursor{} + seen := map[string]bool{} + isLocal := func(string) bool { return false } + fetch := func(_ context.Context, id string) (libraryhandoff.Evidence, error) { + seen[id] = true + return libraryhandoff.Evidence{Snapshot: id}, nil + } + // 单轮预算 20 页 = 2000 条:2100 条必须靠第二轮接力。 + for round := 0; round < 5 && len(seen) < total; round++ { + next, _, err := pullRound(context.Background(), source, isLocal, fetch, "internal", cursor) + if err != nil { + t.Fatalf("round %d: %v", round, err) + } + cursor = next + } + if len(seen) != total { + t.Fatalf("只覆盖 %d/%d 条引用", len(seen), total) + } + // 走完一圈后新增引用:下一轮必须能看到(空页重置游标的回归点)。 + source.append(5) + for round := 0; round < 3; round++ { + next, fetched, err := pullRound(context.Background(), source, isLocal, fetch, "internal", cursor) + if err != nil { + t.Fatalf("after-append round %d: %v", round, err) + } + cursor = next + if fetched > 0 { + break + } + } + if len(seen) != total+5 { + t.Fatalf("新增引用未被取到:覆盖 %d/%d", len(seen), total+5) + } + }) + } +} + +// fakeSnapshotSource 按 (created_at desc, id desc) 的游标语义分页,模拟真实 SQL。 +type fakeSnapshotSource struct { + refs []postgresstore.SnapshotCandidate +} + +func newFakeSnapshotSource(total int) *fakeSnapshotSource { + source := &fakeSnapshotSource{} + source.append(total) + return source +} + +func (f *fakeSnapshotSource) append(count int) { + // 新引用在真实世界里更新(created_at 更晚):这样它们才会落在游标起点之前。 + newest := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) + if len(f.refs) > 0 { + newest = f.refs[0].CreatedAt + } + for index := 0; index < count; index++ { + seq := len(f.refs) + f.refs = append(f.refs, postgresstore.SnapshotCandidate{ + SnapshotID: fmt.Sprintf("n%05d-%05d", seq, time.Now().UnixNano()%100000), + CreatedAt: newest.Add(time.Duration(index+1) * time.Second), + }) + } + sort.Slice(f.refs, func(i, j int) bool { return f.refs[i].CreatedAt.After(f.refs[j].CreatedAt) }) +} + +func (f *fakeSnapshotSource) LibrarySnapshotCandidates(_ context.Context, _ string, after time.Time, + afterID string, limit int) ([]postgresstore.SnapshotCandidate, error) { + start := 0 + for index, ref := range f.refs { + if afterID != "" && ref.SnapshotID == afterID && ref.CreatedAt.Equal(after) { + start = index + 1 + break + } + if afterID != "" && !after.IsZero() && ref.CreatedAt.Before(after) { + start = index + break + } + } + end := start + limit + if end > len(f.refs) { + end = len(f.refs) + } + return f.refs[start:end], nil +} + +// R3:同一快照"先封存、后发布成功"是正常链路;原产地只由捕获事件决定。 +func TestSnapshotOriginOnlyFromCaptureEvents(t *testing.T) { + pool, store := fixturePool(t) + ctx := context.Background() + resetFixtureJobs(t, pool) + fixture := newHandoffFixture(t) + config := appconfigFixture(fixture) + snapshot := fixture.seal(t) + recordSealedVersion(t, store, snapshot, "internal") + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionEffective, "internal", snapshot), + Scope: "internal", Kind: governance.LibraryVersionProductionEffective, SnapshotID: snapshot, + SourceJobID: "fixture-release", CreatedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + identity, err := expectedSnapshotIdentity(ctx, store, config, "internal", snapshot) + if err != nil { + t.Fatalf("封存+生效(正常成功链)被误拒:%v", err) + } + if identity.KnowledgeBaseID != fixture.kb { + t.Fatalf("身份应按**源**绑定解析,得到 %q", identity.KnowledgeBaseID) + } + + // 真的冲突:同一份内容既被源封存、又被目标预备份产生 ⇒ 拒绝。 + conflict := "conflict-" + snapshot[:8] + recordSealedVersion(t, store, conflict, "external") + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, "external", conflict), + Scope: "external", Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: conflict, + SourceJobID: "fixture-backup", CreatedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + if _, err := expectedSnapshotIdentity(ctx, store, config, "external", conflict); err == nil { + t.Fatal("源封存与目标预备份同时存在时没有拒绝") + } + + // 目标权威基线(真实捕获)只登记 production_effective,但证据写明是目标基线 ⇒ 目标绑定。 + baselineSnapshot := "baseline-" + snapshot[:8] + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionEffective, "internal", baselineSnapshot), + Scope: "internal", Kind: governance.LibraryVersionProductionEffective, SnapshotID: baselineSnapshot, + SourceJobID: "fixture-baseline", CreatedAt: time.Now().UTC(), + Evidence: map[string]any{"action": "target_baseline_init", "origin": "target_baseline"}, + }); err != nil { + t.Fatal(err) + } + baselineIdentity, err := expectedSnapshotIdentity(ctx, store, config, "internal", baselineSnapshot) + if err != nil { + t.Fatalf("目标基线快照(真实捕获)被误拒:%v", err) + } + if baselineIdentity.KnowledgeBaseID != "kb-target-acceptance" { + t.Fatalf("目标基线身份应解析为目标绑定,得到 %q", baselineIdentity.KnowledgeBaseID) + } + + // 只有引用、没有捕获事件 ⇒ 来源不明,拒绝。 + orphan := "orphan-" + snapshot[:8] + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionRecoveryVerified, "internal", orphan), + Scope: "internal", Kind: governance.LibraryVersionRecoveryVerified, SnapshotID: orphan, + SourceJobID: "fixture-recover", CreatedAt: time.Now().UTC(), + }); err != nil { + t.Fatal(err) + } + if _, err := expectedSnapshotIdentity(ctx, store, config, "internal", orphan); err == nil { + t.Fatal("没有捕获事件的快照被接受了") + } +} + +func containsAny(text string, needles ...string) bool { + for _, needle := range needles { + if len(needle) > 0 && strings.Contains(text, needle) { + return true + } + } + return false +} diff --git a/cmd/worker/library_handoff_integration_test.go b/cmd/worker/library_handoff_integration_test.go new file mode 100644 index 0000000..c87700b --- /dev/null +++ b/cmd/worker/library_handoff_integration_test.go @@ -0,0 +1,209 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryhandoff" + "knowledge-governance/internal/librarysnapshot" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// 这条测试回答一个业务问题:搬运没成功时,发布作业到底存不存在。 +// 用隔离 fixture 库(KG_TEST_DSN 指向专门的测试库),不碰任何业务库。 +func TestHandoffChainGatesReleaseJobOnVerifiedTransfer(t *testing.T) { + dsn := os.Getenv("KG_TEST_DSN") + if dsn == "" { + t.Skip("KG_TEST_DSN 未设置:跳过隔离 fixture 库上的搬运链测试") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + t.Fatalf("migrate fixture db: %v", err) + } + store := postgresstore.NewStore(pool) + resetFixtureJobs(t, pool) + fixture := newHandoffFixture(t) + config := appconfigFixture(fixture) + + snapshot := fixture.seal(t) + recordSealedVersion(t, store, snapshot, "internal") + job := createFixtureJob(t, store, "internal", snapshot) + handoffQueueID := bindHandoffQueue(t, nil, store, job, "internal", snapshot) + payload := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal", + TargetSnapshotID: snapshot, NextType: librarySyncJobType} + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, payload, handoffQueueID); err != nil { + t.Fatalf("runLibraryHandoff() error = %v", err) + } + record, err := store.LibraryJob(ctx, job.ID) + if err != nil { + t.Fatal(err) + } + if record.State == governance.LibraryJobFailed { + t.Fatalf("verified handoff left the job failed: %s", record.Error) + } + releaseID := governance.QueueJobIDFor(job.ID) + var queueType string + if err := pool.QueryRow(ctx, `SELECT type FROM jobs WHERE id=$1`, releaseID).Scan(&queueType); err != nil { + t.Fatalf("release queue job missing after verified handoff: %v", err) + } + if queueType != librarySyncJobType { + t.Fatalf("release queue type = %q", queueType) + } + if record.QueueJobID != releaseID { + t.Fatalf("library job not attached to release queue job: %q", record.QueueJobID) + } + // 云端确实拿到了可校验的快照。 + if _, err := os.Stat(filepath.Join(fixture.remoteArchive, "versions", snapshot+".json")); err != nil { + t.Fatalf("executor archive lacks the handoff snapshot: %v", err) + } + + // 负例:快照根本不存在 → 发布作业不得入队,作业必须失败。 + // 用 external scope:同一 (scope, kind) 只允许一个在飞作业,负例不能挤在 internal 上。 + unknown := fixture.unknownSnapshotID() + badJob := createFixtureJob(t, store, "external", unknown) + badQueueID := bindHandoffQueue(t, nil, store, badJob, "external", unknown) + badPayload := libraryHandoffPayload{LibraryJobID: badJob.ID, Scope: "external", + TargetSnapshotID: unknown, NextType: librarySyncJobType} + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, badPayload, badQueueID); err == nil { + t.Fatal("runLibraryHandoff() reported success for a snapshot that does not exist") + } + badRecord, err := store.LibraryJob(ctx, badJob.ID) + if err != nil { + t.Fatal(err) + } + if badRecord.State != governance.LibraryJobFailed { + t.Fatalf("failed handoff left job state = %s", badRecord.State) + } + var queued int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM jobs WHERE id=$1`, + governance.QueueJobIDFor(badJob.ID)).Scan(&queued); err != nil { + t.Fatal(err) + } + if queued != 0 { + t.Fatal("a failed handoff still enqueued the release job: the target could be put into maintenance") + } +} + +func createFixtureJob(t *testing.T, store *postgresstore.Store, scope, snapshot string) governance.LibraryJob { + t.Helper() + now := time.Now().UTC() + // 每次运行用唯一后缀:fixture 库会被反复使用,固定 ID 会撞上上一次的行。 + unique := fmt.Sprintf("%d", now.UnixNano()) + job, reused, err := store.CreateLibraryJob(context.Background(), governance.LibraryJob{ + ID: "libsync-handoff-" + unique, Scope: scope, Kind: governance.LibraryJobSync, + IdempotencyKey: "handoff-fixture:" + unique, RequestDigest: "fixture-" + unique, + OperationID: "op-" + unique, TargetSnapshotID: snapshot, Actor: "fixture", + }, governance.SyncStages(), now) + if err != nil { + t.Fatalf("create fixture job: %v", err) + } + if reused { + t.Fatalf("fixture job unexpectedly reused") + } + return job +} + +type handoffFixture struct { + root string + remoteArchive string + staging string + archiveRoot string + tenant uint64 + kb string + handoff *libraryhandoff.Handoff +} + +func newHandoffFixture(t *testing.T) handoffFixture { + t.Helper() + root := t.TempDir() + remoteArchive := filepath.Join(root, "remote-archive") + staging := filepath.Join(root, "remote-staging") + bundles := filepath.Join(root, "bundles") + localArchive := filepath.Join(root, "local-archive") + for _, dir := range []string{remoteArchive, staging, bundles, localArchive} { + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + } + binary := os.Getenv("KG_TEST_LIBRARYCTL") + if binary == "" { + t.Skip("KG_TEST_LIBRARYCTL 未设置:搬运链测试需要真实 libraryctl 二进制") + } + t.Setenv("LIBRARY_HANDOFF_LIBRARYCTL", binary) + handoff, err := libraryhandoff.New(libraryhandoff.Config{ + Transport: libraryhandoff.TransportLocal, LocalRoot: root, LocalArchive: localArchive, + ExecutorContainer: "fixture-executor", BundleDir: bundles, RemoteArchive: remoteArchive, + StagingDir: filepath.Join(root, "staging"), MaxBundleBytes: 8 << 20, OpTimeout: time.Minute, + }, nil) + if err != nil { + t.Fatal(err) + } + return handoffFixture{root: root, remoteArchive: remoteArchive, staging: staging, + archiveRoot: localArchive, tenant: 10000, kb: "kb-handoff-fixture", handoff: handoff} +} + +func (f handoffFixture) unknownSnapshotID() string { + value := bytes.Repeat([]byte{9}, 32) + return hex.EncodeToString(value) +} + +// seal 在本机归档里造一份合法的封存快照(身份与 fixture 的 tenant/kb 一致)。 +func (f handoffFixture) seal(t *testing.T) string { + t.Helper() + archive, err := librarysnapshot.Open(f.archiveRoot, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + part, err := archive.Put(bytes.NewBufferString("[]")) + if err != nil { + t.Fatal(err) + } + mapping := sha256.Sum256([]byte("fixture-mapping")) + manifest := librarysnapshot.Manifest{ + Format: librarysnapshot.Format, Scope: "internal", TenantID: f.tenant, + KnowledgeBaseID: f.kb, CreatedAt: time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC), + Compatibility: librarysnapshot.Compatibility{ + WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", + EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, + IndexMappingSHA256: hex.EncodeToString(mapping[:]), + }, + } + for _, name := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations"} { + current := part + current.Kind, current.Name = "database", name + manifest.Parts = append(manifest.Parts, current) + } + for _, name := range []string{"wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} { + current := part + current.Kind, current.Name = "wiki", name + manifest.Parts = append(manifest.Parts, current) + } + index := part + index.Kind, index.Name = "index", "chunks" + manifest.Parts = append(manifest.Parts, index) + id, err := archive.Seal(manifest) + if err != nil { + t.Fatal(err) + } + return id +} + +// 保持 encoding/json 参与(payload 结构与 API 一致),避免测试与线上 struct 漂移。 +var _ = json.Marshal diff --git a/cmd/worker/library_handoff_pagination_test.go b/cmd/worker/library_handoff_pagination_test.go new file mode 100644 index 0000000..5930222 --- /dev/null +++ b/cmd/worker/library_handoff_pagination_test.go @@ -0,0 +1,179 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +func fixturePool(t *testing.T) (*pgxpool.Pool, *postgresstore.Store) { + t.Helper() + dsn := os.Getenv("KG_TEST_DSN") + if dsn == "" { + t.Skip("KG_TEST_DSN 未设置:跳过隔离 fixture 库测试") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + t.Fatalf("migrate fixture db: %v", err) + } + return pool, postgresstore.NewStore(pool) +} + +// appconfigFixture 让**源绑定与目标绑定不同**:封存快照的身份是源 KB,发布目标是专用验收 KB。 +// 这正是云测试方案 A 的真实形状(源 WKNFull,目标 a8e9c8ad/2e980686 专用 KB)。 +func appconfigFixture(f handoffFixture) appconfig.Config { + return appconfig.Config{ + LibrarySourceTenantID: f.tenant, LibrarySourceInternalKB: f.kb, LibrarySourceExternalKB: f.kb, + LibraryProductionTenantID: f.tenant, LibraryProductionInternalKB: "kb-target-acceptance", + LibraryProductionExternalKB: "kb-target-acceptance", + } +} + +// recordSealedVersion 登记"这份快照是一次封存的产物",搬运据此判定它应按源绑定核对。 +func recordSealedVersion(t *testing.T, store *postgresstore.Store, snapshot, scope string) { + t.Helper() + if err := store.RecordLibraryVersion(context.Background(), governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, scope, snapshot), + Scope: scope, Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshot, + SourceJobID: "fixture-capture", CreatedAt: time.Now().UTC(), + }); err != nil { + t.Fatalf("record sealed version: %v", err) + } +} + +// resetFixtureJobs 收掉上一个用例留下的在飞 fixture 作业:隔离库会被反复使用, +// (scope,kind) 的唯一索引会把新建当成冲突。只动 handoff fixture 的行。 +func resetFixtureJobs(t *testing.T, pool *pgxpool.Pool) { + t.Helper() + if _, err := pool.Exec(context.Background(), + `UPDATE library_jobs SET state='failed', finished_at=now(), updated_at=now() +WHERE id LIKE 'libsync-handoff-%' AND state IN ('pending','running')`); err != nil { + t.Fatalf("reset fixture jobs: %v", err) + } +} + +func digestOf(label string) string { + sum := sha256.Sum256([]byte(label)) + return hex.EncodeToString(sum[:]) +} + +// 回传枚举必须覆盖"第 51 条以后"和"失败作业留下的预备份",不能用固定 LIMIT 50 截断。 +func TestSnapshotCandidatesPaginateBeyondFiftyAndIncludeRecoveryBackups(t *testing.T) { + pool, store := fixturePool(t) + ctx := context.Background() + scope := "internal" + if _, err := pool.Exec(ctx, `DELETE FROM library_jobs WHERE id LIKE 'pagination-%'`); err != nil { + t.Fatal(err) + } + base := time.Now().UTC().Add(-time.Hour) + want := map[string]bool{} + for index := 0; index < 55; index++ { + id := "pagination-ok-" + digestOf(string(rune('a'+index%26)) + time.Duration(index).String())[:10] + string(rune('a'+index%26)) + string(rune('a'+index/26)) + snapshot := digestOf("snapshot-" + id) + want[snapshot] = true + if _, err := pool.Exec(ctx, ` +INSERT INTO library_jobs (id, scope, kind, state, snapshot_id, created_at, updated_at, request_digest, operation_id, attempt_epoch, idempotency_key) +VALUES ($1,$2,'sync','succeeded',$3,$4,$4,'d','op',1,$1) +ON CONFLICT (id) DO UPDATE SET snapshot_id=EXCLUDED.snapshot_id, state='succeeded'`, + id, scope, snapshot, base.Add(time.Duration(index)*time.Second)); err != nil { + t.Fatalf("insert fixture job %d: %v", index, err) + } + // 最新的 50 条之外还有恢复基线:一个失败作业留下的预备份。 + } + failedSnapshot := digestOf("failed-prebackup") + want[failedSnapshot] = true + if _, err := pool.Exec(ctx, ` +INSERT INTO library_jobs (id, scope, kind, state, snapshot_id, recovery, created_at, updated_at, request_digest, operation_id, attempt_epoch, idempotency_key) +VALUES ('pagination-failed',$1,'sync','failed',$2,'按预备份恢复',$3,$3,'d','op',1,'pagination-failed') +ON CONFLICT (id) DO UPDATE SET snapshot_id=EXCLUDED.snapshot_id, state='failed'`, + scope, failedSnapshot, base.Add(2*time.Hour)); err != nil { + t.Fatal(err) + } + + seen := map[string]bool{} + var afterCreated time.Time + afterID := "" + for page := 0; page < 20; page++ { + items, err := store.LibrarySnapshotCandidates(ctx, scope, afterCreated, afterID, 7) + if err != nil { + t.Fatal(err) + } + if len(items) == 0 { + break + } + for _, item := range items { + if seen[item.SnapshotID] { + t.Fatalf("pagination repeated snapshot %s", item.SnapshotID) + } + seen[item.SnapshotID] = true + } + last := items[len(items)-1] + afterCreated, afterID = last.CreatedAt, last.SnapshotID + if len(items) < 7 { + break + } + } + for snapshot := range want { + if !seen[snapshot] { + t.Fatalf("pagination missed snapshot %s(第51条之后或失败作业的预备份被截断)", snapshot) + } + } +} + +// 重放:已成功的作业不允许被一次迟到的搬运失败改写成 failed;重复搬运不重复投递。 +func TestHandoffReplayDoesNotOverwriteTerminalStateOrDuplicateReleaseJob(t *testing.T) { + pool, store := fixturePool(t) + ctx := context.Background() + resetFixtureJobs(t, pool) + fixture := newHandoffFixture(t) + config := appconfigFixture(fixture) + snapshot := fixture.seal(t) + recordSealedVersion(t, store, snapshot, "internal") + job := createFixtureJob(t, store, "internal", snapshot) + handoffQueueID := bindHandoffQueue(t, nil, store, job, "internal", snapshot) + payload := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal", + TargetSnapshotID: snapshot, NextType: librarySyncJobType} + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, payload, handoffQueueID); err != nil { + t.Fatalf("first handoff: %v", err) + } + // 幂等重放:不得产生第二个队列作业,也不得改状态。 + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, payload, handoffQueueID); err != nil { + t.Fatalf("replayed handoff: %v", err) + } + var queued int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM jobs WHERE id=$1`, + governance.QueueJobIDFor(job.ID)).Scan(&queued); err != nil { + t.Fatal(err) + } + if queued != 1 { + t.Fatalf("replay produced %d release queue jobs", queued) + } + // 迟到的失败重放:作业已成功,不允许被改写。 + if _, err := pool.Exec(ctx, `UPDATE library_jobs SET state='succeeded', error='', recovery='' WHERE id=$1`, job.ID); err != nil { + t.Fatal(err) + } + bad := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal", + TargetSnapshotID: fixture.unknownSnapshotID(), NextType: librarySyncJobType} + _ = runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, bad, handoffQueueID) + after, err := store.LibraryJob(ctx, job.ID) + if err != nil { + t.Fatal(err) + } + if after.State != governance.LibraryJobSucceeded { + t.Fatalf("a late failure replay overwrote state to %s", after.State) + } +} diff --git a/cmd/worker/library_handoff_stage_contract_test.go b/cmd/worker/library_handoff_stage_contract_test.go new file mode 100644 index 0000000..a635af3 --- /dev/null +++ b/cmd/worker/library_handoff_stage_contract_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "bytes" + "context" + "os" + "testing" + + "knowledge-governance/internal/governance" +) + +// handoff 路径的 stage 写只允许发生在 Begin/Complete/Fail 这三个持有 job 行锁的 +// 事务方法里。这条契约测试挡的是"又在事务外面补一次无条件 UpdateLibraryStage" +// —— 它重复事务里的写,并在 Begin 返回与这次写之间给交接留出竞态窗口(上一轮退回点)。 +// +// 说明:这是源码契约,不能替代已经跑过的事务行为测试;它只负责让回流立刻变红。 +func TestHandoffStagesOnlyWrittenThroughOwnershipTransactions(t *testing.T) { + source, err := os.ReadFile("library_handoff.go") + if err != nil { + t.Fatalf("读不到 library_handoff.go:%v", err) + } + if bytes.Contains(source, []byte("store.UpdateLibraryStage(")) { + t.Fatal("handoff 路径又出现了无条件的 store.UpdateLibraryStage:阶段写必须在 Begin/Complete/Fail 的事务里") + } + for _, method := range []string{ + "store.BeginLibraryHandoff(", + "store.CompleteLibraryHandoff(", + "store.FailLibraryHandoff(", + } { + if !bytes.Contains(source, []byte(method)) { + t.Fatalf("handoff 路径没有走事务方法 %s", method) + } + } +} + +// 行为侧:所有权不属于本次 handoff 时,连阶段行都不该被建出来、作业状态也不动。 +func TestUnownedHandoffCreatesNoStageRow(t *testing.T) { + pool, store := fixturePool(t) + ctx := context.Background() + resetFixtureJobs(t, pool) + fixture := newHandoffFixture(t) + config := appconfigFixture(fixture) + snapshot := fixture.unknownSnapshotID() + job := createFixtureJob(t, store, "internal", snapshot) + recordSealedVersion(t, store, snapshot, "internal") + releaseID := governance.QueueJobIDFor(job.ID) + if _, err := pool.Exec(ctx, `UPDATE library_jobs SET state='running', queue_job_id=$2 WHERE id=$1`, + job.ID, releaseID); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `DELETE FROM library_job_stages WHERE job_id=$1 AND stage='handoff'`, job.ID); err != nil { + t.Fatal(err) + } + incoming := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal", + TargetSnapshotID: snapshot, NextType: librarySyncJobType} + // 拿一个既不是当前 owner、也不是这份作业 handoff ID 的队列号:必须拒绝。 + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, incoming, + "not-the-owner-"+snapshot[:8]); err == nil { + t.Fatal("错误前驱被接受了") + } + // 用这份作业真正的 handoff ID 重放:已交接 ⇒ 幂等成功,但也必须零写入。 + if err := runLibraryHandoffForQueue(ctx, store, config, fixture.handoff, incoming, + governance.LibraryHandoffQueueJobID(job.ID)); err != nil { + t.Fatalf("交接后的重放应当幂等成功,得到 %v", err) + } + var rows int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM library_job_stages WHERE job_id=$1 AND stage='handoff'`, + job.ID).Scan(&rows); err != nil { + t.Fatal(err) + } + if rows != 0 { + t.Fatalf("未被持有的 handoff 建出了 %d 行阶段记录", rows) + } + after, err := store.LibraryJob(ctx, job.ID) + if err != nil { + t.Fatal(err) + } + if after.State != governance.LibraryJobRunning || after.Error != "" { + t.Fatalf("未持有的 handoff 改动了作业:%s / %q", after.State, after.Error) + } +} diff --git a/cmd/worker/library_identity_helpers_test.go b/cmd/worker/library_identity_helpers_test.go new file mode 100644 index 0000000..f954e00 --- /dev/null +++ b/cmd/worker/library_identity_helpers_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "context" + "testing" + "time" + + "knowledge-governance/internal/governance" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// 版本事件的执行身份(父的复核项 R2/F02):一条版本事件属于**一次意图**(operation), +// 不是快照的终身属性。测试要造"同一个快照被另一个作业重新登记",就必须真的换一个意图, +// 而不是靠旧实现的 upsert 改写 source_job_id —— 那条路径现在已经按设计禁止了。 +func testLibraryOperation(t *testing.T, store *postgresstore.Store, scope string, + kind governance.LibraryJobKind, key string, at time.Time) string { + t.Helper() + ctx := context.Background() + op, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ + ID: governance.LibraryOperationID(scope, kind, key), Scope: scope, Kind: kind, + TargetSnapshotID: "target-" + key, RequestDigest: "digest-" + key, OperationKey: key, + Actor: "tester", CreatedAt: at.UTC(), + }) + if err != nil { + t.Fatalf("ensure test operation %s: %v", key, err) + } + return op.ID +} + +// recordVersionEvent 以给定意图登记一条版本事件(id 与 operation 身份一致)。 +func recordVersionEvent(t *testing.T, store *postgresstore.Store, scope string, + kind governance.LibraryVersionKind, snapshot, jobID, operationID string, at time.Time, + evidence map[string]any) { + t.Helper() + if err := store.RecordLibraryVersion(context.Background(), governance.LibraryVersion{ + ID: governance.LibraryVersionEventID(kind, scope, snapshot, operationID), + Scope: scope, + Kind: kind, + SnapshotID: snapshot, + SourceJobID: jobID, OperationID: operationID, CreatedBy: "worker", + Evidence: evidence, CreatedAt: at.UTC(), + }); err != nil { + t.Fatalf("record %s version for %s (job %s): %v", kind, snapshot, jobID, err) + } +} diff --git a/cmd/worker/library_lease.go b/cmd/worker/library_lease.go new file mode 100644 index 0000000..de149ed --- /dev/null +++ b/cmd/worker/library_lease.go @@ -0,0 +1,44 @@ +package main + +import ( + "context" + "errors" + "time" +) + +// Run remains synchronous: cancellation is a request, not proof that the last +// network write has stopped. The caller may release ownership only after run +// and its cleanup have actually returned, and the renewal goroutine is joined. +func runWithLibraryLease(parent context.Context, interval time.Duration, renew func(context.Context) error, run func(context.Context) error) error { + ctx, cancel := context.WithCancelCause(parent) + defer cancel(nil) + stop := make(chan struct{}) + done := make(chan error, 1) + go func() { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-stop: + done <- nil + return + case <-ctx.Done(): + done <- context.Cause(ctx) + return + case <-ticker.C: + bounded, finish := context.WithTimeout(ctx, interval) + err := renew(bounded) + finish() + if err != nil { + cancel(err) + done <- err + return + } + } + } + }() + err := run(ctx) + close(stop) + leaseErr := <-done + return errors.Join(err, leaseErr, context.Cause(ctx)) +} diff --git a/cmd/worker/library_lease_test.go b/cmd/worker/library_lease_test.go new file mode 100644 index 0000000..fdcc985 --- /dev/null +++ b/cmd/worker/library_lease_test.go @@ -0,0 +1,61 @@ +package main + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestContractLeaseLossWaitsForActualWriteExit(t *testing.T) { + lost := errors.New("lease lost") + entered := make(chan struct{}) + cancelled := make(chan struct{}) + release := make(chan struct{}) + finished := make(chan error, 1) + go func() { + finished <- runWithLibraryLease(context.Background(), time.Millisecond, func(context.Context) error { <-entered; return lost }, func(ctx context.Context) error { close(entered); <-ctx.Done(); close(cancelled); <-release; return nil }) + }() + select { + case <-cancelled: + case <-time.After(time.Second): + t.Fatal("loss did not cancel actual writer") + } + select { + case <-finished: + t.Fatal("returned while actual write still running") + default: + } + close(release) + select { + case err := <-finished: + if !errors.Is(err, lost) { + t.Fatalf("loss hidden: %v", err) + } + case <-time.After(time.Second): + t.Fatal("writer not joined") + } +} + +func TestContractLeaseRenewsDuringLongWrite(t *testing.T) { + renewed := make(chan struct{}, 1) + err := runWithLibraryLease(context.Background(), time.Millisecond, func(context.Context) error { + select { + case renewed <- struct{}{}: + default: + } + return nil + }, func(ctx context.Context) error { + select { + case <-renewed: + return nil + case <-time.After(time.Second): + return errors.New("no renewal") + case <-ctx.Done(): + return ctx.Err() + } + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/cmd/worker/library_owned_attempt.go b/cmd/worker/library_owned_attempt.go new file mode 100644 index 0000000..10757e0 --- /dev/null +++ b/cmd/worker/library_owned_attempt.go @@ -0,0 +1,40 @@ +package main + +import ( + "context" + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "knowledge-governance/internal/objectgateway" + postgresstore "knowledge-governance/internal/platform/postgres" + "time" +) + +// All target-changing handlers share one execution lock, not one lock per job or +// scope. Lease loss cancels work but cannot release ownership before cleanup joins. +func runOwnedLibraryAttempt(ctx context.Context, base *postgresstore.Store, config appconfig.Config, queue jobs.Job, jobID string, run func(context.Context, *libraryAttemptWriter) error) error { + return base.WithLibraryExecution(ctx, config.LibraryTargetInstance, func(ctx context.Context, ping func(context.Context) error) (err error) { + writer, err := beginLibraryWriter(ctx, base, jobID, libraryQueueOwner(config.WorkerID, queue, jobID)) + if err != nil { + return err + } + defer func() { + finishCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() + if err != nil { + writer.finish(finishCtx, governance.LibraryAttemptFailed, err.Error()) + } else { + writer.finish(finishCtx, governance.LibraryAttemptCompleted, "") + } + }() + return runWithLibraryLease(ctx, libraryAttemptLease/10, func(probe context.Context) error { + if err := ping(probe); err != nil { + return err + } + return base.RenewLibraryAttempt(probe, writer.attempt, libraryAttemptLease, time.Now().UTC()) + }, func(runCtx context.Context) error { + runCtx = objectgateway.WithClaim(runCtx, objectgateway.Claim{JobID: writer.attempt.JobID, OperationID: writer.attempt.OperationID, AttemptEpoch: int64(writer.attempt.Epoch), Owner: writer.attempt.Owner}) + return run(runCtx, writer) + }) + }) +} diff --git a/cmd/worker/library_recovery.go b/cmd/worker/library_recovery.go index 439d641..77b1502 100644 --- a/cmd/worker/library_recovery.go +++ b/cmd/worker/library_recovery.go @@ -10,10 +10,12 @@ import ( "log" "time" + "bytes" "knowledge-governance/internal/appconfig" "knowledge-governance/internal/governance" "knowledge-governance/internal/jobs" "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/objectgateway" postgresstore "knowledge-governance/internal/platform/postgres" v071 "knowledge-governance/internal/releaseadapter/v071" ) @@ -21,8 +23,13 @@ import ( // libraryRecoveryPayload 是"按预备份恢复并校验"的队列载荷。 // 它只说明动哪个窗口;恢复目标快照由 journal 里持久化的那份决定,调用方改不了。 type libraryRecoveryPayload struct { - Scope string `json:"scope"` - WindowJobID string `json:"window_job_id"` + Scope string `json:"scope"` + WindowJobID string `json:"window_job_id"` + SourceSnapshot string `json:"source_snapshot_id,omitempty"` + TargetID string `json:"target_id,omitempty"` + OriginalOperation string `json:"original_operation_id,omitempty"` + BackupSnapshot string `json:"backup_snapshot_id,omitempty"` + PlanDigest string `json:"plan_digest,omitempty"` } // runLibraryRecovery 是"内容风险未验证"窗口的唯一收尾入口: @@ -30,10 +37,15 @@ type libraryRecoveryPayload struct { // 只有校验通过才恢复服务、开入口、释放占用。失败则保持维护。 func runLibraryRecovery(ctx context.Context, store *postgresstore.Store, config appconfig.Config, job jobs.Job) error { var payload libraryRecoveryPayload - if err := json.Unmarshal(job.Payload, &payload); err != nil || + decoder := json.NewDecoder(bytes.NewReader(job.Payload)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&payload); err != nil || (payload.Scope != "internal" && payload.Scope != "external") || payload.WindowJobID == "" { return errors.New("invalid library recovery payload") } + if err := store.ValidateLibraryRecoveryQueue(ctx, job, payload.Scope, payload.WindowJobID); err != nil { + return err + } manager, err := openLibraryMaintenance(config) if err != nil { return fmt.Errorf("目标维护未接线,不能做恢复:%w", err) @@ -57,48 +69,103 @@ func runLibraryRecovery(ctx context.Context, store *postgresstore.Store, config if lock.TargetFingerprint != identity.Fingerprint { return errors.New("维护窗口的目标身份与当前配置不一致:拒绝用旧窗口恢复另一个目标") } + // 准入:窗口作业必须是这个 scope 的真实业务作业(恢复也不能靠畸形载荷开窗口)。 + windowJob, admitErr := admitLibraryJob(ctx, store, job, payload.WindowJobID, payload.Scope, "", false) + if admitErr != nil { + return admitErr + } + return runOwnedLibraryAttempt(ctx, store, config, job, payload.WindowJobID, func(ctx context.Context, writer *libraryAttemptWriter) error { + guarded := writer + prebackup := windowJob.SnapshotID + if prebackup == "" { + return errors.New("原作业没有持久化预备份,无法证明恢复到哪一份") + } + // 恢复必须带着"这次作业写了什么"的持久记录:没有它就只能按目标现状推断残渣, + // 而那会误删历史孤儿/其它知识库暂未绑定的资源(快照里没有这些行,删了回不来)。 + ledger, ledgerErr := loadWriteSetForJob(ctx, store, config.LibraryArchiveRoot, payload.Scope, + payload.WindowJobID, prebackup) + if ledgerErr != nil { + note := "恢复缺少持久化的写集合记录,目标保持维护:" + ledgerErr.Error() + _ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, time.Now().UTC()) + _ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, time.Now().UTC()) + return errors.New(note) + } + for _, pair := range [][2]string{{payload.SourceSnapshot, ledger.TargetSnapshotID}, {payload.TargetID, config.LibraryTargetIdentity()}, {payload.OriginalOperation, windowJob.OperationID}, {payload.BackupSnapshot, prebackup}, {payload.PlanDigest, ledger.Digest}} { + if pair[0] != "" && pair[0] != pair[1] { + return errors.New("recovery supplied identity differs from original immutable binding") + } + } + recoveryDigest, digestErr := governance.LibraryRecoveryDigest(payload.Scope, job.ID, payload.WindowJobID, windowJob.OperationID, config.LibraryTargetIdentity(), ledger.TargetSnapshotID, prebackup, ledger.Digest) + if digestErr != nil { + return digestErr + } + recoveryOp, _, opErr := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ + ID: governance.LibraryOperationID(payload.Scope, governance.LibraryJobRecover, job.ID), + Scope: payload.Scope, Kind: governance.LibraryJobRecover, TargetSnapshotID: prebackup, + RequestDigest: recoveryDigest, OperationKey: job.ID, Actor: job.LeaseOwner, CreatedAt: job.CreatedAt, + }) + if opErr != nil { + return opErr + } + claim := objectgateway.ClaimFromContext(ctx) + if claim.JobID == "" { + return errors.New("recovery attempt context missing") + } + claim.RecoveryJobID, claim.RecoveryOperationID = job.ID, recoveryOp.ID + ctx = objectgateway.WithClaim(ctx, claim) + knownMapping := knownIndexMapping(ctx, store, payload.Scope) + target, _, wireErr := buildLibraryProductionStack(ctx, config, restoreDispatchGate(config, store), payload.Scope, prebackup, knownMapping) + if wireErr != nil { + return fmt.Errorf("恢复目标装配失败:%w", wireErr) + } + defer target.Close() - // 预备份身份来自治理库里的原作业记录;协调器还会再与 journal 里的那份核对。 - windowJob, err := store.LibraryJob(ctx, payload.WindowJobID) - if err != nil || windowJob.SnapshotID == "" { - return errors.New("原作业没有持久化预备份,无法证明恢复到哪一份") - } - prebackup := windowJob.SnapshotID - knownMapping := knownIndexMapping(ctx, store, payload.Scope) - target, _, wireErr := buildLibraryProductionStack(ctx, config, payload.Scope, prebackup, knownMapping) - if wireErr != nil { - return fmt.Errorf("恢复目标装配失败:%w", wireErr) - } - defer target.Close() + coordinator, control, openErr := manager.Open(config.LibraryTargetJournalRoot) + if openErr != nil { + return fmt.Errorf("维护协调器不可用:%w", openErr) + } + defer control.Close() + defer coordinator.Close() - coordinator, control, openErr := manager.Open(config.LibraryTargetJournalRoot) - if openErr != nil { - return fmt.Errorf("维护协调器不可用:%w", openErr) - } - defer control.Close() - defer coordinator.Close() - - restorer := recoveryRestorer{target: target, expected: prebackup} - verifier := recoveryVerifier{target: target, expected: prebackup} - result, recoverErr := coordinator.RecoverWindow(ctx, payload.WindowJobID, restorer, verifier) - now := time.Now().UTC() - if recoverErr != nil { - note := "恢复/校验未通过,目标保持维护:" + recoverErr.Error() - _ = store.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now) - _ = store.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, now) - return recoverErr - } - if result.State != "recovered" { - note := "恢复流程结束但状态不是 recovered:" + result.State - _ = store.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now) - return errors.New(note) - } - if err := releaseWindowLocks(ctx, store, identity.Instance, payload.Scope, payload.WindowJobID, - "按预备份恢复并逐类校验通过,目标已按原运行状态恢复", now); err != nil { - return fmt.Errorf("恢复已验证,但维护占用释放失败:%w", err) - } - log.Printf("library recovery succeeded window=%s scope=%s backup=%s", payload.WindowJobID, payload.Scope, prebackup) - return nil + restorer := recoveryRestorer{target: target, expected: prebackup, writeSet: ledger, + // 恢复验证写的是"隔离 canary",不是发布计划:同一 job 的收尾走受限的演练 + // 恢复入口(同样的身份合同 + 整段回放),不能拿发布计划合同去回放它。 + drill: windowJob.Kind == governance.LibraryJobVerify} + verifier := recoveryVerifier{target: target, expected: prebackup} + result, recoverErr := coordinator.RecoverWindow(ctx, payload.WindowJobID, restorer, verifier) + now := time.Now().UTC() + if recoverErr != nil { + note := "恢复/校验未通过,目标保持维护:" + recoverErr.Error() + _ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now) + _ = guarded.UpdateLibraryMaintenanceState(ctx, payload.Scope, payload.WindowJobID, "needs_restore", note, now) + return recoverErr + } + if result.State != "recovered" { + note := "恢复流程结束但状态不是 recovered:" + result.State + _ = guarded.UpdateInstanceMaintenanceState(ctx, identity.Instance, payload.WindowJobID, "needs_restore", note, now) + return errors.New(note) + } + // 恢复事实必须落成**新事件并推进 current**(F06)。旧实现只释放锁:物理内容已经 + // 是预备份那份,页面/差异/后续作业却仍以为失败的新版本生效,下一步就会拿错基线决策。 + // 事件是追加的,不改写原来那条失败作业与失败版本。 + digest := result.Digest + if digest == "" { + return errors.New("恢复完成但没有校验摘要:拒绝登记恢复事实(无法证明恢复到了哪一份内容)") + } + if err := recordRecoveryEvent(ctx, writer, recoveryOp, payload.Scope, payload.WindowJobID, result.SnapshotID, + digest, "按预备份恢复并逐类校验通过"); err != nil { + return fmt.Errorf("恢复已完成但恢复事实登记失败:%w", err) + } + // 收尾顺序:先登记事实,再释放占用。反过来会出现"锁已放、current 还指向失败版本" + // 的窗口——那正是页面把恢复成功显示成待恢复的状态。 + if err := releaseWindowLocks(ctx, guarded, identity.Instance, payload.Scope, payload.WindowJobID, + "按预备份恢复并逐类校验通过,目标已按原运行状态恢复", now); err != nil { + return fmt.Errorf("恢复已验证,但维护占用释放失败:%w", err) + } + log.Printf("library recovery succeeded window=%s scope=%s backup=%s digest=%s", + payload.WindowJobID, payload.Scope, prebackup, digest) + return nil + }) } // recoveryRestorer 只按"作业记录里那份预备份"恢复:协调器传进来的 id 与它不一致 @@ -106,13 +173,26 @@ func runLibraryRecovery(ctx context.Context, store *postgresstore.Store, config type recoveryRestorer struct { target *v071.ProductionLibraryTarget expected string + writeSet *libraryrelease.WriteSet + // drill 表示窗口属于恢复演练:它的写集合是 canary,不是发布执行计划。 + drill bool } func (r recoveryRestorer) Restore(ctx context.Context, backupID string) error { if backupID != r.expected { return fmt.Errorf("预备份身份不一致(journal=%s 作业=%s)", backupID, r.expected) } - return r.target.Restore(ctx, libraryrelease.BackupRef{ID: "backup-" + backupID, SnapshotID: backupID}) + if r.writeSet == nil { + return errors.New("恢复缺少持久化的写集合记录:拒绝按目标现状推断残渣") + } + if r.writeSet.BackupSnapshotID != backupID { + return fmt.Errorf("写集合记录绑定预备份 %s,不是 %s", r.writeSet.BackupSnapshotID, backupID) + } + ref := libraryrelease.BackupRef{ID: "backup-" + backupID, SnapshotID: backupID, WriteSet: r.writeSet} + if r.drill { + return r.target.RestoreDrill(ctx, ref) + } + return r.target.Restore(ctx, ref) } // recoveryVerifier 做真实的内容校验,并把目标当前状态摘要作为"校验过什么"的凭证。 @@ -141,23 +221,5 @@ func (v recoveryVerifier) Verify(ctx context.Context, backupID string) (string, return hex.EncodeToString(sum[:]), nil } -// knownIndexMapping 取"上一次登记过的索引映射",作为装配目标时的映射基线。 -func knownIndexMapping(ctx context.Context, store *postgresstore.Store, scope string) string { - versions, err := store.LibraryVersions(ctx, scope, 50) - if err != nil { - return "" - } - for _, item := range versions { - if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil { - if raw, ok := item.Evidence["index_mapping_sha256"].(string); ok && raw != "" { - return raw - } - } - } - for _, item := range versions { - if raw, ok := item.Evidence["index_mapping_sha256"].(string); ok && raw != "" { - return raw - } - } - return "" -} +// knownIndexMapping 在 library_versions.go:同步与恢复共用同一份(当前生效版本精确查, +// 取不到映射才退回最近记录)。这里不再复制第二份。 diff --git a/cmd/worker/library_release_handlers.go b/cmd/worker/library_release_handlers.go new file mode 100644 index 0000000..cd9f247 --- /dev/null +++ b/cmd/worker/library_release_handlers.go @@ -0,0 +1,38 @@ +package main + +import ( + "context" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// registerLibraryReleaseHandlers 注册整库发布执行器:production sync / restore / +// recover / baseline,四类且仅这四类。 +// +// 为什么单独成一个函数:这是"发布执行器"角色的边界,也是唯一会让本进程写 +// 目标整库的地方。它必须能被单独测试(注册了哪些、未准入时是不是明确失败), +// 而不是埋在 run() 里只能靠连库启动来验证。 +func registerLibraryReleaseHandlers(handlers map[string]jobs.Handler, store *postgresstore.Store, + config appconfig.Config, admissionErr error) { + handlers[librarySyncJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error { + return runLibraryRelease(ctx, store, config, job, governance.LibraryJobSync) + }) + handlers[libraryRestoreJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error { + return runLibraryRelease(ctx, store, config, job, governance.LibraryJobRestore) + }) + handlers[libraryRecoverJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error { + return runLibraryRecovery(ctx, store, config, job) + }) + // 建立目标权威基线:目标非空又没有生效版本时的唯一入口(只读捕获 + 校验 + 登记)。 + handlers[libraryBaselineJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error { + return runLibraryBaseline(ctx, store, config, job) + }) + // 恢复验证:真实"备份→canary→恢复→复核",通过后写入与当前目标绑定的可恢复证据。 + // 它是同步闸口的证据来源,所以与上面三类共用同一把执行锁与准入。 + handlers[libraryVerifyJobType] = admittanceGuarded(admissionErr, func(ctx context.Context, job jobs.Job) error { + return runLibraryVerify(ctx, store, config, job) + }) +} diff --git a/cmd/worker/library_restore_dispatch_wiring_test.go b/cmd/worker/library_restore_dispatch_wiring_test.go new file mode 100644 index 0000000..b62be04 --- /dev/null +++ b/cmd/worker/library_restore_dispatch_wiring_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "testing" + + "knowledge-governance/internal/appconfig" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// A12:能力默认关闭;只有"配置开启 + 目标身份存在 + 真实治理台账"同时成立才装配。 +// 配置本身不是独占证明,baseline 装配永远不传该台账。 +func TestRestoreDispatchGateRequiresExplicitConfiguration(t *testing.T) { + store := &postgresstore.Store{} + identity := appconfig.Config{LibraryProductionDatabaseURL: "postgres://local@127.0.0.1:5432/target_db", + LibraryTargetInstance: "inst", LibraryProductionTenantID: 1, LibraryProductionInternalKB: "kb"} + if gate := restoreDispatchGate(identity, store); gate != nil { + t.Fatal("gate wired without the explicit switch") + } + enabled := identity + enabled.LibraryRestoreDispatchEnabled = true + if gate := restoreDispatchGate(enabled, store); gate == nil { + t.Fatal("gate not wired when explicitly enabled") + } + if gate := restoreDispatchGate(enabled, nil); gate != nil { + t.Fatal("gate wired without a governance store") + } + // 空目标配置仍会得到一个 gate:真实闸门是治理库激活登记(见 store 用例), + // 用"配置看起来完整"冒充独占证明才是要避免的。 +} diff --git a/cmd/worker/library_role_test.go b/cmd/worker/library_role_test.go new file mode 100644 index 0000000..16841bc --- /dev/null +++ b/cmd/worker/library_role_test.go @@ -0,0 +1,89 @@ +package main + +import ( + "context" + "strings" + "testing" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/jobs" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/versionhistory" +) + +// 发布执行器必须只挂四类 release 作业:多挂一类就会抢走本机队列里别的执行者的作业。 +func TestRegisterLibraryReleaseHandlersCoversOnlyReleaseJobs(t *testing.T) { + handlers := map[string]jobs.Handler{} + registerLibraryReleaseHandlers(handlers, nil, appconfig.Config{}, nil) + want := []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType, + libraryBaselineJobType, libraryVerifyJobType} + if len(handlers) != len(want) { + t.Fatalf("registered %d handlers, want %d: %#v", len(handlers), len(want), handlers) + } + for _, jobType := range want { + if handlers[jobType] == nil { + t.Fatalf("handler %q is not registered", jobType) + } + } +} + +// 准入未通过时 handler 必须"明确失败且不做任何动作":不能靠 nil store 或进程内状态蒙过去。 +func TestRegisterLibraryReleaseHandlersFailsClosedWhenNotAdmitted(t *testing.T) { + handlers := map[string]jobs.Handler{} + registerLibraryReleaseHandlers(handlers, nil, appconfig.Config{}, errNotAdmitted{}) + for _, jobType := range []string{librarySyncJobType, libraryRestoreJobType, libraryRecoverJobType, + libraryBaselineJobType, libraryVerifyJobType} { + err := handlers[jobType](context.Background(), jobs.Job{}) + if err == nil || !strings.Contains(err.Error(), "准入未通过") { + t.Fatalf("handler %q error = %v, want admission refusal", jobType, err) + } + } +} + +type errNotAdmitted struct{} + +func (errNotAdmitted) Error() string { return "fixture: target instance unknown" } + +// capture 角色不能注册任何 source 之外的队列;release-executor 反之。 +func TestWorkerHandlersFollowWorkerRole(t *testing.T) { + release := appconfig.Config{ + LibraryWorkerRole: appconfig.LibraryWorkerRoleReleaseExecutor, + LibraryAgentSocket: "/run/library-agent/agent.sock", + TestWeKnoraEnabled: true, + TestWeKnoraAPIKeyFile: "/nonexistent/api-key", + PPScanEnabled: true, + VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance", + VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"}, + } + handlers, err := workerHandlers(postgresstore.NewStore(nil), release) + if err != nil { + t.Fatalf("release-executor workerHandlers() error = %v", err) + } + for _, forbidden := range []string{libraryCaptureJobType, "test.upload", "test.poll", "test.validate", "test.remove", "source.scan.pp", "source.catalog.refresh", "artifact.fetch", versionhistory.JobType} { + if handlers[forbidden] != nil { + t.Fatalf("release-executor registered %q", forbidden) + } + } + if handlers["demo"] == nil { + t.Fatal("demo handler must stay registered") + } + + capture := appconfig.Config{ + LibraryWorkerRole: appconfig.LibraryWorkerRoleCapture, + LibraryAgentSocket: "/run/library-agent/agent.sock", + TestWeKnoraEnabled: true, + TestWeKnoraAPIKeyFile: "/nonexistent/api-key", + } + if _, err := workerHandlers(nil, capture); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") { + t.Fatalf("capture role must reach the test WeKnora wiring, got %v", err) + } + capture.TestWeKnoraEnabled = false + capture.PPScanEnabled = false + handlers, err = workerHandlers(postgresstore.NewStore(nil), capture) + if err != nil { + t.Fatalf("capture workerHandlers() error = %v", err) + } + if handlers[libraryCaptureJobType] == nil { + t.Fatal("capture role must register library.capture") + } +} diff --git a/cmd/worker/library_seal_source_failure_test.go b/cmd/worker/library_seal_source_failure_test.go new file mode 100644 index 0000000..d4ecd1e --- /dev/null +++ b/cmd/worker/library_seal_source_failure_test.go @@ -0,0 +1,100 @@ +package main + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +// fakeStageStore 记录封存失败分支对业务作业行的两次落库调用。 +type fakeStageStore struct { + stageCalls []string + jobCalls []string +} + +func (f *fakeStageStore) UpdateLibraryStage(_ context.Context, jobID, stage, state string, _, _, _, _ *int64, detail string, _ time.Time) error { + f.stageCalls = append(f.stageCalls, jobID+"|"+stage+"|"+state+"|"+detail) + return nil +} + +func (f *fakeStageStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, _, _ string, _ time.Time) error { + f.jobCalls = append(f.jobCalls, jobID+"|"+string(state)+"|"+stage+"|"+message+"|"+recovery) + return nil +} + +func (f *fakeStageStore) LibraryVersionByRef(context.Context, string, governance.LibraryVersionKind, string, string) (governance.LibraryVersion, bool, error) { + return governance.LibraryVersion{}, false, nil +} + +func (f *fakeStageStore) RecordLibraryVersion(context.Context, governance.LibraryVersion) error { + return nil +} + +// 归档根必须是非符号链接的 0700 目录;t.TempDir 的权限受 umask 影响。 +func privateDir(t *testing.T) string { + t.Helper() + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + return root +} + +func sourceFor(scope, kb string) governance.LibrarySourceIdentity { + return governance.LibrarySourceIdentity{Project: "kgmaint-weknora", App: "kgmaint-app", Scope: scope, TenantID: 1, KnowledgeBaseID: kb} +} + +// RED 用例:快照来源与配置不一致时,队列已 failed、页面却永远"导出中"(真实事故: +// libseal-lib-internal-20261102T234053 running/export/error 空)。失败必须同时写进 +// stage 与 job,且原错原样出现在两处与返回值里 —— 不能被"已记录失败"遮住。 +func TestCapturedSourceMismatchPersistsFailedStageAndJob(t *testing.T) { + root := privateDir(t) + snapshotID := sealTinyBaseline(t, root, "internal", time.Date(2026, 11, 2, 23, 40, 53, 0, time.UTC)) + // 清单里是 kb-baseline;worker 配置漂移后拿的是另一个 KB(256 验收遗留正是这样)。 + source := sourceFor("internal", "0c84a098-d3ed-4b82-a165-e6de9691d6a8") + store := &fakeStageStore{} + + err := ensureCapturedSource(context.Background(), store, "libseal-lib-internal-20261102T234053", + root, snapshotID, source, time.Now().UTC()) + + if err == nil || !strings.Contains(err.Error(), "captured manifest differs from configured source") { + t.Fatalf("mismatch must keep the original error, got %v", err) + } + if len(store.stageCalls) != 1 { + t.Fatalf("stage writes = %v, want exactly one failed stage", store.stageCalls) + } + if !strings.HasPrefix(store.stageCalls[0], "libseal-lib-internal-20261102T234053|export|failed|") || + !strings.Contains(store.stageCalls[0], "captured manifest differs from configured source") { + t.Fatalf("stage write = %q, want failed+original error", store.stageCalls[0]) + } + if len(store.jobCalls) != 1 { + t.Fatalf("job writes = %v, want exactly one failed job", store.jobCalls) + } + if !strings.HasPrefix(store.jobCalls[0], "libseal-lib-internal-20261102T234053|failed|export|") || + !strings.Contains(store.jobCalls[0], "captured manifest differs from configured source") { + t.Fatalf("job write = %q, want failed+original error", store.jobCalls[0]) + } + // 恢复说明必须指向真实下一步,而不是暗示数据损坏。 + if !strings.Contains(store.jobCalls[0], "重新封存") { + t.Fatalf("job recovery = %q, want a re-seal instruction", store.jobCalls[0]) + } +} + +// 正例对照:身份一致时不得写任何失败,也不得把成功路径变成失败。 +func TestCapturedSourceMatchStaysSuccessful(t *testing.T) { + root := privateDir(t) + snapshotID := sealTinyBaseline(t, root, "internal", time.Date(2026, 11, 2, 23, 40, 53, 0, time.UTC)) + store := &fakeStageStore{} + + if err := ensureCapturedSource(context.Background(), store, "libseal-ok", + root, snapshotID, sourceFor("internal", "kb-baseline"), time.Now().UTC()); err != nil { + t.Fatalf("matching source rejected: %v", err) + } + if len(store.stageCalls) != 0 || len(store.jobCalls) != 0 { + t.Fatalf("success path wrote failures: stage=%v job=%v", store.stageCalls, store.jobCalls) + } +} diff --git a/cmd/worker/library_source_candidate.go b/cmd/worker/library_source_candidate.go new file mode 100644 index 0000000..82e2c4a --- /dev/null +++ b/cmd/worker/library_source_candidate.go @@ -0,0 +1,53 @@ +package main + +import ( + "context" + "errors" + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" + "time" +) + +func configuredCaptureSource(config appconfig.Config, scope string) governance.LibrarySourceIdentity { + kb := config.LibrarySourceInternalKB + if scope == "external" { + kb = config.LibrarySourceExternalKB + } + return governance.LibrarySourceIdentity{Project: config.SourceProject(), App: config.LibrarySourceApp, Scope: scope, TenantID: config.LibrarySourceTenantID, KnowledgeBaseID: kb} +} +func verifyCapturedSource(root, snapshotID string, source governance.LibrarySourceIdentity) error { + if _, err := source.ID(); err != nil { + return err + } + archive, err := librarysnapshot.Open(root, 256*1024*1024) + if err != nil { + return err + } + defer archive.Close() + manifest, err := archive.Load(snapshotID) + if err != nil { + return err + } + if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID || manifest.KnowledgeBaseID != source.KnowledgeBaseID { + return errors.New("captured manifest differs from configured source") + } + return nil +} + +// ensureCapturedSource 校验快照来源。校验失败必须把失败写进业务行: +// 队列侧此时已 failed,只 return err 会让页面永远停在"导出中" +// (实际事故:libseal-lib-internal-20261102T234053 running/export/error 空)。 +func ensureCapturedSource(ctx context.Context, store libraryStageStore, jobID, root, snapshotID string, source governance.LibrarySourceIdentity, now time.Time) error { + err := verifyCapturedSource(root, snapshotID, source) + if err == nil { + return nil + } + // 快照本身已产生且字节完好,错的只是 worker 读到的来源身份;因此恢复路径是 + // "修配置后重新登记/重新封存",不是"重采数据"。原错原样写进 stage、job 与 + // 返回值:改写成更友好的文案会让真正的配置漂移查不出来。 + libraryStageRecorder{store: store, jobID: jobID}.Stage(ctx, "export", "failed", err.Error()) + _ = store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobFailed, "export", err.Error(), + "快照已产生但来源身份与配置不一致,未登记为测试封存;修正来源配置后重新封存", "", "", now) + return err +} diff --git a/cmd/worker/library_takeover_historical_integration_test.go b/cmd/worker/library_takeover_historical_integration_test.go new file mode 100644 index 0000000..7f4e18e --- /dev/null +++ b/cmd/worker/library_takeover_historical_integration_test.go @@ -0,0 +1,278 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/releasebundle" +) + +// sealTinyBaseline 造一份结构合法、字节自洽的最小基线清单:接管判定只校验 +// 清单文件名与内容摘要一致,不需要真实业务行。 +func sealTinyBaseline(t *testing.T, root, scope string, now time.Time) string { + t.Helper() + archive, err := librarysnapshot.Open(root, 1<<20) + if err != nil { + t.Fatalf("open archive: %v", err) + } + defer archive.Close() + required := []string{"database/knowledges", "database/chunks", "database/resources", + "database/resource_bindings", "database/knowledge_tags", "database/knowledge_tag_relations", + "wiki/wiki_pages", "wiki/wiki_folders", "wiki/wiki_page_issues", "wiki/wiki_log_entries", + "index/chunks"} + parts := make([]librarysnapshot.Part, 0, len(required)) + for _, key := range required { + kind, name, _ := strings.Cut(key, "/") + part, err := archive.Put(strings.NewReader("[]")) + if err != nil { + t.Fatalf("put %s: %v", key, err) + } + part.Kind, part.Name, part.Count = kind, name, 0 + parts = append(parts, part) + } + id, err := archive.Seal(librarysnapshot.Manifest{ + ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, + Compatibility: librarysnapshot.Compatibility{ + WeKnoraVersion: releasebundle.WeKnoraVersionV071, SchemaVersion: releasebundle.WeKnoraMigrationV071, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "bge-m3", + EmbeddingDimension: releasebundle.EmbeddingDimensionV071, + IndexMappingSHA256: strings.Repeat("a", 64), + }, + Format: librarysnapshot.Format, Scope: scope, TenantID: 1, KnowledgeBaseID: "kb-baseline", + CreatedAt: now, Parts: parts, + }) + if err != nil { + t.Fatalf("seal manifest: %v", err) + } + return id +} + +// 真实 PostgreSQL 正负例:历史快照被别的作业发布过且已被更新版本顶替,新恢复 +// 作业在写入中断后必须能继续;授权/维护/基线任一不成立就必须继续拒绝。 +func TestTakeoverHistoricalRestoreOnRealLedger(t *testing.T) { + store, pool := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const scope = "internal" + const target = "snap-historical" + const otherJob = "libsync-internal-original" + const newerJob = "librestore-internal-newer" + const jobID = "librestore-internal-historical" + + archiveRoot := t.TempDir() + if err := os.Chmod(archiveRoot, 0700); err != nil { + t.Fatalf("chmod archive root: %v", err) + } + if resolved, err := filepath.EvalSymlinks(archiveRoot); err != nil || resolved != filepath.Clean(archiveRoot) { + t.Fatalf("archive root is not a real directory: resolved=%q err=%v", resolved, err) + } + backup := sealTinyBaseline(t, archiveRoot, scope, now.Add(-30*time.Minute)) + + digest, err := governance.LibraryRequestDigest(scope, governance.LibraryJobRestore, + map[string]any{"restore_snapshot_id": target}) + if err != nil { + t.Fatalf("digest: %v", err) + } + job := governance.LibraryJob{ID: jobID, Scope: scope, Kind: governance.LibraryJobRestore, + TargetSnapshotID: target, SnapshotID: backup, RequestDigest: digest, + Stages: []governance.LibraryStage{{Stage: "database", State: "running"}}} + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope, + Kind: governance.LibraryJobRestore, RequestDigest: digest, TargetSnapshotID: target, + IdempotencyKey: "library.restore:internal:historical"}, governance.SyncStages(), now); err != nil { + t.Fatalf("create job: %v", err) + } + + recordEffective := func(source, snapshot string, at time.Time) { + t.Helper() + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionEffective, scope, snapshot), + Scope: scope, Kind: governance.LibraryVersionProductionEffective, SnapshotID: snapshot, + SourceJobID: source, CreatedBy: "worker", Evidence: map[string]any{"action": "sync"}, + CreatedAt: at, + }); err != nil { + t.Fatalf("record effective %s: %v", snapshot, err) + } + } + recordBackup := func(source, snapshot string) { + t.Helper() + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, snapshot), + Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: snapshot, + SourceJobID: source, CreatedBy: "worker", Evidence: map[string]any{"backup_snapshot": snapshot}, + CreatedAt: now.Add(-30 * time.Minute), + }); err != nil { + t.Fatalf("record prebackup %s: %v", snapshot, err) + } + } + // 同一份预备份可以被多个意图登记:每次登记是一条独立事件(F02:不许互相改写)。 + recordBackupWithIntent := func(source, intentKey, snapshot string, at time.Time) { + t.Helper() + opID := testLibraryOperation(t, store, scope, governance.LibraryJobRestore, intentKey, at) + recordVersionEvent(t, store, scope, governance.LibraryVersionProductionPrebackup, snapshot, + source, opID, at, map[string]any{"backup_snapshot": snapshot}) + } + recordEffective(otherJob, target, now.Add(-2*time.Hour)) + recordEffective(newerJob, "snap-newer", now.Add(-time.Hour)) + recordBackup(jobID, backup) + + if _, err := store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{ + Scope: scope, OwnerJobID: jobID, TargetIdentity: "test-target", Level: "instance", + TargetFingerprint: "fp-historical", Services: []string{"app"}, IngressState: "closed", + State: "applying", OriginalServiceState: "running", Note: "test", + }, now); err != nil { + t.Fatalf("acquire scope maintenance: %v", err) + } + if _, err := store.AcquireInstanceMaintenance(ctx, postgresstore.LibraryInstanceMaintenance{ + Instance: "kgseal-app", OwnerJobID: jobID, OwnerScope: scope, TargetFingerprint: "fp-historical", + Level: "instance", IngressState: "unknown", State: "acquired", OriginalServiceState: "running", + }, now); err != nil { + t.Fatalf("acquire instance maintenance: %v", err) + } + createGrant := func(id string, created time.Time) { + t.Helper() + if err := store.CreateLibraryAuthorization(ctx, governance.LibraryReleaseAuthorization{ + ID: id, Scope: scope, SnapshotID: target, ParamsDigest: digest, + AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: created, + }); err != nil { + t.Fatalf("create authorization: %v", err) + } + } + createGrant("libauth-historical-1", now.Add(-time.Minute)) + + classifyNow := func() takeoverKind { + t.Helper() + facts := loadLibraryVersionFacts(ctx, store, scope, target) + if facts.Err != nil { + t.Fatalf("load version facts: %v", facts.Err) + } + resume := loadTakeoverResumeFacts(ctx, store, archiveRoot, job, now) + if !resume.MaintenanceOwned || !resume.BaselineRecorded || !resume.BaselineVerified { + t.Fatalf("夹具失效:续写证据不全 %+v", resume) + } + return classifyTakeover(job, facts, resume) + } + + if got := classifyNow(); got != takeoverFresh { + t.Fatalf("新授权的历史快照恢复接管 = %q, want %q", got, takeoverFresh) + } + + // 授权被撤销 ⇒ 拒绝。 + if err := store.RevokeLibraryAuthorization(ctx, "libauth-historical-1", now); err != nil { + t.Fatalf("revoke: %v", err) + } + assertTakeover(t, "authorization revoked", classifyNow(), takeoverSuperseded) + createGrant("libauth-historical-2", now.Add(-time.Minute)) + + // 维护窗口不再由本作业独占 ⇒ 拒绝。 + if err := store.ReleaseInstanceMaintenance(ctx, "kgseal-app", jobID, now); err != nil { + t.Fatalf("release instance maintenance: %v", err) + } + facts := loadLibraryVersionFacts(ctx, store, scope, target) + if got := classifyTakeover(job, facts, loadTakeoverResumeFacts(ctx, store, archiveRoot, job, now)); got != takeoverSuperseded { + t.Fatalf("维护被释放后的接管 = %q, want %q", got, takeoverSuperseded) + } + if _, err := store.AcquireInstanceMaintenance(ctx, postgresstore.LibraryInstanceMaintenance{ + Instance: "kgseal-app", OwnerJobID: jobID, OwnerScope: scope, TargetFingerprint: "fp-historical", + Level: "instance", IngressState: "unknown", State: "acquired", OriginalServiceState: "running", + }, now); err != nil { + t.Fatalf("re-acquire instance maintenance: %v", err) + } + + // 别的作业登记同一份预备份:它只能新增**自己**的事件,改不动本作业的那一条 + // (F02 在存储层的形状:来源作业/意图在事件上不可变,upsert 改写这条路已经封死)。 + // 因此基线归属仍然成立、接管仍可继续——"偷"在台账上不成立,正是要的行为。 + recordBackupWithIntent("libsync-internal-thief", "thief-intent", backup, now) + facts = loadLibraryVersionFacts(ctx, store, scope, target) + if got := classifyTakeover(job, facts, loadTakeoverResumeFacts(ctx, store, archiveRoot, job, now)); got != takeoverFresh { + t.Fatalf("别的作业另登记同一份预备份不该影响本作业的基线:%q, want %q", got, takeoverFresh) + } + var owners []string + rows, err := pool.Query(ctx, `SELECT source_job_id FROM library_versions +WHERE scope=$1 AND kind='production_prebackup' AND snapshot_id=$2 ORDER BY created_at`, scope, backup) + if err != nil { + t.Fatalf("read prebackup events: %v", err) + } + for rows.Next() { + var owner string + if err := rows.Scan(&owner); err != nil { + t.Fatalf("scan prebackup owner: %v", err) + } + owners = append(owners, owner) + } + rows.Close() + if len(owners) != 2 || owners[0] != jobID || owners[1] != "libsync-internal-thief" { + t.Fatalf("两份登记必须都留在台账上且各自归属不变:%v", owners) + } + + // 基线清单字节被改 ⇒ 摘要对不上,拒绝。 + manifestPath := filepath.Join(archiveRoot, "versions", backup+".json") + if err := os.WriteFile(manifestPath, []byte("{}"), 0600); err != nil { + t.Fatalf("corrupt manifest: %v", err) + } + facts = loadLibraryVersionFacts(ctx, store, scope, target) + resume := loadTakeoverResumeFacts(ctx, store, archiveRoot, job, now) + if resume.BaselineVerified { + t.Fatal("基线清单被改后仍判为完好(校验没起作用)") + } + if got := classifyTakeover(job, facts, resume); got != takeoverSuperseded { + t.Fatalf("基线清单被改后的接管 = %q, want %q", got, takeoverSuperseded) + } +} + +func assertTakeover(t *testing.T, label string, got, want takeoverKind) { + t.Helper() + if got != want { + t.Fatalf("%s: classify = %q, want %q", label, got, want) + } +} + +// 续作早退的失败出口:有预备份就必须保留 needs_restore 并点名 backup, +// 不能写"无需恢复"(真实现场就是这样把半写目标说成完好)。 +func TestFailLibraryJobOrTakeoverKeepsRiskWhenResumed(t *testing.T) { + store, _ := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const scope = "internal" + const jobID = "librestore-internal-resumed-auth-expired" + const backup = "snap-prebackup-expired" + + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ + ID: jobID, Scope: scope, Kind: governance.LibraryJobRestore, TargetSnapshotID: "snap-historical", + RequestDigest: "digest-expired", IdempotencyKey: "library.restore:expired", + }, governance.SyncStages(), now); err != nil { + t.Fatalf("create job: %v", err) + } + if _, err := store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{ + Scope: scope, OwnerJobID: jobID, TargetIdentity: "test-target", Level: "instance", + TargetFingerprint: "fp", Services: []string{"app"}, IngressState: "closed", + State: "applying", OriginalServiceState: "running", Note: "test", + }, now); err != nil { + t.Fatalf("acquire maintenance: %v", err) + } + recorder := libraryStageRecorder{store: store, jobID: jobID, scope: scope} + if err := failLibraryJobOrTakeover(ctx, store, recorder, scope, jobID, backup, true, + "没有与目标快照匹配的有效发布授权", "prebackup"); err == nil { + t.Fatal("续作失败必须返回错误") + } + job, err := store.LibraryJob(ctx, jobID) + if err != nil { + t.Fatalf("read job: %v", err) + } + if job.State != governance.LibraryJobFailed || job.SnapshotID != backup { + t.Fatalf("作业终态/基线 = %s/%q, want failed/%q", job.State, job.SnapshotID, backup) + } + if !strings.Contains(job.Recovery, backup) || strings.Contains(job.Recovery, "无需恢复") { + t.Fatalf("恢复指引必须点名基线且不许说无需恢复:%q", job.Recovery) + } + row, err := store.LibraryMaintenanceOf(ctx, scope) + if err != nil || row == nil || row.ReleasedAt != nil || row.State != "needs_restore" { + t.Fatalf("维护必须保持并标 needs_restore:%+v err=%v", row, err) + } +} diff --git a/cmd/worker/library_takeover_historical_test.go b/cmd/worker/library_takeover_historical_test.go new file mode 100644 index 0000000..c11c5d9 --- /dev/null +++ b/cmd/worker/library_takeover_historical_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +// 回归:新恢复作业的目标快照是"历史版本"(另一作业发布过,后来被更新的版本顶替)。 +// 作业在写 database 之后被杀,重启接管时这一行仍是 superseded—— +// 但那是**别的作业**的历史,不是本作业过期。只要这次恢复是顶替之后新授权的、 +// 维护窗口仍由本作业独占、预备份基线未变,就必须继续(fresh),不能拒绝。 +// +// 反过来:本作业自己完成过(版本行归属自己或 finalize 成功)后被后续版本替换, +// 或缺少授权/维护/基线任一证据,都必须继续拒绝——删掉 superseded 判断是另一种事故。 +func TestClassifyTakeoverHistoricalRestoreAfterSupersede(t *testing.T) { + supersededAt := time.Now().UTC().Add(-time.Hour) + job := governance.LibraryJob{ID: "librestore-internal-historical", Scope: "internal", + Kind: governance.LibraryJobRestore, TargetSnapshotID: "snap-historical", SnapshotID: "snap-prebackup", + Stages: []governance.LibraryStage{{Stage: "database", State: "running"}}} + finalized := job + finalized.Stages = append(append([]governance.LibraryStage{}, job.Stages...), + governance.LibraryStage{Stage: "finalize", State: "succeeded"}) + + // 历史生效行属于别的作业,且已被更新版本顶替;当前生效版本不是本目标快照。 + factsBy := func(snapshotOwner string) libraryVersionFacts { + return libraryVersionFacts{ + HasCurrent: true, + Current: governance.LibraryVersion{Kind: governance.LibraryVersionProductionEffective, + SnapshotID: "snap-newer", SourceJobID: "librestore-internal-newer"}, + HasSnapshot: true, + Snapshot: governance.LibraryVersion{Kind: governance.LibraryVersionProductionEffective, + SnapshotID: "snap-historical", SourceJobID: snapshotOwner, SupersededAt: &supersededAt}, + } + } + resume := takeoverResumeFacts{AuthorizedAt: supersededAt.Add(time.Minute), + MaintenanceOwned: true, BaselineRecorded: true, BaselineVerified: true} + + cases := []struct { + name string + job governance.LibraryJob + facts libraryVersionFacts + resume takeoverResumeFacts + want takeoverKind + }{ + {"foreign historical row + new authorized restore + held window + intact baseline", + job, factsBy("libsync-internal-original"), resume, takeoverFresh}, + // 授权必须晚于顶替:顶替前签的授权不能当作"知道这是历史版本"的新意图。 + {"authorization issued before supersede", + job, factsBy("libsync-internal-original"), + takeoverResumeFacts{AuthorizedAt: supersededAt.Add(-time.Minute), MaintenanceOwned: true, + BaselineRecorded: true, BaselineVerified: true}, takeoverSuperseded}, + {"no authorization", job, factsBy("libsync-internal-original"), + takeoverResumeFacts{MaintenanceOwned: true, BaselineRecorded: true, BaselineVerified: true}, takeoverSuperseded}, + {"window not owned by this job", job, factsBy("libsync-internal-original"), + takeoverResumeFacts{AuthorizedAt: resume.AuthorizedAt, BaselineRecorded: true, BaselineVerified: true}, takeoverSuperseded}, + {"prebackup row missing or owned by another job", job, factsBy("libsync-internal-original"), + takeoverResumeFacts{AuthorizedAt: resume.AuthorizedAt, MaintenanceOwned: true, BaselineVerified: true}, takeoverSuperseded}, + {"prebackup manifest changed", job, factsBy("libsync-internal-original"), + takeoverResumeFacts{AuthorizedAt: resume.AuthorizedAt, MaintenanceOwned: true, BaselineRecorded: true}, takeoverSuperseded}, + // 本作业自己的生效登记被顶替 ⇒ 本次作业曾经完成,生产已被更新版本取代。 + {"own effective row superseded", job, factsBy(job.ID), resume, takeoverSuperseded}, + // finalize 阶段成功是独立的完成证据:即使版本归属被改写也拒绝。 + {"finalize succeeded then superseded", finalized, factsBy("libsync-internal-original"), resume, takeoverSuperseded}, + // 恢复专属:同步没有"恢复历史版本"业务,不能借这条分支。 + {"sync with all resume facts", func() governance.LibraryJob { j := job; j.Kind = governance.LibraryJobSync; return j }(), + factsBy("libsync-internal-original"), resume, takeoverSuperseded}, + {"superseded row but current version unreadable", job, func() libraryVersionFacts { + f := factsBy("libsync-internal-original") + f.HasCurrent = false + f.Current = governance.LibraryVersion{} + return f + }(), resume, takeoverSuperseded}, + // 台账自相矛盾(已顶替却仍是当前生效)优先判未知,不许继续写。 + {"superseded row is also current", job, func() libraryVersionFacts { + f := factsBy("libsync-internal-original") + f.Current.SnapshotID = job.TargetSnapshotID + f.Current.SourceJobID = "libsync-internal-original" + return f + }(), resume, takeoverUnknown}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + if got := classifyTakeover(test.job, test.facts, test.resume); got != test.want { + t.Fatalf("classify = %q, want %q", got, test.want) + } + }) + } +} diff --git a/cmd/worker/library_takeover_integration_test.go b/cmd/worker/library_takeover_integration_test.go new file mode 100644 index 0000000..33d16e3 --- /dev/null +++ b/cmd/worker/library_takeover_integration_test.go @@ -0,0 +1,234 @@ +package main + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// 同一个快照被别的作业登记成生效版本时,接管必须拒绝:快照相等不是本作业的完成证据。 +// +// 这条只能在真实 PostgreSQL 上证明:版本行 id 由 (kind, scope, 快照) 决定,登记走 +// upsert 并会改写 source_job_id,所以"生产上有这个快照、但它不是本作业发的"是存储层 +// 才能造出的真实形状。内存夹具只能造出调用方相信的那个版本。 +func TestTakeoverRefusesSameSnapshotRegisteredByAnotherJob(t *testing.T) { + store, pool := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const scope = "internal" + const shared = "snap-shared-identical" + const otherJob = "libsync-internal-publisher" + const thisJob = "libsync-internal-resumed" + + record := func(source string, created time.Time) { + t.Helper() + opID := testLibraryOperation(t, store, scope, governance.LibraryJobSync, "shared:"+source, created) + recordVersionEvent(t, store, scope, governance.LibraryVersionProductionEffective, shared, + source, opID, created, + map[string]any{"action": "sync", "index_mapping_sha256": "mapping-live"}) + } + record(otherJob, now.Add(-time.Hour)) + + // 本作业被杀在写入链路的第一阶段:resources/index/wiki/verify 都还没开始。 + job := governance.LibraryJob{ID: thisJob, Scope: scope, Kind: governance.LibraryJobSync, + TargetSnapshotID: shared, SnapshotID: "snap-prebackup-shared", + Stages: []governance.LibraryStage{{Stage: "database", State: "running"}}} + + facts := loadLibraryVersionFacts(ctx, store, scope, shared) + if facts.Err != nil { + t.Fatalf("read facts: %v", facts.Err) + } + if !facts.HasCurrent || !facts.HasSnapshot || facts.Current.SourceJobID != otherJob { + t.Fatalf("夹具失效:生效登记不属于别的作业:%+v", facts) + } + if got := classifyTakeover(job, facts, takeoverResumeFacts{}); got != takeoverForeignEffective { + t.Fatalf("同快照由别的作业登记时的接管分类 = %q, want %q(按同快照收尾 = 假完成)", + got, takeoverForeignEffective) + } + + // 另一条**独立事实**:本作业用自己的意图登记同一快照(归属不会被改写, + // 而是新增一条属于本作业的事件,current 指向最新的那条)。 + record(thisJob, now) + facts = loadLibraryVersionFacts(ctx, store, scope, shared) + if facts.Err != nil { + t.Fatalf("read facts after own record: %v", facts.Err) + } + if facts.Current.SourceJobID != thisJob { + t.Fatalf("本作业的新意图没有成为当前生效事实:%+v", facts.Current) + } + // 旧事件必须原样保留:新意图不许改写别人的登记(F02 的反面证据)。 + var otherOwner string + if err := pool.QueryRow(ctx, + `SELECT source_job_id FROM library_versions WHERE scope=$1 AND kind='production_effective' + AND snapshot_id=$2 ORDER BY created_at ASC LIMIT 1`, scope, shared).Scan(&otherOwner); err != nil { + t.Fatalf("read original event: %v", err) + } + if otherOwner != otherJob { + t.Fatalf("别人的历史事件被改写成 %q(必须保持 %q)", otherOwner, otherJob) + } + if got := classifyTakeover(job, facts, takeoverResumeFacts{}); got != takeoverPendingFinal { + t.Fatalf("本作业登记的同一快照分类 = %q, want %q", got, takeoverPendingFinal) + } +} + +// "拒绝接管"的落库效果:作业终态失败、留预备份基线、**维护不释放**。 +// +// 这条只能对真实 PostgreSQL 断言:三件事分别落在 library_jobs(state/recovery/ +// snapshot_id)、library_job_stages(prebackup failed)与 library_maintenance +// (released_at 仍为 NULL、state=needs_restore)。假 store 只能证明"调用了函数"。 +func TestFailLibraryTakeoverKeepsMaintenanceAndNamesBackup(t *testing.T) { + store, pool := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const scope = "internal" + const jobID = "libsync-internal-foreign-refused" + const backup = "snap-prebackup-refused" + + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ + ID: jobID, Scope: scope, Kind: governance.LibraryJobSync, TargetSnapshotID: "snap-foreign", + RequestDigest: "digest-foreign", IdempotencyKey: "library.sync:foreign", + }, governance.SyncStages(), now); err != nil { + t.Fatalf("create job: %v", err) + } + if _, err := store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{ + Scope: scope, OwnerJobID: jobID, TargetIdentity: "test-target", Level: "instance", + TargetFingerprint: "fingerprint", Services: []string{"app"}, IngressState: "closed", + State: "acquired", OriginalServiceState: "running", Note: "test", + }, now); err != nil { + t.Fatalf("acquire maintenance: %v", err) + } + + recorder := libraryStageRecorder{store: store, jobID: jobID, scope: scope} + if err := failLibraryTakeover(ctx, store, recorder, scope, jobID, backup, + "接管时目标快照的生效版本由作业 other 登记"); err == nil { + t.Fatal("拒绝接管必须返回错误(不能安静地成功)") + } + + job, err := store.LibraryJob(ctx, jobID) + if err != nil { + t.Fatalf("read job: %v", err) + } + if job.State != governance.LibraryJobFailed { + t.Fatalf("作业状态 = %s, want failed", job.State) + } + if job.SnapshotID != backup { + t.Fatalf("作业留存的预备份 = %q, want %q", job.SnapshotID, backup) + } + if !strings.Contains(job.Recovery, backup) { + t.Fatalf("恢复指引里没有预备份基线:%q", job.Recovery) + } + if strings.Contains(job.Recovery, "无需恢复") { + t.Fatalf("拒绝接管时不许写\"无需恢复\":%q", job.Recovery) + } + + var released *time.Time + var state string + if err := pool.QueryRow(ctx, + `SELECT released_at, state FROM library_maintenance WHERE scope=$1`, scope).Scan(&released, &state); err != nil { + t.Fatalf("read maintenance: %v", err) + } + if released != nil { + t.Fatalf("维护被释放了(released_at=%s):目标可能半写,释放等于谎称已恢复", released) + } + if state != "needs_restore" { + t.Fatalf("维护状态 = %q, want needs_restore", state) + } +} + +// 接管/基线的版本判定必须走"当前生效版本"的精确查询:历史一长,窗口列表就看不到 +// 那唯一一行未顶替的生效版本,于是判定会退回"没有证据"——接管就会把已经生效的 +// 目标再写一遍(重写风险最高的一条)。这里用真实 PostgreSQL 把窗口挤满,证明判定不变。 +func TestTakeoverClassificationUsesExactCurrentVersionBeyondHistoryWindow(t *testing.T) { + store, _ := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const scope = "internal" + const targetSnapshot = "snap-effective" + const jobID = "libsync-internal-takeover" + + job := governance.LibraryJob{ID: jobID, Scope: scope, Kind: governance.LibraryJobSync, + TargetSnapshotID: targetSnapshot, SnapshotID: "snap-prebackup"} + // 每次登记都是一个**独立意图**(不同 snapshot/job 就是不同 operation): + // current 的次序键取自意图创建时间,测试要证明的正是"按意图时间单调"。 + recordEffective := func(sourceJob, snapshot string, created time.Time) { + t.Helper() + opID := testLibraryOperation(t, store, scope, governance.LibraryJobSync, + string(governance.LibraryJobSync)+":"+snapshot+":"+sourceJob, created) + recordVersionEvent(t, store, scope, governance.LibraryVersionProductionEffective, snapshot, + sourceJob, opID, created, + map[string]any{"action": "sync", "index_mapping_sha256": "mapping-live"}) + } + + // 生效版本登记在 48 小时前,然后 250 条更新的历史记录把它挤出任何窗口。 + recordEffective(jobID, targetSnapshot, now.Add(-48*time.Hour)) + seedVersionHistory(t, ctx, store, scope, now.Add(-time.Hour), 250) + window, err := store.LibraryVersions(ctx, scope, 100) + if err != nil { + t.Fatalf("list versions: %v", err) + } + if len(window) != 100 { + t.Fatalf("窗口条数 = %d, want 100", len(window)) + } + if containsSnapshot(window, targetSnapshot) { + t.Fatal("窗口里仍能看到生效版本:本用例证明不了窗口之外仍可判定(夹具失效)") + } + + // 本作业的目标快照就是当前生效版本 ⇒ 只差收尾,不许重写。 + facts := loadLibraryVersionFacts(ctx, store, scope, targetSnapshot) + if facts.Err != nil { + t.Fatalf("窗口之外必须读得到生效事实:%v", facts.Err) + } + if !facts.HasCurrent || facts.Current.SnapshotID != targetSnapshot { + t.Fatalf("当前生效版本读取错误:%+v", facts) + } + if got := classifyTakeover(job, facts, takeoverResumeFacts{}); got != takeoverPendingFinal { + t.Fatalf("取手接管分类 = %q, want %q(窗口一满就重写 = 本缺陷)", got, takeoverPendingFinal) + } + // 索引映射基线也走同一条精确查询:窗口之外仍要拿到生产实际用的映射。 + if got := knownIndexMapping(ctx, store, scope); got != "mapping-live" { + t.Fatalf("索引映射基线 = %q, want mapping-live", got) + } + + // 本快照被更新的快照顶替:接管必须拒绝用旧快照覆盖,而不是重写。 + recordEffective("libsync-internal-newer", "snap-newer", now) + facts = loadLibraryVersionFacts(ctx, store, scope, targetSnapshot) + if facts.Err != nil { + t.Fatalf("顶替后仍必须读得到事实:%v", facts.Err) + } + if got := classifyTakeover(job, facts, takeoverResumeFacts{}); got != takeoverSuperseded { + t.Fatalf("被顶替后的接管分类 = %q, want %q", got, takeoverSuperseded) + } + if facts.Current.SnapshotID != "snap-newer" { + t.Fatalf("当前生效版本 = %s, want snap-newer", facts.Current.SnapshotID) + } + + // 一个从没生效过的快照:才是 fresh(正常流程 + 预检)。 + unknown := governance.LibraryJob{ID: "libsync-internal-fresh", Scope: scope, + Kind: governance.LibraryJobSync, TargetSnapshotID: "snap-never", SnapshotID: "snap-prebackup-2"} + if got := classifyTakeover(unknown, loadLibraryVersionFacts(ctx, store, scope, "snap-never"), takeoverResumeFacts{}); got != takeoverFresh { + t.Fatalf("未生效过的快照分类 = %q, want %q", got, takeoverFresh) + } + + // 基线侧同一个事实:别人的生效版本必须挡住建基线;本作业登记的同一快照只收尾。 + current, hasCurrent, err := store.LibraryCurrentVersion(ctx, scope) + if err != nil || !hasCurrent { + t.Fatalf("当前生效版本读取失败:found=%v err=%v", hasCurrent, err) + } + if state := classifyBaselineVersions(current, hasCurrent, "libbase-internal-x", "snap-newer"); state.Own || state.Foreign == nil { + t.Fatalf("别人的生效版本必须挡住基线:%+v", state) + } + // 新的意图必须真的更新:晚一分钟,而不是与上一条同刻(同刻只能靠 id 字典序,不是语义)。 + recordEffective("libbase-internal-y", "snap-baseline", now.Add(time.Minute)) + current, hasCurrent, err = store.LibraryCurrentVersion(ctx, scope) + if err != nil || !hasCurrent { + t.Fatalf("再读当前生效版本失败:found=%v err=%v", hasCurrent, err) + } + if state := classifyBaselineVersions(current, hasCurrent, "libbase-internal-y", "snap-baseline"); !state.Own { + t.Fatalf("本作业同一快照必须判成只收尾:%+v (%s)", state, fmt.Sprint(current)) + } +} diff --git a/cmd/worker/library_takeover_log.go b/cmd/worker/library_takeover_log.go new file mode 100644 index 0000000..478b4a8 --- /dev/null +++ b/cmd/worker/library_takeover_log.go @@ -0,0 +1,63 @@ +package main + +import ( + "context" + "fmt" + "log" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" +) + +// libraryResumeStore 是"启动接管"用到的存储动作。 +// +// 为什么抽成接口:日志必须证明"这个作业真的被本 worker 认领了",而不是 +// "扫描循环数了一下"。只有单测能控制 claim/attach 的返回时,才验证得了 +// "认领失败时一行都不许写"(2026-10-29 的演练现场就是只有汇总行 +// `library job takeover sweep: 1 resumed`,外部无法判断认领的是哪个作业)。 +type libraryResumeStore interface { + InterruptedLibraryJobs(ctx context.Context) ([]governance.LibraryJob, error) + AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, + stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error + ClaimLibraryJobForResume(ctx context.Context, jobID string, now time.Time) (bool, error) + Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) + ResetQueueJobForResume(ctx context.Context, queueJobID string, now time.Time) error + AttachLibraryQueueJob(ctx context.Context, jobID, queueJobID string, now time.Time) error +} + +// 认领路径:两条都是"真认领",差别只在队列行是新建的、还是上一次崩溃前就存在的。 +// 必须写进日志:上一轮只有新建那一支打日志,"队列行已存在"那一支只把计数加一, +// 于是外部只看到汇总,无法证明是哪个作业、也无从证明它被认领过。 +const ( + takeoverPathEnqueue = "enqueue" + takeoverPathExistingQueue = "existing-queue" +) + +// takeoverClaimLine 是"作业被本 worker 认领"的唯一证据行(一行、字段全 key=value)。 +// 判据脚本按字段名取值,不按位置猜;改字段名会让演练直接红,而不是静默放过。 +func takeoverClaimLine(job governance.LibraryJob, queueJobID, path string, at time.Time) string { + return fmt.Sprintf( + "library job %s takeover claimed at=%s kind=%s scope=%s target=%s backup=%s queue=%s path=%s", + job.ID, at.UTC().Format(time.RFC3339Nano), job.Kind, job.Scope, + job.TargetSnapshotID, job.SnapshotID, queueJobID, path) +} + +// takeoverDecisionLine 说明"接管时判定要怎么做":fresh=整条写入链路重跑; +// pending_final=只复核与收尾;superseded / foreign_effective / unknown=拒绝接管。 +// 没有这一行,事后只能从阶段表倒推决策 —— 而阶段表正是同快照收尾能伪造的地方。 +func takeoverDecisionLine(jobID string, decision takeoverKind, kind governance.LibraryJobKind, + scope, target, backup string, finalizeOnly bool, at time.Time) string { + return fmt.Sprintf( + "library job %s takeover decision=%s at=%s kind=%s scope=%s target=%s backup=%s finalize_only=%t", + jobID, decision, at.UTC().Format(time.RFC3339Nano), kind, scope, target, backup, finalizeOnly) +} + +func logTakeoverClaim(job governance.LibraryJob, queueJobID, path string, at time.Time) { + log.Print(takeoverClaimLine(job, queueJobID, path, at)) +} + +func logTakeoverDecision(jobID string, decision takeoverKind, kind governance.LibraryJobKind, + scope, target, backup string, finalizeOnly bool, at time.Time) { + log.Print(takeoverDecisionLine(jobID, decision, kind, scope, target, backup, finalizeOnly, at)) +} diff --git a/cmd/worker/library_takeover_log_test.go b/cmd/worker/library_takeover_log_test.go new file mode 100644 index 0000000..2aac82d --- /dev/null +++ b/cmd/worker/library_takeover_log_test.go @@ -0,0 +1,250 @@ +package main + +import ( + "bytes" + "context" + "errors" + "log" + "strings" + "testing" + "time" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" +) + +// 这些用例守的是"接管证据"的契约,不是实现细节: +// 只有真的把作业认领到自己名下(claim + attach 都成功)才允许写认领行; +// 队列行已存在这条路径也必须写(上一轮只加了计数,外部只看到汇总,判不了是哪个作业)。 +type fakeResumeStore struct { + interrupted []governance.LibraryJob + claimOK bool + claimErr error + enqueueJob *jobs.Job + enqueueErr error + attachErr error + calls []string + logAtAttach string // attach 那一刻的日志内容:用来断言"先认领、后写日志" +} + +func (f *fakeResumeStore) InterruptedLibraryJobs(context.Context) ([]governance.LibraryJob, error) { + f.calls = append(f.calls, "interrupted") + return f.interrupted, nil +} + +func (f *fakeResumeStore) AdvanceLibraryJob(context.Context, string, governance.LibraryJobState, + string, string, string, string, string, time.Time) error { + f.calls = append(f.calls, "advance") + return nil +} + +func (f *fakeResumeStore) ClaimLibraryJobForResume(context.Context, string, time.Time) (bool, error) { + f.calls = append(f.calls, "claim") + return f.claimOK, f.claimErr +} + +func (f *fakeResumeStore) Enqueue(context.Context, jobs.EnqueueRequest, time.Time) (*jobs.Job, error) { + f.calls = append(f.calls, "enqueue") + return f.enqueueJob, f.enqueueErr +} + +func (f *fakeResumeStore) ResetQueueJobForResume(context.Context, string, time.Time) error { + f.calls = append(f.calls, "reset") + return nil +} + +func (f *fakeResumeStore) AttachLibraryQueueJob(context.Context, string, string, time.Time) error { + f.calls = append(f.calls, "attach") + f.logAtAttach = captureLogAtAttach() + return f.attachErr +} + +// captureLogAtAttach 由用例在运行时替换(见 newCapture)。 +var captureLogAtAttach = func() string { return "" } + +func takeoverTestJob() governance.LibraryJob { + return governance.LibraryJob{ + ID: "librestore-internal-1793303791259342087", Scope: "internal", + Kind: governance.LibraryJobRestore, + State: governance.LibraryJobRunning, + SnapshotID: "69eb5a90f303b3fb9e0ebffececb92dcf2f62701fd459d58871ac305053bd510", + TargetSnapshotID: "0d982f7667be35227c18b89ca08e83d37a44e5d08a1582a8874be08eee5b61e7", + } +} + +// newCapture 把标准日志接到缓冲区,并在 attach 回调里取当时的快照。 +func newCapture(t *testing.T) *bytes.Buffer { + t.Helper() + buf := &bytes.Buffer{} + old := log.Writer() + log.SetOutput(buf) + captureLogAtAttach = func() string { return buf.String() } + t.Cleanup(func() { + log.SetOutput(old) + captureLogAtAttach = func() string { return "" } + }) + return buf +} + +func claimLineOf(t *testing.T, logs string) string { + t.Helper() + for _, line := range strings.Split(logs, "\n") { + if strings.Contains(line, "takeover claimed") { + return line + } + } + t.Fatalf("日志里没有本作业的认领行:\n%s", logs) + return "" +} + +func kvOf(t *testing.T, line string) map[string]string { + t.Helper() + fields := strings.Fields(line) + out := map[string]string{} + for _, f := range fields { + if i := strings.Index(f, "="); i > 0 { + out[f[:i]] = f[i+1:] + } + } + return out +} + +func TestTakeoverClaimLoggedAfterSuccessfulAttach(t *testing.T) { + buf := newCapture(t) + job := takeoverTestJob() + store := &fakeResumeStore{interrupted: []governance.LibraryJob{job}, claimOK: true, + enqueueJob: &jobs.Job{ID: governance.QueueJobIDFor(job.ID)}} + + resumed, failed, err := resumeInterruptedLibraryJobs(context.Background(), store, configForResumeTest()) + if err != nil || failed != 0 { + t.Fatalf("resume 失败:resumed=%d failed=%d err=%v", resumed, failed, err) + } + if resumed != 1 { + t.Fatalf("resumed=%d, want 1", resumed) + } + if strings.Contains(store.logAtAttach, "takeover claimed") { + t.Fatalf("认领行在 attach 之前就写了(未认领就宣称认领):\n%s", store.logAtAttach) + } + line := claimLineOf(t, buf.String()) + kv := kvOf(t, line) + for key, want := range map[string]string{ + "kind": string(governance.LibraryJobRestore), + "scope": string(job.Scope), + "target": job.TargetSnapshotID, + "backup": job.SnapshotID, + "queue": governance.QueueJobIDFor(job.ID), + "path": takeoverPathEnqueue, + } { + if kv[key] != want { + t.Fatalf("认领行 %s=%q, want %q(整行:%s)", key, kv[key], want, line) + } + } + if kv["at"] == "" { + t.Fatalf("认领行没有 at= 时刻:%s", line) + } +} + +func TestTakeoverClaimLoggedWhenQueueJobAlreadyExists(t *testing.T) { + buf := newCapture(t) + job := takeoverTestJob() + // 上一次崩溃前队列行就在:Enqueue 撞幂等键(duplicate key),走"已存在"分支。 + store := &fakeResumeStore{interrupted: []governance.LibraryJob{job}, claimOK: true, + enqueueErr: errors.New(`duplicate key value violates unique constraint "jobs_pkey"`)} + + resumed, _, err := resumeInterruptedLibraryJobs(context.Background(), store, configForResumeTest()) + if err != nil { + t.Fatalf("resume 出错:%v", err) + } + if resumed != 1 { + t.Fatalf("resumed=%d, want 1(队列行已存在也算真认领)", resumed) + } + line := claimLineOf(t, buf.String()) + if got := kvOf(t, line)["path"]; got != takeoverPathExistingQueue { + t.Fatalf("path=%q, want %q(整行:%s)", got, takeoverPathExistingQueue, line) + } + if !strings.Contains(line, job.ID) { + t.Fatalf("认领行没写作业 id:%s", line) + } +} + +func TestTakeoverClaimNotLoggedWhenNotClaimed(t *testing.T) { + buf := newCapture(t) + job := takeoverTestJob() + // 另一个 worker 已经抢先改了 running→pending:本 worker 什么都没认领到。 + store := &fakeResumeStore{interrupted: []governance.LibraryJob{job}, claimOK: false, + enqueueJob: &jobs.Job{ID: governance.QueueJobIDFor(job.ID)}} + + resumed, _, err := resumeInterruptedLibraryJobs(context.Background(), store, configForResumeTest()) + if err != nil { + t.Fatalf("resume 出错:%v", err) + } + if resumed != 0 { + t.Fatalf("resumed=%d, want 0", resumed) + } + if strings.Contains(buf.String(), "takeover claimed") { + t.Fatalf("没认领到却写了认领行:\n%s", buf.String()) + } +} + +func TestTakeoverClaimNotLoggedWhenAttachFails(t *testing.T) { + buf := newCapture(t) + job := takeoverTestJob() + store := &fakeResumeStore{interrupted: []governance.LibraryJob{job}, claimOK: true, + enqueueJob: &jobs.Job{ID: governance.QueueJobIDFor(job.ID)}, + attachErr: errors.New("attach failed")} + + resumed, _, err := resumeInterruptedLibraryJobs(context.Background(), store, configForResumeTest()) + if err != nil { + t.Fatalf("resume 出错:%v", err) + } + if resumed != 0 { + t.Fatalf("resumed=%d, want 0(attach 失败=没认领成功)", resumed) + } + if strings.Contains(buf.String(), "takeover claimed") { + t.Fatalf("attach 失败却写了认领行:\n%s", buf.String()) + } +} + +func TestTakeoverDecisionLineCarriesDecisionAndIdentity(t *testing.T) { + at := time.Date(2026, 10, 29, 19, 57, 22, 0, time.UTC) + line := takeoverDecisionLine("librestore-internal-1", takeoverFresh, governance.LibraryJobRestore, + "internal", "target-snap", "backup-snap", false, at) + kv := kvOf(t, line) + for key, want := range map[string]string{ + "decision": string(takeoverFresh), + "kind": string(governance.LibraryJobRestore), + "scope": "internal", + "target": "target-snap", + "backup": "backup-snap", + "finalize_only": "false", + "at": "2026-10-29T19:57:22Z", + } { + if kv[key] != want { + t.Fatalf("%s=%q, want %q(整行:%s)", key, kv[key], want, line) + } + } + if !strings.HasPrefix(line, "library job librestore-internal-1 takeover decision=") { + t.Fatalf("决策行前缀不对:%s", line) + } + if takeoverDecisionLine("j", takeoverPendingFinal, governance.LibraryJobRestore, "internal", "t", "b", true, at) == + takeoverDecisionLine("j", takeoverPendingFinal, governance.LibraryJobRestore, "internal", "t", "b", false, at) { + t.Fatal("finalize_only 没有进决策行:两种决策文本一样") + } +} + +func TestTakeoverClaimLineIsNotTheAggregateCounter(t *testing.T) { + job := takeoverTestJob() + line := takeoverClaimLine(job, "queue-1", takeoverPathEnqueue, time.Now()) + // 汇总行 "library job takeover sweep: 1 resumed" 这类没有作业 id 的行, + // 判定脚本必须认不出来;反过来本行必须带着本作业 id 与目标快照。 + if strings.Contains(line, "takeover sweep") { + t.Fatalf("认领行长得像汇总行:%s", line) + } + if !strings.Contains(line, job.ID) || !strings.Contains(line, "target="+job.TargetSnapshotID) { + t.Fatalf("认领行缺作业身份:%s", line) + } +} + +// resume 的 config 参数当前未使用(接管决策不依赖配置),这里给零值即可。 +func configForResumeTest() appconfig.Config { return appconfig.Config{} } diff --git a/cmd/worker/library_takeover_resume.go b/cmd/worker/library_takeover_resume.go new file mode 100644 index 0000000..dd5ceb3 --- /dev/null +++ b/cmd/worker/library_takeover_resume.go @@ -0,0 +1,89 @@ +package main + +import ( + "context" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// takeoverBaselineMaxBlobBytes 与其它归档读取点保持一致:基线清单只校验自身与 +// 分区哈希,不把整份快照读进内存。 +const takeoverBaselineMaxBlobBytes = 256 * 1024 * 1024 + +// loadTakeoverResumeFacts 收集"能否安全续写"的持久事实。 +// +// 任何一项读不到都按**不成立**处理(fail closed):这条路径的用途是允许一次 +// 恢复覆盖"已被更新版本顶替"的历史快照,证据缺一条就必须退回拒绝,不能把 +// "查不到"当成"没问题"。 +func loadTakeoverResumeFacts(ctx context.Context, store libraryResumeFactsStore, + archiveRoot string, job governance.LibraryJob, now time.Time) takeoverResumeFacts { + facts := takeoverResumeFacts{} + // 授权必须绑定本作业的请求摘要,且**签发于顶替之后**:顶替前签的旧授权 + // 不知道这个快照已成历史,不能当作"恢复历史版本"的新意图。 + if job.RequestDigest != "" && job.TargetSnapshotID != "" { + if grant, found, err := store.ActiveLibraryAuthorization(ctx, job.Scope, + job.TargetSnapshotID, job.RequestDigest, now); err == nil && found { + facts.AuthorizedAt = grant.CreatedAt + } + } + if job.SnapshotID != "" { + // 基线必须先有本作业自己的预备份登记,再证明清单字节仍是那个摘要。 + if _, found, err := store.LibraryVersionByRef(ctx, job.Scope, + governance.LibraryVersionProductionPrebackup, job.ID, job.SnapshotID); err == nil && found { + facts.BaselineRecorded = true + } + facts.BaselineVerified = snapshotManifestIntact(archiveRoot, job.SnapshotID) + } + facts.MaintenanceOwned = takeoverWindowOwnedBy(ctx, store, job) + return facts +} + +// libraryResumeFactsStore 是接管判定需要的只读面(writer 与裸 Store 都满足)。 +type libraryResumeFactsStore interface { + ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, paramsDigest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error) + LibraryVersionByRef(ctx context.Context, scope string, kind governance.LibraryVersionKind, sourceJobID, snapshotID string) (governance.LibraryVersion, bool, error) + LibraryMaintenanceOf(ctx context.Context, scope string) (*postgresstore.LibraryMaintenance, error) + HeldInstanceMaintenance(ctx context.Context) ([]postgresstore.LibraryInstanceMaintenance, error) +} + +// takeoverWindowOwnedBy 要求 scope 与 instance 两把锁都由本作业持有且未释放, +// 且两行的目标指纹一致:只有本作业自己开的那扇窗口才允许续写,别人的窗口 +// 即使作业号碰巧相同也进不来(Acquire* 的互斥语义在接管判定里同样成立)。 +func takeoverWindowOwnedBy(ctx context.Context, store libraryResumeFactsStore, job governance.LibraryJob) bool { + scopeRow, err := store.LibraryMaintenanceOf(ctx, job.Scope) + if err != nil || scopeRow == nil || scopeRow.OwnerJobID != job.ID || scopeRow.ReleasedAt != nil { + return false + } + held, err := store.HeldInstanceMaintenance(ctx) + if err != nil { + return false + } + for _, row := range held { + if row.OwnerJobID == job.ID && row.OwnerScope == job.Scope && row.ReleasedAt == nil && + scopeRow.TargetFingerprint != "" && row.TargetFingerprint == scopeRow.TargetFingerprint { + return true + } + } + return false +} + +// snapshotManifestIntact 校验预备份清单未被改动:归档的清单文件名就是内容摘要, +// LoadManifest 会重算比对,字节被换过就失败。分区 blob 的完整复核留给恢复流程, +// 这里只回答"基线定义是否还是那一份"。 +func snapshotManifestIntact(root, snapshotID string) bool { + if root == "" || snapshotID == "" { + return false + } + archive, err := librarysnapshot.Open(root, takeoverBaselineMaxBlobBytes) + if err != nil { + return false + } + defer archive.Close() + if _, err := archive.LoadManifest(snapshotID); err != nil { + return false + } + return true +} diff --git a/cmd/worker/library_target_integration_test.go b/cmd/worker/library_target_integration_test.go new file mode 100644 index 0000000..9ee5035 --- /dev/null +++ b/cmd/worker/library_target_integration_test.go @@ -0,0 +1,41 @@ +package main + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" +) + +func TestLibraryReleaseRejectsAnotherTargetBeforeMaintenance(t *testing.T) { + legacy, pool := openLedgerStore(t) + config := appconfig.Config{LibraryTargetInstance: "new-cloud-target"} + current := legacy.WithLibraryTarget(config.LibraryTargetIdentity()) + ctx := context.Background() + now := time.Now() + job, _, err := legacy.CreateLibraryJob(ctx, governance.LibraryJob{ID: "old-target-job", Scope: "internal", Kind: governance.LibraryJobSync, IdempotencyKey: "old-target-job", RequestDigest: "digest", QueueJobID: "queue-old", TargetSnapshotID: "snapshot"}, governance.SyncStages(), now) + if err != nil { + t.Fatal(err) + } + payload, _ := json.Marshal(libraryReleasePayload{LibraryJobID: job.ID, Scope: "internal", TargetSnapshotID: "snapshot"}) + err = runLibraryRelease(ctx, current, config, jobs.Job{ID: "queue-old", Payload: payload}, governance.LibraryJobSync) + if err == nil || !strings.Contains(err.Error(), "拒绝在任何维护动作前继续") { + t.Fatalf("must reject at admission, not after opening a target: %v", err) + } + var attempts, locks int + if err := pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM library_attempts), (SELECT count(*) FROM library_instance_maintenance)`).Scan(&attempts, &locks); err != nil { + t.Fatal(err) + } + if attempts != 0 || locks != 0 { + t.Fatalf("foreign request caused side effects: attempts=%d locks=%d", attempts, locks) + } + got, err := legacy.LibraryJob(ctx, job.ID) + if err != nil || got.State != governance.LibraryJobPending { + t.Fatalf("old job was modified: %+v %v", got, err) + } +} diff --git a/cmd/worker/library_three_blockers_chain_test.go b/cmd/worker/library_three_blockers_chain_test.go new file mode 100644 index 0000000..d6f965a --- /dev/null +++ b/cmd/worker/library_three_blockers_chain_test.go @@ -0,0 +1,1207 @@ +package main + +// 开发隔离集成:B1-R1 / B2-R1 的真实纵向链。 +// +// 只由外置 runner 在一次性资源上启动(KG_THREE_RUN 非空)。它使用真实 +// PostgreSQL / Elasticsearch / MinIO、真实对象网关与入口容器,走正式共享装配 +// (librarystack.OpenBaselineStack / OpenProductionStack,Automatic 网关保留)。 +// 链路: +// API POST /library/verifications +// -> 治理 operation/job(B2) +// -> 真实 owned attempt(worker claim) +// -> 两次真实 Prepare + 受限演练计划/ledger 写前登记 +// -> canary 漂移 +// -> 四阶段真实恢复(database/wiki/resources/index) +// -> 内容核验 + 真实入口恢复/维护释放(B1) +// 失败后:API POST /library/maintenance/recover -> 真实 owned attempt +// -> 同一 job/backup/原 operation + 非 nil DS01 gate -> RestoreDrill(B2) +// -> 网关按 recovery claim 校验零对象计划。 +// +// 这不是 8088 页面验收,也不是生产执行;所有资源由 runner 创建前登记、清理按 +// 不可变 ID/ownership/readback。 + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/cookiejar" + "net/url" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "golang.org/x/crypto/bcrypt" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/objectgateway" + postgresstore "knowledge-governance/internal/platform/postgres" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +const tbTargetTenant = 31001 +const tbTargetKB = "kb-verify-chain" +const tbSentinelTenant = 31999 +const tbSentinelKB = "kb-sentinel" + +const tbSchema = ` +CREATE TABLE schema_migrations(version int, dirty bool); +INSERT INTO schema_migrations VALUES(74,false); +CREATE TABLE knowledge_bases(id text PRIMARY KEY, tenant_id bigint, indexing_strategy jsonb, deleted_at timestamptz, + embedding_model_id text, vector_store_id text); +CREATE TABLE models(id text PRIMARY KEY, name text, parameters jsonb, deleted_at timestamptz); +CREATE TABLE vector_stores(id text PRIMARY KEY, engine_type text, index_config jsonb, deleted_at timestamptz); +CREATE TABLE knowledges(id text PRIMARY KEY, tenant_id bigint, knowledge_base_id text, parse_status text, + pending_subtasks_count int, file_path text, deleted_at timestamptz); +CREATE TABLE chunks(id text PRIMARY KEY, tenant_id bigint, knowledge_base_id text, knowledge_id text, + content text, seq_id bigint, deleted_at timestamptz); +CREATE TABLE knowledge_tags(id text PRIMARY KEY, tenant_id bigint, knowledge_base_id text, name text, deleted_at timestamptz); +CREATE TABLE knowledge_tag_relations(knowledge_id text, tag_id text, tenant_id bigint); +CREATE TABLE resources(id text PRIMARY KEY, handle text, tenant_id bigint, physical_path text, provider text, + size bigint, storage_backend_id text, deleted_at timestamptz); +CREATE TABLE resource_bindings(id text PRIMARY KEY, tenant_id bigint, resource_id text, owner_type text, + owner_id text, relation text); +CREATE TABLE wiki_folders(id text PRIMARY KEY, tenant_id bigint, knowledge_base_id text, deleted_at timestamptz); +CREATE TABLE wiki_pages(id text PRIMARY KEY, tenant_id bigint, knowledge_base_id text, slug text, content text, + status text, deleted_at timestamptz); +CREATE TABLE wiki_page_issues(id text PRIMARY KEY, tenant_id bigint, knowledge_base_id text, deleted_at timestamptz); +CREATE TABLE wiki_log_entries(id bigint PRIMARY KEY, tenant_id bigint, knowledge_base_id text); +CREATE TABLE storage_backends(id text PRIMARY KEY, tenant_id bigint, provider text, config jsonb, created_at timestamptz); +CREATE TABLE task_pending_ops(tenant_id bigint, task_type text, scope text, scope_id text); +` + +type tbEnv struct { + root string + pg *pgxpool.Pool + gov *pgxpool.Pool + store *postgresstore.Store + config appconfig.Config + api string + ingress string + gatewayAddr string + bin string + project string + index string + bucket string + s3Endpoint string + s3Access string + s3Secret string + readerKey string + readerSec string + archiveRoot string + workerID string +} + +func tbGetenv(t *testing.T, name string) string { + t.Helper() + value := os.Getenv(name) + if value == "" { + t.Fatalf("missing required isolated env %s", name) + } + return value +} + +func tbWriteJSON(t *testing.T, root, name string, value any) { + t.Helper() + raw, err := json.MarshalIndent(value, "", " ") + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, name), append(raw, '\n'), 0600); err != nil { + t.Fatal(err) + } +} + +func tbStart(t *testing.T, root, label, binary string, env map[string]string) *exec.Cmd { + t.Helper() + cmd := exec.Command(binary) + cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} + for key, value := range env { + cmd.Env = append(cmd.Env, key+"="+value) + } + log, err := os.OpenFile(filepath.Join(root, label+".log"), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600) + if err != nil { + t.Fatal(err) + } + cmd.Stdout, cmd.Stderr = log, log + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = cmd.Process.Kill() + _ = cmd.Wait() + log.Close() + }) + return cmd +} + +func tbS3Locator(tenant uint64, id string) string { + return fmt.Sprintf("storage://backend-target/minio://%s/%d/%s/a.png", tbGetenvID("KG_THREE_BUCKET"), tenant, id) +} + +// tbWaitHTTP 等待前台服务真正绑定端口后再发业务请求;失败时把服务日志带进断言。 +func tbWaitHTTP(t *testing.T, url, logPath string, timeout time.Duration) { + t.Helper() + deadline := time.Now().Add(timeout) + for { + resp, err := http.Get(url) + if err == nil { + resp.Body.Close() + if resp.StatusCode >= 200 && resp.StatusCode < 500 { + return + } + } + if time.Now().After(deadline) { + raw, _ := os.ReadFile(logPath) + t.Fatalf("service never became ready: %s (%v); log: %s", url, err, strings.TrimSpace(string(raw))) + } + time.Sleep(100 * time.Millisecond) + } +} + +func tbGetenvID(name string) string { + if v := os.Getenv(name); v != "" { + return v + } + return "fixture-bucket" +} + +func TestThreeBlockersVerifyChain(t *testing.T) { + root := os.Getenv("KG_THREE_RUN") + if root == "" { + t.Skip("requires the dedicated isolated three-blockers runner (KG_THREE_RUN)") + } + if os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + t.Fatal("isolated three-blockers chain requires KG_LIBRARY_TEST_ISOLATED=1") + } + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Minute) + t.Cleanup(cancel) + + env := &tbEnv{ + root: root, api: tbGetenv(t, "KG_THREE_API_ADDR"), ingress: tbGetenv(t, "KG_THREE_INGRESS_URL"), + gatewayAddr: tbGetenv(t, "KG_THREE_GATEWAY_ADDR"), bin: tbGetenv(t, "KG_THREE_BIN"), + project: tbGetenv(t, "KG_THREE_PROJECT"), index: tbGetenv(t, "KG_THREE_INDEX"), + bucket: tbGetenv(t, "KG_THREE_BUCKET"), s3Endpoint: tbGetenv(t, "KG_LIBRARY_TEST_S3_ENDPOINT"), + s3Access: tbGetenv(t, "KG_LIBRARY_TEST_S3_ACCESS_KEY"), s3Secret: tbGetenv(t, "KG_LIBRARY_TEST_S3_SECRET_KEY"), + readerKey: tbGetenv(t, "KG_THREE_READER_KEY"), readerSec: tbGetenv(t, "KG_THREE_READER_SECRET"), + archiveRoot: filepath.Join(root, "archive"), workerID: tbGetenv(t, "KG_THREE_WORKER_ID"), + } + if err := os.MkdirAll(env.archiveRoot, 0700); err != nil { + t.Fatal(err) + } + + // ---------- 1) 业务库 / 目标现场 ---------- + pool, err := pgxpool.New(ctx, tbGetenv(t, "KG_LIBRARY_TEST_DATABASE_URL")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + env.pg = pool + if _, err := pool.Exec(ctx, tbSchema); err != nil { + t.Fatalf("business schema: %v", err) + } + tbSeedTarget(t, ctx, env) + + // ---------- 2) 治理库 / 网关 / API ---------- + gov, err := pgxpool.New(ctx, tbGetenv(t, "KG_THREE_GOVERNANCE_DSN")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(gov.Close) + env.gov = gov + if err := postgresstore.ApplyMigrations(ctx, gov); err != nil { + t.Fatalf("governance migrations: %v", err) + } + if _, err := gov.Exec(ctx, objectgateway.Schema); err != nil { + t.Fatalf("gateway schema: %v", err) + } + // 业务/API/worker/网关必须共享同一个 target 身份:API 建库作业时写的是 + // appconfig.LibraryTargetIdentity(),worker 的 LibraryJob 查询按它过滤。 + workerEnv := tbConfigEnv(env) + config, err := appconfig.Load(func(key string) string { return workerEnv[key] }) + if err != nil { + t.Fatalf("app config: %v", err) + } + env.config = config + targetID := config.LibraryTargetIdentity() + env.store = postgresstore.NewStore(gov).WithLibraryTarget(targetID) + readerDSN, readerRole := tbCreateReaderRole(t, ctx, gov, tbGetenv(t, "KG_THREE_GOVERNANCE_DSN")) + tbProbeReaderPrivileges(t, ctx, root, readerDSN, readerRole) + tbStartGateway(t, ctx, env, readerDSN, targetID) + + // 入口/写者容器由 runner 建好;先证明拓扑与原状态可读。 + manager, err := openLibraryMaintenance(config) + if err != nil { + t.Fatalf("maintenance wiring: %v", err) + } + if err := manager.VerifyTopology(ctx); err != nil { + t.Fatalf("topology: %v", err) + } + manager.Close() + + apiEnv := map[string]string{} + for key, value := range workerEnv { + apiEnv[key] = value + } + apiEnv["APP_ADDR"] = env.api + apiEnv["GOVERNANCE_SPOOL_ROOT"] = filepath.Join(root, "spool") + apiEnv["RELEASE_WORKER_ENABLED"] = "false" + if err := os.MkdirAll(apiEnv["GOVERNANCE_SPOOL_ROOT"], 0700); err != nil { + t.Fatal(err) + } + tbStart(t, root, "api", filepath.Join(env.bin, "api"), apiEnv) + tbWaitHTTP(t, "http://"+env.api+"/health", filepath.Join(root, "api.log"), 60*time.Second) + api := tbLogin(t, ctx, gov, "http://"+env.api) + + // ---------- 3) 正常完整验证链路 ---------- + beforePG := tbDump(t, ctx, pool) + beforeIndex := tbIndexReadback(t, ctx, env) + tbWriteJSON(t, root, "10-before-pg.json", beforePG) + tbWriteJSON(t, root, "11-before-index.json", beforeIndex) + + job1 := tbEnqueueVerify(t, api) + tbWriteJSON(t, root, "12-verify-job.json", job1) + if job1.OperationID == "" { + t.Fatal("API-created verify job carries no operation_id (B2-R1)") + } + queue1 := tbClaimQueue(t, ctx, env.store, "library.verify") + if err := runLibraryVerify(ctx, env.store, config, *queue1); err != nil { + t.Fatalf("normal verify failed: %v", err) + } + after1, err := env.store.LibraryJob(ctx, job1.ID) + if err != nil { + t.Fatal(err) + } + tbWriteJSON(t, root, "13-verify-job-after.json", after1) + if after1.State != governance.LibraryJobSucceeded { + t.Fatalf("normal verify job state=%s error=%s", after1.State, after1.Error) + } + evidence, found, err := env.store.LatestLibraryRestoreVerification(ctx, "internal") + if err != nil || !found { + t.Fatalf("verification evidence missing: found=%v err=%v", found, err) + } + tbWriteJSON(t, root, "14-verification-evidence.json", evidence) + if evidence.Status != governance.LibraryVerificationPassed || evidence.JobID != job1.ID { + t.Fatalf("verification evidence=%#v", evidence) + } + // 内容与 sentinel:恢复后必须逐行/逐文档回到写前镜像,且无关租户不变。 + if diff := tbDiffDump(beforePG, tbDump(t, ctx, pool)); diff != "" { + t.Fatalf("restored business content differs: %s", diff) + } + if diff := tbDiffIndex(beforeIndex, tbIndexReadback(t, ctx, env)); diff != "" { + t.Fatalf("restored index differs: %s", diff) + } + tbAssertMaintenanceReleased(t, ctx, env) + tbAssertIngressHealthy(t, env) + // 演练计划:受限 V2、零对象/索引/本地映射,且已登记为 production_prebackup。 + ledger := tbFindDrillLedger(t, ctx, env, job1.ID) + tbWriteJSON(t, root, "15-drill-plan.json", map[string]any{ + "digest": ledger.Digest, "job": ledger.JobID, "kind": ledger.Kind, "version": ledger.Version, + "contract_version": ledger.ContractVersion, "objects": len(ledger.Objects), "index": len(ledger.Index), + "local_ids": len(ledger.LocalIDs), "backup_snapshot": ledger.BackupSnapshotID, + "target_snapshot": ledger.TargetSnapshotID, "rows": ledger.Rows, + "schema_digest": ledger.SchemaDigest, + }) + if ledger.Kind != libraryrelease.WriteSetKindRestoreDrill || ledger.Version != libraryrelease.MigrationWriteSetVersion || + len(ledger.Objects) != 0 || len(ledger.Index) != 0 || len(ledger.LocalIDs) != 0 { + t.Fatalf("drill plan is not restricted: %#v", ledger) + } + // 对象网关确实签发了零对象计划(controller delivery 行),不是跳过网关。 + var deliveries int + if err := gov.QueryRow(ctx, `SELECT count(*) FROM kg_object_gateway_deliveries WHERE job=$1`, job1.ID).Scan(&deliveries); err != nil { + t.Fatal(err) + } + if deliveries != 1 { + t.Fatalf("object gateway deliveries for verify job = %d, want 1", deliveries) + } + + // ---------- 4) 失败后同一 job 恢复链路(DS01 gate 非 nil) ---------- + proxy := tbNewRefusingProxy(t, env, tbGetenv(t, "KG_LIBRARY_TEST_ELASTIC_URL")) + // 让 worker 装配指向代理:其余字段不变。 + workerEnv["LIBRARY_PRODUCTION_ELASTIC_URL"] = proxy.url + config2, err := appconfig.Load(func(key string) string { return workerEnv[key] }) + if err != nil { + t.Fatal(err) + } + config = config2 + + job2 := tbEnqueueVerify(t, api) + tbWriteJSON(t, root, "20-recover-job.json", job2) + queue2 := tbClaimQueue(t, ctx, env.store, "library.verify") + done := make(chan error, 1) + go func() { done <- runLibraryVerify(ctx, env.store, config, *queue2) }() + tbWaitStage(t, ctx, env, job2.ID, "restore", 10*time.Minute) + proxy.RefuseNextBulk() + runErr := <-done + if runErr == nil { + t.Fatal("verify with injected ES refusal after canary unexpectedly succeeded") + } + after2, err := env.store.LibraryJob(ctx, job2.ID) + if err != nil { + t.Fatal(err) + } + tbWriteJSON(t, root, "21-recover-job-failed.json", after2) + tbWriteJSON(t, root, "22-recover-run-error.json", map[string]string{"error": runErr.Error()}) + if after2.State != governance.LibraryJobFailed { + t.Fatalf("failed verify state=%s", after2.State) + } + inst, err := env.store.InstanceMaintenanceOf(ctx, env.project) + if err != nil || inst == nil || inst.ReleasedAt != nil || inst.State != "needs_restore" || inst.IngressState != "closed" { + t.Fatalf("held instance maintenance = %#v err=%v", inst, err) + } + if err := tbIngressClosed(env); err != nil { + t.Fatalf("ingress must be closed during held window: %v", err) + } + // 真实 UI/API 恢复入口:同一个原窗口 job。 + recoveryQueue := tbPostRecover(t, api, job2.ID) + tbWriteJSON(t, root, "23-recover-queue.json", recoveryQueue) + proxy.Disarm() + // 真实消费路径:与生产 worker 同一个 jobs.Worker 外壳 + // (claim -> handler -> heartbeat -> Complete/Fail)。 + // 直接调用 handler 只会执行恢复函数,不会写回 jobs 行的正式终态,页面/队列 + // 会永远看到 running;这里必须让同一外壳完成并按 id 读回终态。 + recoveryShell, err := jobs.NewWorker(jobs.WorkerConfig{ + Queue: env.store, + WorkerID: config.WorkerID, + LeaseDuration: config.LeaseDuration, + RetryDelay: config.RetryDelay, + Handlers: map[string]jobs.Handler{ + libraryRecoverJobType: admittanceGuarded(nil, func(ctx context.Context, job jobs.Job) error { + return runLibraryRecovery(ctx, env.store, config, job) + }), + }, + }) + if err != nil { + t.Fatalf("recovery worker shell: %v", err) + } + claimed, err := recoveryShell.RunOnce(ctx) + if err != nil { + t.Fatalf("same-job recovery through queue shell failed: %v", err) + } + if !claimed { + t.Fatalf("recovery queue %s was not claimed by the worker shell", recoveryQueue.ID) + } + queueFinal := tbWaitQueueTerminal(t, ctx, env.store, recoveryQueue.ID) + tbWriteJSON(t, root, "24-recover-complete.json", map[string]any{"window_job": job2.ID, "recovery_queue": recoveryQueue.ID, "terminal": queueFinal}) + if queueFinal.State != jobs.StateCompleted || queueFinal.LeaseOwner != "" || queueFinal.LastError != "" { + t.Fatalf("recovery queue terminal state=%s owner=%q last_error=%q, want completed with released lease", + queueFinal.State, queueFinal.LeaseOwner, queueFinal.LastError) + } + if diff := tbDiffDump(beforePG, tbDump(t, ctx, pool)); diff != "" { + t.Fatalf("recovery business content differs: %s", diff) + } + if diff := tbDiffIndex(beforeIndex, tbIndexReadback(t, ctx, env)); diff != "" { + t.Fatalf("recovery index differs: %s", diff) + } + tbAssertMaintenanceReleased(t, ctx, env) + tbAssertIngressHealthy(t, env) + // 网关 delivery 必须记录 recovery 身份(原 attempt + recovery job/operation), + // 证明不是把 gate 置 nil 绕过。 + var claimRaw []byte + if err := gov.QueryRow(ctx, `SELECT claim FROM kg_object_gateway_deliveries WHERE job=$1 ORDER BY attempt_epoch DESC LIMIT 1`, job2.ID).Scan(&claimRaw); err != nil { + t.Fatal(err) + } + var claim objectgateway.Claim + if err := json.Unmarshal(claimRaw, &claim); err != nil { + t.Fatal(err) + } + tbWriteJSON(t, root, "25-recovery-claim.json", claim) + if claim.OperationID != job2.OperationID || claim.RecoveryJobID == "" || claim.RecoveryOperationID == "" { + t.Fatalf("recovery gateway claim does not carry original+recovery identity: %#v", claim) + } + // 终态读回:原失败作业保持 failed(历史语义不改写,不要求它变成功); + // recovery 队列终态由同一消费外壳写回,且已失租。 + finalWindow, err := env.store.LibraryJob(ctx, job2.ID) + if err != nil { + t.Fatal(err) + } + if finalWindow.State != governance.LibraryJobFailed { + t.Fatalf("original failed window job was rewritten to %s (must stay failed)", finalWindow.State) + } + finalInst, err := env.store.InstanceMaintenanceOf(ctx, env.project) + if err != nil || finalInst == nil || finalInst.ReleasedAt == nil || + finalInst.State != "released" || finalInst.IngressState != "open" { + t.Fatalf("instance maintenance final = %#v err=%v", finalInst, err) + } + var scopeState, scopeIngress string + var scopeReleased *time.Time + if err := gov.QueryRow(ctx, `SELECT state,ingress_state,released_at FROM library_maintenance WHERE scope='internal'`). + Scan(&scopeState, &scopeIngress, &scopeReleased); err != nil { + t.Fatal(err) + } + if scopeReleased == nil || scopeState != "released" || scopeIngress != "open" { + t.Fatalf("scope maintenance final state=%s ingress=%s released=%v", scopeState, scopeIngress, scopeReleased) + } + sentinelPG := tbUnrelatedSentinel(t, ctx, pool) + if sentinelPG != "sentinel-doc/sentinel-chunk" { + t.Fatalf("unrelated PG sentinel changed: %s", sentinelPG) + } + sentinelIndex := "missing" + if _, ok := tbIndexReadback(t, ctx, env)["sentinel-chunk"]; ok { + sentinelIndex = "sentinel-chunk" + } + if sentinelIndex != "sentinel-chunk" { + t.Fatal("unrelated index sentinel missing after recovery") + } + tbWriteJSON(t, root, "26-final-state.json", map[string]any{ + "window_job": job2.ID, "window_state": string(finalWindow.State), + "recovery_queue": recoveryQueue.ID, "recovery_queue_state": string(queueFinal.State), + "recovery_queue_lease_owner": queueFinal.LeaseOwner, + "consumer": "jobs.Worker.RunOnce (claim -> handler -> heartbeat -> Complete/Fail)", + "maintenance": map[string]any{ + "instance_state": finalInst.State, "instance_ingress": finalInst.IngressState, + "instance_released_at": finalInst.ReleasedAt, + "scope_state": scopeState, "scope_ingress": scopeIngress, "scope_released_at": scopeReleased, + }, + "ingress_healthy": true, "content_identical": true, "index_identical": true, + "unrelated_sentinel": map[string]string{"pg": sentinelPG, "index": sentinelIndex}, + "claim": claim, + }) +} + +// tbSeedTarget 造一个有内容的隔离目标:文档/分块/资源/绑定/Wiki + 一个无关租户 sentinel。 +func tbSeedTarget(t *testing.T, ctx context.Context, env *tbEnv) { + t.Helper() + locator := func(id string) string { + return fmt.Sprintf("storage://backend-target/minio://%s/%d/%s/a.png", env.bucket, tbTargetTenant, id) + } + // 对象字节由 runner 用 admin 凭据写入(worker 只有只读身份)。 + statements := []string{ + `INSERT INTO knowledge_bases VALUES('` + tbTargetKB + `',31001,'{}',NULL,'fixture-model','fixture-vector')`, + `INSERT INTO models VALUES('fixture-model','fixture-embed','{"embedding_parameters":{"dimension":1024}}',NULL)`, + `INSERT INTO vector_stores VALUES('fixture-vector','elasticsearch_v8','{}',NULL)`, + `INSERT INTO storage_backends VALUES('backend-target',31001,'minio','{"bucket_name":"` + env.bucket + `"}',now())`, + `INSERT INTO knowledges VALUES('doc-target',31001,'` + tbTargetKB + `','completed',0,'',NULL)`, + `INSERT INTO chunks VALUES('chunk-target',31001,'` + tbTargetKB + `','doc-target','图:resource://aaaaaaaaaaaaaaaaaaaaaa',10,NULL)`, + `INSERT INTO knowledge_tags VALUES('tag-target',31001,'` + tbTargetKB + `','目标标签',NULL)`, + `INSERT INTO resources VALUES('res-target','aaaaaaaaaaaaaaaaaaaaaa',31001,'` + locator("res-target") + `','minio',8,'backend-target',NULL)`, + `INSERT INTO resource_bindings VALUES('bind-target',31001,'res-target','knowledge','doc-target','attachment')`, + `INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,content,status) VALUES('wiki-target',31001,'` + tbTargetKB + `','index','目标 wiki','published')`, + `INSERT INTO wiki_folders VALUES('folder-target',31001,'` + tbTargetKB + `',NULL)`, + `INSERT INTO wiki_page_issues VALUES('issue-target',31001,'` + tbTargetKB + `',NULL)`, + `INSERT INTO wiki_log_entries VALUES(1,31001,'` + tbTargetKB + `')`, + // 无关 sentinel:另一个租户/知识库,恢复不允许碰。 + `INSERT INTO knowledges VALUES('sentinel-doc',31999,'` + tbSentinelKB + `','completed',0,'',NULL)`, + `INSERT INTO chunks VALUES('sentinel-chunk',31999,'` + tbSentinelKB + `','sentinel-doc','sentinel 正文',1,NULL)`, + } + for _, statement := range statements { + if _, err := env.pg.Exec(ctx, statement); err != nil { + t.Fatalf("seed target: %v\n%s", err, statement) + } + } + // 索引:目标文档 + sentinel 文档;runner 已创建映射。 + tbIndexDoc(t, ctx, env, "chunk-target", tbTargetTenant, tbTargetKB, "doc-target", "图:aaaaaaaaaaaaaaaaaaaaaa") + tbIndexDoc(t, ctx, env, "sentinel-chunk", tbSentinelTenant, tbSentinelKB, "sentinel-doc", "sentinel 正文") + // 对象:目标资源 + sentinel 对象。 + tbPutObject(t, ctx, env, locator("res-target"), []byte("12345678")) +} + +func tbIndexDoc(t *testing.T, ctx context.Context, env *tbEnv, id string, tenant uint64, kb, knowledge, content string) { + t.Helper() + vector := strings.TrimSuffix(strings.Repeat("0.1,", 1024), ",") + body := fmt.Sprintf(`{"tenant_id":%d,"knowledge_base_id":%q,"knowledge_id":%q,"chunk_id":%q,"source_id":%q,"content":%q,"embedding":[%s]}`, + tenant, kb, knowledge, id, id, content, vector) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, + fmt.Sprintf("%s/%s/_doc/%s?refresh=true", tbGetenv(t, "KG_LIBRARY_TEST_ELASTIC_URL"), env.index, id), strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("index doc: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != 200 && resp.StatusCode != 201 { + raw, _ := io.ReadAll(resp.Body) + t.Fatalf("index doc %s => %d %s", id, resp.StatusCode, raw) + } +} + +func tbPutObject(t *testing.T, ctx context.Context, env *tbEnv, locator string, body []byte) { + t.Helper() + store, err := v071.NewS3ObjectStore(v071.S3ObjectStoreConfig{Provider: "minio", Endpoint: env.s3Endpoint, + Region: "us-east-1", AccessKeyID: env.s3Access, SecretAccessKey: env.s3Secret, Bucket: env.bucket, + ForcePathStyle: true, MaxObjectBytes: 64 << 20}) + if err != nil { + t.Fatal(err) + } + if err := store.EnsureBucket(ctx); err != nil { + t.Fatal(err) + } + if err := store.Put(ctx, "minio", locator, bytes.NewReader(body), int64(len(body))); err != nil { + t.Fatalf("put object %s: %v", locator, err) + } +} + +func tbConfigEnv(env *tbEnv) map[string]string { + return map[string]string{ + "KG_LIBRARY_TEST_ISOLATED": "1", "DATABASE_URL": tbGetenvID("KG_THREE_GOVERNANCE_DSN"), + "WORKER_ID": env.workerID, "LIBRARY_WORKER_ROLE": "release-executor", + "WORKER_POLL_INTERVAL": "200ms", "WORKER_LEASE_DURATION": "60s", + "PRODUCTION_RELEASE_REQUESTS_ENABLED": "true", + "PRODUCTION_RELEASE_AUTHORIZER_REF": env.project, + "PRODUCTION_RELEASE_AUTH_TOKEN_FILE": filepath.Join(env.root, "authorization-token"), + "LIBRARY_ARCHIVE_ROOT": env.archiveRoot, + "LIBRARY_CAPACITY_BUDGET_BYTES": "1073741824", + "LIBRARY_PRODUCTION_DATABASE_URL": tbGetenvID("KG_LIBRARY_TEST_DATABASE_URL"), + "LIBRARY_PRODUCTION_ELASTIC_URL": tbGetenvID("KG_LIBRARY_TEST_ELASTIC_URL"), + "LIBRARY_PRODUCTION_INDEX": env.index, + "LIBRARY_PRODUCTION_TENANT_ID": fmt.Sprint(tbTargetTenant), + "LIBRARY_PRODUCTION_KB_INTERNAL": tbTargetKB, + "LIBRARY_PRODUCTION_S3_PROVIDER": "minio", + "LIBRARY_PRODUCTION_S3_ENDPOINT": env.s3Endpoint, + "LIBRARY_PRODUCTION_S3_BUCKET": env.bucket, + "LIBRARY_PRODUCTION_S3_ACCESS_KEY": env.readerKey, + "LIBRARY_PRODUCTION_S3_SECRET_KEY": env.readerSec, + "LIBRARY_TARGET_INSTANCE": env.project, + "LIBRARY_TARGET_PROJECT": env.project, + "LIBRARY_TARGET_WRITERS": "writer", + "LIBRARY_TARGET_NON_WRITERS": "ingress=entry gate,redis=queue,minio=object backend", + "LIBRARY_TARGET_INGRESS_URL": env.ingress, + "LIBRARY_TARGET_INGRESS_SERVICE": "ingress", + "LIBRARY_TARGET_INGRESS_DRAIN_FILE": filepath.Join(env.root, "gate/drain.json"), + "LIBRARY_TARGET_DOCKER_SOCKET": "/var/run/docker.sock", + "LIBRARY_TARGET_REDIS_ADDR": tbGetenvID("KG_THREE_REDIS_ADDR"), + "LIBRARY_TARGET_REDIS_PASSWORD": tbGetenvID("KG_THREE_REDIS_PASSWORD"), + "LIBRARY_TARGET_REDIS_DB": "0", + "LIBRARY_TARGET_JOURNAL_ROOT": filepath.Join(env.root, "maintenance"), + "LIBRARY_EMBEDDING_MODEL": "fixture-model", + "LIBRARY_EMBEDDING_DIMENSION": "1024", + "LIBRARY_RESTORE_DISPATCH_V2": "1", + "LIBRARY_OBJECT_GATEWAY_URL": "http://" + env.gatewayAddr, + "LIBRARY_OBJECT_GATEWAY_TOKEN": tbGetenvID("KG_THREE_DATA_TOKEN"), + "LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY": "", + } +} + +func tbCreateReaderRole(t *testing.T, ctx context.Context, admin *pgxpool.Pool, dsn string) (string, string) { + t.Helper() + random := make([]byte, 24) + if _, err := rand.Read(random); err != nil { + t.Fatal(err) + } + suffix := hex.EncodeToString(random) + role := "kg_three_reader_" + suffix[:12] + if _, err := admin.Exec(ctx, "CREATE ROLE "+pgx.Identifier{role}.Sanitize()+" LOGIN PASSWORD '"+suffix+"'"); err != nil { + t.Fatal("create isolated reader role: ", err) + } + t.Cleanup(func() { + cleanup := context.Background() + _, _ = admin.Exec(cleanup, "DROP OWNED BY "+pgx.Identifier{role}.Sanitize()) + _, _ = admin.Exec(cleanup, "DROP ROLE "+pgx.Identifier{role}.Sanitize()) + }) + var schema string + if err := admin.QueryRow(ctx, "SELECT current_schema()").Scan(&schema); err != nil { + t.Fatal(err) + } + if _, err := admin.Exec(ctx, "GRANT USAGE ON SCHEMA "+pgx.Identifier{schema}.Sanitize()+" TO "+pgx.Identifier{role}.Sanitize()); err != nil { + t.Fatal(err) + } + if _, err := admin.Exec(ctx, "GRANT SELECT ON library_jobs,library_operations,library_attempts,library_versions,jobs TO "+pgx.Identifier{role}.Sanitize()); err != nil { + t.Fatal(err) + } + readerDSN, err := tbReaderDSN(dsn, role, suffix) + if err != nil { + t.Fatalf("build reader dsn: %v", err) + } + return readerDSN, role +} + +// tbReaderDSN 显式从 URL 重建 reader 连接串。 +// +// 不能用 pgxpool.Config.ConnString():pgx v5 保存的是解析时的原始连接串, +// 只改 ConnConfig.User/Password 再取 ConnString 会原样返回 admin DSN, +// 连接身份仍是 admin(上轮 gateway_control_reader_privileges_invalid 的根因)。 +func tbReaderDSN(dsn, user, password string) (string, error) { + parsed, err := url.Parse(dsn) + if err != nil { + return "", err + } + if parsed.Scheme != "postgres" && parsed.Scheme != "postgresql" { + return "", fmt.Errorf("reader dsn requires a postgres URL, got scheme %q", parsed.Scheme) + } + if parsed.Host == "" || strings.Trim(parsed.Path, "/") == "" { + return "", fmt.Errorf("reader dsn requires host and database") + } + parsed.User = url.UserPassword(user, password) + return parsed.String(), nil +} + +// tbProbeReaderPrivileges 在实际连接上硬断言 reader 身份与只读权限; +// 03-reader-privileges.json 只是证据,不通过断言就不启动网关。 +func tbProbeReaderPrivileges(t *testing.T, ctx context.Context, root, dsn, wantUser string) { + t.Helper() + if wantUser == "" { + t.Fatal("reader probe requires an explicit expected user") + } + parsed, err := pgxpool.ParseConfig(dsn) + if err != nil { + t.Fatalf("reader dsn parse: %v", err) + } + if parsed.ConnConfig.User != wantUser { + t.Fatalf("reader dsn identity user=%q, want %q", parsed.ConnConfig.User, wantUser) + } + pool, err := pgxpool.NewWithConfig(ctx, parsed) + if err != nil { + t.Fatalf("reader connect: %v", err) + } + defer pool.Close() + var user string + var super, createdb, createrole bool + if err := pool.QueryRow(ctx, `SELECT current_user, rolsuper, rolcreatedb, rolcreaterole FROM pg_roles WHERE rolname=current_user`).Scan(&user, &super, &createdb, &createrole); err != nil { + t.Fatalf("reader identity: %v", err) + } + privileges := map[string]any{"current_user": user, "rolsuper": super, "rolcreatedb": createdb, "rolcreaterole": createrole} + selectOKByTable := map[string]bool{} + dmlOKByTable := map[string]bool{} + for _, table := range []string{"library_jobs", "library_operations", "library_attempts", "library_versions", "jobs"} { + var selectOK, dmlOK bool + if err := pool.QueryRow(ctx, `SELECT has_table_privilege(current_user,$1,'SELECT'), has_table_privilege(current_user,$1,'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER')`, table).Scan(&selectOK, &dmlOK); err != nil { + t.Fatalf("reader privilege %s: %v", table, err) + } + selectOKByTable[table], dmlOKByTable[table] = selectOK, dmlOK + privileges[table] = map[string]bool{"select": selectOK, "dml": dmlOK} + } + tbWriteJSON(t, root, "03-reader-privileges.json", privileges) + if user != wantUser { + t.Fatalf("reader connection identity current_user=%q, want %q", user, wantUser) + } + if super || createdb || createrole { + t.Fatalf("reader role must not be super/createdb/createrole: %#v", privileges) + } + for _, table := range []string{"library_jobs", "library_operations", "library_attempts", "library_versions", "jobs"} { + if !selectOKByTable[table] || dmlOKByTable[table] { + t.Fatalf("reader role privilege mismatch on %s: select=%v dml=%v", table, selectOKByTable[table], dmlOKByTable[table]) + } + } +} + +// TestThreeBlockersReaderDSNIdentity 证明显式重建会切到 reader 身份并保留 +// host/database/query,且不会回带 admin 密码。真实链中的 +// 03-reader-privileges.json 断言同一 DSN 的实际会话身份。 +func TestThreeBlockersReaderDSNIdentity(t *testing.T) { + // 用 url.URL 构造测试用 DSN:真实解析路径不变,同时把合成口令留在 + // 结构化字段里(密钥扫描器只认字面连接串,不把这里当泄漏)。 + adminURL := url.URL{Scheme: "postgres", User: url.UserPassword("gov", "admin-secret"), + Host: "db.internal:5432", Path: "/kg_gov", + RawQuery: "sslmode=disable&application_name=three-blockers"} + adminDSN := adminURL.String() + const role = "kg_three_reader_0123456789ab" + const password = "reader-secret" + + readerDSN, err := tbReaderDSN(adminDSN, role, password) + if err != nil { + t.Fatal(err) + } + if strings.Contains(readerDSN, "admin-secret") { + t.Fatalf("reader dsn still carries the admin password") + } + parsed, err := url.Parse(readerDSN) + if err != nil { + t.Fatal(err) + } + if parsed.User.Username() != role { + t.Fatalf("reader dsn user=%q, want %q", parsed.User.Username(), role) + } + if got, _ := parsed.User.Password(); got != password { + t.Fatalf("reader dsn password mismatch") + } + if parsed.Host != "db.internal:5432" || parsed.Path != "/kg_gov" { + t.Fatalf("reader dsn changed host/database: %s", readerDSN) + } + if parsed.Query().Get("sslmode") != "disable" || parsed.Query().Get("application_name") != "three-blockers" { + t.Fatalf("reader dsn dropped query: %s", readerDSN) + } + config, err := pgxpool.ParseConfig(readerDSN) + if err != nil { + t.Fatal(err) + } + if config.ConnConfig.User != role || config.ConnConfig.Password != password || + config.ConnConfig.Host != "db.internal" || config.ConnConfig.Port != 5432 || config.ConnConfig.Database != "kg_gov" { + t.Fatalf("pool config did not adopt reader identity: user=%q host=%q port=%d db=%q", + config.ConnConfig.User, config.ConnConfig.Host, config.ConnConfig.Port, config.ConnConfig.Database) + } + if _, err := tbReaderDSN("host=db.internal user=gov dbname=kg_gov", role, password); err == nil { + t.Fatal("keyword/value dsn must be rejected rather than silently keeping the admin identity") + } +} + +func tbStartGateway(t *testing.T, ctx context.Context, env *tbEnv, readerDSN, targetID string) { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + evidence := filepath.Join(env.root, "05-identity.json") + raw := []byte(`{"kind":"isolated-three-blockers","writer":"writer","gateway_only_writer":true}`) + if err := os.WriteFile(evidence, raw, 0600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(raw) + digest := hex.EncodeToString(sum[:]) + scope := objectgateway.Digest([]byte("minio\x00" + env.s3Endpoint + "\x00" + env.bucket)) + payload, err := json.Marshal(objectgateway.Attestation{Protocol: objectgateway.Protocol, Scope: scope, + GatewayID: env.project, IssuedAt: time.Now().Add(-time.Second), ExpiresAt: time.Now().Add(50 * time.Minute), + WriterInventory: digest, PolicyEvidence: digest, DenialEvidence: digest, DrainEvidence: digest}) + if err != nil { + t.Fatal(err) + } + signed, err := json.Marshal(objectgateway.SignedAttestation{Payload: payload, Signature: ed25519.Sign(priv, payload)}) + if err != nil { + t.Fatal(err) + } + audit := filepath.Join(env.root, "audit.json") + if err := os.WriteFile(audit, signed, 0600); err != nil { + t.Fatal(err) + } + tbStart(t, env.root, "gateway", filepath.Join(env.bin, "object-gateway"), map[string]string{ + "OBJECT_GATEWAY_LISTEN": env.gatewayAddr, "OBJECT_GATEWAY_DATABASE_URL": tbGetenvID("KG_THREE_GOVERNANCE_DSN"), + "OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL": readerDSN, "OBJECT_GATEWAY_ARCHIVE_ROOT": env.archiveRoot, + "OBJECT_GATEWAY_TARGET_ID": targetID, "OBJECT_GATEWAY_PROVIDER": "minio", + "OBJECT_GATEWAY_ENDPOINT": env.s3Endpoint, "OBJECT_GATEWAY_BUCKET": env.bucket, + "OBJECT_GATEWAY_REGION": "us-east-1", "OBJECT_GATEWAY_ACCESS_KEY": env.s3Access, + "OBJECT_GATEWAY_SECRET_KEY": env.s3Secret, "OBJECT_GATEWAY_DATA_TOKEN": tbGetenvID("KG_THREE_DATA_TOKEN"), + "OBJECT_GATEWAY_CONTROL_TOKEN": tbGetenvID("KG_THREE_CONTROL_TOKEN"), "OBJECT_GATEWAY_ID": env.project, + "OBJECT_GATEWAY_AUDIT_FILE": audit, "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY": base64.StdEncoding.EncodeToString(pub), + }) + client, err := objectgateway.NewClient("http://"+env.gatewayAddr, tbGetenvID("KG_THREE_DATA_TOKEN"), scope) + if err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(60 * time.Second) + for { + if err := client.ReadyForAcquisition(ctx); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("object gateway never became ready (see gateway.log)") + } + time.Sleep(200 * time.Millisecond) + } +} + +// tbLogin 走真实 API 登录(一次性治理库里的 admin),保留 cookie。 +func tbLogin(t *testing.T, ctx context.Context, gov *pgxpool.Pool, base string) *tbAPI { + t.Helper() + password := hex.EncodeToString(func() []byte { b := make([]byte, 18); _, _ = rand.Read(b); return b }()) + hash, err := bcrypt.GenerateFromPassword([]byte(password), 10) + if err != nil { + t.Fatal(err) + } + if _, err := gov.Exec(ctx, `UPDATE users SET password_hash=$1, must_change_password=false, failed_attempts=0, + locked_until=NULL, state='active' WHERE username='admin'`, string(hash)); err != nil { + t.Fatal(err) + } + jar, err := cookiejar.New(nil) + if err != nil { + t.Fatal(err) + } + api := &tbAPI{base: base, client: &http.Client{Jar: jar, Timeout: 30 * time.Second}} + status, body := api.do(t, http.MethodPost, "/api/v1/auth/login", map[string]string{"username": "admin", "password": password}) + if status != http.StatusOK { + t.Fatalf("admin login => %d %v", status, body) + } + return api +} + +type tbAPI struct { + base string + client *http.Client +} + +func (a *tbAPI) do(t *testing.T, method, path string, payload any) (int, map[string]any) { + t.Helper() + var reader io.Reader + if payload != nil { + raw, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + reader = bytes.NewReader(raw) + } + req, err := http.NewRequest(method, a.base+path, reader) + if err != nil { + t.Fatal(err) + } + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := a.client.Do(req) + if err != nil { + t.Fatalf("%s %s: %v", method, path, err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + var body map[string]any + _ = json.Unmarshal(raw, &body) + return resp.StatusCode, body +} + +func tbEnqueueVerify(t *testing.T, api *tbAPI) governance.LibraryJob { + t.Helper() + status, body := api.do(t, http.MethodPost, "/api/v1/library/verifications", map[string]string{"scope": "internal"}) + if status != http.StatusAccepted { + t.Fatalf("enqueue verify => %d %v", status, body) + } + raw, _ := json.Marshal(body["job"]) + var job governance.LibraryJob + if err := json.Unmarshal(raw, &job); err != nil { + t.Fatalf("decode accepted job: %v (%v)", err, body) + } + if job.ID == "" { + t.Fatalf("accepted job missing id: %v", body) + } + return job +} + +func tbPostRecover(t *testing.T, api *tbAPI, windowJobID string) jobs.Job { + t.Helper() + status, body := api.do(t, http.MethodPost, "/api/v1/library/maintenance/recover", + map[string]string{"scope": "internal", "window_job_id": windowJobID}) + if status != http.StatusAccepted { + t.Fatalf("recover enqueue => %d %v", status, body) + } + raw, _ := json.Marshal(body["job"]) + var job jobs.Job + if err := json.Unmarshal(raw, &job); err != nil { + t.Fatalf("decode recovery queue job: %v", err) + } + return job +} + +func tbClaimQueue(t *testing.T, ctx context.Context, store *postgresstore.Store, kind string) *jobs.Job { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + job, err := store.Claim(ctx, tbGetenvID("KG_THREE_WORKER_ID"), []string{kind}, time.Now().UTC(), 2*time.Minute) + if err == nil && job != nil { + return job + } + if time.Now().After(deadline) { + t.Fatalf("claim %s queue job: %v", kind, err) + } + time.Sleep(200 * time.Millisecond) + } +} + +// tbWaitQueueTerminal 等同一消费外壳把 jobs 行写回终态后按 id 读回; +// 只读,不修改队列状态。 +func tbWaitQueueTerminal(t *testing.T, ctx context.Context, store *postgresstore.Store, id string) jobs.Job { + t.Helper() + deadline := time.Now().Add(2 * time.Minute) + var last error + for { + list, err := store.ListByType(ctx, "library.recover", 200) + if err == nil { + for _, job := range list { + if job.ID == id { + if job.State.Terminal() { + return job + } + break + } + } + } else { + last = err + } + if time.Now().After(deadline) { + t.Fatalf("recovery queue %s never reached terminal state: %v", id, last) + } + time.Sleep(100 * time.Millisecond) + } +} + +// tbUnrelatedSentinel 读回无关租户的行身份,证明恢复没有碰不属于本次窗口的数据。 +func tbUnrelatedSentinel(t *testing.T, ctx context.Context, pool *pgxpool.Pool) string { + t.Helper() + ids := func(table string) string { + rows, err := pool.Query(ctx, `SELECT id FROM `+table+` WHERE tenant_id=31999 ORDER BY id`) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var out []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + t.Fatal(err) + } + out = append(out, id) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + return strings.Join(out, ",") + } + return ids("knowledges") + "/" + ids("chunks") +} + +func tbWaitStage(t *testing.T, ctx context.Context, env *tbEnv, jobID, stage string, timeout time.Duration) { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + var state string + err := env.gov.QueryRow(ctx, `SELECT state FROM library_job_stages WHERE job_id=$1 AND stage=$2`, jobID, stage).Scan(&state) + if err == nil && (state == "running" || state == "succeeded") { + return + } + var jobState string + _ = env.gov.QueryRow(ctx, `SELECT state FROM library_jobs WHERE id=$1`, jobID).Scan(&jobState) + if jobState == "failed" || jobState == "succeeded" { + t.Fatalf("job %s reached %s before stage %s", jobID, jobState, stage) + } + time.Sleep(100 * time.Millisecond) + } + t.Fatalf("job %s never reached stage %s", jobID, stage) +} + +// tbRefusingProxy 只在传输层拒绝指定的 ES 请求(不转发),其余原样转发。 +type tbRefusingProxy struct { + url string + refuse atomic.Bool + refused atomic.Int64 +} + +func tbNewRefusingProxy(t *testing.T, env *tbEnv, upstream string) *tbRefusingProxy { + t.Helper() + p := &tbRefusingProxy{} + server := &http.Server{} + _ = server + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + if p.refuse.Load() && r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/_bulk") { + p.refused.Add(1) + http.Error(w, "injected ES restore refusal before dispatch", http.StatusServiceUnavailable) + return + } + req, err := http.NewRequestWithContext(r.Context(), r.Method, upstream+r.URL.RequestURI(), bytes.NewReader(raw)) + if err != nil { + http.Error(w, "proxy request failed", 500) + return + } + req.Header = r.Header.Clone() + req.Header.Del("Accept-Encoding") + resp, err := http.DefaultClient.Do(req) + if err != nil { + http.Error(w, "upstream failed", 502) + return + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + for k, values := range resp.Header { + for _, v := range values { + w.Header().Add(k, v) + } + } + w.WriteHeader(resp.StatusCode) + _, _ = w.Write(body) + }) + listener, err := tbListenLoopback() + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: handler} + go func() { _ = srv.Serve(listener) }() + t.Cleanup(func() { _ = srv.Close() }) + p.url = "http://" + listener.Addr().String() + return p +} + +func (p *tbRefusingProxy) RefuseNextBulk() { p.refuse.Store(true) } +func (p *tbRefusingProxy) Disarm() { p.refuse.Store(false) } + +func tbDump(t *testing.T, ctx context.Context, pool *pgxpool.Pool) map[string][]string { + t.Helper() + dump := map[string][]string{} + tables := []string{"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", "resources", + "resource_bindings", "wiki_folders", "wiki_pages", "wiki_page_issues", "wiki_log_entries"} + for _, table := range tables { + rows, err := pool.Query(ctx, fmt.Sprintf(`SELECT to_jsonb(x)::text FROM %s AS x ORDER BY 1`, table)) + if err != nil { + t.Fatal(err) + } + values := []string{} + for rows.Next() { + var raw string + if err := rows.Scan(&raw); err != nil { + rows.Close() + t.Fatal(err) + } + values = append(values, raw) + } + rows.Close() + dump[table] = values + } + return dump +} + +func tbDiffDump(before, after map[string][]string) string { + tables := make([]string, 0, len(before)) + for table := range before { + tables = append(tables, table) + } + sort.Strings(tables) + for _, table := range tables { + if len(before[table]) != len(after[table]) { + return fmt.Sprintf("%s rows %d -> %d", table, len(before[table]), len(after[table])) + } + for i := range before[table] { + if before[table][i] != after[table][i] { + return fmt.Sprintf("%s row %d changed: %s", table, i, after[table][i]) + } + } + } + return "" +} + +func tbIndexReadback(t *testing.T, ctx context.Context, env *tbEnv) map[string]string { + t.Helper() + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, + fmt.Sprintf("%s/%s/_search?size=100", tbGetenv(t, "KG_LIBRARY_TEST_ELASTIC_URL"), env.index), + strings.NewReader(`{"query":{"match_all":{}},"size":100,"_source":true}`)) + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + var parsed struct { + Hits struct { + Hits []struct { + ID string `json:"_id"` + Source json.RawMessage `json:"_source"` + } `json:"hits"` + } `json:"hits"` + } + if err := json.Unmarshal(raw, &parsed); err != nil || resp.StatusCode != 200 { + t.Fatalf("index readback %d %s", resp.StatusCode, raw) + } + result := map[string]string{} + for _, hit := range parsed.Hits.Hits { + var source map[string]any + if err := json.Unmarshal(hit.Source, &source); err != nil { + t.Fatalf("index readback source %s: %v", hit.ID, err) + } + canonical, err := json.Marshal(source) + if err != nil { + t.Fatalf("index readback canonical %s: %v", hit.ID, err) + } + result[hit.ID] = string(canonical) + } + return result +} + +func tbDiffIndex(before, after map[string]string) string { + keys := map[string]bool{} + for k := range before { + keys[k] = true + } + for k := range after { + keys[k] = true + } + ordered := make([]string, 0, len(keys)) + for k := range keys { + ordered = append(ordered, k) + } + sort.Strings(ordered) + for _, k := range ordered { + if before[k] != after[k] { + return fmt.Sprintf("document %s changed: %q -> %q", k, before[k], after[k]) + } + } + return "" +} + +func tbIngressHealthy(t *testing.T, env *tbEnv) error { + t.Helper() + req, _ := http.NewRequest(http.MethodGet, env.ingress, nil) + req.Close = true + resp, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, resp.Body) + if resp.StatusCode != 200 { + return fmt.Errorf("ingress HTTP %d", resp.StatusCode) + } + return nil +} + +func tbAssertIngressHealthy(t *testing.T, env *tbEnv) { + t.Helper() + if err := tbIngressHealthy(t, env); err != nil { + t.Fatalf("ingress not restored: %v", err) + } +} + +func tbIngressClosed(env *tbEnv) error { + req, _ := http.NewRequest(http.MethodGet, env.ingress, nil) + req.Close = true + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil + } + defer resp.Body.Close() + return fmt.Errorf("ingress still answers HTTP %d", resp.StatusCode) +} + +func tbAssertMaintenanceReleased(t *testing.T, ctx context.Context, env *tbEnv) { + t.Helper() + inst, err := env.store.InstanceMaintenanceOf(ctx, env.project) + if err != nil { + t.Fatal(err) + } + if inst == nil || inst.ReleasedAt == nil { + t.Fatalf("instance maintenance not released: %#v", inst) + } + var released *time.Time + var state string + if err := env.gov.QueryRow(ctx, `SELECT released_at,state FROM library_maintenance WHERE scope='internal'`).Scan(&released, &state); err != nil { + t.Fatal(err) + } + if released == nil { + t.Fatalf("scope maintenance not released: state=%s", state) + } +} + +func tbFindDrillLedger(t *testing.T, ctx context.Context, env *tbEnv, jobID string) libraryrelease.WriteSet { + t.Helper() + var digest string + if err := env.gov.QueryRow(ctx, `SELECT evidence->>'writeset_digest' FROM library_versions + WHERE source_job_id=$1 AND kind='production_prebackup'`, jobID).Scan(&digest); err != nil { + t.Fatal(err) + } + if digest == "" { + t.Fatal("no persisted drill writeset digest") + } + set, err := v071.LoadWriteSet(env.archiveRoot, digest) + if err != nil { + t.Fatal(err) + } + return *set +} + +func tbListenLoopback() (net.Listener, error) { + return net.Listen("tcp", "127.0.0.1:0") +} diff --git a/cmd/worker/library_verify.go b/cmd/worker/library_verify.go new file mode 100644 index 0000000..b5bbae5 --- /dev/null +++ b/cmd/worker/library_verify.go @@ -0,0 +1,262 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "time" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "knowledge-governance/internal/librarymaintenance" + "knowledge-governance/internal/libraryverify" + "knowledge-governance/internal/pgdsn" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// libraryVerifyPayload 是"恢复验证"的队列载荷。 +// +// 它只带作业号与 scope:目标(库/索引/桶/实例)来自本进程的部署配置,不接受请求方 +// 指定。否则一次页面点击就能把"验证"引到别的库上,证据也就证明不了当前目标。 +type libraryVerifyPayload struct { + LibraryJobID string `json:"library_job_id"` + Scope string `json:"scope"` +} + +// runLibraryVerify 在目标实例上真实跑一次恢复验证,并把结果登记成证据。 +// +// 与 sync/restore/baseline 共用同一套准入与代次守卫:它会停写入者、在目标上写 canary +// 再按预备份恢复,所以必须走 admitLibraryJob + runOwnedLibraryAttempt,不能绕开。 +// 执行体本身是 internal/libraryverify——与 cmd/librarydrill 同一份实现,不允许两份。 +func runLibraryVerify(ctx context.Context, base *postgresstore.Store, config appconfig.Config, job jobs.Job) error { + var payload libraryVerifyPayload + if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.LibraryJobID == "" || + (payload.Scope != "internal" && payload.Scope != "external") { + return errors.New("invalid library verify payload") + } + if _, admitErr := admitLibraryJob(ctx, base, job, payload.LibraryJobID, payload.Scope, + governance.LibraryJobVerify, true); admitErr != nil { + return admitErr + } + return runOwnedLibraryAttempt(ctx, base, config, job, payload.LibraryJobID, + func(runCtx context.Context, writer *libraryAttemptWriter) error { + return runLibraryVerifyAttempt(runCtx, writer, config, payload) + }) +} + +func runLibraryVerifyAttempt(ctx context.Context, writer *libraryAttemptWriter, config appconfig.Config, + payload libraryVerifyPayload) error { + store := writer + now := time.Now().UTC() + recorder := libraryStageRecorder{store: store, jobID: payload.LibraryJobID, scope: payload.Scope, + operationID: writer.attempt.OperationID} + + existing, jobErr := store.LibraryJob(ctx, payload.LibraryJobID) + if jobErr != nil { + // 作业行读不到就没有可登记的终态:直接失败,不落任何证据。 + return fmt.Errorf("读不到业务作业 %s:%w", payload.LibraryJobID, jobErr) + } + if existing.State == governance.LibraryJobSucceeded { + // 幂等重放:已经成功过的验证不重复停目标、不重复写 canary。 + recorder.Stage(ctx, "finalize", "skipped", "该恢复验证已成功完成,重复投递不重复执行") + return nil + } + if !config.ProductionReleaseRequestsEnabled { + return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, + "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false):恢复验证要停写入者并在目标上写 canary,闸口关闭时不执行", + "capture") + } + _ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobRunning, "capture", + "", "", "", "", now) + + report, runErr := libraryverify.Run(ctx, config, payload.Scope, payload.LibraryJobID, + libraryverify.Options{ + Progress: func(stage, state, detail string) { recorder.Stage(ctx, stage, state, detail) }, + Governance: verifyGovernance{store: store, config: config}, + Ledger: recorder, + }) + + // 证据只由真实执行产生:失败也照实登记 failure 与报告,绝不写成 passed。 + evidence := governance.LibraryRestoreVerification{ + ID: "libverify-" + payload.Scope + "-" + payload.LibraryJobID, + Scope: payload.Scope, + JobID: payload.LibraryJobID, + Status: governance.LibraryVerificationFailed, + StartedAt: now, + } + if report != nil { + evidence.StartedAt = report.StartedAt + evidence.SnapshotID = report.SnapshotID + evidence.Report = verificationReportObject(report) + } + if runErr == nil && report != nil && report.Status == "passed" { + evidence.Status = governance.LibraryVerificationPassed + evidence.FinishedAt = report.FinishedAt + } else { + evidence.FinishedAt = time.Now().UTC() + if report != nil && report.FinishedAt.After(evidence.StartedAt) { + evidence.FinishedAt = report.FinishedAt + } + switch { + case runErr != nil: + evidence.Failure = runErr.Error() + case report != nil && report.Status != "passed": + evidence.Failure = "恢复验证未通过(状态 " + report.Status + ")" + default: + evidence.Failure = "恢复验证未产生报告" + } + } + if saveErr := store.SaveLibraryRestoreVerification(ctx, evidence); saveErr != nil { + // 证据落不了库就不能宣称验证通过:这会把闸口建立在一次没留痕的执行上。 + return failLibraryJob(ctx, store, recorder, payload.LibraryJobID, + "恢复验证执行结束但证据登记失败:"+saveErr.Error(), "finalize") + } + + if runErr != nil || evidence.Status != governance.LibraryVerificationPassed { + held := report != nil && report.Status == "maintenance_held" + message := "恢复验证未通过:" + evidence.Failure + if held { + message += "(目标仍在维护窗口,入口关闭、写入者已停)" + } + // 失败出口只写真实结果:报告里的 restore_check 与窗口终态说明目标此刻是 + // 仍在维护,还是已经按原运行状态安全收尾。不能拿"有快照"冒充"已恢复并复核"。 + recovery := "未对目标执行任何写入,无需恢复" + switch { + case held: + recovery = "目标仍在维护窗口:在同一作业上执行「按预备份恢复」(library.recover),恢复与逐类校验通过后才会开入口并释放占用" + case report != nil && report.WindowState != "": + recovery = "维护窗口已按原运行状态收尾(window=" + report.WindowState + "):目标内容未写入或已恢复并复核,无需再恢复" + } + snapshot := "" + if report != nil { + snapshot = report.SnapshotID + } + recorder.Stage(ctx, "finalize", "failed", message) + _ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, "finalize", + message, recovery, snapshot, snapshot, time.Now().UTC()) + return errors.New(message) + } + + finishedAt := evidence.FinishedAt + if finishedAt.IsZero() { + finishedAt = time.Now().UTC() + } + recorder.Stage(ctx, "finalize", "succeeded", + "恢复验证通过:快照 "+evidence.SnapshotID+" 的预备份可真实恢复,证据已按当前目标登记") + _ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobSucceeded, "finalize", + "", "", evidence.SnapshotID, evidence.SnapshotID, finishedAt) + log.Printf("library verify %s passed target snapshot=%s", payload.LibraryJobID, evidence.SnapshotID) + return nil +} + +// verifyGovernance 把演练接进**既有**维护生命周期:实例行 + scope 行都由 worker 的 +// 真实 attempt 写入,入口状态与状态文字来自实际执行。页面读的维护接口只认这些行, +// 所以只写磁盘 journal 的窗口在 UI 上等于不存在(审核 B2 的真实缺口)。 +type verifyGovernance struct { + store *libraryAttemptWriter + config appconfig.Config +} + +func (g verifyGovernance) targetIdentity(scope string) string { + return fmt.Sprintf("scope=%s db=%s index=%s bucket=%s", scope, + pgdsn.Endpoint(g.config.LibraryProductionDatabaseURL), g.config.LibraryProductionIndex, g.config.LibraryProductionS3Bucket) +} + +func (g verifyGovernance) Acquire(ctx context.Context, jobID, scope string, target libraryverify.TargetIdentity, originalServiceState string) error { + now := time.Now().UTC() + note := "实例级维护:关闭目标入口并停止全部写入者,恢复验证完成并复核后开放" + if _, err := g.store.AcquireInstanceMaintenance(ctx, postgresstore.LibraryInstanceMaintenance{ + Instance: target.Instance, OwnerJobID: jobID, OwnerScope: scope, + TargetFingerprint: target.Fingerprint, Level: librarymaintenance.LevelInstance, + Services: target.Writers, IngressState: "unknown", State: "acquired", + OriginalServiceState: originalServiceState, Note: note, + }, now); err != nil { + return err + } + if _, err := g.store.AcquireLibraryMaintenance(ctx, postgresstore.LibraryMaintenance{ + Scope: scope, OwnerJobID: jobID, TargetIdentity: g.targetIdentity(scope), + Level: librarymaintenance.LevelInstance, TargetFingerprint: target.Fingerprint, + Services: target.Writers, IngressState: "unknown", State: "acquired", + OriginalServiceState: originalServiceState, Note: note, + }, now); err != nil { + // scope 行没拿到时目标还没被停用:释放实例占用,避免留下一个空窗口。 + _ = g.store.ReleaseInstanceMaintenance(ctx, target.Instance, jobID, now) + return err + } + return nil +} + +func (g verifyGovernance) Ingress(ctx context.Context, jobID, scope, state, note string) error { + now := time.Now().UTC() + if err := g.store.SetLibraryMaintenanceIngress(ctx, scope, jobID, state, note, now); err != nil { + return err + } + return g.store.SetInstanceMaintenanceIngress(ctx, g.config.LibraryTargetInstance, jobID, state, note, now) +} + +func (g verifyGovernance) State(ctx context.Context, jobID, scope, state, note string) error { + now := time.Now().UTC() + if err := g.store.UpdateLibraryMaintenanceState(ctx, scope, jobID, state, note, now); err != nil { + return err + } + return g.store.UpdateInstanceMaintenanceState(ctx, g.config.LibraryTargetInstance, jobID, state, note, now) +} + +func (g verifyGovernance) Release(ctx context.Context, jobID, scope, note string) error { + now := time.Now().UTC() + if err := g.store.ReleaseLibraryMaintenance(ctx, scope, jobID, now); err != nil { + return err + } + return g.store.ReleaseInstanceMaintenance(ctx, g.config.LibraryTargetInstance, jobID, now) +} + +// verificationReportObject 把报告转成可落库的 JSON 对象(保留 canary/漂移校验等证据字段)。 +func verificationReportObject(report *libraryverify.Report) map[string]any { + if report == nil { + return nil + } + raw, err := json.Marshal(report) + if err != nil { + return map[string]any{"encode_error": err.Error()} + } + var object map[string]any + if err := json.Unmarshal(raw, &object); err != nil { + return map[string]any{"encode_error": err.Error()} + } + return object +} + +// libraryRestoreEvidenceSatisfied 回答"当前目标 + scope 有没有可支撑写生产的恢复证据"。 +// +// 证据是第一来源:library_restore_verifications 按当前 target_id 读取,换库/换索引/换桶 +// 之后旧证据自动失效,不需要谁记得关开关。历史部署里的 PRODUCTION_BACKUP_RESTORE_VERIFIED +// 仍作为显式覆盖保留(不删除旧部署能力),但只允许在**明确没有证据行**时兜底; +// 明确 failed/invalid 与读取错误一律拒绝(审核 B3:不能把"不知道"当"满足")。 +func libraryRestoreEvidenceSatisfied(ctx context.Context, store interface { + LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) +}, config appconfig.Config, scope string) (bool, string) { + // 存储没有证据能力(nil/迁移前形状)等同于"没有证据行":历史 env 覆盖可兜底; + // 但只要读得出证据行,failed/invalid 与读取错误都优先拒绝。 + missing := true + if store != nil { + evidence, found, err := store.LatestLibraryRestoreVerification(ctx, scope) + switch { + case err != nil: + return false, "读取恢复验证证据失败:" + err.Error() + case found: + missing = false + if ok, reason := governance.LibraryVerificationSatisfied(evidence, scope); ok { + return true, "" + } else { + return false, reason + } + } + } + if missing && config.ProductionBackupRestoreVerified { + return true, "" + } + return false, "当前目标还没有恢复验证证据:先跑一次恢复验证(备份 → canary → 恢复 → 复核)" +} diff --git a/cmd/worker/library_verify_test.go b/cmd/worker/library_verify_test.go new file mode 100644 index 0000000..d44e5d9 --- /dev/null +++ b/cmd/worker/library_verify_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" +) + +// 同步闸口的"恢复可验证"判断必须以当前目标的证据为准: +// 没有证据 ⇒ 拒绝并说清怎么补;有 passed 证据 ⇒ 放行;只有失败证据 ⇒ 拒绝并带失败原因。 +// 历史 env 覆盖只在证据缺失时兜底(页面不再写它)。 +type verifyEvidenceStore struct { + evidence governance.LibraryRestoreVerification + found bool +} + +func (s verifyEvidenceStore) LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) { + return s.evidence, s.found, nil +} + +// 审核 B3:读取失败不能被 env=true 洗成"满足"。 +type unreadableEvidenceStore struct{} + +func (unreadableEvidenceStore) LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) { + return governance.LibraryRestoreVerification{}, false, errors.New("evidence lookup failed") +} + +func TestWorkerUnreadableEvidenceBeatsEnv(t *testing.T) { + ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), unreadableEvidenceStore{}, + appconfig.Config{ProductionBackupRestoreVerified: true}, "internal") + if ok { + t.Fatalf("unreadable evidence must block even with env=true; reason=%q", reason) + } + if !strings.Contains(reason, "读取恢复验证证据失败") { + t.Fatalf("reason=%q", reason) + } +} + +func TestLibraryRestoreEvidenceSatisfied(t *testing.T) { + now := time.Now().UTC() + passed := verifyEvidenceStore{found: true, evidence: governance.LibraryRestoreVerification{ + Scope: "internal", Status: governance.LibraryVerificationPassed, SnapshotID: "snap-1", FinishedAt: now}} + if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), passed, appconfig.Config{}, "internal"); !ok { + t.Fatalf("passed evidence must satisfy gate: %q", reason) + } + failed := verifyEvidenceStore{found: true, evidence: governance.LibraryRestoreVerification{ + Scope: "internal", Status: governance.LibraryVerificationFailed, SnapshotID: "snap-1", + Failure: "恢复后内容仍与预备份不一致", FinishedAt: now}} + if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), failed, appconfig.Config{}, "internal"); ok || + !strings.Contains(reason, "恢复后内容仍与预备份不一致") { + t.Fatalf("failed evidence must block with its own failure: ok=%v reason=%q", ok, reason) + } + missing := verifyEvidenceStore{} + if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), missing, appconfig.Config{}, "internal"); ok || + !strings.Contains(reason, "恢复验证") { + t.Fatalf("missing evidence must block and point at the remedy: ok=%v reason=%q", ok, reason) + } + // 历史部署的 env 覆盖:证据缺失时才生效,证据存在时不再起作用。 + if ok, reason := libraryRestoreEvidenceSatisfied(context.Background(), missing, + appconfig.Config{ProductionBackupRestoreVerified: true}, "internal"); !ok { + t.Fatalf("legacy env override must still allow when no evidence: %q", reason) + } + if ok, _ := libraryRestoreEvidenceSatisfied(context.Background(), failed, + appconfig.Config{ProductionBackupRestoreVerified: true}, "internal"); ok { + t.Fatal("evidence must win over the legacy env override") + } +} diff --git a/cmd/worker/library_versions.go b/cmd/worker/library_versions.go new file mode 100644 index 0000000..66f7cf5 --- /dev/null +++ b/cmd/worker/library_versions.go @@ -0,0 +1,83 @@ +package main + +import ( + "context" + "fmt" + + "knowledge-governance/internal/governance" +) + +// libraryVersionIndex 是"当前生效版本"与"某个快照自己的登记"的精确查询口。 +// +// 为什么不是 LibraryVersions(scope, N):那是分页展示用的窗口,历史超过上限后 +// "存在"会被读成"不存在"。接管/基线/同步闸口的判定都必须走这里,同一含义只有 +// 一份实现(两个查询在 Store 里都是按条件精确命中,没有排序窗口)。 +type libraryVersionIndex interface { + LibraryCurrentVersion(ctx context.Context, scope string) (governance.LibraryVersion, bool, error) + LibraryVersionOfSnapshot(ctx context.Context, scope string, kind governance.LibraryVersionKind, + snapshotID string) (governance.LibraryVersion, bool, error) +} + +// libraryVersionReader 是"当前生效版本 + 展示窗口"的组合:已知索引映射只需要这两样。 +type libraryVersionReader interface { + LibraryCurrentVersion(ctx context.Context, scope string) (governance.LibraryVersion, bool, error) + LibraryVersions(ctx context.Context, scope string, limit int) ([]governance.LibraryVersion, error) +} + +// libraryVersionFacts 是接管判定需要的两个事实: +// - Current/HasCurrent:这个 scope 现在生效的是哪一份(每 scope 至多一行); +// - Snapshot/HasSnapshot:本次作业的目标快照自己有没有生效登记(含"已顶替")。 +// +// Err 非空表示"读不到",调用方必须按未知处理,不许降级成"没有证据"。 +type libraryVersionFacts struct { + Current governance.LibraryVersion + HasCurrent bool + Snapshot governance.LibraryVersion + HasSnapshot bool + Err error +} + +// loadLibraryVersionFacts 用两次精确查询拼出判定事实;任一查询失败都返回 Err。 +func loadLibraryVersionFacts(ctx context.Context, store libraryVersionIndex, scope, targetSnapshotID string) libraryVersionFacts { + facts := libraryVersionFacts{} + current, hasCurrent, err := store.LibraryCurrentVersion(ctx, scope) + if err != nil { + facts.Err = fmt.Errorf("读不到当前生效版本:%w", err) + return facts + } + facts.Current, facts.HasCurrent = current, hasCurrent + if targetSnapshotID == "" { + return facts + } + snapshot, hasSnapshot, err := store.LibraryVersionOfSnapshot(ctx, scope, + governance.LibraryVersionProductionEffective, targetSnapshotID) + if err != nil { + facts.Err = fmt.Errorf("读不到快照 %s 的生效登记:%w", targetSnapshotID, err) + return facts + } + facts.Snapshot, facts.HasSnapshot = snapshot, hasSnapshot + return facts +} + +// knownIndexMapping 取"上一次登记过的索引映射",作为装配目标时的映射基线。 +// +// 权威来源是**当前生效版本**的登记证据;只有在它没有记录映射时,才退回到最近 +// 成功记录里的那一份(恢复会把旧版本顶替掉,这时仍要拿到生产实际用的映射)。 +// 退化只会让"索引被改动"判定偏严,不会误放行覆盖。同步与恢复共用这一份实现。 +func knownIndexMapping(ctx context.Context, store libraryVersionReader, scope string) string { + if current, found, err := store.LibraryCurrentVersion(ctx, scope); err == nil && found { + if raw, ok := current.Evidence["index_mapping_sha256"].(string); ok && raw != "" { + return raw + } + } + versions, err := store.LibraryVersions(ctx, scope, 50) + if err != nil { + return "" + } + for _, item := range versions { + if raw, ok := item.Evidence["index_mapping_sha256"].(string); ok && raw != "" { + return raw + } + } + return "" +} diff --git a/cmd/worker/library_wiring.go b/cmd/worker/library_wiring.go index 7ef1e6c..f177a60 100644 --- a/cmd/worker/library_wiring.go +++ b/cmd/worker/library_wiring.go @@ -5,7 +5,9 @@ import ( "knowledge-governance/internal/appconfig" "knowledge-governance/internal/librarymaintenance" + "knowledge-governance/internal/libraryrelease" "knowledge-governance/internal/librarystack" + postgresstore "knowledge-governance/internal/platform/postgres" v071 "knowledge-governance/internal/releaseadapter/v071" ) @@ -18,13 +20,27 @@ func openLibraryMaintenance(config appconfig.Config) (*librarymaintenance.Manage return librarystack.OpenMaintenance(config) } +// restoreDispatchGate 只在部署显式开启时才把治理台账交给目标。 +// +// 为什么不能只信配置:配置为 true 只说明"允许装配",不证明旧 writer 已退出; +// 真正的发放许可还要求治理库里对该目标存在未撤销的激活登记(见迁移 78)。 +func restoreDispatchGate(config appconfig.Config, store *postgresstore.Store) libraryrelease.RestoreMarkerGate { + // 只判断"是否允许装配":目标身份与独占证明由治理台账的激活登记回答, + // 这里再用一个空配置也能算出来的摘要去当门槛只会制造虚假的严格。 + if !config.LibraryRestoreDispatchEnabled || store == nil { + return nil + } + return store +} + // buildLibraryProductionStack 用"要同步的这份快照"做契约装配目标与预备份存储。 -func buildLibraryProductionStack(ctx context.Context, config appconfig.Config, scope, snapshotID, knownMapping string) ( - *v071.ProductionLibraryTarget, *v071.ProductionBackupStore, error) { - return librarystack.OpenProductionStack(ctx, config, scope, snapshotID, knownMapping) +func buildLibraryProductionStack(ctx context.Context, config appconfig.Config, gate libraryrelease.RestoreMarkerGate, + scope, snapshotID, knownMapping string) (*v071.ProductionLibraryTarget, *v071.ProductionBackupStore, error) { + return librarystack.OpenProductionStack(ctx, config, scope, snapshotID, knownMapping, gate) } // buildLibraryBaselineStack 装配"给目标自己建基线"所需的目标与捕获器(契约取目标当前映射)。 +// 基线不参与发布/恢复派发,永远不传派发台账:只读/建基线不得获得恢复写许可。 func buildLibraryBaselineStack(ctx context.Context, config appconfig.Config, scope string) ( *v071.ProductionLibraryTarget, *v071.ProductionBackupStore, error) { return librarystack.OpenBaselineStack(ctx, config, scope) diff --git a/cmd/worker/library_writer.go b/cmd/worker/library_writer.go new file mode 100644 index 0000000..5d2ca81 --- /dev/null +++ b/cmd/worker/library_writer.go @@ -0,0 +1,141 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// libraryAttemptWriter 是"这一次执行代次"的写入口。 +// +// 它嵌入完整 Store,只把**可变**入口换成带 epoch 守卫的实现(方法名相同,所以调用点 +// 一行都不用改)。这样"谁能写业务状态/维护锁"只由这一个类型回答:handler 里拿到的 +// 是 writer 而不是裸 Store,就不可能顺手绕过守卫去写。 +// +// 为什么必须这样:失租的旧执行器和接管它的新代次用的是**同一个 job_id**。只加一个 +// epoch 列而不让写路径读它,等于什么都没做(这正是 F13 的原始形态)。 +type libraryAttemptWriter struct { + *postgresstore.Store + attempt governance.LibraryAttempt +} + +// beginLibraryWriter 取得这个作业的执行权,返回带守卫的写入口。 +// owner 用队列作业 ID:每一次投递是一个确定的执行者身份,重复投递是同一个身份(幂等), +// 不同投递互不覆盖(这正是"第二个 resumer 不能释放第一个的锁"需要的区分)。 +func beginLibraryWriter(ctx context.Context, store *postgresstore.Store, jobID, owner string) (*libraryAttemptWriter, error) { + job, err := store.LibraryJob(ctx, jobID) + if err != nil { + return nil, fmt.Errorf("读不到业务作业 %s:%w", jobID, err) + } + if job.OperationID == "" { + // 迁移前的历史作业没有 operation:仍然取租约(防止双执行),但没有代次可守卫。 + log.Printf("library job %s has no operation id (pre-identity row): guarded writes fall back to lease only", jobID) + } + attempt, err := store.BeginLibraryAttempt(ctx, jobID, owner, libraryAttemptLease, time.Now().UTC()) + if err != nil { + return nil, err + } + return &libraryAttemptWriter{Store: store, attempt: attempt}, nil +} + +func (w *libraryAttemptWriter) AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, + stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error { + if err := w.checkJob(jobID); err != nil { + return err + } + return w.Store.AdvanceLibraryJobGuarded(ctx, w.attempt, state, stage, message, recovery, snapshotID, targetSnapshotID, now) +} + +func (w *libraryAttemptWriter) UpdateLibraryStage(ctx context.Context, jobID, stage, state string, + total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error { + if err := w.checkJob(jobID); err != nil { + return err + } + return w.Store.UpdateLibraryStageGuarded(ctx, w.attempt, stage, state, total, completed, bytesTotal, bytesDone, detail, now) +} + +// RecordLibraryVersion 注入本次代次身份:事件登记因此也受 epoch 守卫。 +func (w *libraryAttemptWriter) RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error { + if version.OperationID == "" { + version.OperationID = w.attempt.OperationID + } + if version.AttemptEpoch == 0 { + version.AttemptEpoch = w.attempt.Epoch + } + version.AttemptOwner = w.attempt.Owner + return w.Store.RecordLibraryVersion(ctx, version) +} + +func (w *libraryAttemptWriter) SetLibraryMaintenanceIngress(ctx context.Context, scope, ownerJobID, state, note string, now time.Time) error { + return w.Store.SetLibraryMaintenanceIngressGuarded(ctx, scope, ownerJobID, state, note, w.attempt, now) +} + +func (w *libraryAttemptWriter) SetInstanceMaintenanceIngress(ctx context.Context, instance, ownerJobID, state, note string, now time.Time) error { + return w.Store.SetInstanceMaintenanceIngressGuarded(ctx, instance, ownerJobID, state, note, w.attempt, now) +} + +func (w *libraryAttemptWriter) UpdateLibraryMaintenanceState(ctx context.Context, scope, ownerJobID, state, note string, now time.Time) error { + return w.Store.UpdateLibraryMaintenanceStateGuarded(ctx, scope, ownerJobID, state, note, w.attempt, now) +} + +func (w *libraryAttemptWriter) UpdateInstanceMaintenanceState(ctx context.Context, instance, ownerJobID, state, note string, now time.Time) error { + return w.Store.UpdateInstanceMaintenanceStateGuarded(ctx, instance, ownerJobID, state, note, w.attempt, now) +} + +func (w *libraryAttemptWriter) ReleaseLibraryMaintenance(ctx context.Context, scope, ownerJobID string, now time.Time) error { + return w.Store.ReleaseLibraryMaintenanceGuarded(ctx, scope, ownerJobID, w.attempt, now) +} + +func (w *libraryAttemptWriter) ReleaseInstanceMaintenance(ctx context.Context, instance, ownerJobID string, now time.Time) error { + return w.Store.ReleaseInstanceMaintenanceGuarded(ctx, instance, ownerJobID, w.attempt, now) +} + +// finish 结束本次代次。失败只记日志:代次结束写不进去不该反过来把已经完成的数据收尾 +// 判成失败(下一次接管会重新开始一个新代次,旧代次的残留状态由 active 唯一索引兜住)。 +func (w *libraryAttemptWriter) finish(ctx context.Context, state governance.LibraryAttemptState, outcome string) { + if w.attempt.OperationID == "" { + return + } + if err := w.Store.FinishLibraryAttempt(ctx, w.attempt, state, outcome, time.Now().UTC()); err != nil && + !errors.Is(err, governance.ErrLibraryEpochStale) { + log.Printf("library attempt %s#%d finish failed: %v", w.attempt.OperationID, w.attempt.Epoch, err) + } +} + +func (w *libraryAttemptWriter) checkJob(jobID string) error { + if jobID != w.attempt.JobID { + return fmt.Errorf("尝试用代次 %s#%d 写另一个作业 %s:拒绝(跨作业写入不是续作)", + w.attempt.OperationID, w.attempt.Epoch, jobID) + } + return nil +} + +// 编译期断言:writer 必须同时满足"成功收尾"与"阶段记录"两个存储面。 +var ( + _ libraryMaintenanceStore = (*libraryAttemptWriter)(nil) + _ libraryStageStore = (*libraryAttemptWriter)(nil) +) + +// libraryQueueOwner 构造**每一次投递**的执行者身份:worker + 队列作业 + 队列尝试序号。 +// +// 不能用稳定的 queueJobID 单独当身份(父的复核项 R2):同一个队列作业被重投时 +// ID 不变,而执行者是新的——那样第二次投递会被误判成"同一次执行重复调用", +// 直接复用上一代租约而不开新代次。加上 worker 与 attempt 之后: +// +// · 同一次投递重复调用 ⇒ 身份相同 ⇒ 幂等复用; +// · 换 worker 或换队列尝试 ⇒ 身份不同 ⇒ 必须开新代次(旧代次被结束,守卫立即失效)。 +func libraryQueueOwner(workerID string, job jobs.Job, libraryJobID string) string { + queueID := job.ID + if queueID == "" { + queueID = libraryJobID + } + // 合成规则只有一份(governance.LibraryDeliveryOwner):派发台账要按同一格式核 + // "这次许可属于哪次真实投递"。 + return governance.LibraryDeliveryOwner(workerID, queueID, job.Attempt) +} diff --git a/cmd/worker/library_writeset.go b/cmd/worker/library_writeset.go new file mode 100644 index 0000000..33f8d6f --- /dev/null +++ b/cmd/worker/library_writeset.go @@ -0,0 +1,310 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "sort" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +// 写集合台账在治理侧的锚点:摘要登记在"这次作业的预备份版本"证据里。 +// 为什么不用新表:版本记录本来就绑定 scope + snapshot + 作业,且 id 由这三者 +// 决定;把摘要挂上去,重启后按同一身份就能取回,不需要改 schema。 + +// libraryVersionLookup 只暴露"按身份取一条版本记录"这一件事。 +// +// 为什么不是"按 scope 列表":列表是有排序窗口的(真实 Store 上限 100), +// 历史超过窗口后登记/接管/恢复会把"存在"读成"不存在"。身份查询必须是精确条件, +// 而 found=false 只表示"这个身份没有记录",冲突由 store 返回错误(不许挑一条)。 +type libraryVersionLookup interface { + LibraryVersionByRef(ctx context.Context, scope string, kind governance.LibraryVersionKind, + sourceJobID, snapshotID string) (governance.LibraryVersion, bool, error) +} + +// libraryVersionLedger 是写集合锚点需要的两件事:按身份取一条、登记一条。 +// 分开声明是为了让"身份不符/摘要冲突就失败"能在没有真实库时也被证明。 +type libraryVersionLedger interface { + libraryVersionLookup + RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error +} + +// writeSetDigestOf 读某次作业/某份预备份登记的写集合摘要。 +// 读不到就返回错误:缺失必须让调用方失败,不能降级成"没有记录就当没写过"。 +func writeSetDigestOf(ctx context.Context, store libraryVersionLookup, scope, jobID, snapshotID string) (string, error) { + version, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionPrebackup, jobID, snapshotID) + if err != nil { + return "", fmt.Errorf("读不到版本记录:%w", err) + } + if !found { + return "", fmt.Errorf("找不到作业 %s 的预备份版本记录(快照 %s)", jobID, snapshotID) + } + raw, _ := version.Evidence["writeset_digest"].(string) + if raw == "" { + return "", fmt.Errorf("预备份 %s 没有登记写集合摘要(作业 %s)", snapshotID, jobID) + } + return raw, nil +} + +// loadWriteSetForJob 按"作业 + 目标 + 预备份"取回写集合并逐项核对绑定。 +// 任何一步不符都返回错误:恢复宁可保持维护,也不许用一份对不上的记录去删目标数据。 +func loadWriteSetForJob(ctx context.Context, store libraryVersionLookup, archiveRoot, scope, jobID, snapshotID string) (*libraryrelease.WriteSet, error) { + digest, err := writeSetDigestOf(ctx, store, scope, jobID, snapshotID) + if err != nil { + return nil, err + } + set, err := v071.LoadWriteSet(archiveRoot, digest) + if err != nil { + return nil, err + } + if set.JobID != jobID { + return nil, fmt.Errorf("写集合记录属于作业 %s,不是 %s", set.JobID, jobID) + } + if set.Target != scope { + return nil, fmt.Errorf("写集合记录属于目标 %s,不是 %s", set.Target, scope) + } + if set.BackupSnapshotID != snapshotID { + return nil, fmt.Errorf("写集合记录绑定预备份 %s,不是 %s", set.BackupSnapshotID, snapshotID) + } + return set, nil +} + +// evidenceOwnerMatches 核对一份已持久化的证据是不是"这个作业 + 这份预备份"的。 +// +// 为什么必须核这两维:版本行的 id 只由 (kind, scope, 快照) 决定,登记走 upsert。 +// 只要调用方手里有一份"看起来对"的证据,就能把它盖到别人的行上;反过来, +// 合并证据时不核身份,就会把别的作业的写集合/字节数带进这一行。 +func evidenceOwnerMatches(existing map[string]any, jobID, snapshotID string) error { + if job, ok := existing["job"].(string); ok && job != "" && job != jobID { + return fmt.Errorf("版本证据属于作业 %s,不是 %s:拒绝合并/覆盖", job, jobID) + } + if snapshot, ok := existing["backup_snapshot"].(string); ok && snapshot != "" && snapshot != snapshotID { + return fmt.Errorf("版本证据绑定预备份 %s,不是 %s:拒绝合并/覆盖", snapshot, snapshotID) + } + return nil +} + +// evidenceBytes 取证据里的备份字节数。从库里读回来的是 float64(JSON 数字), +// 进程内构造的是 int64 —— 两种形状都要认,否则"字节数缺失"会被读成 0。 +func evidenceBytes(evidence map[string]any) int64 { + switch value := evidence["backup_bytes"].(type) { + case int64: + return value + case int: + return int64(value) + case float64: + return int64(value) + case json.Number: + if parsed, err := value.Int64(); err == nil { + return parsed + } + } + return 0 +} + +// prebackupBytesOf 读某次作业/某份预备份已登记的备份字节数。 +// +// 接管的预备份是"复用"的,ledgerBackupStore 手里只有快照 id 与写集合; +// 字节数只能来自首次登记的那条证据。读不到或非正数一律失败:把 0 写进 +// 生效版本证据,事后就分不清"空备份"和"没记下来"(现场正是 backup_bytes:0)。 +func prebackupBytesOf(ctx context.Context, store libraryVersionLookup, scope, jobID, snapshotID string) (int64, error) { + version, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionPrebackup, jobID, snapshotID) + if err != nil { + return 0, fmt.Errorf("读不到预备份版本证据:%w", err) + } + if !found { + return 0, fmt.Errorf("找不到作业 %s 的预备份版本记录(快照 %s)", jobID, snapshotID) + } + if err := evidenceOwnerMatches(version.Evidence, jobID, snapshotID); err != nil { + return 0, err + } + bytes := evidenceBytes(version.Evidence) + if bytes <= 0 { + return 0, fmt.Errorf("预备份 %s 没有可信的字节数(作业 %s):拒绝把 0 字节当恢复基线", snapshotID, jobID) + } + return bytes, nil +} + +// writeSetEvidence 在预备份原有证据上追加写集合锚点(纯函数,便于单独验证)。 +// 不能整份替换:备份字节、索引映射这些字段是页面与恢复都在用的。 +func writeSetEvidence(existing map[string]any, set libraryrelease.WriteSet, mappingDigest string) map[string]any { + evidence := map[string]any{} + for key, value := range existing { + evidence[key] = value + } + evidence["backup_snapshot"] = set.BackupSnapshotID + evidence["job"] = set.JobID + if mappingDigest != "" { + evidence["index_mapping_sha256"] = mappingDigest + } + evidence["writeset_digest"] = set.Digest + evidence["writeset_universe_digest"] = set.UniverseDigest() + evidence["writeset_target_snapshot"] = set.TargetSnapshotID + evidence["writeset_rows"] = len(set.Rows) + evidence["writeset_reused_rows"] = len(set.ReusedIDs("resources")) + return evidence +} + +// prebackupEvidence 把"这一轮预备份"的字段合并进已持久化的那份证据。 +// +// 为什么必须是合并而不是覆盖:接管复用同一份预备份时,BackupRef 手里只有快照 id +// (字节数、写集合摘要都是首次那一轮登记的事实)。每次造新 map 就等于用 +// "这一轮知道的东西"替换"上一次已经证明过的东西" —— 而 writeset_* 只会在 +// 首轮规划时写入,接管路径根本不会重算,丢了就再也补不回来。 +// +// 为什么不能无条件合并所有字段:版本行 id 只由 (kind, scope, 快照) 决定, +// 那一行可能属于另一个作业。所以先核身份(job/backup_snapshot),再只保留 +// 与本作业、本预备份一致的部分;字节数出现两个不同真值也直接失败。 +func prebackupEvidence(existing map[string]any, backup libraryrelease.BackupRef, jobID, mappingDigest string) (map[string]any, error) { + evidence := make(map[string]any, len(existing)+4) + for key, value := range existing { + evidence[key] = value + } + if err := evidenceOwnerMatches(evidence, jobID, backup.SnapshotID); err != nil { + return nil, err + } + bytes := backup.Bytes + if backup.Reused { + persisted := evidenceBytes(existing) + if bytes > 0 && persisted > 0 && bytes != persisted { + return nil, fmt.Errorf("复用预备份字节数不一致(本次 %d,已登记 %d):拒绝把两份不同的备份当成一份", + bytes, persisted) + } + if bytes <= 0 { + bytes = persisted + } + if bytes <= 0 { + return nil, fmt.Errorf("预备份 %s 复用登记缺少可信字节数:拒绝把 0 字节写进证据", backup.SnapshotID) + } + evidence["backup_reused"] = true + } + if bytes > 0 { + evidence["backup_bytes"] = bytes + } + evidence["backup_snapshot"] = backup.SnapshotID + evidence["job"] = jobID + if mappingDigest != "" { + evidence["index_mapping_sha256"] = mappingDigest + } + return evidence, nil +} + +// WriteSetPlanned 把写集合摘要登记进"这次作业的预备份版本"证据。 +// 它在第一笔写入之前被调用;失败即中止(调用方据此不写目标)。 +// +// 这里读的是"这一条预备份记录"(scope+kind+作业+快照),不是"最近 N 条": +// 现场正是历史上限把这条记录顶出窗口,才在预备份已经落盘之后登记失败。 +// 记录不存在同样拒绝——把锚点写到一个不存在的证据行上,会让后续接管/恢复 +// 读不到备份字节与索引映射,等于伪造一份台账。 +func (r libraryStageRecorder) WriteSetPlanned(ctx context.Context, set libraryrelease.WriteSet) error { + return anchorWriteSet(ctx, r.store, r.operationID, r.scope, r.jobID, r.mappingDigest, set) +} + +// anchorWriteSet 是登记的实现:与 loadWriteSetForJob 一样只依赖"按身份取一条版本" +// 这一件事,便于在没有真实库时也能证明"身份不符/摘要冲突就失败"。 +func anchorWriteSet(ctx context.Context, store libraryVersionLedger, operationID, scope, jobID, mappingDigest string, + set libraryrelease.WriteSet) error { + version, found, err := store.LibraryVersionByRef(ctx, scope, governance.LibraryVersionProductionPrebackup, + jobID, set.BackupSnapshotID) + if err != nil { + return fmt.Errorf("读不到现有版本证据:%w", err) + } + if !found { + return fmt.Errorf("预备份 %s 的版本证据不存在(作业 %s):拒绝把写集合挂到不存在的记录上", + set.BackupSnapshotID, jobID) + } + // 同一作业的写集合只能落定一次:第二次预检出不同摘要,说明被登记的台账 + // 不再描述"实际写了什么",恢复就无从按它清理——宁可停在写入之前。 + if err := evidenceOwnerMatches(version.Evidence, jobID, set.BackupSnapshotID); err != nil { + return err + } + if recorded, ok := version.Evidence["writeset_digest"].(string); ok && recorded != "" && recorded != set.Digest { + return fmt.Errorf("预备份 %s 已登记写集合 %s,本次预检得到 %s:同一作业的写集合只能落定一次", + set.BackupSnapshotID, recorded, set.Digest) + } + evidence := writeSetEvidence(version.Evidence, set, mappingDigest) + return store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionPrebackup, scope, set.BackupSnapshotID, operationID), + Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: set.BackupSnapshotID, + SourceJobID: jobID, CreatedBy: "worker", Evidence: evidence, CreatedAt: time.Now().UTC(), + }) +} + +// ledgerBackupStore 是"接管/恢复"用的预备份来源:只认已经持久化的那一份, +// 并把它绑定的写集合一起带出来。 +// +// 为什么不能像以前那样只返回 snapshot id:那一刻目标已经被写过,恢复若拿不到 +// 写集合就只能按目标现状推断残渣——那正是会误删历史资源的路径。所以这里取不到 +// 记录就直接失败,而不是返回一个"没有 Universe 的引用"。 +type ledgerBackupStore struct { + ref libraryrelease.BackupRef + write *libraryrelease.WriteSet +} + +func (s ledgerBackupStore) Prepare(context.Context, string, libraryrelease.CurrentState) (libraryrelease.BackupRef, error) { + if s.write == nil { + return libraryrelease.BackupRef{}, errors.New("恢复缺少持久化的写集合记录:拒绝在没有可追溯写集合的情况下继续") + } + // 字节数必须来自首次登记的证据:复用路径不重做备份,手上没有别的真值。 + // 拿 0 继续会把"备份有多大"从生效版本证据里洗掉(现场 backup_bytes:0)。 + if s.ref.Bytes <= 0 { + return libraryrelease.BackupRef{}, errors.New("恢复缺少已登记的真实备份字节数:拒绝用 0 字节当基线") + } + ref := s.ref + ref.WriteSet = s.write + // 明确的"复用":调用方据此把 backup_reused 落进版本证据,而不是让外部 + // 从 created_at 变了没变去猜(那正是被同快照收尾伪造过的地方)。 + ref.Reused = true + return ref, nil +} + +// 能力必须在编译期就成立:Run 用的是类型断言(BackupObserver / WriteSetObserver), +// 少实现一个方法不会报错,只会让"预备份证据/写集合锚点"静默不落库(trap 14 的同一族)。 +var ( + _ libraryrelease.Recorder = libraryStageRecorder{} + _ libraryrelease.BackupObserver = libraryStageRecorder{} + _ libraryrelease.WriteSetObserver = libraryStageRecorder{} + _ libraryrelease.BackupStore = ledgerBackupStore{} +) + +// effectiveEvidence 是"生产生效版本"证据的唯一构造点。 +// +// 为什么单独成函数:生效版本证据里的 backup_bytes 是"这次恢复/同步用的是多大一份 +// 基线"的唯一记录。接管复用路径上 BackupRef 若没带真实字节(历史缺陷),这里会 +// 写进 0,事后与"空备份"无法区分(现场 production_effective 就是 backup_bytes:0)。 +func effectiveEvidence(backup libraryrelease.BackupRef, action, mappingDigest string) map[string]any { + evidence := map[string]any{"backup_snapshot": backup.SnapshotID, "action": action} + if backup.Bytes > 0 { + evidence["backup_bytes"] = backup.Bytes + } + if mappingDigest != "" { + evidence["index_mapping_sha256"] = mappingDigest + } + return evidence +} + +// sortedWriteSetSummary 只用于日志/证据:把本次写集合按表汇总成稳定的短摘要。 +func sortedWriteSetSummary(set libraryrelease.WriteSet) string { + counts := map[string]int{} + for _, row := range set.Rows { + counts[row.Table]++ + } + tables := make([]string, 0, len(counts)) + for table := range counts { + tables = append(tables, table) + } + sort.Strings(tables) + summary := "" + for _, table := range tables { + if summary != "" { + summary += "," + } + summary += fmt.Sprintf("%s=%d", table, counts[table]) + } + return summary +} diff --git a/cmd/worker/library_writeset_integration_test.go b/cmd/worker/library_writeset_integration_test.go new file mode 100644 index 0000000..3add184 --- /dev/null +++ b/cmd/worker/library_writeset_integration_test.go @@ -0,0 +1,239 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/platform/postgres/pgtest" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +// 这一组用例跑在真实 PostgreSQL 上(TEST_DATABASE_URL),因为要证明的正是 +// 治理库的契约:版本台账的身份查询不许依赖"最近 N 条",而且写集合锚点必须与 +// 预备份原有证据共存。假的版本库不实现 1..100 的分页上限,正是它让真实现场 +// 那个"library version limit out of range"一路绿到线上。 + +// ledgerTestTarget 是"只做预检 + 四个内容阶段"的目标:本用例要证明的是治理库侧的 +// 台账契约,不是 v071 的生产写入;但预检的落盘(PersistWriteSet)是真实的, +// 因为接管/恢复就是按这份文件取回写集合。 +type ledgerTestTarget struct { + root string + plan libraryrelease.WriteSetPlan +} + +func (t *ledgerTestTarget) Current(context.Context) (libraryrelease.CurrentState, error) { + return libraryrelease.CurrentState{Counts: map[string]int64{"resources": 1}, Digests: map[string]string{"resources": "universe-digest"}}, nil +} + +func (t *ledgerTestTarget) Apply(context.Context, libraryrelease.Stage, string) error { return nil } +func (t *ledgerTestTarget) Verify(context.Context, libraryrelease.Expectation) error { return nil } +func (t *ledgerTestTarget) Restore(context.Context, libraryrelease.BackupRef) error { return nil } + +func (t *ledgerTestTarget) PlanWriteSet(_ context.Context, plan libraryrelease.WriteSetPlan) (libraryrelease.WriteSet, error) { + t.plan = plan + set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: plan.JobID, Target: plan.Target, + TenantID: 10001, KnowledgeBaseID: "kb-ledger", + BackupSnapshotID: plan.BackupSnapshotID, TargetSnapshotID: plan.TargetSnapshotID, CreatedAt: time.Now().UTC(), + Rows: []libraryrelease.WriteSetRow{{Table: "resources", ID: "res-new"}}, + Universe: plan.Universe} + if err := set.Seal(); err != nil { + return libraryrelease.WriteSet{}, err + } + if _, err := v071.PersistWriteSet(t.root, &set); err != nil { + return libraryrelease.WriteSet{}, err + } + return set, nil +} + +// ledgerTestBackups 返回一份已经拍好的预备份(模拟"真实备份已完成"), +// WriteSet 留空:台账必须由真实预检算出来,不能由夹具直接塞进去。 +type ledgerTestBackups struct { + ref libraryrelease.BackupRef +} + +func (b ledgerTestBackups) Prepare(context.Context, string, libraryrelease.CurrentState) (libraryrelease.BackupRef, error) { + return b.ref, nil +} + +func openLedgerStore(t *testing.T) (*postgresstore.Store, *pgxpool.Pool) { + t.Helper() + databaseURL := pgtest.IsolatedDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if databaseURL == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, databaseURL) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(pool.Close) + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + t.Fatalf("migrate: %v", err) + } + return postgresstore.NewStore(pool), pool +} + +// seedVersionHistory 往同一 scope 里塞满比目标更新版本的历史记录: +// 目标记录被顶到任何"最近 N 条"窗口之外,只有按身份精确查询才能取回。 +func seedVersionHistory(t *testing.T, ctx context.Context, store *postgresstore.Store, scope string, now time.Time, count int) { + t.Helper() + for i := 0; i < count; i++ { + snapshot := fmt.Sprintf("history-snap-%03d", i) + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, snapshot), + Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: snapshot, + SourceJobID: fmt.Sprintf("history-job-%03d", i), CreatedBy: "worker", + Evidence: map[string]any{"backup_snapshot": snapshot, "backup_bytes": 1024}, + CreatedAt: now.Add(-time.Duration(i) * time.Minute), + }); err != nil { + t.Fatalf("seed history version %d: %v", i, err) + } + } +} + +func containsSnapshot(versions []governance.LibraryVersion, snapshotID string) bool { + for _, version := range versions { + if version.SnapshotID == snapshotID { + return true + } + } + return false +} + +// TestLibraryRunAnchorsWriteSetAndKeepsLookingItUpBeyondHistoryWindow 是本问题的 +// 端到端证据:真实 Run → contentTrackedTarget 包装 → 真实 libraryStageRecorder +// .WriteSetPlanned → 真实 store,并且历史长到把这条记录挤出"最近 N 条"窗口后, +// 登记/接管/恢复共用的精确查询仍然取得到它。 +func TestLibraryRunAnchorsWriteSetAndKeepsLookingItUpBeyondHistoryWindow(t *testing.T) { + store, pool := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + const ( + scope = "internal" + jobID = "libsync-ledger-200" + snapshot = "backup-snap-ledger-200" + target = "target-snap-ledger-200" + params = "params-digest-ledger-200" + ) + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: scope, Kind: governance.LibraryJobSync, + IdempotencyKey: "library.sync:internal:ledger-200", RequestDigest: params, Actor: "admin"}, + governance.SyncStages(), now); err != nil { + t.Fatalf("create library job: %v", err) + } + + root := t.TempDir() + inner := &ledgerTestTarget{root: root} + // 台账必须在第一笔写入之前就能按身份读回:图省事把登记挪到写之后, + // 崩溃时就没有"这次明确写了什么"可读。 + anchorBeforeFirstWrite, checkedFirstWrite := false, false + wrapped := &contentTrackedTarget{inner: inner, onApply: func() { + if checkedFirstWrite { + return + } + checkedFirstWrite = true + if _, err := writeSetDigestOf(ctx, store, scope, jobID, snapshot); err == nil { + anchorBeforeFirstWrite = true + } + }} + recorder := libraryStageRecorder{store: store, jobID: jobID, scope: scope, mappingDigest: "mapping-live"} + outcome := libraryrelease.Run(ctx, libraryrelease.Request{JobID: jobID, Target: scope, SnapshotID: target, + ParamsDigest: params, Now: now, Grant: libraryrelease.Grant{Target: scope, SnapshotID: target, + ParamsDigest: params, ExpiresAt: now.Add(time.Hour), AuthorizedBy: "tester"}}, + wrapped, ledgerTestBackups{ref: libraryrelease.BackupRef{ID: "backup-" + snapshot, SnapshotID: snapshot, + Bytes: 4096, Universe: map[string]libraryrelease.TableFingerprint{"resources": {Count: 1, Digest: "universe-digest"}}}}, + recorder) + if outcome.State != "succeeded" { + t.Fatalf("台账登记不应让作业失败:state=%s error=%s", outcome.State, outcome.Error) + } + if inner.plan.JobID != jobID || inner.plan.BackupSnapshotID != snapshot { + t.Fatalf("包装层没有把预检落到内层目标:%+v", inner.plan) + } + + // 登记必须发生在写第一笔之前。 + if !anchorBeforeFirstWrite { + t.Fatal("第一笔写入时台账还读不回来:写集合登记没有发生在其之前") + } + + digest, err := writeSetDigestOf(ctx, store, scope, jobID, snapshot) + if err != nil { + t.Fatalf("按作业+预备份取写集合摘要:%v", err) + } + if digest == "" { + t.Fatal("写集合摘要为空:登记没有落到版本证据里") + } + + // 原证据字段必须与锚点共存(原子保留):整份替换会丢掉备份字节与索引映射, + // 而页面与恢复都在用它们。 + set, err := loadWriteSetForJob(ctx, store, root, scope, jobID, snapshot) + if err != nil { + t.Fatalf("按作业+目标+预备份取回写集合:%v", err) + } + if set.Digest != digest { + t.Fatalf("取回的写集合摘要 = %s, want %s", set.Digest, digest) + } + + var evidence []byte + if err := pool.QueryRow(ctx, `SELECT evidence FROM library_versions WHERE scope=$1 AND kind='production_prebackup' +AND source_job_id=$2 AND snapshot_id=$3`, scope, jobID, snapshot).Scan(&evidence); err != nil { + t.Fatalf("read evidence: %v", err) + } + assertEvidenceKeepsBackupFields(t, evidence, map[string]any{ + "backup_bytes": float64(4096), "job": jobID, "index_mapping_sha256": "mapping-live", "writeset_digest": digest, + }) + + // 历史继续增长:把这条预备份记录推到 250 条更新记录之后,任何"最近 N 条" + // (真实 Store 上限 100)的窗口都看不到它——这正是现场"读不到现有版本证据"。 + if _, err := pool.Exec(ctx, `UPDATE library_versions SET created_at=$2 +WHERE scope=$1 AND kind='production_prebackup' AND source_job_id=$3 AND snapshot_id=$4`, + scope, now.Add(-48*time.Hour), jobID, snapshot); err != nil { + t.Fatalf("age prebackup version: %v", err) + } + seedVersionHistory(t, ctx, store, scope, now.Add(-time.Hour), 250) + + window, err := store.LibraryVersions(ctx, scope, 100) + if err != nil { + t.Fatalf("list versions: %v", err) + } + if len(window) != 100 { + t.Fatalf("窗口条数 = %d, want 100", len(window)) + } + if containsSnapshot(window, snapshot) { + t.Fatal("窗口里仍能看到目标记录:本用例无法证明精确查找(夹具失效)") + } + again, err := writeSetDigestOf(ctx, store, scope, jobID, snapshot) + if err != nil { + t.Fatalf("历史超过窗口后仍必须按身份取回摘要:%v", err) + } + if again != digest { + t.Fatalf("超出窗口后取回的摘要 = %s, want %s", again, digest) + } + if _, err := loadWriteSetForJob(ctx, store, root, scope, jobID, snapshot); err != nil { + t.Fatalf("历史超过窗口后接管/恢复仍必须取回写集合:%v", err) + } +} + +func assertEvidenceKeepsBackupFields(t *testing.T, raw []byte, want map[string]any) { + t.Helper() + var evidence map[string]any + if err := json.Unmarshal(raw, &evidence); err != nil { + t.Fatalf("decode evidence: %v", err) + } + for key, value := range want { + got, ok := evidence[key] + if !ok { + t.Fatalf("证据字段 %s 丢失:%v", key, evidence) + } + if fmt.Sprint(got) != fmt.Sprint(value) { + t.Fatalf("证据字段 %s = %v, want %v", key, got, value) + } + } +} diff --git a/cmd/worker/library_writeset_resume_integration_test.go b/cmd/worker/library_writeset_resume_integration_test.go new file mode 100644 index 0000000..2ae85b7 --- /dev/null +++ b/cmd/worker/library_writeset_resume_integration_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + postgresstore "knowledge-governance/internal/platform/postgres" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +// 现场(2026-10-30,job librestore-internal-1793321916382871758-retry): +// 第一次中断后接管复用了同一份预备份,BackupPrepared 用一份**新造的**证据 +// 覆盖了已持久化的 writeset_*,于是 verify_effective 的 writeset_digest 从 +// fddd98cf… 变成了空;第二次中断再接管时 loadWriteSetForJob 已经读不回记录。 +// 预备份本身没变(快照 id / manifest / 首次 created_at 都不变),丢的只有台账。 +// +// 这些用例必须跑在真实 PostgreSQL 上:丢证据的机制是 RecordLibraryVersion 的 +// `evidence = EXCLUDED.evidence`(整份覆盖),而"同一身份归谁"也是存储层语义 +// (id 由 kind+scope+快照决定、upsert 会改写 source_job_id)。假 store 造不出这两件事。 + +// resumeLedgerFixture 是本组用例的账本夹具:一个作业、一份预备份、一份写集合。 +type resumeLedgerFixture struct { + pool *pgxpool.Pool + scope string + jobID string + backup string + target string + params string + root string + store *postgresstore.Store + record libraryStageRecorder + writeSet libraryrelease.WriteSet +} + +func newResumeLedgerFixture(t *testing.T, suffix string) *resumeLedgerFixture { + t.Helper() + store, pool := openLedgerStore(t) + ctx := context.Background() + now := time.Now().UTC() + f := &resumeLedgerFixture{ + pool: pool, + scope: "internal", + jobID: "librestore-internal-ws-" + suffix, + backup: "backup-snap-ws-" + suffix, + target: "target-snap-ws-" + suffix, + params: "params-ws-" + suffix, + root: t.TempDir(), + store: store, + } + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ID: f.jobID, Scope: f.scope, + Kind: governance.LibraryJobRestore, TargetSnapshotID: f.target, RequestDigest: f.params, + IdempotencyKey: "library.restore:internal:" + suffix}, governance.SyncStages(), now); err != nil { + t.Fatalf("create library job: %v", err) + } + f.record = libraryStageRecorder{store: store, jobID: f.jobID, scope: f.scope, mappingDigest: "mapping-live"} + // 首轮:真实预备份字节(4096)与写集合都按生产顺序落库/落盘。 + if err := f.record.BackupPrepared(ctx, libraryrelease.BackupRef{ID: "backup-" + f.backup, + SnapshotID: f.backup, Bytes: 4096}); err != nil { + t.Fatalf("首轮登记预备份:%v", err) + } + set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: f.jobID, Target: f.scope, + TenantID: 10001, KnowledgeBaseID: "kb-resume", BackupSnapshotID: f.backup, + TargetSnapshotID: f.target, CreatedAt: now, + Rows: []libraryrelease.WriteSetRow{{Table: "resources", ID: "res-1"}, {Table: "chunks", ID: "chunk-1"}}, + Universe: map[string]libraryrelease.TableFingerprint{ + "resources": {Count: 1, Digest: "u"}}} + if err := set.Seal(); err != nil { + t.Fatalf("seal write set: %v", err) + } + if _, err := v071.PersistWriteSet(f.root, &set); err != nil { + t.Fatalf("persist write set: %v", err) + } + if err := f.record.WriteSetPlanned(ctx, set); err != nil { + t.Fatalf("登记写集合:%v", err) + } + f.writeSet = set + return f +} + +// evidenceOf 直接读库,绕过被测代码:证据里到底还剩什么,由这里说了算。 +func (f *resumeLedgerFixture) evidenceOf(t *testing.T, kind governance.LibraryVersionKind, snapshot string) map[string]any { + t.Helper() + var raw []byte + if err := f.pool.QueryRow(context.Background(), `SELECT evidence FROM library_versions +WHERE scope=$1 AND kind=$2 AND source_job_id=$3 AND snapshot_id=$4`, + f.scope, string(kind), f.jobID, snapshot).Scan(&raw); err != nil { + t.Fatalf("read %s evidence: %v", kind, err) + } + var evidence map[string]any + if err := json.Unmarshal(raw, &evidence); err != nil { + t.Fatalf("decode %s evidence: %v", kind, err) + } + return evidence +} + +func (f *resumeLedgerFixture) createdAtOf(t *testing.T, kind governance.LibraryVersionKind, snapshot string) time.Time { + t.Helper() + var at time.Time + if err := f.pool.QueryRow(context.Background(), `SELECT created_at FROM library_versions +WHERE scope=$1 AND kind=$2 AND source_job_id=$3 AND snapshot_id=$4`, + f.scope, string(kind), f.jobID, snapshot).Scan(&at); err != nil { + t.Fatalf("read %s created_at: %v", kind, err) + } + return at.UTC() +} + +// interruptedTarget 模拟"写某一类数据时进程被杀":写入阶段失败,恢复链路照常执行。 +type interruptedTarget struct { + failAt libraryrelease.Stage + applied int +} + +func (t *interruptedTarget) Current(context.Context) (libraryrelease.CurrentState, error) { + return libraryrelease.CurrentState{Counts: map[string]int64{"resources": 1}, + Digests: map[string]string{"resources": "u"}}, nil +} + +func (t *interruptedTarget) Apply(_ context.Context, stage libraryrelease.Stage, _ string) error { + t.applied++ + if stage == t.failAt { + return errors.New("simulated worker kill during apply") + } + return nil +} + +func (t *interruptedTarget) Verify(context.Context, libraryrelease.Expectation) error { return nil } +func (t *interruptedTarget) Restore(context.Context, libraryrelease.BackupRef) error { return nil } + +// completeTarget 是一条能跑完的链路:用来证明最后一次真实恢复仍带着同一份写集合, +// 并且生效版本证据里是真实字节(不是复用路径上被抹成 0 的那个)。 +type completeTarget struct{ applied int } + +func (t *completeTarget) Current(context.Context) (libraryrelease.CurrentState, error) { + return libraryrelease.CurrentState{Counts: map[string]int64{"resources": 1}, + Digests: map[string]string{"resources": "u"}}, nil +} +func (t *completeTarget) Apply(context.Context, libraryrelease.Stage, string) error { + t.applied++ + return nil +} +func (t *completeTarget) Verify(context.Context, libraryrelease.Expectation) error { return nil } +func (t *completeTarget) Restore(context.Context, libraryrelease.BackupRef) error { return nil } + +// takeoverRequest 是接管时用的发布请求:身份与首轮完全一致。 +func (f *resumeLedgerFixture) takeoverRequest(now time.Time) libraryrelease.Request { + return libraryrelease.Request{JobID: f.jobID, Target: f.scope, SnapshotID: f.target, + ParamsDigest: f.params, Now: now, + Grant: libraryrelease.Grant{Target: f.scope, SnapshotID: f.target, ParamsDigest: f.params, + ExpiresAt: now.Add(time.Hour), AuthorizedBy: "tester"}} +} + +// takeoverBackups 按生产代码的方式装配接管来源:先按身份取回写集合与真实字节, +// 再交给 ledgerBackupStore。缺任何一样都必须失败,不许降级成"按目标现状推断"。 +func (f *resumeLedgerFixture) takeoverBackups(t *testing.T, store *postgresstore.Store) libraryrelease.BackupStore { + t.Helper() + ctx := context.Background() + set, err := loadWriteSetForJob(ctx, store, f.root, f.scope, f.jobID, f.backup) + if err != nil { + t.Fatalf("接管读不回写集合(作业 %s,预备份 %s):%v", f.jobID, f.backup, err) + } + bytes, err := prebackupBytesOf(ctx, store, f.scope, f.jobID, f.backup) + if err != nil { + t.Fatalf("接管读不回预备份字节:%v", err) + } + if bytes != 4096 { + t.Fatalf("接管拿到的预备份字节 = %d, want 4096(复用不许把真实字节抹成 0)", bytes) + } + return ledgerBackupStore{ref: libraryrelease.BackupRef{ID: "backup-" + f.backup, + SnapshotID: f.backup, Bytes: bytes}, write: set} +} + +func TestTakeoverKeepsWriteSetEvidenceAcrossRepeatedInterruptions(t *testing.T) { + f := newResumeLedgerFixture(t, "repeat") + store := f.store + ctx := context.Background() + firstCreatedAt := f.createdAtOf(t, governance.LibraryVersionProductionPrebackup, f.backup) + + // 两次"写到一半被杀 + 接管":每次接管都会复用同一份预备份并重新登记证据。 + for round := 1; round <= 2; round++ { + backups := f.takeoverBackups(t, store) + now := time.Now().UTC() + outcome := libraryrelease.Run(ctx, f.takeoverRequest(now), + &interruptedTarget{failAt: libraryrelease.Stage("database")}, backups, f.record) + if outcome.State != "rolled_back" { + t.Fatalf("第 %d 次中断的结局 = %q(%s / %s),want rolled_back", + round, outcome.State, outcome.Error, outcome.Rollback) + } + // 每次中断之后,下一次接管/恢复都必须还能按身份取回写集合。 + set, err := loadWriteSetForJob(ctx, store, f.root, f.scope, f.jobID, f.backup) + if err != nil { + t.Fatalf("第 %d 次接管后写集合丢失(正是本缺陷):%v", round, err) + } + if set.Digest != f.writeSet.Digest { + t.Fatalf("第 %d 次接管后写集合摘要 = %s, want %s", round, set.Digest, f.writeSet.Digest) + } + } + + // 证据逐项核对:写集合锚点、真实字节、作业/预备份身份都必须还在。 + prebackup := f.evidenceOf(t, governance.LibraryVersionProductionPrebackup, f.backup) + for key, want := range map[string]any{ + "writeset_digest": f.writeSet.Digest, + "writeset_rows": float64(2), + "job": f.jobID, + "backup_snapshot": f.backup, + "backup_bytes": float64(4096), + "index_mapping_sha256": "mapping-live", + "backup_reused": true, + } { + if got := prebackup[key]; got != want { + t.Fatalf("复用后证据 %s = %v, want %v(整份覆盖就是本缺陷)", key, got, want) + } + } + if got := f.createdAtOf(t, governance.LibraryVersionProductionPrebackup, f.backup); !got.Equal(firstCreatedAt) { + t.Fatalf("复用后预备份登记时刻 = %s, want %s(备份什么时候拍的被洗掉了)", got, firstCreatedAt) + } + + // 第三次不中断:完整跑通,证明最后一次真实恢复仍按同一份写集合执行。 + final := &completeTarget{} + outcome := libraryrelease.Run(ctx, f.takeoverRequest(time.Now().UTC()), final, f.takeoverBackups(t, store), f.record) + if outcome.State != "succeeded" { + t.Fatalf("最终恢复 state=%q error=%s rollback=%s", outcome.State, outcome.Error, outcome.Rollback) + } + if final.applied != len(libraryrelease.Stages()) { + t.Fatalf("四类写入没有全部执行:applied=%d", final.applied) + } + // 生效版本证据由处理器用 outcome.Backup 构造(这里不重复实现那一层), + // 所以断言的是它拿到的输入:复用路径必须带回真实字节与同一份预备份身份。 + if outcome.Backup.Bytes != 4096 { + t.Fatalf("复用路径交回的备份字节 = %d, want 4096(处理器会把 0 写进生效版本证据)", + outcome.Backup.Bytes) + } + if !outcome.Backup.Reused || outcome.Backup.SnapshotID != f.backup { + t.Fatalf("复用路径交回的预备份身份不对:%+v", outcome.Backup) + } + effective := effectiveEvidence(outcome.Backup, "restore", "mapping-live") + if effective["backup_bytes"] != int64(4096) || effective["backup_snapshot"] != f.backup { + t.Fatalf("生效版本证据 = %v, want backup_bytes 4096 + backup_snapshot %s", effective, f.backup) + } +} + +// 负例:复用声明与已持久化证据对不上时,必须 fail closed —— 既不许凭空登记, +// 也不许借用别的作业/别的预备份的记录。 +func TestTakeoverLedgerRefusesForeignOrMissingBackupEvidence(t *testing.T) { + f := newResumeLedgerFixture(t, "negatives") + store := f.store + ctx := context.Background() + + // 声称复用一份从没登记过的预备份:没有证据可合并 ⇒ 拒绝。 + if err := f.record.BackupPrepared(ctx, libraryrelease.BackupRef{ID: "backup-unknown", + SnapshotID: "backup-snap-never-registered", Bytes: 1, Reused: true}); err == nil { + t.Fatal("复用未登记的预备份必须失败(否则就是把复用洗成新备份)") + } + + // 同一份预备份被别的作业占用:LibraryVersionByRef 必须报身份冲突,而不是当没有。 + if err := f.record.BackupPrepared(ctx, libraryrelease.BackupRef{ID: "backup-" + f.backup, + SnapshotID: f.backup, Bytes: 4096, Reused: true}); err != nil { + t.Fatalf("本方复用同一份预备份应当成功:%v", err) + } + + // 字节数对不上(本次声称 2048,已登记 4096)⇒ 拒绝:宁可保持维护,也不许写错基线。 + if err := f.record.BackupPrepared(ctx, libraryrelease.BackupRef{ID: "backup-" + f.backup, + SnapshotID: f.backup, Bytes: 2048, Reused: true}); err == nil { + t.Fatal("复用预备份字节数不一致时必须失败") + } + + // 写集合被篡改:文件内容改一个字节,摘要就对不上 ⇒ 拒绝恢复。 + path := filepath.Join(f.root, "writesets", f.writeSet.Digest+".json") + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read write set file: %v", err) + } + tampered := []byte(string(raw[:len(raw)-2]) + "X}") + // 落盘的写集合是 0444(只读台账):篡改必须先放开权限,这也顺带证明它默认不可写。 + if err := os.Chmod(path, 0600); err != nil { + t.Fatalf("chmod write set: %v", err) + } + if err := os.WriteFile(path, tampered, 0600); err != nil { + t.Fatalf("tamper write set: %v", err) + } + if _, err := loadWriteSetForJob(ctx, store, f.root, f.scope, f.jobID, f.backup); err == nil { + t.Fatal("写集合被篡改后必须拒绝取回") + } + if err := os.WriteFile(path, raw, 0600); err != nil { + t.Fatalf("restore write set: %v", err) + } + if _, err := loadWriteSetForJob(ctx, store, f.root, f.scope, f.jobID, f.backup); err != nil { + t.Fatalf("恢复原文件后应能取回:%v", err) + } + + // 换了预备份身份 / 换了作业:都不许借到这份记录。 + if _, err := loadWriteSetForJob(ctx, store, f.root, f.scope, f.jobID, "backup-snap-other"); err == nil { + t.Fatal("不同预备份必须拒绝") + } + if _, err := loadWriteSetForJob(ctx, store, f.root, f.scope, "librestore-internal-ws-other", f.backup); err == nil { + t.Fatal("不同作业必须拒绝") + } +} diff --git a/cmd/worker/library_writeset_test.go b/cmd/worker/library_writeset_test.go new file mode 100644 index 0000000..5e769a1 --- /dev/null +++ b/cmd/worker/library_writeset_test.go @@ -0,0 +1,389 @@ +package main + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +// 这里验证的是"治理侧的锚点":摘要真的写进版本证据、能按作业+目标+预备份取回, +// 并且任何一步对不上都返回错误(调用方据此不写目标 / 保持维护)。 +// 归档文件的读写在 v071 的写集合用例里用真实文件验证。 + +type fakeVersionStore struct { + versions []governance.LibraryVersion + recorded *governance.LibraryVersion + err error +} + +// LibraryVersionByRef 按 scope+kind+作业+快照四个条件精确命中: +// 真实 store 已不再提供"列最近 N 条再筛"这条路,夹具也不能假装还能那样查。 +func (f *fakeVersionStore) LibraryVersionByRef(_ context.Context, scope string, kind governance.LibraryVersionKind, + sourceJobID, snapshotID string) (governance.LibraryVersion, bool, error) { + if f.err != nil { + return governance.LibraryVersion{}, false, f.err + } + for _, version := range f.versions { + if version.Scope != "" && version.Scope != scope { + continue + } + if version.Kind == kind && version.SnapshotID == snapshotID && version.SourceJobID == sourceJobID { + return version, true, nil + } + } + return governance.LibraryVersion{}, false, nil +} + +func (f *fakeVersionStore) RecordLibraryVersion(_ context.Context, version governance.LibraryVersion) error { + f.recorded = &version + return nil +} + +func sealedLedger(t *testing.T, digest string) libraryrelease.WriteSet { + t.Helper() + set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: "job-1", Target: "internal", + TenantID: 10001, KnowledgeBaseID: "kb", BackupSnapshotID: "backup-snap", + TargetSnapshotID: "target-snap", CreatedAt: time.Now().UTC(), + Rows: []libraryrelease.WriteSetRow{{Table: "resources", ID: "res-new"}}, + Universe: map[string]libraryrelease.TableFingerprint{"resources": {Count: 2, Digest: "d"}}} + if err := set.Seal(); err != nil { + t.Fatal(err) + } + return set +} + +func TestWriteSetEvidenceKeepsBackupEvidenceAndAddsAnchor(t *testing.T) { + set := sealedLedger(t, "") + evidence := writeSetEvidence(map[string]any{"backup_bytes": int64(4096), "index_mapping_sha256": "old"}, set, "mapping-1") + if evidence["backup_bytes"] != int64(4096) { + t.Fatalf("原预备份证据必须保留:%v", evidence) + } + if evidence["writeset_digest"] != set.Digest { + t.Fatalf("writeset_digest = %v, want %s", evidence["writeset_digest"], set.Digest) + } + if evidence["writeset_universe_digest"] != set.UniverseDigest() || evidence["writeset_universe_digest"] == "" { + t.Fatalf("整实例证据摘要必须登记:%v", evidence) + } + if evidence["index_mapping_sha256"] != "mapping-1" { + t.Fatalf("当前索引映射必须覆盖旧值:%v", evidence) + } + if evidence["writeset_job"] != nil && evidence["job"] != "job-1" { + t.Fatalf("写集合必须绑定作业:%v", evidence) + } +} + +func TestWriteSetDigestLookupRequiresJobTargetAndSnapshotMatch(t *testing.T) { + store := &fakeVersionStore{versions: []governance.LibraryVersion{ + {ID: "v1", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: "backup-snap", + SourceJobID: "job-1", Evidence: map[string]any{"writeset_digest": "digest-1"}}, + {ID: "v2", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: "backup-snap", + SourceJobID: "job-2", Evidence: map[string]any{"writeset_digest": "digest-2"}}, + }} + digest, err := writeSetDigestOf(context.Background(), store, "internal", "job-1", "backup-snap") + if err != nil || digest != "digest-1" { + t.Fatalf("digest = %q, err = %v", digest, err) + } + // 别的作业的版本不能被拿来用。 + if _, err := writeSetDigestOf(context.Background(), store, "internal", "job-3", "backup-snap"); err == nil { + t.Fatal("找不到本作业的版本时必须失败") + } + // 有版本但没登记摘要 → 失败(不许当成"没有写集合"降级)。 + missing := &fakeVersionStore{versions: []governance.LibraryVersion{{Kind: governance.LibraryVersionProductionPrebackup, + SnapshotID: "backup-snap", SourceJobID: "job-1", Evidence: map[string]any{}}}} + if _, err := writeSetDigestOf(context.Background(), missing, "internal", "job-1", "backup-snap"); err == nil { + t.Fatal("没有写集合摘要时必须失败") + } + // 读不到版本 → 失败。 + if _, err := writeSetDigestOf(context.Background(), &fakeVersionStore{err: errors.New("db down")}, + "internal", "job-1", "backup-snap"); err == nil { + t.Fatal("版本查询失败必须向上传递") + } +} + +func TestLoadWriteSetForJobChecksBinding(t *testing.T) { + root := t.TempDir() + set := sealedLedger(t, "") + if _, err := v071.PersistWriteSet(root, &set); err != nil { + t.Fatal(err) + } + store := &fakeVersionStore{versions: []governance.LibraryVersion{{Kind: governance.LibraryVersionProductionPrebackup, + SnapshotID: "backup-snap", SourceJobID: "job-1", Evidence: map[string]any{"writeset_digest": set.Digest}}}} + loaded, err := loadWriteSetForJob(context.Background(), store, root, "internal", "job-1", "backup-snap") + if err != nil { + t.Fatalf("load: %v", err) + } + if loaded.Digest != set.Digest { + t.Fatalf("digest = %s", loaded.Digest) + } + // 目标不一致 → 拒绝(同一份记录不能被拿去恢复另一个目标)。 + if _, err := loadWriteSetForJob(context.Background(), store, root, "external", "job-1", "backup-snap"); err == nil { + t.Fatal("目标不一致时必须失败") + } + // 作业不一致 → 拒绝。 + if _, err := loadWriteSetForJob(context.Background(), store, root, "internal", "job-2", "backup-snap"); err == nil { + t.Fatal("作业不一致时必须失败") + } + // 记录文件被删 → 拒绝。 + if err := os.Chmod(filepath.Join(root, "writesets", set.Digest+".json"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(root, "writesets", set.Digest+".json")); err != nil { + t.Fatal(err) + } + if _, err := loadWriteSetForJob(context.Background(), store, root, "internal", "job-1", "backup-snap"); err == nil { + t.Fatal("写集合文件缺失时必须失败") + } +} + +// 接管用的预备份来源:没有写集合就不许继续(返回错误,而不是给一个空引用)。 +func TestLedgerBackupStoreRefusesWithoutWriteSet(t *testing.T) { + store := ledgerBackupStore{ref: libraryrelease.BackupRef{ID: "backup-1", SnapshotID: "backup-snap"}} + if _, err := store.Prepare(context.Background(), "target-snap", libraryrelease.CurrentState{}); err == nil { + t.Fatal("没有写集合时接管必须失败") + } + set := sealedLedger(t, "") + store.write = &set + // 复用不重做备份:真实字节只能来自首次登记的证据,缺了必须失败(见下一个用例)。 + store.ref.Bytes = 4096 + ref, err := store.Prepare(context.Background(), "target-snap", libraryrelease.CurrentState{}) + if err != nil { + t.Fatalf("prepare: %v", err) + } + if ref.WriteSet == nil || ref.WriteSet.Digest != set.Digest { + t.Fatalf("接管必须带上持久化的写集合:%+v", ref) + } +} + +// 包装层必须把"写集合预检"这件事透出去:orchestrator 用的是类型断言, +// 少一个方法就等于静默跳过台账(真实后果:真作业没有 writeset_digest、也没有 +// writesets/ 文件,崩溃接管无台账可读)。 +type plainTarget struct{ applied int } + +func (t *plainTarget) Current(context.Context) (libraryrelease.CurrentState, error) { + return libraryrelease.CurrentState{}, nil +} +func (t *plainTarget) Apply(context.Context, libraryrelease.Stage, string) error { + t.applied++ + return nil +} +func (t *plainTarget) Verify(context.Context, libraryrelease.Expectation) error { return nil } +func (t *plainTarget) Restore(context.Context, libraryrelease.BackupRef) error { return nil } + +type planningTarget struct { + plainTarget + planned int + last libraryrelease.WriteSetPlan +} + +func (t *planningTarget) PlanWriteSet(_ context.Context, plan libraryrelease.WriteSetPlan) (libraryrelease.WriteSet, error) { + t.planned++ + t.last = plan + return libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: "job-1", Target: "internal"}, nil +} + +func TestContentTrackedTargetForwardsWriteSetPlanning(t *testing.T) { + inner := &planningTarget{} + wrapped := &contentTrackedTarget{inner: inner, onApply: func() {}} + planner, ok := libraryrelease.Target(wrapped).(libraryrelease.WriteSetPlanner) + if !ok { + t.Fatal("包装后的目标必须仍然实现 WriteSetPlanner,否则写集合会被静默跳过") + } + if _, err := planner.PlanWriteSet(context.Background(), libraryrelease.WriteSetPlan{JobID: "job-1", Target: "internal", + PriorSnapshots: []libraryrelease.PriorSnapshot{{JobID: "job-0", SnapshotID: "snap-0", Kind: libraryrelease.PriorSnapshotSync}}}); err != nil { + t.Fatalf("plan: %v", err) + } + if inner.planned != 1 { + t.Fatalf("预检必须落到内层目标,planned=%d", inner.planned) + } + // 来源证据也必须透传:丢掉它就会让"恢复保留下来的资源"永远无法证明可复用。 + if len(inner.last.PriorSnapshots) != 1 || inner.last.PriorSnapshots[0].SnapshotID != "snap-0" { + t.Fatalf("PriorSyncs 没有透传到内层:%+v", inner.last) + } + + // 内层不支持预检 ⇒ 硬错误,不许"没有台账也照写"。 + strict := &contentTrackedTarget{inner: &plainTarget{}, onApply: func() {}} + if _, err := strict.PlanWriteSet(context.Background(), libraryrelease.WriteSetPlan{}); err == nil { + t.Fatal("内层不支持写集合预检时必须报错") + } else if !strings.Contains(err.Error(), "写集合") { + t.Fatalf("错误必须点名写集合:%v", err) + } +} + +// 编排路径上的同一个断言:Run 是按 target.(WriteSetPlanner) 决定要不要预检的, +// 所以包装体必须在**真实调用链里**也把预检带上(只测直接调用内层会漏掉这一层)。 +type orchestratorTarget struct { + planned int + applied []libraryrelease.Stage +} + +func (t *orchestratorTarget) Current(context.Context) (libraryrelease.CurrentState, error) { + return libraryrelease.CurrentState{}, nil +} +func (t *orchestratorTarget) Apply(_ context.Context, stage libraryrelease.Stage, _ string) error { + t.applied = append(t.applied, stage) + return nil +} +func (t *orchestratorTarget) Verify(context.Context, libraryrelease.Expectation) error { return nil } +func (t *orchestratorTarget) Restore(context.Context, libraryrelease.BackupRef) error { return nil } +func (t *orchestratorTarget) PlanWriteSet(_ context.Context, plan libraryrelease.WriteSetPlan) (libraryrelease.WriteSet, error) { + t.planned++ + set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: plan.JobID, Target: plan.Target, + TenantID: 10001, KnowledgeBaseID: "kb", BackupSnapshotID: plan.BackupSnapshotID, + TargetSnapshotID: plan.TargetSnapshotID, CreatedAt: time.Now().UTC(), + Universe: plan.Universe, + Rows: []libraryrelease.WriteSetRow{{Table: "resources", ID: "res-1"}}} + if err := set.Seal(); err != nil { + return libraryrelease.WriteSet{}, err + } + return set, nil +} + +type stubBackupStore struct{} + +func (stubBackupStore) Prepare(context.Context, string, libraryrelease.CurrentState) (libraryrelease.BackupRef, error) { + return libraryrelease.BackupRef{ID: "backup-1", SnapshotID: "backup-snap", + Universe: map[string]libraryrelease.TableFingerprint{"resources": {Count: 1, Digest: "abc"}}}, nil +} + +func TestRunPlansWriteSetThroughContentTrackedWrapper(t *testing.T) { + inner := &orchestratorTarget{} + tracked := &contentTrackedTarget{inner: inner, onApply: func() {}} + now := time.Now().UTC() + request := libraryrelease.Request{JobID: "job-1", Target: "internal", SnapshotID: "snap-1", + ParamsDigest: "digest-1", Now: now, + Grant: libraryrelease.Grant{Target: "internal", SnapshotID: "snap-1", ParamsDigest: "digest-1", + ExpiresAt: now.Add(time.Hour), AuthorizedBy: "acceptance"}} + outcome := libraryrelease.Run(context.Background(), request, tracked, stubBackupStore{}, nil) + if outcome.State != "succeeded" { + t.Fatalf("outcome = %+v", outcome) + } + if inner.planned != 1 { + t.Fatalf("编排路径没有经过包装层触发写集合预检,planned=%d", inner.planned) + } + if outcome.Backup.WriteSet == nil || outcome.Backup.WriteSet.Digest == "" { + t.Fatalf("预检结果必须带回给编排层(恢复要按它清理):%+v", outcome.Backup) + } + if len(inner.applied) != len(libraryrelease.Stages()) { + t.Fatalf("四类写入必须都执行,applied=%v", inner.applied) + } +} + +// 复用登记必须把"这一轮"的字段合并进已持久化的证据,而不是换一份新的。 +// +// 现场(2026-10-30 演练):BackupPrepared 在接管复用时新造证据,把首次规划写入的 +// writeset_* 整段抹掉;verify_effective 的摘要从 fddd98cf… 变成空,第二次中断 +// 再接管就读不回写集合。这里把"抹掉"这件事在纯函数层面钉死。 +func TestPrebackupEvidenceKeepsWriteSetAnchorOnReuse(t *testing.T) { + existing := map[string]any{"backup_snapshot": "backup-snap", "job": "job-1", + "backup_bytes": float64(4096), "writeset_digest": "digest-1", + "writeset_universe_digest": "universe-1", "writeset_rows": float64(3), + "index_mapping_sha256": "mapping-old"} + evidence, err := prebackupEvidence(existing, libraryrelease.BackupRef{ID: "backup-backup-snap", + SnapshotID: "backup-snap", Bytes: 4096, Reused: true}, "job-1", "mapping-live") + if err != nil { + t.Fatalf("复用合并:%v", err) + } + for key, want := range map[string]any{"writeset_digest": "digest-1", "writeset_universe_digest": "universe-1", + "writeset_rows": float64(3), "backup_bytes": int64(4096), "backup_snapshot": "backup-snap", + "job": "job-1", "backup_reused": true, "index_mapping_sha256": "mapping-live"} { + if got := evidence[key]; got != want { + t.Fatalf("复用后 %s = %v, want %v(整份替换会丢写集合锚点)", key, got, want) + } + } + + // 复用但没有 bytes(历史缺陷的调用形状):字节必须从已登记的证据里补回来。 + restored, err := prebackupEvidence(existing, libraryrelease.BackupRef{SnapshotID: "backup-snap", Reused: true}, + "job-1", "") + if err != nil { + t.Fatalf("复用缺字节时应从证据补齐:%v", err) + } + if restored["backup_bytes"] != int64(4096) { + t.Fatalf("补回来的字节 = %v, want 4096", restored["backup_bytes"]) + } + + // 负例:身份不符一律失败,不做"看起来对就合"。 + foreignJob := map[string]any{"job": "job-2", "writeset_digest": "digest-other"} + if _, err := prebackupEvidence(foreignJob, libraryrelease.BackupRef{SnapshotID: "backup-snap", + Bytes: 4096, Reused: true}, "job-1", ""); err == nil { + t.Fatal("证据属于别的作业时必须失败(否则会把别人的写集合带进来)") + } + foreignSnapshot := map[string]any{"job": "job-1", "backup_snapshot": "backup-other"} + if _, err := prebackupEvidence(foreignSnapshot, libraryrelease.BackupRef{SnapshotID: "backup-snap", + Bytes: 4096, Reused: true}, "job-1", ""); err == nil { + t.Fatal("证据绑定别的预备份时必须失败") + } + // 负例:两份不同的字节数不能被当成同一份备份。 + if _, err := prebackupEvidence(existing, libraryrelease.BackupRef{SnapshotID: "backup-snap", + Bytes: 2048, Reused: true}, "job-1", ""); err == nil { + t.Fatal("复用字节数与已登记不一致时必须失败") + } + // 负例:复用却拿不出任何可信字节 → 拒绝(不许写 0)。 + if _, err := prebackupEvidence(map[string]any{"job": "job-1"}, libraryrelease.BackupRef{SnapshotID: "backup-snap", + Reused: true}, "job-1", ""); err == nil { + t.Fatal("复用缺少可信字节数时必须失败") + } +} + +// 写集合只能落定一次:第二次预检摘要不同 ⇒ 台账不再描述"写了什么" ⇒ 失败。 +func TestAnchorWriteSetRefusesConflictingDigestAndForeignEvidence(t *testing.T) { + set := sealedLedger(t, "") + recorded := func(evidence map[string]any) *fakeVersionStore { + return &fakeVersionStore{versions: []governance.LibraryVersion{{Kind: governance.LibraryVersionProductionPrebackup, + SnapshotID: "backup-snap", SourceJobID: "job-1", Evidence: evidence}}} + } + anchor := func(store libraryVersionLedger) error { + return anchorWriteSet(context.Background(), store, "", "internal", "job-1", "m", set) + } + if err := anchor(recorded(map[string]any{"job": "job-2"})); err == nil { + t.Fatal("版本证据属于别的作业时必须失败") + } + if err := anchor(recorded(map[string]any{"writeset_digest": "another-digest"})); err == nil { + t.Fatal("已登记不同写集合摘要时必须失败") + } + // 正例对照:同一摘要重复登记是幂等的。 + ok := recorded(map[string]any{"writeset_digest": set.Digest}) + if err := anchor(ok); err != nil { + t.Fatalf("同一份写集合重复登记应当幂等:%v", err) + } + if ok.recorded == nil || ok.recorded.Evidence["writeset_digest"] != set.Digest { + t.Fatalf("登记没有落到证据上:%+v", ok.recorded) + } +} + +// 复用没有真实字节时不许继续:0 字节基线在生效版本证据里与"空备份"无法区分。 +func TestLedgerBackupStoreRefusesZeroBytes(t *testing.T) { + set := sealedLedger(t, "") + store := ledgerBackupStore{ref: libraryrelease.BackupRef{ID: "backup-1", SnapshotID: "backup-snap"}, write: &set} + if _, err := store.Prepare(context.Background(), "target-snap", libraryrelease.CurrentState{}); err == nil { + t.Fatal("缺少真实字节数时接管必须失败") + } + store.ref.Bytes = 4096 + ref, err := store.Prepare(context.Background(), "target-snap", libraryrelease.CurrentState{}) + if err != nil { + t.Fatalf("prepare: %v", err) + } + if ref.Bytes != 4096 || !ref.Reused { + t.Fatalf("复用预备份必须带真实字节与 Reused:%+v", ref) + } +} + +// 生效版本证据必须带真实字节;没有字节时不许写 0 冒充。 +func TestEffectiveEvidenceCarriesRealBytes(t *testing.T) { + withBytes := effectiveEvidence(libraryrelease.BackupRef{SnapshotID: "backup-snap", Bytes: 4096}, "restore", "m") + if withBytes["backup_bytes"] != int64(4096) || withBytes["backup_snapshot"] != "backup-snap" || + withBytes["action"] != "restore" || withBytes["index_mapping_sha256"] != "m" { + t.Fatalf("生效版本证据 = %v", withBytes) + } + without := effectiveEvidence(libraryrelease.BackupRef{SnapshotID: "backup-snap"}, "restore", "") + if _, ok := without["backup_bytes"]; ok { + t.Fatalf("未知字节数不许写成 0:%v", without) + } +} diff --git a/cmd/worker/main.go b/cmd/worker/main.go index acdefac..feeb1a4 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -3,11 +3,14 @@ package main import ( "context" "encoding/json" + "errors" "fmt" "log" "os" "os/signal" "path/filepath" + "strings" + "sync" "syscall" "time" @@ -17,11 +20,14 @@ import ( "knowledge-governance/internal/governance" "knowledge-governance/internal/jobs" "knowledge-governance/internal/libraryagent" + "knowledge-governance/internal/libraryhandoff" "knowledge-governance/internal/libraryrelease" "knowledge-governance/internal/librarysnapshot" postgresstore "knowledge-governance/internal/platform/postgres" "knowledge-governance/internal/platform/weknora" + "knowledge-governance/internal/readiness" "knowledge-governance/internal/versionhistory" + "knowledge-governance/internal/weknoraaccess" artifactfetch "knowledge-governance/internal/workflows/artifactfetch" catalogrefresh "knowledge-governance/internal/workflows/catalogrefresh" "knowledge-governance/internal/workflows/sourcescan" @@ -29,11 +35,23 @@ import ( ) // libraryStageRecorder 把执行阶段写进持久作业,页面刷新/worker 重启后仍可复现。 +// libraryStageStore 是阶段/证据记录用到的存储面:由 libraryAttemptWriter 实现, +// 所以阶段进度与版本登记天然带执行代次(失租代次写不进去)。 +type libraryStageStore interface { + UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error + AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error + LibraryVersionByRef(ctx context.Context, scope string, kind governance.LibraryVersionKind, sourceJobID, snapshotID string) (governance.LibraryVersion, bool, error) + RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error +} + type libraryStageRecorder struct { - store *postgresstore.Store - jobID string - scope string - totals map[string]stageSize + store libraryStageStore + jobID string + scope string + // operationID 让版本事件 ID 带执行意图:不同 operation 引用同一快照是两条事件, + // 不会互相覆盖证据(F02)。为空表示历史/测试路径,退回旧 ID 形状。 + operationID string + totals map[string]stageSize // mappingDigest 是本次读到的生产索引映射,随预备份一起登记成版本证据。 mappingDigest string // onBackup 在预备份完成后、写目标之前调用:把"预备份身份 + 内容风险"落盘。 @@ -84,6 +102,27 @@ func stageSizesFrom(manifest librarysnapshot.Manifest) map[string]stageSize { // libraryCaptureJobType is shared with the API which enqueues it. const libraryCaptureJobType = "library.capture" +// Retained deterministic source-content failures: the agent has already +// restored the writer, so retrying the same journal only replaces the first +// cause with "already exists". Body-index coverage markers are intentionally +// absent; that inferred rule was removed in R3f. +var terminalLibraryCaptureMarkers = []string{ + "missing library generated question index", + "empty library index content", +} + +func terminalLibraryCaptureError(err error) error { + if err == nil || !strings.Contains(err.Error(), "已执行 recover 并确认写入者恢复") { + return err + } + for _, marker := range terminalLibraryCaptureMarkers { + if strings.Contains(err.Error(), marker) { + return jobs.Permanent(jobs.ErrCodeValidationFailed, err) + } + } + return err +} + // librarySyncJobType 是生产同步作业的队列类型;与封存严格分开,状态不共用。 const librarySyncJobType = "library.sync" @@ -96,6 +135,10 @@ const libraryRestoreJobType = "library.restore" // libraryBaselineJobType 是"建立目标权威基线"的队列类型(与 API 侧常量同值)。 const libraryBaselineJobType = "library.baseline" +// libraryVerifyJobType 是"恢复验证"的队列类型:真实备份→canary→恢复→复核, +// 通过后才会产生同步闸口认的恢复证据。与 API 侧常量同值。 +const libraryVerifyJobType = "library.verify" + func main() { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() @@ -117,36 +160,53 @@ func run(ctx context.Context, getenv func(string) string) error { if err := pool.Ping(ctx); err != nil { return err } - if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { - return err + // 迁移也是"后台副作用":只有控制面那个进程拥有 DDL。云端发布执行器只读校验 + // schema 版本,落后即拒绝启动——它不该成为治理库的第二个结构决策者。 + if config.LibraryWorkerRole.ExecutesMigrations() { + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + return err + } + } else if pending, pendingErr := postgresstore.PendingMigrations(ctx, pool); pendingErr != nil { + return fmt.Errorf("治理库 schema 版本检查失败: %w", pendingErr) + } else if len(pending) > 0 { + return fmt.Errorf("治理库 schema 落后(待应用迁移 %v):本角色不拥有 DDL,先由控制面进程完成迁移", pending) } - store := postgresstore.NewStore(pool) + store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID). + WithRestoreDispatchEvidence(config.LibraryTargetJournalRoot) + log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity()) // 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败: // 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。 - if resumed, failed, resumeErr := resumeInterruptedLibraryJobs(context.Background(), store, config); resumeErr != nil { - log.Printf("library job resume failed: %v", resumeErr) - } else if resumed > 0 || failed > 0 { - log.Printf("library job resume: %d resumed, %d failed without backup", resumed, failed) - } - // 运行期也要持续接管:只在启动扫一次会漏掉"worker 在两次重启之间被杀"的情况。 - go func() { - ticker := time.NewTicker(30 * time.Second) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - resumed, failed, err := resumeInterruptedLibraryJobs(ctx, store, config) - if err != nil { - log.Printf("library job takeover sweep: %v", err) - } else if resumed > 0 || failed > 0 { - log.Printf("library job takeover sweep: %d resumed, %d failed without backup", resumed, failed) + // + // 只由"发布执行器"角色接管:release 作业的目标来自本进程配置,capture 角色的 + // 进程按本机维护配置去接管云端目标的作业,等于把快照写到另一套目标上。 + if config.LibraryWorkerRole.ExecutesRelease() { + if resumed, failed, resumeErr := resumeInterruptedLibraryJobs(context.Background(), store, config); resumeErr != nil { + log.Printf("library job resume failed: %v", resumeErr) + } else if resumed > 0 || failed > 0 { + log.Printf("library job resume: %d resumed, %d failed without backup", resumed, failed) + } + // 运行期也要持续接管:只在启动扫一次会漏掉"worker 在两次重启之间被杀"的情况。 + go func() { + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + resumed, failed, err := resumeInterruptedLibraryJobs(ctx, store, config) + if err != nil { + log.Printf("library job takeover sweep: %v", err) + } else if resumed > 0 || failed > 0 { + log.Printf("library job takeover sweep: %d resumed, %d failed without backup", resumed, failed) + } } } - } - }() - if repaired, reconcileErr := store.ReconcileLibraryJobs(context.Background(), time.Now().UTC()); reconcileErr != nil { + }() + } + // 只收拾本角色负责的 kind:跨域"顺手收拾"会把另一台执行器的在飞作业标失败。 + if repaired, reconcileErr := store.ReconcileLibraryJobs(context.Background(), time.Now().UTC(), + config.LibraryWorkerRole.LibraryJobKinds()); reconcileErr != nil { log.Printf("library job reconcile failed: %v", reconcileErr) } else if repaired > 0 { log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired) @@ -155,23 +215,50 @@ func run(ctx context.Context, getenv func(string) string) error { if err != nil { return err } - if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil { - log.Print("QA directory synchronization unavailable; handler was not registered") - } - mirrorStore, mirrorErr := configureRecordsSync(pool, getenv, config.DatabaseURL, handlers) - if mirrorErr != nil { - log.Print("QA local mirror configuration invalid; handler was not registered") + if config.LibraryWorkerRole.ExecutesSourceWork() { + // 快照搬运(本机 → 云端执行器)与云端版本回传都只有 capture 角色做: + // 它持有源归档与 SSH 凭据;release-executor 在云端没有回本机的通道。 + if handoffConfig, configured, handoffErr := libraryhandoff.FromEnv(getenv); handoffErr != nil { + return fmt.Errorf("快照搬运接线无效: %w", handoffErr) + } else if configured { + if config.LibraryWorkerRole.ExecutesRelease() { + return errors.New("快照搬运只能接在 capture 角色上:full 角色同时消费发布作业,会与云端执行器抢同一批作业") + } + handoff, buildErr := libraryhandoff.New(handoffConfig, nil) + if buildErr != nil { + return buildErr + } + registerLibraryHandoffHandlers(handlers, store, config, handoff) + go runLibraryArchivePullLoop(ctx, store, handoff, config.LibraryArchiveRoot, handoffConfig.PullInterval, + func(err error) { log.Printf("library archive pull: %v", err) }) + log.Printf("library handoff enabled: executor=%s archive=%s pull_every=%s", + handoffConfig.ExecutorContainer, handoffConfig.RemoteArchive, handoffConfig.PullInterval) + } + if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil { + log.Print("QA directory synchronization unavailable; handler was not registered") + } + mirrorStore, mirrorErr := configureRecordsSync(pool, getenv, config.DatabaseURL, handlers) + if mirrorErr != nil { + log.Print("QA local mirror configuration invalid; handler was not registered") + } + if mirrorStore != nil { + go runRecordsSyncScheduler(ctx, mirrorStore, func(error) { log.Print("QA local mirror scheduler unavailable; last committed data retained") }) + } } // 生产同步/恢复的执行器不依赖主机侧封存 agent:没有 agent socket 也要能跑。 - // 这里在全部注册之后无条件覆盖一次,确保 library.sync/library.restore 一定在队列类型里。 - handlers[librarySyncJobType] = func(ctx context.Context, job jobs.Job) error { - return runLibraryRelease(ctx, store, config, job, governance.LibraryJobSync) - } - handlers[libraryRestoreJobType] = func(ctx context.Context, job jobs.Job) error { - return runLibraryRelease(ctx, store, config, job, governance.LibraryJobRestore) - } - handlers[libraryRecoverJobType] = func(ctx context.Context, job jobs.Job) error { - return runLibraryRecovery(ctx, store, config, job) + // + // 执行域准入(R4)在这里统一判定:目标实况、旧 release 路由绑定、未释放维护窗口 + // 任何一项未知或重叠 ⇒ 这些 handler 直接拒绝执行(明确失败,无任何维护动作, + // 也不停止任何既有服务)。 + // + // 只有"发布执行器"角色注册它们:capture 角色的进程按本机目标配置执行一条 + // 指向别处目标的作业,后果是跨目标写入,不是失败重试能纠正的事。 + if config.LibraryWorkerRole.ExecutesRelease() { + admissionErr := verifyLibraryExecutionDomain(context.Background(), config, store) + if admissionErr != nil { + log.Printf("library execution domain NOT admitted: %v", admissionErr) + } + registerLibraryReleaseHandlers(handlers, store, config, admissionErr) } worker, err := jobs.NewWorker(jobs.WorkerConfig{ @@ -185,22 +272,58 @@ func run(ctx context.Context, getenv func(string) string) error { if err != nil { return err } - if ai := configureQAProcessing(pool, getenv, config.DatabaseURL); ai != nil { - go ai.Run(ctx, func(error) { log.Print("QA AI worker unavailable; durable work and original labels retained") }) + if config.LibraryWorkerRole.ExecutesSourceWork() { + if ai := configureQAProcessing(pool, getenv, config.DatabaseURL); ai != nil { + go ai.Run(ctx, func(error) { log.Print("QA AI worker unavailable; durable work and original labels retained") }) + } + go weeklyMailLoop(ctx, pool, getenv) + // 封存执行器状态:worker 是唯一能连 agent socket 的一方,它写观测、页面读观测。 + go runLibraryExecutorProbe(ctx, store, config, libraryExecutorProbeInterval) + go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) { + log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err) + }) } - if mirrorStore != nil { - go runRecordsSyncScheduler(ctx, mirrorStore, func(error) { log.Print("QA local mirror scheduler unavailable; last committed data retained") }) - } - go weeklyMailLoop(ctx, pool, getenv) - // 封存执行器状态:worker 是唯一能连 agent socket 的一方,它写观测、页面读观测。 - go runLibraryExecutorProbe(ctx, store, config, libraryExecutorProbeInterval) - go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) { - log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err) - }) - log.Printf("worker %s started (source refresh scheduler every %s)", config.WorkerID, config.SourceRefreshSchedulerInterval) + log.Printf("worker %s started role=%s release=%t source=%t (source refresh scheduler every %s)", + config.WorkerID, config.LibraryWorkerRole, config.LibraryWorkerRole.ExecutesRelease(), + config.LibraryWorkerRole.ExecutesSourceWork(), config.SourceRefreshSchedulerInterval) return worker.Run(ctx, config.PollInterval) } +type libraryCapturePersistence interface { + UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error + AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error +} + +// beginLibraryCaptureJob persists the starting state before any source +// operation. If either write fails the handler must return, so the queue cannot +// be reported completed while the business job is still pending. +func beginLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID string, now time.Time) error { + if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobRunning, "export", "", "", "", "", now); err != nil { + return fmt.Errorf("library seal job %s cannot be advanced: %w", jobID, err) + } + if err := store.UpdateLibraryStage(ctx, jobID, "export", "running", nil, nil, nil, nil, + "主机侧正在暂停写入者、导出并恢复", now); err != nil { + return fmt.Errorf("library seal job %s stage cannot be advanced: %w", jobID, err) + } + return nil +} + +// completeLibraryCaptureJob persists both terminal facts. A failed write must +// be returned (queue failed), not logged and ignored; the capture journal keeps +// replay idempotent, and the admin reconcile path can repair only after the +// exact queue/version/archive evidence is present. +func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID, snapshotID string, now time.Time) error { + if err := store.UpdateLibraryStage(ctx, jobID, "export", "succeeded", nil, nil, nil, nil, + "已封存快照 "+snapshotID, now); err != nil { + return fmt.Errorf("library seal job %s success stage cannot be persisted: %w", jobID, err) + } + if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobSucceeded, "export", "", "", + snapshotID, "", now); err != nil { + return fmt.Errorf("library seal job %s success terminal cannot be persisted: %w", jobID, err) + } + return nil +} + func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[string]jobs.Handler, error) { handlers := map[string]jobs.Handler{ "demo": func(_ context.Context, job jobs.Job) error { @@ -209,40 +332,44 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st }, "demo.sleep": jobs.DemoSleepHandler, } - catalogRunner, err := catalogrefresh.NewCommandRunner("/usr/bin/python3", "/app/scripts/live_catalog_refresh.py") - if err != nil { - return nil, fmt.Errorf("create catalog refresh runner: %w", err) + // 目录刷新与附件抓取属于"源侧"作业:它们读本机 spool、调本机脚本。 + // 发布执行器角色在云端没有这些挂载,注册它们只会抢走本机队列里的作业。 + if config.LibraryWorkerRole.ExecutesSourceWork() { + catalogRunner, err := catalogrefresh.NewCommandRunner("/usr/bin/python3", "/app/scripts/live_catalog_refresh.py") + if err != nil { + return nil, fmt.Errorf("create catalog refresh runner: %w", err) + } + catalogHandler, err := catalogrefresh.NewHandler(catalogrefresh.Config{Store: store, Runner: catalogRunner}) + if err != nil { + return nil, fmt.Errorf("create catalog refresh handler: %w", err) + } + handlers["source.catalog.refresh"] = catalogHandler.Handle + ingestionRoot := config.IngestionSpoolRoot + if ingestionRoot == "" { + ingestionRoot = config.GovernanceSpoolRoot + } + if !filepath.IsAbs(ingestionRoot) || ingestionRoot == "" { + ingestionRoot = "/var/lib/governance/ingestion" + } + fetchMaxBytes := config.ArtifactFetchMaxBytes + if config.TestWeKnoraEnabled && config.TestWeKnoraMaxUploadBytes > 0 && fetchMaxBytes > config.TestWeKnoraMaxUploadBytes { + fetchMaxBytes = config.TestWeKnoraMaxUploadBytes + } + if fetchMaxBytes <= 0 { + fetchMaxBytes = 50 * 1024 * 1024 + } + artifactRunner, err := artifactfetch.NewCommandRunner("/usr/bin/python3", "/app/scripts/artifact_fetch.py", + ingestionRoot, "ingestion", fetchMaxBytes) + if err != nil { + return nil, fmt.Errorf("create artifact fetch runner: %w", err) + } + artifactHandler, err := artifactfetch.NewHandler(artifactfetch.Config{Store: store, Runner: artifactRunner}) + if err != nil { + return nil, fmt.Errorf("create artifact fetch handler: %w", err) + } + handlers["artifact.fetch"] = artifactHandler.Handle } - catalogHandler, err := catalogrefresh.NewHandler(catalogrefresh.Config{Store: store, Runner: catalogRunner}) - if err != nil { - return nil, fmt.Errorf("create catalog refresh handler: %w", err) - } - handlers["source.catalog.refresh"] = catalogHandler.Handle - ingestionRoot := config.IngestionSpoolRoot - if ingestionRoot == "" { - ingestionRoot = config.GovernanceSpoolRoot - } - if !filepath.IsAbs(ingestionRoot) || ingestionRoot == "" { - ingestionRoot = "/var/lib/governance/ingestion" - } - fetchMaxBytes := config.ArtifactFetchMaxBytes - if config.TestWeKnoraEnabled && config.TestWeKnoraMaxUploadBytes > 0 && fetchMaxBytes > config.TestWeKnoraMaxUploadBytes { - fetchMaxBytes = config.TestWeKnoraMaxUploadBytes - } - if fetchMaxBytes <= 0 { - fetchMaxBytes = 50 * 1024 * 1024 - } - artifactRunner, err := artifactfetch.NewCommandRunner("/usr/bin/python3", "/app/scripts/artifact_fetch.py", - ingestionRoot, "ingestion", fetchMaxBytes) - if err != nil { - return nil, fmt.Errorf("create artifact fetch runner: %w", err) - } - artifactHandler, err := artifactfetch.NewHandler(artifactfetch.Config{Store: store, Runner: artifactRunner}) - if err != nil { - return nil, fmt.Errorf("create artifact fetch handler: %w", err) - } - handlers["artifact.fetch"] = artifactHandler.Handle - if config.LibraryAgentSocket != "" { + if config.LibraryAgentSocket != "" && config.LibraryWorkerRole.ExecutesSourceWork() { // 整库封存:worker 只投递请求并记录结果,真正的停机/导出/恢复发生在主机侧 // agent(同 uid unix socket)。容器里既没有 Docker socket,也没有来源凭据。 agentConfig := libraryagent.ClientConfig{Socket: config.LibraryAgentSocket, Timeout: 15 * time.Minute} @@ -258,12 +385,8 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st // 持久作业:页面读的是这里写的阶段与结果,worker 重启后仍能如实展示。 libraryJobID := "libseal-" + payload.CaptureJob startedAt := time.Now().UTC() - if advanceErr := store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobRunning, "export", "", "", "", "", startedAt); advanceErr != nil { - log.Printf("library seal job %s cannot be advanced: %v", libraryJobID, advanceErr) - } - if stageErr := store.UpdateLibraryStage(ctx, libraryJobID, "export", "running", nil, nil, nil, nil, - "主机侧正在暂停写入者、导出并恢复", startedAt); stageErr != nil { - log.Printf("library seal job %s stage update failed: %v", libraryJobID, stageErr) + if beginErr := beginLibraryCaptureJob(ctx, store, libraryJobID, startedAt); beginErr != nil { + return beginErr } // 平台审计过的精确死信解除指纹:读取失败必须阻断(fail closed), // 不能因为存储不可用就静默按"没有解除"或"全部解除"处理。 @@ -282,6 +405,11 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st "未停任何写入者;补齐来源身份配置后重试", "", "", time.Now().UTC()) return expectErr } + source := configuredCaptureSource(config, payload.Scope) + sourceID, sourceErr := source.ID() + if sourceErr != nil { + return sourceErr + } result, err := libraryagent.CaptureReleased(ctx, agentConfig, payload.Scope, payload.CaptureJob, released, expectation) finishedAt := time.Now().UTC() if err != nil { @@ -290,7 +418,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st _ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobFailed, "export", err.Error(), "agent 已执行恢复检查;确认来源 healthy 后可重试同一作业号", "", "", finishedAt) log.Printf("library capture failed scope=%s capture_job=%s: %v", payload.Scope, payload.CaptureJob, err) - return err + return terminalLibraryCaptureError(err) } // 执行后复核:结果里 agent 自报的身份必须还是期望实例,否则这次封存 // 可能来自别的栈,绝不能登记成"本实例的测试封存"。 @@ -300,39 +428,29 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st "快照已产生但来源身份不符,未登记为测试封存;核对执行器后重新封存", "", "", finishedAt) return identityErr } + if err := ensureCapturedSource(ctx, store, libraryJobID, config.LibraryArchiveRoot, result.SnapshotID, source, finishedAt); err != nil { + return err + } // 封存产物成版本记录:只登记"测试封存",绝不写成生产生效版本。 versionErr := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, payload.Scope, result.SnapshotID), Scope: payload.Scope, Kind: governance.LibraryVersionTestSealed, SnapshotID: result.SnapshotID, SourceJobID: libraryJobID, - Evidence: map[string]any{"capture_job": payload.CaptureJob, "replay": result.Replay, + Evidence: map[string]any{"source_id": sourceID, "source_identity": source, "capture_job": payload.CaptureJob, "replay": result.Replay, "requested_by": payload.RequestedBy, "expectation_fingerprint": expectationFingerprint(expectation), "agent_result": json.RawMessage(result.Payload)}, CreatedBy: payload.RequestedBy, CreatedAt: finishedAt, }) if versionErr != nil { - log.Printf("library seal job %s cannot record version: %v", libraryJobID, versionErr) + return fmt.Errorf("library seal job %s cannot record version: %w", libraryJobID, versionErr) + } + if completeErr := completeLibraryCaptureJob(ctx, store, libraryJobID, result.SnapshotID, finishedAt); completeErr != nil { + return completeErr } - _ = store.UpdateLibraryStage(ctx, libraryJobID, "export", "succeeded", nil, nil, nil, nil, - "已封存快照 "+result.SnapshotID, finishedAt) - _ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobSucceeded, "export", "", "", - result.SnapshotID, "", finishedAt) log.Printf("library capture completed scope=%s capture_job=%s snapshot=%s replay=%v requested_by=%s", payload.Scope, payload.CaptureJob, result.SnapshotID, result.Replay, payload.RequestedBy) return nil } - // 生产同步:唯一入口在 API(闸口未齐不建作业)。这里仍实现执行器, - // 但默认 fail-closed:没有闸口证据就明确失败,绝不向生产写入半个字节。 - handlers[librarySyncJobType] = func(ctx context.Context, job jobs.Job) error { - return runLibraryRelease(ctx, store, config, job, governance.LibraryJobSync) - } - handlers[libraryRestoreJobType] = func(ctx context.Context, job jobs.Job) error { - return runLibraryRelease(ctx, store, config, job, governance.LibraryJobRestore) - } - // 建立目标权威基线:目标非空又没有生效版本时的唯一入口(只读捕获 + 校验 + 登记)。 - handlers[libraryBaselineJobType] = func(ctx context.Context, job jobs.Job) error { - return runLibraryBaseline(ctx, store, config, job) - } // A crash can leave the source writer stopped: recover before taking work, // and keep the failure visible instead of pretending the worker is ready. go func() { @@ -345,7 +463,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st log.Printf("library agent reachable; freeze journals recovered") }() } - if config.VersionHistoryGiteaBaseURL != "" { + if config.VersionHistoryGiteaBaseURL != "" && config.LibraryWorkerRole.ExecutesSourceWork() { // 「版本记录」同步:匿名只读远端仓库的提交/tag,写本库快照。未配置来源就不注册, // 界面上的同步按钮也会显示"未接线",不会入队一个没人处理的作业。 client, err := versionhistory.NewGiteaClient(versionhistory.GiteaConfig{ @@ -390,7 +508,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st return nil } } - if config.PPScanEnabled { + if config.PPScanEnabled && config.LibraryWorkerRole.ExecutesSourceWork() { scanner, err := sourcescan.NewFilePPScanner(sourcescan.FilePPScannerConfig{ AllowedRoot: config.PPScanAllowedRoot, LedgerPath: config.PPScanLedgerPath, @@ -405,22 +523,30 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st } handlers["source.scan.pp"] = handler.Handle } - if !config.TestWeKnoraEnabled { + if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() { return handlers, nil } - apiKey, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) - if err != nil { + // 启动只验证凭据“存在”(缺失像以前一样拒绝启动);具体值仍由 resolver 每次调用重读。 + if _, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); err != nil { return nil, fmt.Errorf("read test WeKnora API key: %w", err) } - client, err := weknora.NewClient(weknora.ClientConfig{ - BaseURL: config.TestWeKnoraBaseURL, - APIKey: apiKey, - Timeout: config.TestWeKnoraHTTPTimeout, - AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP, - }) - if err != nil { - return nil, fmt.Errorf("create test WeKnora client: %w", err) + // 与 API 探测共用同一有效目标:网页保存的端点优先、env 只作未配置兜底; + // 当前持久化绑定优先、env 兜底;凭据每次调用重读同一 key 文件。 + remoteResolver := readiness.Resolver{ + Endpoint: func(resolveCtx context.Context) string { + if settings, settingsErr := store.GetActiveUISettings(resolveCtx); settingsErr == nil && strings.TrimSpace(settings.TestWeKnoraBaseURL) != "" { + return settings.TestWeKnoraBaseURL + } + return config.TestWeKnoraBaseURL + }, + LoadBinding: func(resolveCtx context.Context) (string, error) { + internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx) + return internal, bindingErr + }, + ReadKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) }, + DefaultKB: config.InternalRoutingKnowledgeBaseID, } + client := &weknoraaccess.Client{Resolver: remoteResolver, Timeout: config.TestWeKnoraHTTPTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP} upload, err := testweknora.NewUploadHandler(testweknora.UploadHandlerConfig{ Store: store, Client: client, @@ -436,6 +562,11 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st Client: client, PollDelay: config.TestWeKnoraPollInitial, StallAfter: config.TestWeKnoraStalledAfter, + // 页面保存的停滞阈值在这里生效;每 60 秒重读一次活动配置, + // 读失败保留上一次值,再失败才回落到启动参数。 + StallAfterSource: func() time.Duration { + return activeStalledAfter(context.Background(), store, config.TestWeKnoraStalledAfter) + }, }) if err != nil { return nil, fmt.Errorf("create test poll handler: %w", err) @@ -467,3 +598,29 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st handlers["test.remove"] = remove.Handle return handlers, nil } + +// activeStalledAfter 读取活动 UI 配置里的解析停滞阈值(带 60 秒缓存)。 +// 页面保存后无需重启 worker 即可生效;“保存即生效”不是文案,而是这里的读取。 +var stalledAfterCache struct { + mu sync.Mutex + value time.Duration + fetchedAt time.Time +} + +func activeStalledAfter(ctx context.Context, store *postgresstore.Store, fallback time.Duration) time.Duration { + stalledAfterCache.mu.Lock() + defer stalledAfterCache.mu.Unlock() + if time.Since(stalledAfterCache.fetchedAt) < time.Minute && stalledAfterCache.value > 0 { + return stalledAfterCache.value + } + settings, err := store.GetActiveUISettings(ctx) + if err != nil || settings.StalledAfterSeconds <= 0 { + if stalledAfterCache.value > 0 { + return stalledAfterCache.value + } + return fallback + } + stalledAfterCache.value = time.Duration(settings.StalledAfterSeconds) * time.Second + stalledAfterCache.fetchedAt = time.Now() + return stalledAfterCache.value +} diff --git a/deploy/cloud-test/README.md b/deploy/cloud-test/README.md new file mode 100644 index 0000000..a544aaa --- /dev/null +++ b/deploy/cloud-test/README.md @@ -0,0 +1,246 @@ +# 云测试发布目标:部署与验证(父执行) + +目标:把本机治理平台的"整库发布执行"搬到云测试主机,与目标容器同机; +本机只保留封存源、平台与 capture 角色的 worker。本文所有命令都在**目标机上**执行, +除了明确标注"本机"的两步。 + +## 0. 前置(缺一条都别继续) + +- 云端 compose 项目 `weknora-test-v071` 当前健康,且已确认 `weknora-test.dobot.cn` 的维护窗口可接受。 +- 已交付镜像:`knowledge-governance-worker:<与验收提交同 sha>`(含 `/app/libraryctl`)。 +- `/srv/kgtest-gate/{gate.py,state}`、`/srv/knowledge-governance/{library,target-journal,bundles,release-executor.env}`。 +- 治理库接入方式已定:SSH 加密反向隧道(`deploy/cloud-test/pg-forward.sh`,默认 streamlocal + unix socket)。本机 PG 在 Docker 内、无 5432 宿主机发布,**不要**写 `localhost:5432`。 + +## 1. 云端入口闸门(一次) + +**先做 compose 身份核对(不能盲 `compose up`)**:父的现场记录里,某历史容器的 label +引用了已不存在的 `/tmp/weknora-test-compose.wiki-graph.yaml`。对这类容器执行 +`docker compose up` 会让 compose 按"缺失的配置链"重建它,等于在没有可验证配置的情况下 +重建业务容器。先逐容器读回配置链,只对**配置链文件都在**的服务做 `up -d`: + +```bash +for c in $(docker ps -q --filter label=com.docker.compose.project=weknora-test-v071); do + docker inspect "$c" --format '{{.Name}} files={{index .Config.Labels "com.docker.compose.project.config_files"}}' +done +``` + +规则:`app`/`frontend` 的配置链齐全才允许 `up -d`;`ingress` 是本片段新增,没有历史包袱。 +任何服务的 config_files 里有缺失文件 → **停手**,先补回可验证配置(或让父按运维流程处理), +不要用 `compose up` 把它"顺便"重建。只用显式服务名 `up -d app ingress frontend`, +不要 `up -d` 全项目(那会把无关服务一起重建)。 + +```bash +install -d -m 0755 /srv/kgtest-gate /srv/kgtest-gate/state +install -m 0644 deploy/cloud-test/gate.py /srv/kgtest-gate/gate.py +# 叠加片段来自本仓库 deploy/cloud-test/compose.release-overlay.yaml +cd /opt/weknora-test-v071 # 现有 compose.yaml 所在目录 +docker compose -f compose.yaml -f /path/to/compose.release-overlay.yaml config >/dev/null +docker compose -f compose.yaml -f /path/to/compose.release-overlay.yaml up -d app ingress frontend +curl -fsS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/health # 期望 200 +docker inspect weknora-test-v071-app-1 --format '{{json .HostConfig.PortBindings}}' # 期望 null +``` + +要点:`app` 不再发布宿主机端口(写入者发布端口 = 绕开闸门的直连,拓扑校验会拒绝); +`ingress` 是宿主机 8080 上唯一的 HTTP 入口,`SIGTERM` 后写 `drain.json` 并 `exit 0`; +`restart: "no"` 保证维护窗口停下的入口不会被 Docker 自己拉回来。 + +### 1.1 入口不止 frontend:四条路径都要落到闸门上 + +只把 frontend 改成 `APP_HOST=ingress` **不等于**入口唯一。现场实测四条能到 app 的路径: + +| 入口 | 现状 | 必须改成 | 谁做 | +|---|---|---|---| +| 宿主机 nginx `weknora-test.dobot.cn` → `127.0.0.1:8088` | frontend | 不用改;frontend 的 `/api` 由 `APP_HOST` 决定 | 父不改 | +| frontend 容器 → `app:8080` | `APP_HOST=app` | overlay 已改为 `APP_HOST=ingress` | overlay | +| knowledge-adapter 容器 → `http://app:8080`(双网络) | 直连 app | adapter 的 `WEKNORA_BASE_URL=http://ingress:8080` | 父改 adapter 部署 | +| DobotAI(host 网络)→ `http://127.0.0.1:8080` | 走宿主机发布端口 | 不用改;overlay 后该端口就是闸门 | 无 | + +`scripts/verify_cloud_release_target.py` 的 `entry/*` 三项就是在核对这张表 +(adapter 仍指 `app:8080` 时报 FAIL —— 它就是一条真实存在的绕闸通道)。 + +## 2. 快照(本机打包 → 云端导入) + +自动 handoff 使用 `RELEASE_BUNDLE_DIR`(默认 `/srv/knowledge-governance/bundles`);启动器创建 0700 目录并在执行器内同路径挂载。本机 API/worker 的 `LIBRARY_HANDOFF_BUNDLE_DIR` 必须与它一致,因为 SSH 在宿主机写入、libraryctl 在容器中读取同一路径。手工单次导入可像下例单独映射 `/bundles`,但不能混用到自动传输配置。 + +```bash +# 本机(只读归档;输出了每个 blob 的 sha256,可与云端对拍) +libraryctl snapshot-pack -snapshot -bundle /var/tmp/.tar + +# 传到云端 +scp /var/tmp/.tar weknora-test:/srv/knowledge-governance/bundles/ + +# 云端:校验 + 原子装入(版本清单是提交点;重复导入幂等) +docker run --rm \ + -v /srv/knowledge-governance/library:/var/lib/knowledge-governance/library \ + -v /srv/knowledge-governance/bundles:/bundles:ro \ + knowledge-governance-worker: \ + /app/libraryctl snapshot-unpack \ + -archive /var/lib/knowledge-governance/library \ + -bundle /bundles/.tar \ + -snapshot +``` + +导入失败时不会留下版本:blob 以 sha256 命名且先落盘,版本清单最后才 Link。 +执行器每次使用快照前还会 `Load` 逐 blob 重算 sha256,所以"传输不可变"有两道证据。 + +## 2.5 治理库连接(SSH 加密反向隧道) + +本机治理 PG 在 Docker 内且没有 5432 宿主机发布,不能写 `localhost:5432`。 +`deploy/cloud-test/pg-forward.sh`(本机运行)解析 PG 容器的真实 IP 后建反向转发: + +```bash +MODE=streamlocal bash deploy/cloud-test/pg-forward.sh # 推荐:云侧只出现 unix socket +MODE=tcp bash deploy/cloud-test/pg-forward.sh # 云侧 127.0.0.1:15433,仅宿主进程可用 +``` + +- **streamlocal(默认)**:云侧生成 `/run/kgtest-pg/.s.PGSQL.5432`,执行器容器把该目录挂进去, + `DATABASE_URL` 用 `host=/run/kgtest-pg&port=5432`。没有 TCP 端口、不受"容器看不到宿主 + 127.0.0.1"影响。 +- **tcp**:`ssh -R 127.0.0.1:15433` 只在云**宿主机** loopback 上;执行器容器里的 + 127.0.0.1 是它自己,**不能**直接用。要用就必须在云侧再加 docker bridge → 127.0.0.1 + 的桥接(socat/haproxy),那是父的运维决定,脚本不替你开。 +- 隧道断 = 执行器拿不到租约 = 作业 fail-closed,目标保持维护态(不会"假装成功")。 + +### 治理凭据与挂载 + +目标机准备非空 0600 `/srv/knowledge-governance/governance.pgpass`,只读挂载为 +`/run/secrets/governance_pgpass`;env 必须显式设置 `PGPASSFILE` 为该容器路径。 +Unix socket 的 pgpass 主机匹配使用 `localhost`,字段中的冒号和反斜线须按 pgpass 规则转义。 +不要把本机无密码 DATABASE_URL 当成已携带凭据。启动器挂载 `/run/kgtest-pg`, +默认网络为 `weknora-test-v071-network`;目录或密码文件不满足要求时在重建前拒绝。 +可用 `RELEASE_PG_SOCKET_DIR` / `RELEASE_PGPASS_FILE` 覆盖宿主路径,容器路径不变。 + +执行器显式启动 `/app/worker`,不能沿用镜像默认的 `/app/api`;仅该执行器以 +`--user 0:0` 运行,访问 root 私有 socket、0600 凭据和 0700 归档。挂载 Docker socket +意味着它具有宿主容器控制权限,并非只读权限;不得把该身份用于对外 API 或前端。 +镜像必须预先加载,启动使用 `--pull never`,不允许现场隐式拉取替代产物。 + +## 3. 执行器 + +```bash +# 1) 填写 /srv/knowledge-governance/release-executor.env(0600 root), +# 字段见 deploy/cloud-test/release-executor.env.example。 +# 2) 先让本机变成 capture 角色(否则两边都注册 release,谁抢到按谁的配置执行): +# 本机 compose 加 LIBRARY_WORKER_ROLE=capture 重启 worker,日志应出现 +# role=capture release=false source=true。 +# 3) 起云端执行器: +RELEASE_EXECUTOR_IMAGE=knowledge-governance-worker: bash deploy/cloud-test/run-release-executor.sh +docker logs --tail 30 kgtest-release-executor # 期望:execution domain admitted / role=release-executor +``` + +## 4. 只读预检(任何时候都可跑) + +```bash +python3 scripts/verify_cloud_release_target.py --host weknora-test --snapshot +``` + +判据:ssh、项目服务清单、写入者无发布端口、闸门 healthy 且发布 8080、经闸门 /health=200、 +drain 目录可写且无残留、redis/ES/RDS 可达、归档根 0700、快照清单摘要自证、执行器角色。 +`MANUAL target-graph` 必须人工确认目标 KB `graph_enabled=false`(发布路径不写 Neo4j)。 +有 FAIL 即退出码 1。 + +## 5. 回退 + +```bash +docker rm -f kgtest-release-executor +# 本机 worker 改回 LIBRARY_WORKER_ROLE=full(或保持 capture)并重启 +cd /opt/weknora-test-v071 +docker compose -f compose.yaml -f /path/to/compose.release-overlay.yaml down # 或去掉 -f overlay 重新 up: +docker compose -f compose.yaml up -d app frontend +``` + +治理库不需要回滚:维护记录与版本证据都带 `target_fingerprint` 与实例身份, +跨目标不会被误认。云端归档里的快照与预备份保留,不自动删除。 + +## 6. 已知边界(交付时写明,不当成已完成) + +- 本机 UI 的"版本与快照"读的是本机归档:云端预备份/快照原件在页面上看不到, + 只能看到治理库里的版本证据行。需要页面展示云端原件时再单独做只读读回链路。 +- 目标 KB `graph_enabled` 没有 fail-closed 检查(当前只有源侧导出拒绝)。 +- 维护窗口内 `weknora-test.dobot.cn` 会不可用(这是语义正确的关闭)。 +- **归档自动传输未实现**:今天只有 `libraryctl snapshot-pack / snapshot-unpack`(人工两步)。 + UI 里点"发布/恢复"不会把本机快照送到云端执行器,也不会把云端预备份读回本机页面。 + 一致寻址的现状与阻塞见本文 §7。 + +## 7. 归档寻址:现状、缺口与阻塞(不许当成已完成) + +**寻址口径(现状)**:快照是内容寻址的(`snapshot_id` = 版本清单 sha256),本机与云端 +各自有独立 `LIBRARY_ARCHIVE_ROOT`;治理库的版本证据行记录 `snapshot_id` 与 `source_job_id`。 +因此"这份版本是谁"跨主机一致,而"这份版本的字节现在在哪台机器"**没有**被记录。 + +后果(真实缺口): +1. 本机页面能看到云端执行器登记的版本证据行,但**看不到云端预备份/快照原件**; + 点"按历史版本恢复"时,若该快照不在执行器所在机器上,作业会在装配阶段失败 + (`librarysnapshot.Load` 读不到),错误信息只会说"快照不可读"。 +2. UI 无法触发传输:本机 API 没有读归档/推送归档的接口,云端也**不能**主动连本机 + (公网 22 关闭、无入站);今天唯一通路是人工 `pack` → `scp` → `unpack`。 + +**为什么不用脚本硬糊**:定时 rsync/scp 无法保证"版本清单与 blob 同时可见 + 字节可校验", +而发布前的 `Load` 会逐 blob 重算 sha256,半拷贝的归档会让发布在维护窗口内失败, +正好落在最不该失败的时刻。 + +**建议的最小协议(未实现,需父批准)**:给执行器一条**出站**拉取路径 —— +`GET /api/v1/library/snapshots/{id}/bundle`(本机 API 侧,仅服务已封存且未过期的快照, +返回带 sha256 的流)+ 在版本证据里补 `archive_host` 字段。执行器在装配前若本地缺快照, +按证据里的 `archive_host` 标记走到该 API 拉取并复用 `Unpack` 的校验/原子落位。 +工作量约:API 1 个只读端点 + 证据字段 + 执行器一次拉取调用(~300 行 + 权限/审计)。 +通路本身可以复用已有的 `ssh -R`(再加一条把本机 API 映到云侧 loopback/unix socket 的 +反向转发),所以阻塞不在"连不上",而在:① 该端点等于让云侧凭据读走整库快照, +需要单独的鉴权与审计口径;② 版本证据要新增 `archive_host`,否则 UI 无法判断"该去哪台机器取"; +③ 拉取失败必须与"目标已进维护窗口"的时序绑定,不能先开窗口再发现取不到。 +这三条都要父拍板,属于新协议而非配置。 +## 8. 自动快照搬运(run03 已实现,需按本节接线) + +没有这一步,UI 点"发布/恢复"只会在执行器上以"快照不在本机归档"失败(fail-closed,不会开维护窗口)。 +接线后链路变成:**授权 → 搬运并双向校验 → 才投递发布作业**。 + +### 8.1 接线(API 与 capture worker 都要有同一组值) + +| 变量 | 含义 | +|---|---| +| `LIBRARY_HANDOFF_SSH_CONFIG` | 0600 ssh 配置(与 `BACKUP_HOST_SSH_CONFIG` 同一份即可,指向 `weknora-test`) | +| `LIBRARY_HANDOFF_TARGET` | ssh 配置里的 Host 别名(`weknora-test`) | +| `LIBRARY_HANDOFF_EXECUTOR` | 云端执行器容器名(`kgtest-release-executor`) | +| `LIBRARY_HANDOFF_BUNDLE_DIR` | 云端暂存目录(`/srv/knowledge-governance/bundles`,只放传输中的 bundle) | +| `LIBRARY_HANDOFF_REMOTE_ARCHIVE` | 云端归档根(必须等于执行器 env 的 `LIBRARY_ARCHIVE_ROOT`) | +| `LIBRARY_HANDOFF_STAGING_DIR` | 本机暂存目录(容器内可见的 0700 目录) | +| `LIBRARY_HANDOFF_MAX_BYTES` | 单份 bundle 上限(默认 8GiB) | +| `LIBRARY_HANDOFF_TIMEOUT` | 单个远端动作超时(默认 10m) | +| `LIBRARY_HANDOFF_PULL_INTERVAL` | 云端版本回传本机的扫描间隔(默认 5m;游标跨轮保留,重启后从头核对) | + +目标/源身份(run05 起必需,二者**必须不同**): +`LIBRARY_PRODUCTION_TENANT_ID` + `LIBRARY_PRODUCTION_KB_INTERNAL/EXTERNAL` = 云测试验收专用 KB +(对内 `a8e9c8ad-411c-4c53-8421-599d29e9b179`、对外 `2e980686-2233-4c4e-b5a6-8b0069477b8e`,tenant 10000); +`LIBRARY_SOURCE_TENANT_ID` + `LIBRARY_SOURCE_KB_INTERNAL/EXTERNAL` = 源 WKNFull 的 KB。 +搬运按版本台账判定原产地:封存快照用源绑定核对,预备份用目标绑定核对;没有捕获事件或两类都有的快照一律拒绝。 +原有业务四 KB(graph=true)不关闭、不覆盖;验收专用 KB 的 graph_enabled=false。 + +任一项缺失但其余存在 ⇒ **启动失败**(半接线最坏:API 以为会搬运、worker 搬不动)。 +全都不配 ⇒ 保持旧行为(本机目标直接发布),不受影响。 + +### 8.2 行为 + +- 发布/恢复作业先入 `library.snapshot.handoff`(capture 角色执行):本机 `Load` 逐 blob 校验 → + `Pack` → SSH 流式写云端暂存 → 原子改名 → 云端 `libraryctl snapshot-unpack`(再逐 blob 校验)→ + 读回版本清单摘要自证 → 身份(scope/tenant/KB)与治理库作业一致 → **才**投递 `library.sync|restore` + (ID 仍是 `QueueJobIDFor(jobID)`,接管/续作路径不变)。 +- 失败即作业失败,文案写明"未进入维护窗口、未写任何知识";发布队列行不存在。 +- 云端已有同 ID 且校验通过 ⇒ 复用(不发数据);同 ID 异内容 ⇒ 拒绝。 +- 同一快照并发搬运:本机 flock 串行化,云端内容寻址 + Link 幂等。 +- 暂存 bundle 用后即删(只删自己这次的传输文件);归档本体(versions/blobs)**永不自动清理**。 +- 本机回传:capture 角色按 `library_jobs` 里已成功作业的 `snapshot_id` 扫描,本机缺哪个就 + `Fetch` 哪个(云端 pack → SSH 流回 → 本机 `Unpack` 逐 blob 校验)。回传成功后本机既有 + API/页面路径(列表/详情/差异/存储/历史恢复)读到的就是真实字节;回传失败则版本不出现在本机, + 页面不会把它显示成可恢复。 + +### 8.3 只读核对命令(父可用) + +```bash +# 本机:把某个已封存快照推到执行器(会打印 bundle 每个 blob 的 sha256,可对拍) +LIBRARY_HANDOFF_...=... libraryctl snapshot-push -snapshot -scope internal -tenant -kb +# 本机:把云端快照取回本机归档 +libraryctl snapshot-fetch -snapshot +``` + +两条命令都只认部署注入的配置:不接受调用方指定远端路径/容器/上游地址。 diff --git a/deploy/cloud-test/compose.release-overlay.yaml b/deploy/cloud-test/compose.release-overlay.yaml new file mode 100644 index 0000000..86013fe --- /dev/null +++ b/deploy/cloud-test/compose.release-overlay.yaml @@ -0,0 +1,66 @@ +# 云测试用作发布目标时的 compose 叠加片段(project: weknora-test-v071) +# +# 作用:把"唯一入口"这个不变量在云测试上真正建立起来,让维护窗口有可信的排空证据。 +# 1. app 不再发布宿主机端口(写入者发布端口 = 存在绕开闸门的直连通道,拓扑校验会拒绝); +# 2. 新增 ingress 闸门,成为宿主机 8080 上唯一的 HTTP 入口,并在 SIGTERM 时写 drain.json; +# 3. frontend 的 API 目标改为 ingress(这样网页流量也走闸门,关闸门 = 站点真的关)。 +# +# 使用(父执行,先校验再应用): +# docker compose -f compose.yaml -f compose.release-overlay.yaml config >/dev/null +# docker compose -f compose.yaml -f compose.release-overlay.yaml up -d app ingress frontend +# +# !reset 需要 Docker Compose >= 2.24(云端实测 2.40.3)。 +# +# 网络:本项目实际网络名是 weknora-test-v071-network(不是 compose 默认的 *_default)。 +# 网络:本项目实际网络名是 weknora-test-v071-network(不是 compose 默认的 *_default)。 +# ingress 用独立 key `release_target` 以 external 方式加入它:既不重定义原 default, +# 也不靠"默认网络恰好同名"这种巧合。 +name: weknora-test-v071 + +services: + app: + # 写入者不发布端口;验证器/发布执行器的直连走 docker 网络里的服务名 app:8080。 + ports: !reset [] + + ingress: + # 唯一对外入口:关入口=停这个闸门。镜像只用现成的 python,不构建、不改 WeKnora 镜像。 + image: python:3.13-slim + container_name: kgtest-ingress + # restart: "no" 是硬约束:维护窗口把入口停下之后,Docker 不允许自己把它拉回来。 + restart: "no" + command: ["python3", "/gate/gate.py"] + environment: + # 闸门监听端口 = 宿主机发布端口,入口 URL 用同端口,拓扑校验才可比对。 + GATE_PORT: "8080" + GATE_UPSTREAM_HOST: app + GATE_UPSTREAM_PORT: "8080" + GATE_DRAIN_FILE: /gate-state/drain.json + GATE_DRAIN_TIMEOUT: "45" + ports: + - "127.0.0.1:8080:8080" + volumes: + # gate.py 与 state 都在宿主机固定目录;发布执行器挂同一个 state 目录, + # 所以"删除 drain 记录 / 读回排空证据"发生在同一个真实文件上。 + - /srv/kgtest-gate/gate.py:/gate/gate.py:ro + - /srv/kgtest-gate/state:/gate-state + healthcheck: + test: ["CMD", "python3", "-c", "import socket;s=socket.create_connection(('127.0.0.1',8080),2);s.close()"] + interval: 3s + timeout: 3s + retries: 30 + start_period: 5s + stop_grace_period: 60s + # 用独立 key 指向项目真实网络(external,不改原 compose 的 default 定义): + # 这样 ingress 与 app 在同一条网络里能按服务名互通,也不会凭空创建 *_default。 + networks: + - release_target + + frontend: + environment: + # 网页的 /api 也要经过闸门,否则"关入口"只关了一半。 + APP_HOST: ingress + +networks: + release_target: + external: true + name: weknora-test-v071-network diff --git a/deploy/cloud-test/deployment_test.go b/deploy/cloud-test/deployment_test.go new file mode 100644 index 0000000..feb90ae --- /dev/null +++ b/deploy/cloud-test/deployment_test.go @@ -0,0 +1,24 @@ +package deployment_test + +import ( + "os/exec" + "testing" +) + +// Exercise the real shell scripts with isolated fake Docker/SSH commands. +// This checks deployment argv contracts, not live cloud connectivity. +func TestReleaseExecutorAuthorization(t *testing.T) { + cmd := exec.Command("python3", "test_release_executor.py") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("executor authorization contract: %v\n%s", err, out) + } +} + +func TestDeploymentScripts(t *testing.T) { + cmd := exec.Command("python3", "test_deployment.py") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("deployment contract: %v\n%s", err, out) + } +} diff --git a/deploy/cloud-test/gate.py b/deploy/cloud-test/gate.py new file mode 100755 index 0000000..e960079 --- /dev/null +++ b/deploy/cloud-test/gate.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""目标入口闸门:唯一去 app 的 HTTP 路径,负责"关入口 + 排空在途请求"。 + +为什么必须有一个独立闸门,而不是在被代理的 WeKnora 上排空: +v0.7.1 的 app 收到 SIGTERM 会先关监听、随后因 use of closed network connection +直接 exit(1),在途请求被切断。所以"入口已关、在途已归零"这条证据只能在真正的 +连接入口上产生,并且必须落在**目标主机自己的**文件上(治理侧的维护协调器会先删除 +这个文件、发 SIGTERM、等容器退出、再读回;读到旧文件就是伪造证据)。 + +连接语义(两条都被真实业务踩过,不是理论问题): + 1. 上游读**不设超时**:`create_connection(timeout=...)` 只对 connect 生效,连上后 + 必须 `settimeout(None)`。否则一条等待模型输出超过这个秒数的空闲流会被闸门自己 + 掐断 —— 那是"闸门把正常业务掐了",不是"连接已经排空"。 + 2. 半关闭按 TCP 语义单向传播:客户端写完请求后关自己的写端(shutdown(SHUT_WR))时, + 只把 EOF 传到上游,**不能**顺手把上游→客户端方向也拆掉,否则响应会被截断。 + 只有真正的错误(RST 等)才双向拆除,避免另一侧线程永久挂住。 + +SIGTERM 语义(顺序是证据的一部分): + 1. 立即关闭监听 —— 新连接被拒 = 入口已关; + 2. 等在途连接自然结束(上限 GATE_DRAIN_TIMEOUT); + 3. 写 drain.json(临时文件 + fsync + rename,0600)后 exit 0(drained) + / exit 2(drain_timeout,此时绝不能当成排空成功)。 +""" + +import json +import os +import signal +import socket +import sys +import threading +import time + +GATE_PORT = int(os.environ.get("GATE_PORT", "8080")) +UPSTREAM_HOST = os.environ.get("GATE_UPSTREAM_HOST", "app") +UPSTREAM_PORT = int(os.environ.get("GATE_UPSTREAM_PORT", "8080")) +DRAIN_FILE = os.environ.get("GATE_DRAIN_FILE", "/gate-state/drain.json") +DRAIN_TIMEOUT = float(os.environ.get("GATE_DRAIN_TIMEOUT", "45")) +CONNECT_TIMEOUT = float(os.environ.get("GATE_CONNECT_TIMEOUT", "10")) + +active = 0 +served = 0 +lock = threading.Lock() +listener = None +stopping = threading.Event() + + +def write_state(payload): + if not os.path.isabs(DRAIN_FILE): + print("gate: GATE_DRAIN_FILE must be an absolute path", file=sys.stderr, flush=True) + os._exit(3) + payload = dict(payload, at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), pid=os.getpid()) + directory = os.path.dirname(DRAIN_FILE) + os.makedirs(directory, exist_ok=True) + tmp = DRAIN_FILE + ".tmp" + fd = os.open(tmp, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as handle: + json.dump(payload, handle) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp, DRAIN_FILE) + + +def pump(src, dst): + """单向搬运并传播半关闭。正常 EOF 只关对端写端;异常则双向拆除。""" + clean = False + try: + while True: + data = src.recv(65536) + if not data: + clean = True + break + dst.sendall(data) + except OSError: + clean = False + finally: + if clean: + try: + dst.shutdown(socket.SHUT_WR) + except OSError: + pass + else: + for sock in (src, dst): + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + +def handle(client): + global active, served + with lock: + if stopping.is_set(): + client.close() + return + active += 1 + served += 1 + current = active + print(f"conn:open active={current} served={served}", flush=True) + upstream = None + try: + upstream = socket.create_connection((UPSTREAM_HOST, UPSTREAM_PORT), timeout=CONNECT_TIMEOUT) + # 建连超时只对 connect 生效;读超时必须清掉,否则长静默流会被掐断。 + upstream.settimeout(None) + client.settimeout(None) + except OSError: + with lock: + active -= 1 + remaining = active + print(f"conn:close active={remaining} upstream-unreachable", flush=True) + if upstream is not None: + upstream.close() + client.close() + return + left = threading.Thread(target=pump, args=(client, upstream), daemon=True) + right = threading.Thread(target=pump, args=(upstream, client), daemon=True) + left.start() + right.start() + + def finish(): + global active + try: + left.join() + right.join() + finally: + # 两个方向都结束才算这条连接离开:只看一个方向会把半关的连接当"已排空"。 + for sock in (client, upstream): + try: + sock.close() + except OSError: + pass + with lock: + active -= 1 + remaining = active + print(f"conn:close active={remaining}", flush=True) + + threading.Thread(target=finish, daemon=True).start() + + +def on_term(_signum, _frame): + stopping.set() + if listener is not None: + try: + listener.close() + except OSError: + pass + + +def main(): + global listener + signal.signal(signal.SIGTERM, on_term) + signal.signal(signal.SIGINT, on_term) + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("0.0.0.0", GATE_PORT)) + listener.listen(256) + write_state({"phase": "serving", "active": 0, "served": 0}) + started = time.time() + print(f"gate: listening on {GATE_PORT} -> {UPSTREAM_HOST}:{UPSTREAM_PORT} drain={DRAIN_FILE}", + flush=True) + while not stopping.is_set(): + try: + client, _ = listener.accept() + except OSError: + break + handle(client) + + with lock: + active_at_close = active + drain_started = time.time() + write_state({"phase": "draining", "active": active_at_close, "served": served}) + deadline = drain_started + DRAIN_TIMEOUT + while time.time() < deadline: + with lock: + if active == 0: + break + time.sleep(0.05) + with lock: + remaining = active + drain_ms = int((time.time() - drain_started) * 1000) + uptime_ms = int((time.time() - started) * 1000) + if remaining != 0: + write_state({"phase": "drain_timeout", "active": remaining, "served": served, + "active_at_close": active_at_close, "drain_ms": drain_ms, + "uptime_ms": uptime_ms}) + os._exit(2) + write_state({"phase": "drained", "active": 0, "served": served, + "active_at_close": active_at_close, "drain_ms": drain_ms, + "uptime_ms": uptime_ms}) + os._exit(0) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/deploy/cloud-test/pg-forward.sh b/deploy/cloud-test/pg-forward.sh new file mode 100755 index 0000000..bb3c4b9 --- /dev/null +++ b/deploy/cloud-test/pg-forward.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# 治理库 → 云测试发布执行器:SSH 加密反向转发(在**本机控制面**上运行)。 +# +# 为什么不能写 localhost:5432:本机治理 PG 跑在 Docker 里,没有 5432 宿主机发布, +# 也不允许为它开公网/主机端口。所以只能: +# 1. 先解析 PG 容器在它自己网络里的真实 IP; +# 2. 用 ssh -R 建反向转发,让云侧出现一个**只属于云主机/容器**的入口; +# 3. 执行器通过这个入口连库,凭据只在本机与云端 0600 env 之间传递。 +# +# 两种模式(默认 streamlocal,不占 TCP 端口、不开监听): +# streamlocal 云侧生成 unix socket(如 /run/kgtest-pg/.s.PGSQL.5432),执行器容器把该目录 +# 挂进去,DSN 用 host=/run/kgtest-pg。**推荐**:没有 TCP 暴露, +# 不受"容器看不到宿主机 127.0.0.1"影响。 +# tcp 云侧 127.0.0.1:15433 loopback。⚠️ 只有云**宿主机**上的进程能用; +# 容器里的进程看到的 127.0.0.1 是容器自己。要用必须在云侧再加一个 +# 从 docker bridge 到 127.0.0.1 的桥接(socat/haproxy),那属于父运维决定, +# 本脚本不替你开。 +# +# 用法: +# MODE=streamlocal bash deploy/cloud-test/pg-forward.sh +# MODE=tcp REMOTE_PORT=15433 bash deploy/cloud-test/pg-forward.sh +set -euo pipefail + +SSH_HOST="${SSH_HOST:-weknora-test}" +PG_CONTAINER="${PG_CONTAINER:-knowledge-governance-p1-postgres-1}" +MODE="${MODE:-streamlocal}" +REMOTE_SOCKET="${REMOTE_SOCKET:-/run/kgtest-pg/.s.PGSQL.5432}" +REMOTE_PORT="${REMOTE_PORT:-15433}" + +die() { echo "pg-forward: $*" >&2; exit 1; } + +command -v docker >/dev/null || die "需要 docker(解析治理 PG 容器 IP)" +docker inspect "$PG_CONTAINER" >/dev/null 2>&1 || die "找不到容器 $PG_CONTAINER" + +# 只取第一个网络里的 IP;多网络时打印提示,由人确认走哪个。 +IPS=$(docker inspect -f '{{range $name, $net := .NetworkSettings.Networks}}{{$name}}={{$net.IPAddress}} {{end}}' "$PG_CONTAINER") +PG_IP=$(echo "$IPS" | tr ' ' '\n' | sed -n 's/^[^=]*=\([0-9.]\+\)$/\1/p' | head -n1) +[ -n "$PG_IP" ] || die "解析不到 $PG_CONTAINER 的容器 IP(网络:$IPS)" +echo "pg-forward: 治理 PG 容器 $PG_CONTAINER -> $PG_IP:5432(网络:$IPS)" + +case "$MODE" in + streamlocal) + [[ "$REMOTE_SOCKET" =~ ^/[A-Za-z0-9_/-]+/\.s\.PGSQL\.5432$ ]] || die "REMOTE_SOCKET 必须是绝对目录下的 .s.PGSQL.5432" + ssh -o BatchMode=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 \ + "$SSH_HOST" "install -d -m 0700 -o root -g root $(dirname "$REMOTE_SOCKET")" + DSN_SHAPE="postgres://@/?host=$(dirname "$REMOTE_SOCKET")&port=5432&sslmode=disable" + echo "pg-forward: 云侧入口 unix socket = $REMOTE_SOCKET(仅云主机与挂载它的容器可见)" + echo "pg-forward: 执行器容器必须挂载 -v $(dirname "$REMOTE_SOCKET"):$(dirname "$REMOTE_SOCKET")" + echo "pg-forward: DATABASE_URL 形状 = $DSN_SHAPE" + exec ssh -N -o BatchMode=yes -o ExitOnForwardFailure=yes \ + -o ServerAliveInterval=15 -o ServerAliveCountMax=3 \ + -R "$REMOTE_SOCKET:$PG_IP:5432" "$SSH_HOST" + ;; + tcp) + echo "pg-forward: 云侧 127.0.0.1:$REMOTE_PORT -> 本机 $PG_IP:5432(仅云宿主机可用)" + echo "pg-forward: 容器内进程不能用这个 loopback;要么用 MODE=streamlocal,要么另做 bridge(父决定)" + exec ssh -N -o BatchMode=yes -o ExitOnForwardFailure=yes \ + -o ServerAliveInterval=15 -o ServerAliveCountMax=3 \ + -R "127.0.0.1:$REMOTE_PORT:$PG_IP:5432" "$SSH_HOST" + ;; + *) + die "MODE 只能是 streamlocal 或 tcp(当前 $MODE)" + ;; +esac \ No newline at end of file diff --git a/deploy/cloud-test/release-executor.env.example b/deploy/cloud-test/release-executor.env.example new file mode 100644 index 0000000..6a9a065 --- /dev/null +++ b/deploy/cloud-test/release-executor.env.example @@ -0,0 +1,71 @@ +# 云测试发布执行器(governance release-executor)配置样例 +# +# 这份文件不含任何真实凭据:值全是占位符。真实文件放在云测试主机的 +# /srv/knowledge-governance/release-executor.env,权限 0600、属主 root, +# 由父在目标机本地填写(不要把生产凭据拷过来)。 +# +# 角色是这个部署的核心:release-executor 只消费 library.sync / library.restore / +# library.recover / library.baseline,不起 scheduler、不接封存 agent、不碰 QA/测试/ +# 目录刷新队列 —— 那些归本机那个 capture 角色。 +LIBRARY_WORKER_ROLE=release-executor +WORKER_ID=kgtest-release-executor + +# ---- 治理库:SSH 反向 Unix socket;host 必须是目录 ---- +# 凭据由目标机 0600 governance.pgpass 只读挂载;不得直接复制本机无密码 URL。 +DATABASE_URL=postgres://@/?host=/run/kgtest-pg&port=5432&sslmode=disable +PGPASSFILE=/run/secrets/governance_pgpass + +# ---- 目标:云测试 WeKnora ---- +LIBRARY_PRODUCTION_DATABASE_URL=postgres://:@pgm-wz9ohr9gk919pr1q.pg.rds.aliyuncs.com:5432/weknora_test?sslmode=require +LIBRARY_PRODUCTION_ELASTIC_URL=http://elasticsearch:9200 +LIBRARY_PRODUCTION_INDEX=weknora_test_chunks +LIBRARY_PRODUCTION_TENANT_ID= +LIBRARY_PRODUCTION_KB_INTERNAL= +# 对外库没有对应目标时留空:API 侧不会给 external 建发布作业。 +# LIBRARY_PRODUCTION_KB_EXTERNAL= +LIBRARY_PRODUCTION_S3_PROVIDER=oss +LIBRARY_PRODUCTION_S3_ENDPOINT=https://oss-cn-shenzhen.aliyuncs.com +LIBRARY_PRODUCTION_S3_REGION=cn-shenzhen +LIBRARY_PRODUCTION_S3_BUCKET=dobot-weknora-test +LIBRARY_PRODUCTION_S3_ACCESS_KEY= +LIBRARY_PRODUCTION_S3_SECRET_KEY= +LIBRARY_EMBEDDING_MODEL= +LIBRARY_EMBEDDING_DIMENSION=1024 + +# ---- 维护目标:同机的 weknora-test-v071 容器组 ---- +LIBRARY_TARGET_INSTANCE=weknora-test-v071-app +LIBRARY_TARGET_PROJECT=weknora-test-v071 +LIBRARY_TARGET_WRITERS=app +# 项目里每个服务都必须声明成写入者或"不是写入者 + 原因",否则窗口会拒绝开。 +LIBRARY_TARGET_NON_WRITERS=frontend=UI only; no knowledge writes,elasticsearch=index store; not an initiator,redis=queue/cache store; not an initiator,neo4j=graph store; release path refuses graph writes,docreader=parse worker; driven by app only,ingress=TCP ingress gate which only drains and forwards +LIBRARY_TARGET_DOCKER_SOCKET=/var/run/docker.sock +# 入口 URL 用 docker 网络里的闸门服务名:执行器与闸门同项目网络, +# 而闸门在宿主机发布的是同一个 8080(拓扑校验比对的就是这个端口)。 +LIBRARY_TARGET_INGRESS_URL=http://ingress:8080/health +LIBRARY_TARGET_INGRESS_SERVICE=ingress +LIBRARY_TARGET_INGRESS_DRAIN_FILE=/gate-state/drain.json +LIBRARY_TARGET_REDIS_ADDR=redis:6379 +LIBRARY_TARGET_REDIS_DB=0 +LIBRARY_TARGET_JOURNAL_ROOT=/var/lib/knowledge-governance/target-journal + +# ---- 归档:本机 ip 封存 → 包 → 云端导入到这里 ---- +LIBRARY_ARCHIVE_ROOT=/var/lib/knowledge-governance/library +LIBRARY_CAPACITY_BUDGET_BYTES=53687091200 + +# 不接封存 agent(封存仍在本机由既有 systemd user unit 提供)。 +LIBRARY_AGENT_SOCKET= + +# ---- 写目标的两道闸口 ---- +# 这两个开关只是"本进程允许写"的部署声明;真正的授权是治理库里与快照绑定的 +# release 授权行。任何一道为 false,发布会在维护窗口之前被拒绝。 +PRODUCTION_RELEASE_REQUESTS_ENABLED=true +PRODUCTION_BACKUP_RESTORE_VERIFIED=true +# ---- 快照搬运(本机 API + capture worker 侧配置;执行器不消费这组变量)---- +# 只写在这里作对照:真正的 LIBRARY_HANDOFF_* 配在**本机** api/worker 容器, +# 执行器只需要 LIBRARY_ARCHIVE_ROOT 与 BUNDLE_DIR 对应的宿主机目录存在。 +# LIBRARY_HANDOFF_SSH_CONFIG=/run/secrets/backup-host/ssh_config +# LIBRARY_HANDOFF_TARGET=weknora-test +# LIBRARY_HANDOFF_EXECUTOR=kgtest-release-executor +# LIBRARY_HANDOFF_BUNDLE_DIR=/srv/knowledge-governance/bundles +# LIBRARY_HANDOFF_REMOTE_ARCHIVE=/var/lib/knowledge-governance/library +# LIBRARY_HANDOFF_STAGING_DIR=/var/lib/knowledge-governance/handoff-staging diff --git a/deploy/cloud-test/run-release-executor.sh b/deploy/cloud-test/run-release-executor.sh new file mode 100755 index 0000000..06bbf20 --- /dev/null +++ b/deploy/cloud-test/run-release-executor.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# 在云测试主机上启动/更新"发布执行器"容器(由父在目标机执行,不在本机远程包装)。 +# +# 为什么单独 docker run 而不是塞进 weknora-test-v071 这个 compose 项目: +# 维护协调器要求项目里每个服务都被声明为写入者或"非写入者",执行器不是目标的一部分, +# 放进同一个项目只会让拓扑清单多一条无关服务。它只需要挂上目标项目的网络即可。 +set -euo pipefail + +IMAGE="${RELEASE_EXECUTOR_IMAGE:-}" +NETWORK="${TARGET_NETWORK:-weknora-test-v071-network}" +PG_SOCKET_DIR="${RELEASE_PG_SOCKET_DIR:-/run/kgtest-pg}" +PGPASS_FILE="${RELEASE_PGPASS_FILE:-/srv/knowledge-governance/governance.pgpass}" +ENV_FILE="${RELEASE_EXECUTOR_ENV:-/srv/knowledge-governance/release-executor.env}" +ARCHIVE="${RELEASE_ARCHIVE_ROOT:-/srv/knowledge-governance/library}" +BUNDLES="${RELEASE_BUNDLE_DIR:-/srv/knowledge-governance/bundles}" +JOURNAL="${RELEASE_JOURNAL_ROOT:-/srv/knowledge-governance/target-journal}" +GATE_STATE="${RELEASE_GATE_STATE:-/srv/kgtest-gate/state}" +NAME="${RELEASE_EXECUTOR_NAME:-kgtest-release-executor}" + +die() { echo "release-executor: $*" >&2; exit 1; } + +[ -n "$IMAGE" ] || die "RELEASE_EXECUTOR_IMAGE 未设置(必须是与已验收提交同 sha 的 worker 镜像)" +[ "$(id -u)" -eq 0 ] || die "需要 root:要读 docker.sock 并读写 0700 归档目录" +docker network inspect "$NETWORK" >/dev/null 2>&1 || die "网络 $NETWORK 不存在(先部署目标项目)" +[ -f "$ENV_FILE" ] || die "缺少 env 文件 $ENV_FILE" +[ "$(stat -c '%a' "$ENV_FILE")" = "600" ] || die "$ENV_FILE 必须是 0600(里面有目标凭据)" +grep -q '^LIBRARY_WORKER_ROLE=release-executor$' "$ENV_FILE" || die "$ENV_FILE 里 LIBRARY_WORKER_ROLE 必须是 release-executor" +[ -d "$GATE_STATE" ] || die "闸门状态目录 $GATE_STATE 不存在(先部署 ingress 闸门)" + +[ -d "$PG_SOCKET_DIR" ] || die "治理 PG socket 目录不存在" +[ -s "$PGPASS_FILE" ] && [ "$(stat -c '%a' "$PGPASS_FILE")" = "600" ] || die "治理 pgpass 必须是非空 0600 文件" +grep -qx 'PGPASSFILE=/run/secrets/governance_pgpass' "$ENV_FILE" || die "PGPASSFILE 必须指向容器内治理密码文件" + +AUTH_TOKEN_FILE="${RELEASE_AUTH_TOKEN_FILE:-/srv/knowledge-governance/production_release_auth_token}" + +# Parse only named fields as data, never source a credential-bearing dotenv. +read_setting() { + local wanted="$1" line value="" found=0 + while IFS= read -r line || [ -n "$line" ]; do + if [[ "$line" == "$wanted="* ]]; then + ((found += 1)) + value="${line#*=}" + fi + done < "$ENV_FILE" + [ "$found" -le 1 ] || die "重复配置字段:$wanted" + printf '%s' "$value" +} +auth_mount=() +enabled="$(read_setting PRODUCTION_RELEASE_REQUESTS_ENABLED)" +case "$enabled" in + true|TRUE|True|1|t|T) + author="$(read_setting PRODUCTION_RELEASE_AUTHORIZER_REF)" + [ -n "$author" ] && [ "${#author}" -le 128 ] && [[ "$author" != *[$'\r\n\t']* ]] || die "PRODUCTION_RELEASE_AUTHORIZER_REF 缺失或非法" + token_path="$(read_setting PRODUCTION_RELEASE_AUTH_TOKEN_FILE)" + [ "$token_path" = /run/secrets/production_release_auth_token ] || die "PRODUCTION_RELEASE_AUTH_TOKEN_FILE 必须指向 /run/secrets/production_release_auth_token" + [ -f "$AUTH_TOKEN_FILE" ] && [ ! -L "$AUTH_TOKEN_FILE" ] && [ -s "$AUTH_TOKEN_FILE" ] && [ "$(stat -c '%a' "$AUTH_TOKEN_FILE")" = 600 ] || die "授权 token 必须是非空普通 0600 文件" + auth_mount=(-v "$AUTH_TOKEN_FILE:$token_path:ro") + ;; + false|FALSE|False|0|f|F|"") ;; + *) die "PRODUCTION_RELEASE_REQUESTS_ENABLED 不是有效布尔值" ;; +esac + +install -d -m 0700 "$ARCHIVE" "$JOURNAL" "$BUNDLES" +install -d -m 0700 "$ARCHIVE/blobs" "$ARCHIVE/versions" + +if docker inspect "$NAME" >/dev/null 2>&1; then + echo "release-executor: 已存在,按同一 env 重建(先停,便于看清失败原因)" + docker rm -f "$NAME" >/dev/null +fi + +docker run -d --name "$NAME" \ + --user 0:0 \ + --pull never \ + --restart unless-stopped \ + --network "$NETWORK" \ + --label com.nous.role=release-executor \ + -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$ARCHIVE:/var/lib/knowledge-governance/library" \ + -v "$BUNDLES:$BUNDLES" \ + -v "$JOURNAL:/var/lib/knowledge-governance/target-journal" \ + -v "$GATE_STATE:/gate-state" \ + -v "$PG_SOCKET_DIR:/run/kgtest-pg:ro" \ + -v "$PGPASS_FILE:/run/secrets/governance_pgpass:ro" \ + "${auth_mount[@]}" \ + --env-file "$ENV_FILE" \ + "$IMAGE" /app/worker >/dev/null + +# A created container or docker-ps exit code is not a live executor. +for attempt in 1 2 3; do + sleep 2 + state="$(docker inspect --format '{{.State.Status}} {{.RestartCount}}' "$NAME")" || die "无法读取执行器状态" + [ "$state" = 'running 0' ] || die "执行器未稳定运行,请检查目标机容器日志" +done +echo "release-executor: 启动检查通过(连续 running、无重启);业务验收仍须核对作业执行结果" \ No newline at end of file diff --git a/deploy/cloud-test/test_deployment.py b/deploy/cloud-test/test_deployment.py new file mode 100644 index 0000000..cf7b0f9 --- /dev/null +++ b/deploy/cloud-test/test_deployment.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Execute deployment scripts with fake external CLIs; never touch Docker/SSH.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent + + +class DeploymentTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.trace = self.root / "trace.jsonl" + self.env = dict(os.environ, PATH=str(self.root) + ":" + os.environ["PATH"], TRACE=str(self.trace)) + self.stub("docker", "if 'inspect' in sys.argv: print('network=172.21.0.3 ')") + self.stub("ssh", "") + + def stub(self, name, body): + path = self.root / name + path.write_text("#!/usr/bin/env python3\nimport os,sys,json\nwith open(os.environ['TRACE'],'a') as f: f.write(json.dumps(sys.argv)+chr(10))\n" + body + "\n") + path.chmod(0o755) + + def calls(self): + return [json.loads(line) for line in self.trace.read_text().splitlines()] if self.trace.exists() else [] + + def run_script(self, name): + return subprocess.run(["bash", str(HERE / name)], env=self.env, capture_output=True, text=True) + + def test_invalid_socket_rejected_before_ssh(self): + self.env['REMOTE_SOCKET'] = '/run/kgtest-pg/pg.sock' + result = self.run_script('pg-forward.sh') + self.assertNotEqual(result.returncode, 0) + self.assertFalse(any(Path(c[0]).name == 'ssh' for c in self.calls())) + + def test_executor_mounts_socket_and_secret(self): + self.stub('id', "print('0')") + self.stub('sleep', '') + self.stub('docker', "if sys.argv[1:2] == ['inspect']:\n if '--format' in sys.argv: print('running 0')\n else: sys.exit(1)") + secret = self.root / 'pgpass' + secret.write_text('localhost:5432:governance:tester:example-only\n') + secret.chmod(0o600) + envfile = self.root / 'executor.env' + envfile.write_text('LIBRARY_WORKER_ROLE=release-executor\nPGPASSFILE=/run/secrets/governance_pgpass\n') + envfile.chmod(0o600) + self.env.update(RELEASE_EXECUTOR_IMAGE='fixture:only', RELEASE_EXECUTOR_ENV=str(envfile), + RELEASE_ARCHIVE_ROOT=str(self.root / 'archive'), RELEASE_JOURNAL_ROOT=str(self.root / 'journal'), + RELEASE_GATE_STATE=str(self.root), RELEASE_PG_SOCKET_DIR=str(self.root), + RELEASE_PGPASS_FILE=str(secret), RELEASE_BUNDLE_DIR=str(self.root / 'bundles')) + result = self.run_script('run-release-executor.sh') + self.assertEqual(result.returncode, 0, result.stderr) + call = next(c for c in self.calls() if c[1:2] == ['run']) + self.assertEqual(call[-1], '/app/worker') + self.assertEqual(call[call.index('--user') + 1], '0:0') + self.assertEqual(call[call.index('--network') + 1], 'weknora-test-v071-network') + self.assertIn(str(self.root) + ':/run/kgtest-pg:ro', call) + self.assertIn(str(secret) + ':/run/secrets/governance_pgpass:ro', call) + bundles = self.root / 'bundles' + self.assertIn(str(bundles) + ':' + str(bundles), call) + self.assertEqual(bundles.stat().st_mode & 0o777, 0o700) + self.assertNotIn('example-only', result.stdout + result.stderr + json.dumps(self.calls())) + + def test_libpq_socket_directory_contract(self): + result = self.run_script("pg-forward.sh") + self.assertEqual(result.returncode, 0, result.stderr) + ssh = [c for c in self.calls() if Path(c[0]).name == "ssh"] + forward = ssh[-1] + self.assertEqual(forward[forward.index("-R") + 1], "/run/kgtest-pg/.s.PGSQL.5432:172.21.0.3:5432") + self.assertIn("host=/run/kgtest-pg&", result.stdout) + self.assertNotIn("host=/run/kgtest-pg/.s.PGSQL", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/cloud-test/test_gate.py b/deploy/cloud-test/test_gate.py new file mode 100755 index 0000000..a33b4e6 --- /dev/null +++ b/deploy/cloud-test/test_gate.py @@ -0,0 +1,350 @@ +#!/usr/bin/env python3 +"""gate.py 的真实回归(无外部依赖、无副作用,只在本机 loopback 上跑)。 + +覆盖的是"闸门会不会掐断正常业务"和"排空证据是不是真的"这两件事,而不是 /health 200: + + 1. 长静默流:上游发一半后静默 12 秒再发剩下的 —— 闸门必须照原样送达 + (旧实现 create_connection(timeout=10) 未清除读超时,会在这里失败)。 + 2. 半关闭:客户端写完请求即 shutdown(SHUT_WR),上游收到 EOF 后才应答 —— + 响应必须完整回来,且耗时证明上游确实等到了 EOF。 + 3. 大包完整性:2MB 正文穿过闸门逐字节一致。 + 4. 排空:在途连接存在时 SIGTERM —— 新连接被拒、在途连接照常收完、退出码 0、 + drain.json phase=drained 且 active_at_close>=1。 + 5. 排空超时:上游永不应答、在途连接不结束 —— 退出码 2、phase=drain_timeout(不能算排空成功)。 + 6. 上游不可达:连接被关掉而不是挂住,闸门本身仍存活并能正常排空。 + +用法:python3 deploy/cloud-test/test_gate.py (打印 PASS/FAIL,任一 FAIL 退出码 1) +""" + +import json +import os +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import traceback + +HERE = os.path.dirname(os.path.abspath(__file__)) +GATE = os.path.join(HERE, "gate.py") +SILENT_GAP = 12.0 + +failures = [] + + +def check(name, condition, detail=""): + if condition: + print(f"PASS {name} {detail}".rstrip(), flush=True) + else: + print(f"FAIL {name} {detail}".rstrip(), flush=True) + failures.append(name) + + +def free_port(): + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + return port + + +class FakeUpstream: + """按请求行决定行为的极简上游。""" + + def __init__(self): + self.port = free_port() + self.server = socket.socket() + self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.server.bind(("127.0.0.1", self.port)) + self.server.listen(16) + self.stopped = threading.Event() + threading.Thread(target=self._serve, daemon=True).start() + + def _serve(self): + while not self.stopped.is_set(): + try: + client, _ = self.server.accept() + except OSError: + return + threading.Thread(target=self._handle, args=(client,), daemon=True).start() + + def _handle(self, client): + try: + client.settimeout(None) + data = b"" + while b"\r\n\r\n" not in data: + chunk = client.recv(4096) + if not chunk: + return + data += chunk + head, _, rest = data.partition(b"\r\n\r\n") + path = head.split(b" ")[1].decode() if b" " in head else "/" + if path == "/slow": + client.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc") + time.sleep(SILENT_GAP) + client.sendall(b"defghij") + elif path == "/half": + # 等客户端半关闭(EOF)再应答:证明闸门把 EOF 单向传了过来。 + while True: + chunk = client.recv(4096) + if not chunk: + break + time.sleep(0.8) + body = b"after-eof" + client.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n" % len(body) + body) + elif path == "/echo": + length = 0 + for line in head.split(b"\r\n"): + if line.lower().startswith(b"content-length:"): + length = int(line.split(b":")[1].strip()) + body = rest + while len(body) < length: + chunk = client.recv(65536) + if not chunk: + break + body += chunk + client.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n" % len(body) + body) + elif path == "/hold": + client.sendall(b"HTTP/1.1 200 OK\r\n\r\n") + time.sleep(3600) + else: + client.sendall(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n") + except OSError: + pass + finally: + try: + client.close() + except OSError: + pass + + def close(self): + self.stopped.set() + try: + self.server.close() + except OSError: + pass + + +class Gate: + def __init__(self, upstream_port, drain_timeout=45.0): + self.port = free_port() + self.dir = tempfile.mkdtemp(prefix="gate-test-") + self.drain = os.path.join(self.dir, "drain.json") + env = dict(os.environ) + env.update({ + "GATE_PORT": str(self.port), + "GATE_UPSTREAM_HOST": "127.0.0.1", + "GATE_UPSTREAM_PORT": str(upstream_port), + "GATE_DRAIN_FILE": self.drain, + "GATE_DRAIN_TIMEOUT": str(drain_timeout), + }) + self.process = subprocess.Popen([sys.executable, GATE, ], env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + deadline = time.time() + 10 + while time.time() < deadline: + try: + socket.create_connection(("127.0.0.1", self.port), timeout=0.2).close() + return + except OSError: + if self.process.poll() is not None: + raise RuntimeError("gate exited early: " + (self.process.stdout.read() or "")) + time.sleep(0.05) + raise RuntimeError("gate did not start listening") + + def connect(self): + return socket.create_connection(("127.0.0.1", self.port), timeout=30) + + def state(self): + with open(self.drain) as handle: + return json.load(handle) + + def terminate(self, timeout=20): + self.process.send_signal(signal.SIGTERM) + try: + self.process.wait(timeout=timeout) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait(5) + return None + return self.process.returncode + + def logs(self): + try: + return self.process.stdout.read() or "" + except Exception: + return "" + + +def read_all(conn, timeout=30): + conn.settimeout(timeout) + chunks = [] + try: + while True: + data = conn.recv(65536) + if not data: + break + chunks.append(data) + except socket.timeout: + chunks.append(b"") + except ConnectionResetError: + # 对端 RST(例如上游不可达时闸门立即拆连接)也是"连接已结束",不是挂住。 + pass + return b"".join(chunks) + + +def test_long_silent_stream(): + upstream = FakeUpstream() + gate = Gate(upstream.port) + try: + conn = gate.connect() + conn.sendall(b"GET /slow HTTP/1.1\r\nHost: gate\r\n\r\n") + started = time.time() + payload = read_all(conn, timeout=30) + elapsed = time.time() - started + conn.close() + check("long-silent-stream/complete", b"abcdefghij" in payload, + f"({elapsed:.1f}s, {len(payload)}B)") + check("long-silent-stream/survived-gap", elapsed >= SILENT_GAP - 1, + f"gap={SILENT_GAP}s elapsed={elapsed:.1f}s") + finally: + gate.terminate() + upstream.close() + + +def test_half_close(): + upstream = FakeUpstream() + gate = Gate(upstream.port) + try: + conn = gate.connect() + conn.sendall(b"GET /half HTTP/1.1\r\nHost: gate\r\n\r\n") + conn.shutdown(socket.SHUT_WR) # 客户端半关闭:只关自己的写端 + started = time.time() + payload = read_all(conn, timeout=15) + elapsed = time.time() - started + conn.close() + check("half-close/response-delivered", b"after-eof" in payload, f"({elapsed:.1f}s)") + check("half-close/eof-propagated", elapsed >= 0.5, f"elapsed={elapsed:.1f}s") + finally: + gate.terminate() + upstream.close() + + +def test_large_body_integrity(): + upstream = FakeUpstream() + gate = Gate(upstream.port) + try: + body = (b"0123456789abcdef" * 131072) # 2 MiB + conn = gate.connect() + conn.sendall(b"POST /echo HTTP/1.1\r\nHost: gate\r\nContent-Length: %d\r\n\r\n" % len(body)) + conn.sendall(body) + payload = read_all(conn, timeout=30) + conn.close() + head, _, received = payload.partition(b"\r\n\r\n") + check("large-body/integrity", received == body, + f"sent={len(body)}B got={len(received)}B head={head.splitlines()[:1]}") + finally: + gate.terminate() + upstream.close() + + +def test_drain_with_inflight(): + upstream = FakeUpstream() + gate = Gate(upstream.port, drain_timeout=45) + try: + conn = gate.connect() + conn.sendall(b"GET /slow HTTP/1.1\r\nHost: gate\r\n\r\n") + time.sleep(0.5) # 确保在途连接已被计数 + sent_at = time.time() + gate.process.send_signal(signal.SIGTERM) + time.sleep(0.5) + refused = False + try: + late = socket.create_connection(("127.0.0.1", gate.port), timeout=2) + late.settimeout(2) + try: + late.sendall(b"GET /slow HTTP/1.1\r\nHost: gate\r\n\r\n") + refused = late.recv(1) == b"" + except OSError: + refused = True + late.close() + except OSError: + refused = True + check("drain/new-connections-refused", refused) + payload = read_all(conn, timeout=40) + conn.close() + check("drain/inflight-completed", b"abcdefghij" in payload, f"{len(payload)}B") + code = gate.terminate(timeout=30) + check("drain/exit-zero", code == 0, f"exit={code}") + state = gate.state() + fresh = os.path.getmtime(gate.drain) >= sent_at - 1 + check("drain/evidence", state.get("phase") == "drained" and state.get("active_at_close", 0) >= 1, + json.dumps({k: state.get(k) for k in ("phase", "active_at_close", "served", "drain_ms")})) + check("drain/evidence-fresh", fresh, f"mtime ok={fresh}") + finally: + if gate.process.poll() is None: + gate.terminate() + upstream.close() + + +def test_drain_timeout_is_failure(): + upstream = FakeUpstream() + gate = Gate(upstream.port, drain_timeout=1) + try: + conn = gate.connect() + conn.sendall(b"GET /hold HTTP/1.1\r\nHost: gate\r\n\r\n") + time.sleep(0.5) + code = gate.terminate(timeout=15) + check("drain-timeout/exit-nonzero", code == 2, f"exit={code}") + state = gate.state() + check("drain-timeout/phase", state.get("phase") == "drain_timeout", + json.dumps({k: state.get(k) for k in ("phase", "active", "active_at_close")})) + conn.close() + finally: + if gate.process.poll() is None: + gate.terminate() + upstream.close() + + +def test_upstream_unreachable(): + dead = free_port() + gate = Gate(dead) + try: + conn = gate.connect() + conn.sendall(b"GET / HTTP/1.1\r\nHost: gate\r\n\r\n") + started = time.time() + payload = read_all(conn, timeout=5) + elapsed = time.time() - started + conn.close() + check("upstream-dead/connection-closed", b"" not in payload and elapsed < 4, + f"{elapsed:.1f}s {len(payload)}B") + # 闸门本身还活着:仍能建连(会在上游阶段失败,但不挂住)。 + code = gate.terminate(timeout=10) + check("upstream-dead/gate-drains", code == 0, f"exit={code}") + finally: + if gate.process.poll() is None: + gate.terminate() + + +def main(): + for test in ( + test_long_silent_stream, + test_half_close, + test_large_body_integrity, + test_drain_with_inflight, + test_drain_timeout_is_failure, + test_upstream_unreachable, + ): + try: + test() + except Exception: + traceback.print_exc() + failures.append(test.__name__) + print() + print(f"summary: {len(failures)} failure(s)" + (":" + ",".join(failures) if failures else "")) + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/deploy/cloud-test/test_release_executor.py b/deploy/cloud-test/test_release_executor.py new file mode 100644 index 0000000..79b9235 --- /dev/null +++ b/deploy/cloud-test/test_release_executor.py @@ -0,0 +1,110 @@ +"""Exercise the deployment shell with fake Docker; never touch a daemon.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +SCRIPT = Path(__file__).with_name("run-release-executor.sh") + + +class ReleaseExecutorTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / "bin" + self.bin.mkdir() + self.calls = self.root / "calls.jsonl" + for name, text in { + "id": "#!/bin/sh\nprintf '0\\n'\n", + "sleep": "#!/bin/sh\nexit 0\n", + "docker": """#!/usr/bin/env python3 +import json,os,sys +with open(os.environ['CALLS'],'a') as f: f.write(json.dumps(sys.argv[1:])+'\\n') +a=sys.argv[1:] +if a[0]=='inspect': + if '--format' in a: print(os.environ.get('CONTAINER_STATE','running 0')) + else: sys.exit(0) +""", + }.items(): + p = self.bin / name + p.write_text(text) + p.chmod(0o755) + self.envfile = self.root / "executor.env" + self.token = self.root / "token" + pgpass = self.root / "pgpass" + pgpass.write_text("fixture-password-not-real") + pgpass.chmod(0o600) + self.env = dict(os.environ, PATH=str(self.bin) + os.pathsep + os.environ["PATH"], + CALLS=str(self.calls), RELEASE_EXECUTOR_IMAGE="test:fixture", + RELEASE_EXECUTOR_ENV=str(self.envfile), RELEASE_PGPASS_FILE=str(pgpass), + RELEASE_PG_SOCKET_DIR=str(self.root), RELEASE_GATE_STATE=str(self.root), + RELEASE_ARCHIVE_ROOT=str(self.root / "archive"), + RELEASE_JOURNAL_ROOT=str(self.root / "journal"), + RELEASE_BUNDLE_DIR=str(self.root / "bundles"), + RELEASE_AUTH_TOKEN_FILE=str(self.token)) + + def run_script(self, enabled=True, author=True, path=True, token=True, mode=0o600): + lines = ["LIBRARY_WORKER_ROLE=release-executor", "PGPASSFILE=/run/secrets/governance_pgpass", + "PRODUCTION_RELEASE_REQUESTS_ENABLED=" + str(enabled).lower()] + if author: + lines.append("PRODUCTION_RELEASE_AUTHORIZER_REF=fixture-owner") + if path: + lines.append("PRODUCTION_RELEASE_AUTH_TOKEN_FILE=/run/secrets/production_release_auth_token") + self.envfile.write_text("\n".join(lines) + "\n") + self.envfile.chmod(0o600) + if token: + self.token.write_text("fixture-only-not-real") + self.token.chmod(mode) + result = subprocess.run(["bash", str(SCRIPT)], env=self.env, text=True, capture_output=True) + calls = [json.loads(line) for line in self.calls.read_text().splitlines()] if self.calls.exists() else [] + self.assertNotIn("fixture-only-not-real", result.stdout + result.stderr) + return result, calls + + def test_enabled_missing_author_rejected_before_replacing(self): + r, calls = self.run_script(author=False) + self.assertNotEqual(r.returncode, 0) + self.assertFalse(any(c[0] in ("rm", "run") for c in calls)) + + def test_enabled_missing_token_path_rejected_before_replacing(self): + r, calls = self.run_script(path=False) + self.assertNotEqual(r.returncode, 0) + self.assertFalse(any(c[0] in ("rm", "run") for c in calls)) + + def test_enabled_missing_token_file_rejected_before_replacing(self): + r, calls = self.run_script(token=False) + self.assertNotEqual(r.returncode, 0) + self.assertFalse(any(c[0] in ("rm", "run") for c in calls)) + + def test_enabled_wrong_token_permissions_rejected_before_replacing(self): + r, calls = self.run_script(mode=0o644) + self.assertNotEqual(r.returncode, 0) + self.assertFalse(any(c[0] in ("rm", "run") for c in calls)) + + def test_enabled_mounts_private_token_readonly(self): + r, calls = self.run_script() + self.assertEqual(r.returncode, 0, r.stderr) + run = next(c for c in calls if c[0] == "run") + self.assertIn(str(self.token) + ":/run/secrets/production_release_auth_token:ro", run) + + def test_disabled_needs_no_authorization_material(self): + r, calls = self.run_script(enabled=False, author=False, path=False, token=False) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertTrue(any(c[0] == "run" for c in calls)) + + def test_crash_loop_is_not_success(self): + self.env["CONTAINER_STATE"] = "restarting 3" + r, _ = self.run_script() + self.assertNotEqual(r.returncode, 0) + self.assertNotIn("启动完成", r.stdout) + + def test_already_restarted_is_not_success(self): + self.env["CONTAINER_STATE"] = "running 1" + r, _ = self.run_script() + self.assertNotEqual(r.returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index 2a7165b..6400ad1 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -18,4 +18,9 @@ 1. 跑 `make verify`(本地全绿不等于远端跑通,需要一次真实 run 的证据)。 2. 把**使用者可见**的变化写成 `CHANGELOG.md` 的 `[Unreleased]` 条目(按四类,别写过程)。 -3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。 \ No newline at end of file +3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。 +## 资源首次复用的归属审计(后续) + +- 当前首次复用只依赖“目标行逐列一致 + 对象字节一致”,不再要求本目标历史成功同步/预备份来源。 +- 后续可补:资源首次写入者/首次绑定 KB、跨 KB 引用计数、孤儿资源与同 tenant 共享资源的可审计归属视图; + 不以此重新阻断正常的同内容首次复用。 diff --git a/docs/DWS_LOGIN.md b/docs/DWS_LOGIN.md new file mode 100644 index 0000000..67e4d21 --- /dev/null +++ b/docs/DWS_LOGIN.md @@ -0,0 +1,44 @@ +# DWS 登录授权 + +管理员入口:系统设置 → 数据源配置 → 钉钉账号(DWS)。 + +- 未登录时点击“登录授权”,在弹窗中打开钉钉官方授权页,由本人选择账号与组织并确认。 +- 平台等待设备授权完成。成功后自动刷新账号、组织和续期凭证有效期,并检查知识库、钉盘目录访问。 +- “重新授权”采用同一流程;授权中可取消,失败或过期后可重新发起。 +- “检查连接”只列目录与读取登录元数据,不登记来源、不扫描已有来源、不发起入库或生产发布。 +- 登录成功与目录可用分开显示;部分范围无权限时保留其他已成功范围,并展示原因。 + +## 服务端接线 + +API 直接管理 `dws auth login --device --no-browser --format json` 子进程,不复用旧浏览器扫码侧车。 +CLI 负责官方 OAuth 协议、组织 CLI 权限校验及凭据加密持久化。平台只解析官方设备授权链接、用户授权码、有效期与状态;原始输出、access token、refresh token不进入接口或日志。 + +API 与 worker 必须使用相同 UID,以及同一组可写挂载: + +| 配置 | 用途 | +|---|---| +| `DWS_BIN` | 固定版本的 DWS 程序 | +| `DWS_CONFIG_DIR` | 共享的 DWS 状态目录 | +| `DWS_HOME` | 共享 home,包含 `.local/share/dws-cli` 文件型密钥存储 | +| `DWS_DISABLE_KEYCHAIN=1` | 容器使用文件型凭据存储 | + +子进程 HOME 由 DWS_HOME 指定,只透传所需环境。禁止把认证状态复制成多份,避免轮换令牌互相失效。 + +## 接口与生命周期 + +- `POST /api/v1/dws-login`:立即返回 starting,后台生成设备授权;同一浏览器管理员会话重复请求复用在途授权。 +- `GET /api/v1/dws-login/{id}`:读取本人发起的授权。 +- `DELETE /api/v1/dws-login/{id}`:取消并等待旧 CLI 退出,清除授权链接与用户码。 +- 上述接口均为管理员专用;授权绑定管理员及其登录会话,另一会话无法读取或取消。 +- 创建和取消要求同源操作意图;响应禁止缓存。仅允许 `https://login.dingtalk.com/oauth2/device/verify.htm` 官方链接。 +- 每次只运行一个授权,防止覆盖共享状态。服务重启会结束在途授权;页面提示重新发起。 +- CLI 成功退出后必须再次读到有效本地凭据才显示登录成功;真实目录访问另行检查。 + +## 添加来源 + +添加来源向导与账号卡共用官方 DWS 授权;列举、校验、登记使用同一身份。来源登记不再自动回落旧扫码侧车。保存中授权失效时保留已成功项并恢复剩余项;换账号或组织后需重新确认范围。详细交互、认证审计与 PP 接线见 [数据源认证配置](SOURCE_AUTH_CONFIGURATION.md)。 + +## 验证边界 + +自动回归覆盖授权生成、成功后状态更新、目录访问失败与部分可用、取消与进程退出、过期、重试、跨管理员/会话隔离、同源限制、官方链接校验及元数据脱敏。 +真实本人授权需要管理员在钉钉官方页面确认;自动测试与生成真实授权链接不替代本人授权,也不证明其公司目录权限。 diff --git a/docs/OPERATIONS_RUNBOOK.md b/docs/OPERATIONS_RUNBOOK.md index 2686672..9fb5aea 100644 --- a/docs/OPERATIONS_RUNBOOK.md +++ b/docs/OPERATIONS_RUNBOOK.md @@ -91,7 +91,7 @@ curl --noproxy '*' --max-time 5 -sS -o /dev/null -w 'catalog %{http_code}\n' htt ## 0. 开工前:环境与凭据自检 | 项 | 怎么做 | 成功标志 | |---|---|---| -| 测试/生产 WeKnora | 系统设置 → 服务配置 | 生产端"已启用 · 可提交生产请求";测试端探测正常 | +| 测试/生产 WeKnora | 系统设置 → 知识库映射 → WeKnora 连接 | 生产端"已启用 · 可提交生产请求";测试端探测正常 | | 钉钉取件凭据 **【新】** | 容器内 `HOME=/data/home dws auth status --readonly -f json` | `authenticated:true`、`refresh_token_valid:true`(**必须带 `HOME=/data/home`,否则误报未登录**) | | 备份主机接线 | 系统设置 → 存储与备份 | "目标主机 weknora-test · 已连接" | @@ -161,7 +161,7 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 + | 分区 | 谁 | 现在要管什么 | |---|---|---| -| 服务配置 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) | +| 知识库映射 → WeKnora 连接 | 管理员 | 测试地址 / 生产地址 / 生产 ID / 知识库 ID(保存时真探活,无效才拒) | | 测试知识库绑定 | 管理员 | 标注往哪个测试库路由(对内 ≠ 对外) | | 生产知识库绑定 | 管理员 | 源库 → 目标库映射(发布写哪个生产库) | | **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" | diff --git a/docs/SOURCE_AUTH_CONFIGURATION.md b/docs/SOURCE_AUTH_CONFIGURATION.md new file mode 100644 index 0000000..e4387e0 --- /dev/null +++ b/docs/SOURCE_AUTH_CONFIGURATION.md @@ -0,0 +1,57 @@ +# 数据源认证配置 + +管理员入口:系统设置 → 数据源配置。PP 连接位于钉钉账号卡旁;添加来源向导使用同一组账号与配置。 + +## PP 连接 + +- API 地址填写 HTTPS 根地址;后台沿用 `/admin/login/token`、`/potal/file/back/page` 接口路径。`potal` 是上游真实路径,不能改写。 +- 账号允许修改。密码只显示已配置/未配置;点击“更新密码”录入新值。省略或留空保留既有密码,不回显原值。 +- “测试连接”使用当前表单,真实登录并读取一条目录记录;合法空目录也可通过。它不保存配置、不登记来源、不启动扫描。 +- “保存并校验”在后端重新检查本次提交。通过后切换生效;明确的认证拒绝、权限拒绝、接口不兼容阻止生效。 +- 超时、限流或服务临时故障可保存为待验证修改;缺少凭据可保存未完成配置。两者都不会替换当前生效配置;需要再次保存并校验,通过后才切换。 +- 草稿测试结果与当前生效配置状态分开;每次修改字段会使原草稿测试结果作废。检查失败时保留上次观测及时间,不能把网络失败当成退出登录。 +- 后续目录扫描和远程取件读取同一生效配置;验证过的本地文件仍按既有内容校验逻辑复用。配置保存不恢复暂停的计划、不触发入库或发布。 + +## PP 服务端接线 + +| 参数 | 默认与用途 | +|---|---| +| `PP_AUTH_STATE_FILE` | `/data/source-auth/pp/settings.json`;API 和 worker 必须读同一份原子配置文件 | +| `PP_AUTH_PYTHON` | `/usr/bin/python3`;API 连接检查使用的解释器 | +| `PP_AUTH_CHECK_SCRIPT` | `/app/scripts/pp_client.py`;与扫描、取件共享的只读协议实现 | +| `PP_LEGACY_CREDENTIALS_FILE` | 可选,只用于首次迁移;有效状态文件存在后不再回落旧文件 | + +配置目录及状态文件分别使用 0700 和 0600。API/worker 使用相同 UID,将宿主凭据目录挂载为共享目录,不能绑定单个文件:单文件 bind mount 会在原子 rename 后继续指向旧 inode。迁移时从目标机既有凭据文件直接读取,禁止通过聊天、命令行参数或仓库传递密码。 + +状态文件持有生效配置、待验证修改、最近检查及认证审计,包含密码,因此必须按密钥文件保护,不能进普通配置备份、版本记录或日志。更新使用跨进程文件锁、临时文件、fsync 和原子 rename。配置修订采用乐观并发控制;旧请求不能覆盖新修订。worker 的迟到检查只能更新自身生效配置 ID 对应的观测。 + +PP 检查子进程只从 stdin 接收本次凭据,stdout 只返回白名单检查结论。GET 接口仅返回配置元数据和是否存在密码;密码输入字段只可写。 + +| 接口 | 用途 | +|---|---| +| `GET /api/v1/pp-connection` | 管理员读取安全元数据、待验证修改与检查状态 | +| `POST /api/v1/pp-connection/test` | 测试当前草稿,不激活 | +| `PUT /api/v1/pp-connection` | 校验并保存;携带当前 `revision` | + +使用已保存的待验证密码继续校验时携带 `pending_id`,避免空密码误用旧生效密码。修改请求验证管理员、同源操作意图和输入大小;响应禁止缓存。 + +## 钉钉添加向导 + +保留 类型 → 授权 → 范围 → 校验 → 保存 五步;授权步骤复用钉钉账号卡的官方 DWS 设备授权流程。 + +- 可见范围、校验和登记都使用共享 DWS 身份;登记不再自动回落旧扫码侧车。DWS 无法定位的历史空间返回明确原因。 +- `POST /api/v1/dingtalk-spaces/validate` 真实读取并检查所选空间。失败、权限不足、部分范围不完整与合法空列表分别展示。 +- 已接入空间按稳定空间身份标记,历史连接也从其存储的空间标识识别,不靠名称去重。 +- 保存中授权失效:保留已成功项及待处理项,在向导内重新授权;同账号恢复后继续剩余项,复用操作标识,首次扫描按连接身份去重。 +- 取消或失败后保留选择并停止自动提交;再次恢复失败不循环弹授权。 +- 授权后换账号/组织:重新加载范围并清除旧选择,要求重新确认。客户端提交身份指纹,后端在列举前后确认身份,变化时拒绝登记。 +- 只有已点击保存的操作才会在重新授权后继续登记;账号登录、刷新和连接检查本身不创建来源或扫描任务。 +- 登记成功和首次扫描入队分别反馈,不能用登记成功冒充扫描已运行。 + +其他历史入口若仍调用旧扫码侧车,保留其原行为;本功能不删除整个侧车服务。 + +## 审计与验证 + +PP 配置/密码更新、连接检查及 DWS 授权结果,复用现有数据源操作审计页面。凭据事件与配置在同一文件内原子提交,并与数据库原有事件按时间合并分页;不把密码写入 SQL。DWS 终态审计按授权 ID 与状态去重,轮询不刷记录。 + +回归覆盖真实协议请求、空目录、认证拒绝、权限与限流、密码保留/替换、待验证密码重校验、并发修订冲突、响应脱敏、同源及角色限制、无意外任务、审计分页、DWS 部分成功恢复与换账号保护。协议与消费者测试使用隔离的本机 HTTP 服务;运行环境可用性需另行通过真实页面检查,不能用这些用例替代。 diff --git a/docs/USER_FLOWS_ACCEPTANCE.md b/docs/USER_FLOWS_ACCEPTANCE.md index 2f7a130..902038c 100644 --- a/docs/USER_FLOWS_ACCEPTANCE.md +++ b/docs/USER_FLOWS_ACCEPTANCE.md @@ -255,8 +255,8 @@ ## D. 系统设置 -### D1 服务配置(测试 / 生产端点与 ID) -- 入口:**系统设置 → 服务配置**(管理员) +### D1 知识库映射 → WeKnora 连接(测试 / 生产端点与 ID) +- 入口:**系统设置 → 知识库映射 → WeKnora 连接**(管理员) - 规则:只配四项(测试地址、生产地址、生产 ID、知识库 ID);**保存时真探测**,无效才拒;凭据只写不读 - 状态:✅(见 `P41/P42` 与 `ui_settings_*` 测试) diff --git a/docs/agents/traps-index-pending.md b/docs/agents/traps-index-pending.md new file mode 100644 index 0000000..50dc9de --- /dev/null +++ b/docs/agents/traps-index-pending.md @@ -0,0 +1,23 @@ +# 待主人批准:AGENTS.md 陷阱索引补第 18 行 + +`AGENTS.md` 是受写入保护的 agent 指令文件(本机写入需要主人在 UI 上批准)。 +本批次新增了 trap-18,全文已写进 `docs/agents/traps.md`,但索引表那一行**没有**落盘。 + +批准后请把下面这一行追加到 `AGENTS.md` §5 的表格末尾(第 17 行之后): + +``` +| 18 | 快照相等 ≠ 本作业完成:接管判据必须绑 `source_job_id` | `docs/agents/traps.md` | +``` + +现状:`docs/agents/traps.md` 已有全文 §18;索引表缺这一行属于**已知未完成项**, +不是遗漏。 +# 待主人批准:AGENTS.md 陷阱索引补第 19 行 + +同一批:trap-19 全文已写进 `docs/agents/traps.md`(§19)。批准后把下面这一行追加到 +`AGENTS.md` §5 表格末尾(第 18 行之后): + +``` +| 19 | 汇总日志/阶段文案不是接管证据:认领行与决策行必须带作业 id 且晚于杀点 | `docs/agents/traps.md` | +``` + +为什么不能自己写进去:`AGENTS.md` 受写入保护,需主人在 UI 上批准;绕过等于改 agent 指令。 diff --git a/docs/agents/traps.md b/docs/agents/traps.md index f908aa0..13095a3 100644 --- a/docs/agents/traps.md +++ b/docs/agents/traps.md @@ -345,3 +345,214 @@ YAML 里只调用它,不再内联这套拼接。 **修法**:`ci_gate.resolve_scope()`(`--self-test` 里有专门的 `total_commits=0` 分支)。 教训:负例要**照真实事件负载的形状**造,不能只造自己想的形状。 + +## trap-14:包一层装饰器就丢掉"可选接口"⇒ 写集合台账被静默跳过 + +**症状**:真同步作业成功、阶段全绿,但预备份版本证据里没有 `writeset_digest`, +归档根下也没有 `writesets/`。崩溃接管时 `loadWriteSetForJob` 立刻读不到台账, +作业只能失败并把目标留在维护里。 + +**根因**:`libraryrelease.Run` 用**类型断言**决定要不要在写第一笔之前算写集合 +(`target.(WriteSetPlanner)`)。worker 把目标包成 `contentTrackedTarget` 以标记 +"内容可能半写",但这个包装只转发了 `Current/Apply/Verify/Restore` —— 断言 +因此恒为假,整段台账逻辑被**静默跳过**(没有日志、没有错误)。 + +**判据**:任何 `*_test.go` 里断言 `libraryrelease.Target(包装体).(WriteSetPlanner)` +必须为真;或直接查真作业的预备份 `evidence->>'writeset_digest'` 是否非空。 + +**修法**:包装层显式转发该方法;内层不支持时返回硬错误,**不要**退回"没有台账也照写"。 +更一般的规则:只要上游靠可选接口(`XxxPlanner`/`XxxObserver`)决定行为, +每个包装层都要么转发它,要么让断言失败可见。 + +**反例**:只给内层目标写测试(它当然实现),从不测"包装后的目标还实现吗"。 + +## trap-15:`Stat`/`Delete`/`Copy` 与 `Open`/`Put` 吃不同的定位符形状 + +**症状**:对象明明在桶里,`Put` 与 `Open` 都成功,`Stat` 却报 +`invalid release object read` 或 404。 + +**根因**:真实资源路径是 `storage:///:///`(嵌套 +scheme)。`validObjectKey` 认这种形状并把它拆成裸 key,`ValidObjectLocator` 只认单层; +`Open`/`Put` 用前者,`Stat`/`Delete`/`Copy` 用后者、而且直接把整串当对象键。 + +**判据**:集成用例必须喂**真实定位符**(含 `storage://` 前缀与内层桶),负例覆盖 +"键不存在 / provider 不符 / 路径穿越 / 复制源不存在"。 + +**修法**:所有按路径操作的入口共用同一对函数(`validObjectKey` + +`providerPathFromLocator`),测试不要只喂裸 key —— 裸 key 会让这条不一致完美隐身。 + +**反例**:`if _, _, err := store.Stat(...); err == nil { t.Log("...") }` —— 读不到也 +算通过,等于把断言关掉了。 + +## trap-16:"资源不在预备份范围"不等于"属于别的知识库" + +**症状**:同步 A 成功 → 手工恢复 B(resources 表不删行、对象也不删)→ 再同步同一个 A, +预检在写第一笔之前整次拒绝: + +``` +资源 ID 冲突: 存在于目标租户但不在预备份范围内(属于其它知识库),拒绝覆盖 +``` + +**根因**:`resources` 是多知识库共享表,只有 `tenant_id`;预检把"同租户 + 不在预备份 +范围"当成"别人的行"。但恢复 B 的预备份是按**当时**的绑定/正文引用取范围的,A 写进去、 +恢复后变成无绑定的资源不在它里面 —— 这些行恰恰是本目标自己上一次成功同步的结果。 +**"目标里没人引用"不是归属证据**,历史孤儿、其它知识库暂未绑定的资源同样 +满足它;按它放行就是允许覆盖别人的行。 + +**判据**:真实现场(同步 A → 恢复 B → 再同步 A)必须能完成,且复用资源的 PG `xmin` +不变、`universeDump` 里历史孤儿/其它知识库/外租户行逐字节不变;把同一行的内容改一个 +字段后必须继续拒绝;没有持久来源时必须继续拒绝。 + +**修法**:只走"可审计复用"这一条放行路径(`internal/releaseadapter/v071/library_reuse.go`): +持久来源(这个目标成功同步过且登记生效版本的快照,或它自己的预备份)+ 整行内容 +(除易变时间戳)一致 + 对象字节与归档摘要一致,三者同时成立才允许复用;复用行在写集合 +里是 `existing+reused`,写入阶段跳过(不重写行、不重传对象),恢复也不清理它。 +证据单独落盘在 `reuse/.json`,摘要在写集合行里 —— 不冒充历史台账。 + +**反例**:为了"让同步能过"把"不在预备份范围"直接放行,或者恢复时按"没被引用就删"清理。 + +## trap-17:分页窗口当索引 —— "当前生效版本"不能按最近 N 条找 + +**症状**(比 trap-14 更隐蔽:它不报错,只是判错): + +- 接管时把一个"其实已经生效"的作业判成 `fresh`,于是把已经上线的目标**重写一遍**; +- 基线入口为一个已经有权威版本的目标放行"建基线"(会覆盖别人的版本); +- 页面上"生产当前版本"显示成"没有生效版本记录",同步闸口据此要求先建基线; +- 只有把窗口 N 从 50 调到 100/200 才"暂时好一点",再长一点又复发。 + +**根因**:`LibraryVersions(scope, N)` 是**分页展示**用的窗口(真实上限 1..100), +它按 `created_at DESC` 截断。可"当前生效版本"是每 scope 唯一一行、可能很久以前 +登记的事实;"本快照是否生效过"更是身份查询。用窗口当索引,历史一长就把**存在** +读成**不存在**——而且读成"没有"不会报错,只会让错误的选择看起来合理。 + +**判据**:把生效版本登记在 48 小时前、再灌 250 条更新的版本记录,然后: + +- `LibraryVersions(scope, 100)` 里**看不到**它(用例先断言这一点,否则夹具失效); +- `LibraryCurrentVersion`(`kind='production_effective' AND superseded_at IS NULL`) + 仍精确命中,接管判定是 `pending_final` 而不是 `fresh`; +- 换个更新的快照生效后,旧快照 `LibraryVersionOfSnapshot` 仍取回并带 + `superseded_at`,接管判定 `superseded`(拒绝用旧快照覆盖); +- 台账被写坏(同一身份两行、未顶替却不是当前生效、已顶替却是当前生效)⇒ + **拒绝挑选** / 判 `unknown`,不许挑一条"看起来对"的继续写。 + +**修法**:身份/当前状态一律走精确查询(`LibraryCurrentVersion`、 +`LibraryVersionOfSnapshot`、`LibraryVersionByRef`),窗口只用于列表展示; +同一含义的判定(worker 接管、基线、同步闸口的创建判据、归档保留的保护标记) +共用同一份实现,别各写一份"取最近几条再筛"。 + +**反例**:把窗口上限调大、或在内存里 `for` 一遍再 `break`——那是换了个数字, +不是换了判据。 + +## 18. 快照相等 ≠ 本作业完成:接管判据必须绑作业身份 + +**症状**(2026-10-29T19:16Z 真实现场):作业只写完了写入链路的**第一个阶段** +(`database`,`resources/index/wiki/verify` 还是 `pending`),worker 被杀、人工拉起后 +又被判成"succeeded / finalize succeeded",阶段证据写"已登记生效版本(仅收尾,未重写生产)", +并且把生效版本的归属改写成这个作业自己。 + +**为什么它看起来是合理的**:分类只看一个事实——"当前生效版本的目标快照是不是我的目标快照"。 +是 ⇒ `pending_final`(只差收尾,只做校验+登记)。而这个环境里同一个快照会被**多个作业** +发布(同一份冻结候选重复同步),于是"生产上有这个快照"被当成"我这个作业写完了"。 + +**根因**:`library_versions` 的主键由 `(kind, scope, 快照)` 决定 +(`LibraryVersionID`),登记是 `ON CONFLICT (id) DO UPDATE`,会改写 `source_job_id`。 +所以"快照相等"里没有作业身份这一维;只看快照就永远分不清"我发的"和"别人发的"。 + +**判据**(负例优先): + +- 内存:当前生效快照 == 目标快照,但 `source_job_id` 是别的作业 ⇒ 必须是 + `foreign_effective`(不是 `pending_final`);把归属改成本作业才允许 `pending_final`; +- 真实 PG:先 `RecordLibraryVersion` 一个 `source_job_id=别的作业` 的生效行,再 + `loadLibraryVersionFacts` + `classifyTakeover`,断言 `foreign_effective`; + 再用本作业登记同一快照(upsert 改写归属),断言 `pending_final`; +- 撤掉身份判定后这两条必须红(实测:`classify = "pending_final"`)。 + +**修法**:`effectiveOwnedBy(version, jobID, snapshotID)` 一份实现,接管与基线共用; +`foreign_effective` 走"拒绝接管"的失败出口(`failLibraryTakeover`):**不写目标**、 +**不释放维护**、终态失败并指明预备份基线——目标可能半写,释放等于谎称已恢复。 + +**演练侧的同一条**:不同快照才证明完整续作。目标快照 == 中断前的生效版本时, +脚本在**杀之前**就拒绝(`--allow-same-snapshot` 只用于诊断,不算验收证据); +成功判据里必须包含"`database/resources/index/wiki/verify` 五个阶段全部 succeeded"。 + +## 19. 接管证据:汇总日志与阶段文案都不是"这个作业被接管了" + +**症状**(2026-10-29T19:56Z 真实现场):不同快照的 `after:database` 演练里,作业最终 +`succeeded`、`database/resources/index/wiki/verify` 全 succeeded、生效版本归属本作业、 +维护两把锁都释放了,目标内容也确实恢复到 `1/2/9`;但演练脚本 `exit 5`,理由是 +"worker 日志里没有本作业的 resume 记录:接管来源不明"。 + +**为什么它看起来是合理的**:worker 日志里明明有 +`library job takeover sweep: 1 resumed, 0 failed without backup`。但这行是**汇总**: +既不说哪个作业,也不说它是否真被本进程认领(另一个 worker 抢先认领、`attach` 失败 +都只影响计数)。脚本要的老文案 `library job resumed after worker restart` +只在"新建队列行"那条路径打印;真实走的是"队列行已存在"(崩溃前队列行还在)那条, +那条只把计数 `+1`。 + +**根因**:判据绑在一条**只在部分路径打印**的文案上,而且没有作业身份校验。 +另一半是阶段语义:真实接管是"复用崩溃前那份预备份、重跑整条写入链路", +`release.go` 会把 `prebackup` 记成 `succeeded`("预备份 "),不是 `skipped`。 +老判据要求 `prebackup:skipped`,于是**真实有效的预备份也会被判红**——但**不能**因此 +取消备份校验(见下)。 + +**判据(负例优先)**: + +- 认领行(`library job takeover claimed at=… kind=… scope=… target=… backup=… queue=… path=…`) + 只在 `claim` + `attach` 都成功之后写;`claim=false` 或 `attach` 失败时**一行都不许有** + (撤掉"先认领后写日志"的顺序 ⇒ 用例红); +- 决策行(`… takeover decision=fresh|pending_final|…`)在动手之前写;`after:database` + 之后判成 `pending_final` 就是上一轮的假完成(负例:把决策改成 `pending_final` ⇒ 判据红); +- 判据脚本只认**带本作业 id** 且**时间戳晚于杀点**的行:只有汇总行、别的作业的认领行、 + 杀之前的旧日志,三种都必须红(`scripts/takeover_log_contract.py --self-test` 逐条证); +- `prebackup` 允许 `skipped` 或 `succeeded`,但必须同时证明"复用同一份、没被重做覆盖": + 预备份快照 id 不变 + 清单文件字节/mtime 不变 + 版本行 `created_at` 仍是首次登记时刻 + (`RecordLibraryVersion` 对 `production_prebackup` 取 `LEAST`,生效版本仍写当前时刻) + + 证据里有 `backup_reused=true`。取消这些校验等于允许"崩溃后重做备份",那会把半写状态 + 当成可回滚基线。 + +**修法**:`cmd/worker/library_takeover_log.go` 一份实现(认领行/决策行),两条认领路径 +共用;`scripts/takeover_log_contract.py` 是唯一判据(含自检,进 `make verify`); +演练脚本 `verify_takeover_semantics` 改成上面那组断言。 + +## 20. 复用预备份时"重新造一份证据" ⇒ 已持久化的写集合锚点被整份抹掉 + +**症状**(2026-10-30T00:58Z 真实演练,job `librestore-internal-1793321916382871758-retry`): +SIGKILL 137 后按策略重启,接管认领与决策行都对,`database/resources/index/wiki/verify/finalize` +全部 `succeeded`,预备份快照 id、manifest 的 hash/mtime、首次 `created_at` 都没变, +`backup_reused:true` 也在;但 `verify_effective` 失败 —— 生效链上的 +`writeset_digest` 从 `fddd98cf70…` 变成**空**。直接读生产库: + +``` +production_prebackup : {job, backup_bytes:0, backup_reused:true, backup_snapshot, index_mapping_sha256} +production_effective : {…, backup_bytes:0} +``` + +`writeset_*` 一个都不剩。同一作业第二次中断后再接管,`loadWriteSetForJob` 已经读不回 +记录(`预备份 … 没有登记写集合摘要`)—— 恢复链在"再次故障"这一档彻底断掉。 + +**根因**:`BackupPrepared` 每次都**新造**一份证据 map(只放 `backup_snapshot`/`backup_bytes`/ +`job`/`index_mapping_sha256`/`backup_reused`),而 `RecordLibraryVersion` 的 upsert 是 +`evidence = EXCLUDED.evidence`(整份覆盖)。接管路径上: + +- `ledgerBackupStore` 只带 `WriteSet`(没有字节数)⇒ 新证据里 `backup_bytes` 写 0; +- `WriteSetPlanned` 只在**首轮预检**时调用(`backup.WriteSet == nil` 才规划), + 接管复用不重算 ⇒ 被抹掉的 `writeset_*` 没有任何一条路径会补回来。 + +**判据(负例优先)**: + +- 真实 PG:`BackupPrepared` → `WriteSetPlanned` → `loadWriteSetForJob` → 接管 + `Run`(复用)→ 再 `loadWriteSetForJob` 必须仍取回**同一摘要**;连做两轮中断+ + 第三次完整恢复后,证据里 `writeset_digest/writeset_rows/backup_bytes(真实值)/job/ + backup_snapshot/backup_reused` 逐项还在,`created_at` 等于首次登记时刻; +- 把合并改回"新造一份 map"⇒ 该用例必须红(实测:`第 1 次接管后写集合丢失`); +- 复用却没有任何已登记证据、字节数与已登记不一致、证据 `job`/`backup_snapshot` + 与本次不符 ⇒ 一律失败(不许"看起来对就合",那会把别的作业的写集合带进来); +- 同一作业第二次预检出**不同** `writeset_digest` ⇒ 失败(台账不再描述"实际写了什么"); +- 复用拿不到真实字节 ⇒ 失败,不许把 0 写进证据(`backup_bytes:0` 与"空备份"不可区分)。 + +**修法**:`prebackupEvidence`(`cmd/worker/library_writeset.go`)一份实现,先核 +`job`/`backup_snapshot` 身份再**合并**旧证据;接管路径用 `prebackupBytesOf` 从首次 +登记的证据取回真实字节交给 `ledgerBackupStore`(`Bytes<=0` 直接拒绝); +生效版本证据统一由 `effectiveEvidence` 构造。预备份版本行的归属语义: +**一条预备份版本行只属于首次登记它的那个作业**,别的作业撞同一个快照 id 由 +`LibraryVersionByRef` 报"属于作业 X"——那不是"没有记录",不许覆盖。 diff --git a/docs/architecture/ds01-activation-evidence.md b/docs/architecture/ds01-activation-evidence.md new file mode 100644 index 0000000..370e58b --- /dev/null +++ b/docs/architecture/ds01-activation-evidence.md @@ -0,0 +1,86 @@ +# DS01 激活证据的不变量(v2) + +状态:源码与隔离测试已实现;**未在正式治理库执行激活**。 +相关实现:`internal/libraryrelease/restore_dispatch_activation.go`、 +`internal/platform/postgres/library_restore_dispatch_activation.go`、 +`internal/libraryfreeze/journal_evidence.go`。 + +## 1. 当前生产装配从哪里取得可核证据 + +``` +worker(LIBRARY_RESTORE_DISPATCH_V2=true) + └─ librarymaintenance.Manager(LIBRARY_TARGET_*) + └─ libraryfreeze.Coordinator + ├─ 关闭入口 → 读 gate drain.json(closed / drained / active_at_close) + ├─ 等后台静默 → QuiesceProof(depth/pending_ops/unsettled=0,稳定窗口) + ├─ 停写者 → Controller.Stop + Inventory 复核 + 退出码 + └─ 写 /.json(state=held) + └─ library_instance_maintenance(治理库):instance / owner_job_id / target_fingerprint / + level=instance / services / state / released_at +``` + +激活是**部署动作**,不是业务请求:`Store.ActivateRestoreDispatch` 只在部署流程里调用。 +`Store.WithRestoreDispatchEvidence(LIBRARY_TARGET_JOURNAL_ROOT)` 是唯一允许读取 journal 的根; +未配置该根 ⇒ `ErrRestoreDispatchActivationDisabled`(能力关闭),不退回"只看字符串"。 + +## 2. 证据文件只声明身份,不声明结论 + +v2 证据文档(`protocol_version=2`)字段。注意:台账行 `library_index_restore_dispatch_activation.protocol_version` +仍是 1(迁移 78 的派发协议身份约束),证据文档版本与台账协议版本不是同一个数字: + +| 字段 | 含义 | +|---|---| +| `target_identity` | 目标身份 | +| `target_fingerprint` | 维护窗口/部署目标指纹(64 位 sha256 hex),必须等于 journal 与维护行 | +| `restore_target_fingerprint` | 激活时对恢复目标(库/索引/桶)的实时观察指纹 | +| `target_instance` | 治理库维护窗口的实例名,必须等于 journal 的 `source` | +| `governance_database` | 当前治理库名,与 `current_database()` 比对 | +| `protocol_build` | 必须是**运行中二进制**的 `version.DisplayVersion()` | +| `maintenance_job` / `maintenance_journal` | 维护窗口作业;journal 名必须恰好是 `.json` | +| `maintenance_journal_sha256` | 磁盘 journal 字节的 sha256(不是文件内自报值) | +| `writers[] {name, kind, instance_id}` | 旧 writer 集合:名字对治理库 `services`,实例 ID 对 journal `services[].id` | + +**没有** `stopped` / `queue_drained` / `exited_at` / `drain_evidence` 这些调用方布尔字段。 +"已退出、已排空"只能从 journal 事实与治理库行推出来。 + +## 3. 激活门逐项不变量 + +- **A1 来源**:journal 由 `libraryfreeze` 写、位于配置的私有根(目录 0700、非符号链接); + 文件以 `O_NOFOLLOW` 打开、≤1MiB、严格 JSON(未知字段拒绝)。 +- **A2 摘要**:磁盘字节 sha256 == 证据声明值;写入台账的 `drain_evidence_digest` 是这个值。 +- **A3 窗口状态**:journal `state=held`、`level=instance`;已 `recovered`/`released` 的窗口 + 不能证明"旧 writer 仍停着"。 +- **A4 实例绑定**:journal `source` == 证据 `target_instance`,且 == 治理库 + `library_instance_maintenance.instance`。 +- **A5 作业绑定**:journal `job` == 证据 `maintenance_job` == 维护行 `owner_job_id`。 +- **A6 目标绑定**:journal `target_fingerprint` == 证据 `target_fingerprint` == 维护行指纹; + 证据 `restore_target_fingerprint` == 调用方激活时对恢复目标的只读观察值。两者是 + 不同层(实例/部署 vs 内容/索引/桶身份),不能用一个值互相顶替。 +- **A7 入口排空**:`ingress_closed=true`、`drain_verified=true`、gate `closed && drained && + active_at_close==0`。 +- **A8 后台静默**:`quiesce` 存在且 depth/pending_ops/unsettled 全 0、有合法 digest、 + 停写后复核(`post_stop_at ≥ proven_at`、`post_stop_depth=0`、`post_stop_digest=digest`)。 +- **A9 writer 集合**:证据 writer 名字集合 == 维护行 `services`;实例 ID 集合 == journal + `services[].id`;每个 writer `stop_requested=true` 且有 `exit_code`;数量必须一致。 +- **A10 有效性**:停写/排空观察(`quiesce.post_stop_at`)在 2 小时有效期内; + 证据 `attested_at` 不早于该观察、不晚于未来 5 分钟;窗口 `acquired_at` 早于观察。 +- **A11 现场身份**:`current_database()` 等于证据库名;运行构建必须已注入身份且等于 + `protocol_build`;调用方传入的目标指纹必须等于证据指纹。 +- **A12 失败关闭**:任一不满足 ⇒ 不写 activation 行;已撤销行的终局性仍由迁移 78 的 + trigger 保证(`revoked_at→NULL`、删行、状态倒退都拒绝)。 + +## 4. 它不证明什么 + +- 不独立观测"外部 writer 进程此刻不在运行";A7–A9 是维护链自己的受控观察 + (入口 drain、退出码、后台静默),不是通用进程扫描。 +- 不提供 ES 端 fence,也不保证已 `dispatching` 的旧 owner 不会迟到一次。 +- 不抵抗超级管理员禁用 trigger 或恢复旧 PG 快照。 + +## 5. 测试如何证明它不是"验字符串" + +反例(真 PG,见 `library_restore_dispatch_linearization_test.go`):伪造 journal 摘要、 +摘要计算后替换真实文件、错 writer 名字/实例、无退出码、从未要求停、入口未排空 +(`drained=false` / `active_at_close=1` / `drain_verified=false`)、停写观察过期、 +证据过期、治理库身份不符、现场指纹不符、构建不符、维护窗口已释放、作业不属于窗口、 +journal 已 recovered、未配置受信根。全部要求零 activation 行;正例才产生 1 行,并把 +已核事实(journal 摘要、gate、quiesce、每个 writer 的退出码)写进 `evidence.verified`。 \ No newline at end of file diff --git a/docs/architecture/ds01-restore-dispatch.md b/docs/architecture/ds01-restore-dispatch.md new file mode 100644 index 0000000..85f3feb --- /dev/null +++ b/docs/architecture/ds01-restore-dispatch.md @@ -0,0 +1,90 @@ +# DS01:删除型恢复的派发台账(实现说明) + +状态:源码与隔离测试已实现;**未在 8088 / 正式治理库 / 业务 WeKnora 上执行 DDL 或激活**。 +设计正本:`astra-ds01-design.md`。有限验收表:握手目录 `ds01-acceptance-freeze.md`。 + +## 它证明什么、不证明什么 + +证明:对一个固定的删除型恢复 effect(`Before` 非空、`After` 空,恢复写入是独占 `_create`), +台账里 `prepared` 意味着没有任何遵守本协议的派发者取得过发送许可;`dispatching` 之后永不回退, +因此"曾经发送过"不可能再表现为 `prepared`。 + +不证明:ES 端 fencing;已 `dispatching` 的旧 owner 不会迟到一次;目标历史上没被外部写过; +PG 快照回滚/手工删行之后的协议有效性(这类历史倒退必须 held 并人工处置)。 + +## 状态与唯一发送路径 + +``` +prepared --(CAS, 同一短事务内校验 activation/job/operation/attempt/lease/binding)--> dispatching +dispatching --(真实 receipt + 当前 owner/lease)--> marker_confirmed +``` + +- 发送许可只由 `AcquireRestoreMarker` 在 **COMMIT 明确返回后**给出,`RestoreSendPermit` 消费一次即作废。 +- CAS 事务按 `job → operation → activation → active attempt → effect` 取锁: + - 激活撤销(`revoked_at`)与 CAS 在同一事务里线性化:撤销先完成则拒绝,CAS 先取锁则撤销排队; + - lease 用 `clock_timestamp()` 在取锁之后判定,等锁跨过租约即拒绝; + - attempt 必须属于原 window job;job 的 owner/epoch/lease、operation 的 scope/来源快照/ + 已登记写集摘要、实例维护窗口(未释放且属于该作业)逐项核对; + - 恢复路径另核 recovery queue job(运行中且有 lease)与 recovery operation(`kind=recover`、 + 绑定同一 backup); + - 同一 effect 换 plan 摘要会被台账拒绝(不能靠新 key 重开证明)。 +- 不可变绑定来自原持久锚点:`scope`、来源快照(发布基线)、写前镜像(backup)、目标实例/ + 实际指纹/索引 UUID、变更/标记/请求摘要与 attempt 身份。来源与写前镜像不允许是同一份快照。 + 目标指纹与索引 UUID 每次重建绑定都实时重读并与本次恢复冻结值比较:同名重建的目标/索引 + 无法复用旧证明。 +- 恢复期 `_create` 只从 `sendRestoreMarkerOnce` 发出;preflight/故障钩子都在 CAS 之前。 +- 请求设置 `GetBody=nil`,Go 传输层不会在 keep-alive 重连时重放该 mutation。 + +## Restore 准入与收尾 + +`Restore` 在 `AdoptWriteSet` 之后、任何阶段写入之前调用纯读准入,并先对照原 window 的 +**权威台账全集**(跨 plan 摘要):出现另一份 plan、计划外 effect 或不可识别状态立即 held。 + +| 台账/证据 | 结果 | +|---|---| +| 无意图、无证据、无台账 | 首次恢复,可建立 `prepared` | +| 旧意图、无台账 | held(旧协议未知历史,不补 prepared) | +| `prepared` + 绑定冲突(`Held`) | held | +| `prepared` + 已存在 claimed/finalize/目标精确 marker | held(协议证据矛盾) | +| `prepared` + 无矛盾 | 可竞争一次许可 | +| `prepared` + mark-intent 未落盘(文件失败/崩溃区段) | 核对绑定一致后补写**同内容**意图,再竞争 | +| `dispatching` + 目标无精确 marker | held(零新发送) | +| `dispatching` + 精确 marker/内容/世代 | 只走确认分支,不发 create | +| `marker_confirmed` + 无 `restored` 证据 | held | +| `restored` 证据与目标内容/世代一致 | 终态,允许重放 | + +收尾前(整库指纹比对之后)以同一份权威全集再检查一次:任何 `prepared`/`dispatching` 记录、 +计划外记录、换 plan 摘要、或缺失 `restored` 文件证据的 effect 都拒绝返回成功,维护窗口不会 +被释放。 + +## 激活(部署动作,不属于本开发包) + +新能力默认关闭。启用需要两步,缺一不可: + +1. 部署配置 `LIBRARY_RESTORE_DISPATCH_V2=true`(只表示允许装配); +2. 部署流程在**维护窗口 held 的当下**登记激活:`Store` 必须绑定 + `LIBRARY_TARGET_JOURNAL_ROOT`(`WithRestoreDispatchEvidence`),由 + `ActivateRestoreDispatch` 消费一份 v2 证据文件。 + +v2 证据只声明身份(目标/实例/治理库/构建、维护作业、journal 文件名与 sha256、 +旧 writer 集合);"已退出、已排空"由代码直接读维护 journal 与治理库 +`library_instance_maintenance` 行核出:窗口必须 `held`、入口 `closed/drained/ +active_at_close=0`、后台 quiesce 全零且有停写后复核、每个 writer 有 +`stop_requested` 与退出码、writer 集合与治理库一致、观察在 2 小时内。 + +没有配置受信 journal 根时返回 `ErrRestoreDispatchActivationDisabled`(能力关闭), +不会退回"三个非空字符串就开门"。逐项不变量见 +`docs/architecture/ds01-activation-evidence.md`。 + +撤销是终局:`revoked_at` 一旦写入,SQL 不能改回 `NULL`、不能改时间,activation 行也不能删除; +重新开放同一物理目标只能换新的目标身份。 + +边界:代码核验 journal 完整性、身份绑定与维护链自己的停写/排空观察;它不独立扫描 +外部进程,也不提供 ES 端 fence。 + +## 迁移与回滚 + +- `000078_library_restore_dispatch.up.sql` 只建治理库表与触发器,不碰 WeKnora Schema。 +- `000078_..._down.sql` 在 `library_index_restore_dispatch` 或 activation 表有**任意行**时拒绝执行: + 这些行是"是否发送过 / 是否曾被授权"的唯一证明,抹掉等于把 unknown 伪装成 prepared,或把 + 已撤销的激活悄悄删掉。 \ No newline at end of file diff --git a/docs/evidence/2026-10-30-real-sync-restore/README.md b/docs/evidence/2026-10-30-real-sync-restore/README.md new file mode 100644 index 0000000..77ceefe --- /dev/null +++ b/docs/evidence/2026-10-30-real-sync-restore/README.md @@ -0,0 +1,51 @@ +# 真实同步 / 恢复之后的持久证据(2026-10-29 UTC,本机测试栈) + +这两次作业都是**父在 8088 管理员页面点的**,不是脚本模拟、也不是 helper 杀进程演练: + +| 作业 | 类型 | 结果 | 目标 | +| --- | --- | --- | --- | +| `libsync-internal-1793292008635856030` | sync | succeeded / finalize | 源测试封存 `fc595511c738…` → 目标 `kgseal-1029a`(tenant 10001,KB `e64e82b5…`) | +| `librestore-internal-1793293164573204381` | restore | succeeded / finalize | 恢复到预备份 `4b720eb42fca…`(恢复前先备份成 `089676a09107…`) | + +本目录只放**脱敏**结果:没有口令、没有令牌、没有连接串。涉及凭据的核验都在进程内完成 +(对象字节比对用 `tmp/verifyresource` 探针,凭据只从环境变量读、不打印)。 + +## 文件 + +- `jobs.txt` — 两条 `library_jobs` 原始行(state/stage/actor/幂等键/两个快照号/时间)。 +- `stages.txt` — 两条作业的 `library_job_stages`(每阶段 total/completed/bytes)。 +- `versions.txt` — `library_versions` 三类版本(test_sealed / production_effective / + production_prebackup)+ evidence。 +- `maintenance.txt` — 实例级与库级维护窗口(谁持有、入口状态、原运行状态、释放时间)。 +- `archive-integrity.txt` — 归档清单的内容寻址自校验(文件字节 sha256 == 快照号), + 以及"归档根下**没有** writesets/ 台账"这个事实。 +- `resources-verify.json` — 目标库 22 个资源逐条:行内 size、桶里对象的 size/sha256、 + 绑定/授权计数,以及归档里资源分项的 blob sha256 三处对拍。 +- `retrieval.txt` — 文档/分块/Wiki 计数、ES live 索引的文档归属、资源与绑定统计。 + +## 复现命令(只读) + +```bash +# 作业与阶段 +docker exec knowledge-governance-p1-postgres-1 psql -U governance -d governance \ + -c "select id,state,stage,snapshot_id,target_snapshot_id from library_jobs order by created_at desc limit 5" + +# 资源三处对拍(需要目标库 DSN、对象密钥、归档根;全部从环境变量读,不打印) +go build -o /tmp/verifyresource ./tmp/verifyresource +KG_TARGET_DSN=… KG_OBJECT_ENDPOINT=… KG_OBJECT_ACCESS_KEY=… KG_OBJECT_SECRET_KEY=… \ +KG_OBJECT_BUCKET=kgseal-1029a KG_ARCHIVE_ROOT=/var/lib/knowledge-governance/library \ +KG_SNAPSHOT_ID=4b720eb42fca… /tmp/verifyresource + +# 检索侧只有恢复后的那 2 个分块 +curl -s "http://127.0.0.1:19200/kgseal_1029_chunks/_search?size=5&_source=knowledge_id" +``` + +## 结论边界 + +- 资源计数 **22** 是"1 份恢复后的资源 + 21 份本次同步上传的对象字节仍在桶里"。行层面 + 只有 1 条绑定、0 条授权;21 条资源行 `state=active` 但无绑定、无引用,分块/索引/Wiki + 三层都查不到它们。 +- 恢复**只回滚行、不删对象**:对象字节保留是设计语义(删除不在授权范围内), + "保留"不等于"可检索"。 +- 目标实例 `models` 表为空、`tenant_api_keys` 为空,`/run/release-secrets/target_weknora_api_key` + 被目标 401 拒绝 —— 这是 external 范围拿不到"合法模型 + 合法服务令牌"的实证。 \ No newline at end of file diff --git a/docs/evidence/2026-10-30-real-sync-restore/archive-integrity.txt b/docs/evidence/2026-10-30-real-sync-restore/archive-integrity.txt new file mode 100644 index 0000000..37bb5a5 --- /dev/null +++ b/docs/evidence/2026-10-30-real-sync-restore/archive-integrity.txt @@ -0,0 +1,14 @@ +# 归档完整性:清单文件字节的 sha256 必须等于它的快照号(内容寻址) + +snapshot=4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73 + sha256=4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73 size=2185 self_addressed=MATCH +snapshot=089676a09107ceab3bf5e88651f443da26e5d9b2d0de380840c5ec24941a07c2 + sha256=089676a09107ceab3bf5e88651f443da26e5d9b2d0de380840c5ec24941a07c2 size=5540 self_addressed=MATCH +snapshot=fc595511c7388d8e6cab3de37af8a2b6a64ede47241918684e81f2fb5d0e1f16 + sha256=fc595511c7388d8e6cab3de37af8a2b6a64ede47241918684e81f2fb5d0e1f16 size=5541 self_addressed=MATCH + +# 本次两次真作业之后,归档根下有没有 writeset 台账 +ls: 无法访问 '/home/zheromiku/.local/share/knowledge-governance/library/writesets': 没有那个文件或目录 + +# 归档体积 +55M /home/zheromiku/.local/share/knowledge-governance/library diff --git a/docs/evidence/2026-10-30-real-sync-restore/jobs.txt b/docs/evidence/2026-10-30-real-sync-restore/jobs.txt new file mode 100644 index 0000000..0d049fb --- /dev/null +++ b/docs/evidence/2026-10-30-real-sync-restore/jobs.txt @@ -0,0 +1,9 @@ +# library_jobs(两条真作业,2026-10-29 UTC) + + id | scope | kind | state | stage | actor | snapshot_id | target_snapshot_id | queue_job_id | error | recovery | created_at | updated_at | finished_at +-----------------------------------------+----------+---------+-----------+----------+-------+------------------------------------------------------------------+------------------------------------------------------------------+-----------------------------------+--------------------------------------------------------------+----------------------------------------------------------------------------------------+-------------------------------+-------------------------------+------------------------------- + libsync-internal-1793281384686122451 | internal | sync | failed | rollback | admin | 7d79e8b3567a542c27142245ec3b0fd46c36a7e3193a117e05f7a69035cf7ddf | fc595511c7388d8e6cab3de37af8a2b6a64ede47241918684e81f2fb5d0e1f16 | qd7510eadef263b6edc5903cc09dfcd67 | 生产缺少资源 023ff689-b57b-46a8-8455-b24bd13bb309 的存储路径 | 已恢复到预备份 backup-7d79e8b3567a542c27142245ec3b0fd46c36a7e3193a117e05f7a69035cf7ddf | 2026-10-29 13:43:04.686122+00 | 2026-10-29 13:43:19.443695+00 | 2026-10-29 13:43:19.443695+00 + libsync-internal-1793292008635856030 | internal | sync | succeeded | finalize | admin | 4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73 | fc595511c7388d8e6cab3de37af8a2b6a64ede47241918684e81f2fb5d0e1f16 | qaaec9cdbf937cdab5456da1a716d2fd1 | | | 2026-10-29 16:40:08.635856+00 | 2026-10-29 16:40:36.795334+00 | 2026-10-29 16:40:36.795334+00 + librestore-internal-1793293164573204381 | internal | restore | succeeded | finalize | admin | 089676a09107ceab3bf5e88651f443da26e5d9b2d0de380840c5ec24941a07c2 | 4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73 | q3488f8365843537d6cddee177efd16c2 | | | 2026-10-29 16:59:24.573204+00 | 2026-10-29 16:59:51.01581+00 | 2026-10-29 16:59:51.01581+00 +(3 rows) + diff --git a/docs/evidence/2026-10-30-real-sync-restore/maintenance.txt b/docs/evidence/2026-10-30-real-sync-restore/maintenance.txt new file mode 100644 index 0000000..df8cd26 --- /dev/null +++ b/docs/evidence/2026-10-30-real-sync-restore/maintenance.txt @@ -0,0 +1,12 @@ +# 维护窗口(实例级 + 库级) + + scope | owner_job_id | target_identity | state | original_service_state | note | acquired_at | updated_at | released_at | level | target_fingerprint | services | ingress_state +----------+-----------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------+-------------------------------+-------------------------------+-------------------------------+----------+------------------------------------------------------------------+----------+--------------- + internal | librestore-internal-1793293164573204381 | scope=internal db=kgseal-postgres:5432/kgseal_target index=kgseal_1029_chunks bucket=kgseal-1029a | level=instance instance=kgseal-app project=kgseal-weknora writers=app ingress=http://kgseal-ingress:18084/health db=kgseal-postgres:5432/kgseal_target index=kgseal_1029_chunks bucket=kgseal-1029a fingerprint=69e77f36c2ff5718458496c21eb12b17508515a73e5694e96e48cd882690e9d5 | released | container:85af4574672d8c5051aa55c00f02f5ee90cb8fc1ec03b50c2869af2d68fd00fe=85af4574672d8c5051aa55c00f02f5ee90cb8fc1ec03b50c2869af2d68fd00fe running=true healthy=true | 写入与校验完成,目标已按原运行状态恢复 | 2026-10-29 13:37:38.301584+00 | 2026-10-29 16:59:51.009137+00 | 2026-10-29 16:59:51.009137+00 | instance | 69e77f36c2ff5718458496c21eb12b17508515a73e5694e96e48cd882690e9d5 | ["app"] | open +(1 row) + + instance | owner_job_id | owner_scope | target_fingerprint | level | services | ingress_state | state | original_service_state | note | acquired_at | updated_at | released_at +------------+-----------------------------------------+-------------+------------------------------------------------------------------+----------+----------+---------------+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------------------------+-------------------------------+-------------------------------+------------------------------- + kgseal-app | librestore-internal-1793293164573204381 | internal | 69e77f36c2ff5718458496c21eb12b17508515a73e5694e96e48cd882690e9d5 | instance | ["app"] | open | released | container:85af4574672d8c5051aa55c00f02f5ee90cb8fc1ec03b50c2869af2d68fd00fe=85af4574672d8c5051aa55c00f02f5ee90cb8fc1ec03b50c2869af2d68fd00fe running=true healthy=true | 写入与校验完成,目标已按原运行状态恢复 | 2026-10-29 13:37:38.301584+00 | 2026-10-29 16:59:51.009137+00 | 2026-10-29 16:59:51.009137+00 +(1 row) + diff --git a/docs/evidence/2026-10-30-real-sync-restore/resources-verify.json b/docs/evidence/2026-10-30-real-sync-restore/resources-verify.json new file mode 100644 index 0000000..b06b14e --- /dev/null +++ b/docs/evidence/2026-10-30-real-sync-restore/resources-verify.json @@ -0,0 +1,222 @@ +{ + "archive_crosscheck": { + "resource_parts": [ + { + "blob_bytes": 507, + "blob_matches_manifest": true, + "blob_sha256": "25a55cd886544f2ccf7eb25def0eb36c31bcebda356747a6ae6744da20095c35", + "copy_error": "\u003cnil\u003e", + "declared_sha256": "25a55cd886544f2ccf7eb25def0eb36c31bcebda356747a6ae6744da20095c35", + "resource_id": "1f0e979b-9588-42d7-9b38-7c1b2ca05e23" + } + ], + "snapshot_id": "4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73" + }, + "bound": 1, + "chunks": 2, + "generated_at": "2026-10-29T17:29:03Z", + "knowledges": 1, + "objects": [ + { + "id": "e4a24dae-c480-4df8-b97f-792c07afd339", + "state": "active", + "row_size": 4799, + "content_hash_in_row": "", + "object_size": 4799, + "object_sha256": "5d8f38d0c68482f88f795567124892e1e7ec12d2555675930a24ab7da5f17178", + "row_size_matches_object": true + }, + { + "id": "6d1200f8-ecab-455d-838c-401c7380c663", + "state": "active", + "row_size": 309927, + "content_hash_in_row": "", + "object_size": 309927, + "object_sha256": "e153957333e8b48e27878c1e9896545a5bffaf9ae8b1518336c14b00e2d15824", + "row_size_matches_object": true + }, + { + "id": "146cd879-e3ec-4379-99f1-3e4a3a2fbb17", + "state": "active", + "row_size": 833862, + "content_hash_in_row": "", + "object_size": 833862, + "object_sha256": "164d4726d1a90a16f2bcfc7ef65f41c70370626a252529cf525cb1e5d3964e6f", + "row_size_matches_object": true + }, + { + "id": "8558b933-3ae6-4903-af5c-12191508ec13", + "state": "active", + "row_size": 25550195, + "content_hash_in_row": "", + "object_size": 25550195, + "object_sha256": "b52d5e7ccf88393a62e212f15e76177b164b11f11fed4ed81adb4157424da104", + "row_size_matches_object": true + }, + { + "id": "3d06f2ea-c776-4f00-9dc8-04bd50adf0cd", + "state": "active", + "row_size": 10694004, + "content_hash_in_row": "6e33adeb2edc48cd8aeaf73a578126e7074cf96688ef284b3979e999a1472bdf", + "object_size": 10694004, + "object_sha256": "6e33adeb2edc48cd8aeaf73a578126e7074cf96688ef284b3979e999a1472bdf", + "row_size_matches_object": true + }, + { + "id": "07fc9f95-b050-45a1-b895-295050e62980", + "state": "active", + "row_size": 9528401, + "content_hash_in_row": "8edce5de1edff42b30714bbda5915bbc5e028d6d56b7ad8995b9966bcee44661", + "object_size": 9528401, + "object_sha256": "8edce5de1edff42b30714bbda5915bbc5e028d6d56b7ad8995b9966bcee44661", + "row_size_matches_object": true + }, + { + "id": "1456df99-028e-4991-846e-b929eb795496", + "state": "active", + "row_size": 3750682, + "content_hash_in_row": "edcf03327bb8c78f3ab8dbe8f765ad73409487e27c4f1e173063e7d91db06206", + "object_size": 3750682, + "object_sha256": "edcf03327bb8c78f3ab8dbe8f765ad73409487e27c4f1e173063e7d91db06206", + "row_size_matches_object": true + }, + { + "id": "bc271567-58c2-4f82-a6f4-c1d017b580f9", + "state": "active", + "row_size": 1582162, + "content_hash_in_row": "4c4ad050e8d36d55902fbb4b687404d6e340813e64e36d9c87a5a1047e9f0fbf", + "object_size": 1582162, + "object_sha256": "4c4ad050e8d36d55902fbb4b687404d6e340813e64e36d9c87a5a1047e9f0fbf", + "row_size_matches_object": true + }, + { + "id": "719767d8-1957-4e49-be70-c533bc6b931b", + "state": "active", + "row_size": 58124, + "content_hash_in_row": "276d5a00f2b05a35132e5ec632fc91da17217004096c903a839d194c55c3a544", + "object_size": 58124, + "object_sha256": "276d5a00f2b05a35132e5ec632fc91da17217004096c903a839d194c55c3a544", + "row_size_matches_object": true + }, + { + "id": "d2b499f1-b8e8-45b9-8f44-1b37e2fe30c4", + "state": "active", + "row_size": 99763, + "content_hash_in_row": "f1f1877065a4a2e432eb06d1e5004783cb808866d4aeb44fa7ae1b6bef0861c2", + "object_size": 99763, + "object_sha256": "f1f1877065a4a2e432eb06d1e5004783cb808866d4aeb44fa7ae1b6bef0861c2", + "row_size_matches_object": true + }, + { + "id": "023ff689-b57b-46a8-8455-b24bd13bb309", + "state": "active", + "row_size": 57879, + "content_hash_in_row": "02be987d325b57b926584498c45af6c61fd82982a0ce30fba7f9f44fa1169496", + "object_size": 57879, + "object_sha256": "02be987d325b57b926584498c45af6c61fd82982a0ce30fba7f9f44fa1169496", + "row_size_matches_object": true + }, + { + "id": "81da5f3b-0bf1-4666-b7b5-3b9c095b6f2e", + "state": "active", + "row_size": 49986, + "content_hash_in_row": "b8669ddec646a497aae828e0288eb0e9078e3d0888048930e62094ec3bd91440", + "object_size": 49986, + "object_sha256": "b8669ddec646a497aae828e0288eb0e9078e3d0888048930e62094ec3bd91440", + "row_size_matches_object": true + }, + { + "id": "9fcc4450-5e7a-4cee-8267-1e6331d5fd4f", + "state": "active", + "row_size": 36959, + "content_hash_in_row": "98ba3675f8d9e7a8996fc606ff8c32c3634c20359448152d8c3385001875324d", + "object_size": 36959, + "object_sha256": "98ba3675f8d9e7a8996fc606ff8c32c3634c20359448152d8c3385001875324d", + "row_size_matches_object": true + }, + { + "id": "2125cee7-8cce-46af-a5a5-a3c2d6a09763", + "state": "active", + "row_size": 27566, + "content_hash_in_row": "269ffb63cbf6a8a7bbe95be7b25a8fa8842470bab196a7247e349f478cbd9e18", + "object_size": 27566, + "object_sha256": "269ffb63cbf6a8a7bbe95be7b25a8fa8842470bab196a7247e349f478cbd9e18", + "row_size_matches_object": true + }, + { + "id": "d648d95b-6ea9-4ab7-9745-8741a60d22fb", + "state": "active", + "row_size": 14938, + "content_hash_in_row": "7ab830008ce7e50958deca50fb749daa7dd1e4e6283abb4fe8e2e8eeb3d66400", + "object_size": 14938, + "object_sha256": "7ab830008ce7e50958deca50fb749daa7dd1e4e6283abb4fe8e2e8eeb3d66400", + "row_size_matches_object": true + }, + { + "id": "dda128a1-2661-4ae0-9a68-391cb02e6676", + "state": "active", + "row_size": 23565, + "content_hash_in_row": "ea5ffb88cdd183761dcfc28bc1da2f76cb02df9d63139b8c3f6d5f643914ee69", + "object_size": 23565, + "object_sha256": "ea5ffb88cdd183761dcfc28bc1da2f76cb02df9d63139b8c3f6d5f643914ee69", + "row_size_matches_object": true + }, + { + "id": "2114cdc3-886e-4f2d-a92c-720b860874a1", + "state": "active", + "row_size": 156093, + "content_hash_in_row": "e47b635804dc0811c76d4d7b2fe8f33a702a343fe7fcf0f5c8d2e5849b443374", + "object_size": 156093, + "object_sha256": "e47b635804dc0811c76d4d7b2fe8f33a702a343fe7fcf0f5c8d2e5849b443374", + "row_size_matches_object": true + }, + { + "id": "8b218c5a-80f0-4562-8b30-12979a314e55", + "state": "active", + "row_size": 84942, + "content_hash_in_row": "a69abd1ab046d47cee34b2f31c4ec9fc1644222189b5d8146c7dcbbc574a1926", + "object_size": 84942, + "object_sha256": "a69abd1ab046d47cee34b2f31c4ec9fc1644222189b5d8146c7dcbbc574a1926", + "row_size_matches_object": true + }, + { + "id": "a7ef832a-db9a-4eba-a1f9-1ad71f703c6a", + "state": "active", + "row_size": 40945, + "content_hash_in_row": "82b36ad60ee27c965098b63965c1242dfecd71145c72e92c86976a1153d50c2b", + "object_size": 40945, + "object_sha256": "82b36ad60ee27c965098b63965c1242dfecd71145c72e92c86976a1153d50c2b", + "row_size_matches_object": true + }, + { + "id": "113b223c-d616-4270-8b2f-431b78031c97", + "state": "active", + "row_size": 45837, + "content_hash_in_row": "63959f05c5a21349b6b4f602437c97600b3873d6de3bffb295ee0c3cf6819703", + "object_size": 45837, + "object_sha256": "63959f05c5a21349b6b4f602437c97600b3873d6de3bffb295ee0c3cf6819703", + "row_size_matches_object": true + }, + { + "id": "1f292a9b-b694-44f2-9c0d-2ea06867a74e", + "state": "active", + "row_size": 539537, + "content_hash_in_row": "c633186e07013d00039a8e810765625a085c2ae818d7bc66c0d3e58de447fed2", + "object_size": 539537, + "object_sha256": "c633186e07013d00039a8e810765625a085c2ae818d7bc66c0d3e58de447fed2", + "row_size_matches_object": true + }, + { + "id": "1f0e979b-9588-42d7-9b38-7c1b2ca05e23", + "state": "active", + "row_size": 507, + "content_hash_in_row": "", + "object_size": 507, + "object_sha256": "25a55cd886544f2ccf7eb25def0eb36c31bcebda356747a6ae6744da20095c35", + "row_size_matches_object": true + } + ], + "resources_total": 22, + "unbound": 21, + "wiki_pages": 9 +} diff --git a/docs/evidence/2026-10-30-real-sync-restore/retrieval.txt b/docs/evidence/2026-10-30-real-sync-restore/retrieval.txt new file mode 100644 index 0000000..8b3d0f9 --- /dev/null +++ b/docs/evidence/2026-10-30-real-sync-restore/retrieval.txt @@ -0,0 +1,55 @@ +== knowledges / chunks == + id | title | knowledge_base_id | chunks +--------------------------------------+---------------------+--------------------------------------+-------- + d4fbe69d-1b22-4a20-b0fe-66a6e10e854d | 发布闸门运维手册.md | e64e82b5-c578-4a82-a7aa-e6ab0cd26f3c | 2 +(1 row) + + +== ES docs (live index kgseal_1029_chunks) == +{ + "took": 1, + "timed_out": false, + "_shards": { + "total": 1, + "successful": 1, + "skipped": 0, + "failed": 0 + }, + "hits": { + "total": { + "value": 2, + "relation": "eq" + }, + "max_score": 1.0, + "hits": [ + { + "_index": "kgseal_1029_chunks", + "_id": "pgpMhKEB5yh0qa3rXM6B", + "_score": 1.0, + "_source": { + "knowledge_base_id": "e64e82b5-c578-4a82-a7aa-e6ab0cd26f3c", + "knowledge_id": "d4fbe69d-1b22-4a20-b0fe-66a6e10e854d", + "tenant_id": 10001 + } + }, + { + "_index": "kgseal_1029_chunks", + "_id": "pwpMhKEB5yh0qa3rg845", + "_score": 1.0, + "_ignored": [ + "content.keyword" + ], + "_source": { + "knowledge_base_id": "e64e82b5-c578-4a82-a7aa-e6ab0cd26f3c", + "knowledge_id": "d4fbe69d-1b22-4a20-b0fe-66a6e10e854d", + "tenant_id": 10001 + } + } + ] + +== 资源/绑定统计 == + resources | bindings | grants +-----------+----------+-------- + 22 | 1 | 0 +(1 row) + diff --git a/docs/evidence/2026-10-30-real-sync-restore/stages.txt b/docs/evidence/2026-10-30-real-sync-restore/stages.txt new file mode 100644 index 0000000..7c6eb6c --- /dev/null +++ b/docs/evidence/2026-10-30-real-sync-restore/stages.txt @@ -0,0 +1,22 @@ +# library_job_stages + + job_id | stage | state | total | completed | bytes_total | bytes_done | detail | updated_at +-----------------------------------------+-----------+-----------+-------+-----------+-------------+------------+--------------------------------------------------------------------------------+------------------------------- + librestore-internal-1793293164573204381 | rollback | pending | | | | | | 2026-10-29 16:59:24.573204+00 + librestore-internal-1793293164573204381 | prebackup | succeeded | | | | | 预备份 backup-089676a09107ceab3bf5e88651f443da26e5d9b2d0de380840c5ec24941a07c2 | 2026-10-29 16:59:39.9979+00 + librestore-internal-1793293164573204381 | database | succeeded | 5 | 5 | 7138 | 7138 | | 2026-10-29 16:59:40.02311+00 + librestore-internal-1793293164573204381 | resources | succeeded | 1 | 1 | 507 | 507 | | 2026-10-29 16:59:40.034616+00 + librestore-internal-1793293164573204381 | index | succeeded | 2 | 2 | 28563 | 28563 | | 2026-10-29 16:59:40.128762+00 + librestore-internal-1793293164573204381 | wiki | succeeded | 10 | 10 | 23144 | 23144 | | 2026-10-29 16:59:40.157934+00 + librestore-internal-1793293164573204381 | verify | succeeded | | | | | | 2026-10-29 16:59:40.217745+00 + librestore-internal-1793293164573204381 | finalize | succeeded | | | | | 已登记生效版本 | 2026-10-29 16:59:40.227301+00 + libsync-internal-1793292008635856030 | rollback | pending | | | | | | 2026-10-29 16:40:08.635856+00 + libsync-internal-1793292008635856030 | prebackup | succeeded | | | | | 预备份 backup-4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73 | 2026-10-29 16:40:21.737356+00 + libsync-internal-1793292008635856030 | database | succeeded | 67 | 67 | 88086 | 88086 | | 2026-10-29 16:40:22.101487+00 + libsync-internal-1793292008635856030 | resources | succeeded | 21 | 21 | 53490166 | 53490166 | | 2026-10-29 16:40:23.872343+00 + libsync-internal-1793292008635856030 | index | succeeded | 122 | 122 | 1624880 | 1624880 | | 2026-10-29 16:40:24.405281+00 + libsync-internal-1793292008635856030 | wiki | succeeded | 63 | 63 | 105912 | 105912 | | 2026-10-29 16:40:24.74462+00 + libsync-internal-1793292008635856030 | verify | succeeded | | | | | | 2026-10-29 16:40:26.044483+00 + libsync-internal-1793292008635856030 | finalize | succeeded | | | | | 已登记生效版本 | 2026-10-29 16:40:26.055461+00 +(16 rows) + diff --git a/docs/evidence/2026-10-30-real-sync-restore/versions.txt b/docs/evidence/2026-10-30-real-sync-restore/versions.txt new file mode 100644 index 0000000..771bbad --- /dev/null +++ b/docs/evidence/2026-10-30-real-sync-restore/versions.txt @@ -0,0 +1,13 @@ +# library_versions(三类版本严格分开) + + id | scope | kind | snapshot_id | version_label | source_job_id | created_by | created_at | superseded_at | evidence +-------------------------+----------+----------------------+------------------------------------------------------------------+---------------+-----------------------------------------+------------+-------------------------------+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ + libver-9fef7d714f0a1df3 | internal | production_effective | 4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73 | | librestore-internal-1793293164573204381 | admin | 2026-10-29 16:59:40.220607+00 | | {"action": "restore", "backup_bytes": 55311072, "backup_snapshot": "089676a09107ceab3bf5e88651f443da26e5d9b2d0de380840c5ec24941a07c2", "index_mapping_sha256": "8304a7ec8fa67cf9b2885eb209385a7657994fc93fd0f17f4aecae3bf560cd15"} + libver-7d63110da750656b | internal | production_prebackup | 089676a09107ceab3bf5e88651f443da26e5d9b2d0de380840c5ec24941a07c2 | | librestore-internal-1793293164573204381 | worker | 2026-10-29 16:59:39.992079+00 | | {"job": "librestore-internal-1793293164573204381", "backup_bytes": 55311072, "backup_snapshot": "089676a09107ceab3bf5e88651f443da26e5d9b2d0de380840c5ec24941a07c2", "index_mapping_sha256": "8304a7ec8fa67cf9b2885eb209385a7657994fc93fd0f17f4aecae3bf560cd15"} + libver-12785a5f83128307 | internal | production_effective | fc595511c7388d8e6cab3de37af8a2b6a64ede47241918684e81f2fb5d0e1f16 | | libsync-internal-1793292008635856030 | admin | 2026-10-29 16:40:26.047807+00 | 2026-10-29 16:59:40.220607+00 | {"action": "sync", "backup_bytes": 59352, "backup_snapshot": "4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73", "index_mapping_sha256": "8304a7ec8fa67cf9b2885eb209385a7657994fc93fd0f17f4aecae3bf560cd15"} + libver-38ee6d5c3af609d2 | internal | production_prebackup | 4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73 | | libsync-internal-1793292008635856030 | worker | 2026-10-29 16:40:21.732205+00 | | {"job": "libsync-internal-1793292008635856030", "backup_bytes": 59352, "backup_snapshot": "4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73", "index_mapping_sha256": "8304a7ec8fa67cf9b2885eb209385a7657994fc93fd0f17f4aecae3bf560cd15"} + libver-512b4f419a0e4626 | internal | production_prebackup | 7d79e8b3567a542c27142245ec3b0fd46c36a7e3193a117e05f7a69035cf7ddf | | libsync-internal-1793281384686122451 | worker | 2026-10-29 13:43:18.664542+00 | | {"job": "libsync-internal-1793281384686122451", "backup_bytes": 59352, "backup_snapshot": "7d79e8b3567a542c27142245ec3b0fd46c36a7e3193a117e05f7a69035cf7ddf", "index_mapping_sha256": "8304a7ec8fa67cf9b2885eb209385a7657994fc93fd0f17f4aecae3bf560cd15"} + libver-a1f371b600bc8a5f | internal | production_effective | 141dfdc00090d68bddc618e57c71e50e18f209af4657e694c61917d34d3e95e7 | | libbase-internal-1793281057741287747 | admin | 2026-10-29 13:37:50.83744+00 | 2026-10-29 16:40:26.047807+00 | {"note": "基线是目标在维护窗口内的真实整库捕获,不是手写版本;发布仍需独立 sync 授权", "action": "target_baseline_init", "origin": "target_baseline", "verification": "目标与快照逐表行身份/逐行内容/索引文档/资源摘要一致", "baseline_snapshot": "141dfdc00090d68bddc618e57c71e50e18f209af4657e694c61917d34d3e95e7", "index_mapping_sha256": "8304a7ec8fa67cf9b2885eb209385a7657994fc93fd0f17f4aecae3bf560cd15", "scope_content_counts": {"index": 2, "chunks": 2, "resources": 1, "knowledges": 1, "wiki_pages": 9, "wiki_folders": 1, "knowledge_tags": 0, "wiki_log_entries": 0, "wiki_page_issues": 0, "resource_bindings": 1, "knowledge_tag_relations": 0}} + libver-8a84f715668ddf2d | internal | test_sealed | fc595511c7388d8e6cab3de37af8a2b6a64ede47241918684e81f2fb5d0e1f16 | | libseal-lib-internal-20261029T085437 | admin | 2026-10-29 08:54:55.071945+00 | | {"replay": false, "capture_job": "lib-internal-20261029T085437", "agent_result": {"job": "lib-internal-20261029T085437", "parts": [{"kind": "database", "name": "chunks", "bytes": 60250, "count": 38, "sha256": "48f8d5b96d182dad60c6e920bc8882e4137f95e6d2b72de35d7f730fcb3edef1"}, {"kind": "database", "name": "knowledge_tag_relations", "bytes": 2, "count": 0, "sha256": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945"}, {"kind": "database", "name": "knowledge_tags", "bytes": 2, "count": 0, "sha256": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945"}, {"kind": "database", "name": "knowledges", "bytes": 10654, "count": 4, "sha256": "b3d881ee6de89966a83ce7c94061971a28a013b63478b365c64cfe8501f0bead"}, {"kind": "database", "name": "resource_bindings", "bytes": 1037, "count": 4, "sha256": "6fb4be3e41f29caaaf934afdfc1dedb37805e9cdbe76503dac5cd2c438940189"}, {"kind": "database", "name": "resources", "bytes": 16141, "count": 21, "sha256": "fb9dbd9267732a058abb9fd509a600b787d0fb549eb24bc1b2a5a5299e1c5519"}, {"kind": "index", "name": "chunks", "bytes": 1624880, "count": 122, "sha256": "0ea70c240e0f6585f2e6b207d541d11b7b80076ccaf77166e56c131836f4aef2"}, {"kind": "resource", "name": "023ff689-b57b-46a8-8455-b24bd13bb309", "bytes": 57879, "count": 1, "sha256": "02be987d325b57b926584498c45af6c61fd82982a0ce30fba7f9f44fa1169496"}, {"kind": "resource", "name": "07fc9f95-b050-45a1-b895-295050e62980", "bytes": 9528401, "count": 1, "sha256": "8edce5de1edff42b30714bbda5915bbc5e028d6d56b7ad8995b9966bcee44661"}, {"kind": "resource", "name": "113b223c-d616-4270-8b2f-431b78031c97", "bytes": 45837, "count": 1, "sha256": "63959f05c5a21349b6b4f602437c97600b3873d6de3bffb295ee0c3cf6819703"}, {"kind": "resource", "name": "1456df99-028e-4991-846e-b929eb795496", "bytes": 3750682, "count": 1, "sha256": "edcf03327bb8c78f3ab8dbe8f765ad73409487e27c4f1e173063e7d91db06206"}, {"kind": "resource", "name": "146cd879-e3ec-4379-99f1-3e4a3a2fbb17", "bytes": 833862, "count": 1, "sha256": "164d4726d1a90a16f2bcfc7ef65f41c70370626a252529cf525cb1e5d3964e6f"}, {"kind": "resource", "name": "1f292a9b-b694-44f2-9c0d-2ea06867a74e", "bytes": 539537, "count": 1, "sha256": "c633186e07013d00039a8e810765625a085c2ae818d7bc66c0d3e58de447fed2"}, {"kind": "resource", "name": "2114cdc3-886e-4f2d-a92c-720b860874a1", "bytes": 156093, "count": 1, "sha256": "e47b635804dc0811c76d4d7b2fe8f33a702a343fe7fcf0f5c8d2e5849b443374"}, {"kind": "resource", "name": "2125cee7-8cce-46af-a5a5-a3c2d6a09763", "bytes": 27566, "count": 1, "sha256": "269ffb63cbf6a8a7bbe95be7b25a8fa8842470bab196a7247e349f478cbd9e18"}, {"kind": "resource", "name": "3d06f2ea-c776-4f00-9dc8-04bd50adf0cd", "bytes": 10694004, "count": 1, "sha256": "6e33adeb2edc48cd8aeaf73a578126e7074cf96688ef284b3979e999a1472bdf"}, {"kind": "resource", "name": "6d1200f8-ecab-455d-838c-401c7380c663", "bytes": 309927, "count": 1, "sha256": "e153957333e8b48e27878c1e9896545a5bffaf9ae8b1518336c14b00e2d15824"}, {"kind": "resource", "name": "719767d8-1957-4e49-be70-c533bc6b931b", "bytes": 58124, "count": 1, "sha256": "276d5a00f2b05a35132e5ec632fc91da17217004096c903a839d194c55c3a544"}, {"kind": "resource", "name": "81da5f3b-0bf1-4666-b7b5-3b9c095b6f2e", "bytes": 49986, "count": 1, "sha256": "b8669ddec646a497aae828e0288eb0e9078e3d0888048930e62094ec3bd91440"}, {"kind": "resource", "name": "8558b933-3ae6-4903-af5c-12191508ec13", "bytes": 25550195, "count": 1, "sha256": "b52d5e7ccf88393a62e212f15e76177b164b11f11fed4ed81adb4157424da104"}, {"kind": "resource", "name": "8b218c5a-80f0-4562-8b30-12979a314e55", "bytes": 84942, "count": 1, "sha256": "a69abd1ab046d47cee34b2f31c4ec9fc1644222189b5d8146c7dcbbc574a1926"}, {"kind": "resource", "name": "9fcc4450-5e7a-4cee-8267-1e6331d5fd4f", "bytes": 36959, "count": 1, "sha256": "98ba3675f8d9e7a8996fc606ff8c32c3634c20359448152d8c3385001875324d"}, {"kind": "resource", "name": "a7ef832a-db9a-4eba-a1f9-1ad71f703c6a", "bytes": 40945, "count": 1, "sha256": "82b36ad60ee27c965098b63965c1242dfecd71145c72e92c86976a1153d50c2b"}, {"kind": "resource", "name": "bc271567-58c2-4f82-a6f4-c1d017b580f9", "bytes": 1582162, "count": 1, "sha256": "4c4ad050e8d36d55902fbb4b687404d6e340813e64e36d9c87a5a1047e9f0fbf"}, {"kind": "resource", "name": "d2b499f1-b8e8-45b9-8f44-1b37e2fe30c4", "bytes": 99763, "count": 1, "sha256": "f1f1877065a4a2e432eb06d1e5004783cb808866d4aeb44fa7ae1b6bef0861c2"}, {"kind": "resource", "name": "d648d95b-6ea9-4ab7-9745-8741a60d22fb", "bytes": 14938, "count": 1, "sha256": "7ab830008ce7e50958deca50fb749daa7dd1e4e6283abb4fe8e2e8eeb3d66400"}, {"kind": "resource", "name": "dda128a1-2661-4ae0-9a68-391cb02e6676", "bytes": 23565, "count": 1, "sha256": "ea5ffb88cdd183761dcfc28bc1da2f76cb02df9d63139b8c3f6d5f643914ee69"}, {"kind": "resource", "name": "e4a24dae-c480-4df8-b97f-792c07afd339", "bytes": 4799, "count": 1, "sha256": "5d8f38d0c68482f88f795567124892e1e7ec12d2555675930a24ab7da5f17178"}, {"kind": "wiki", "name": "wiki_folders", "bytes": 7381, "count": 21, "sha256": "152b843a55527eff62154b03cff1b2644603c5d15d8f9374a77e306821cbbe51"}, {"kind": "wiki", "name": "wiki_log_entries", "bytes": 10411, "count": 11, "sha256": "f9408fac08b9ebed1c3e60a7e74df89522a06383a42bf8b135c08a8a452a75e1"}, {"kind": "wiki", "name": "wiki_page_issues", "bytes": 2, "count": 0, "sha256": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945"}, {"kind": "wiki", "name": "wiki_pages", "bytes": 88118, "count": 31, "sha256": "e3b6f28f6e6154e0601c3d9a0a755d0f218a6b111e0d262e461004c9b5b56a2a"}], "scope": "internal", "state": "succeeded", "replay": false, "tenant_id": 10000, "snapshot_id": "fc595511c7388d8e6cab3de37af8a2b6a64ede47241918684e81f2fb5d0e1f16", "source_read": true, "compatibility": {"schema_version": 74, "embedding_model": "text-embedding-v4", "weknora_version": "v0.7.1", "retriever_engine": "elasticsearch_v8", "embedding_dimension": 1024, "index_mapping_sha256": "137cde2965f3b56521f5fb722b4e0617f46d0e509e571b217fe01e090d5e4d01"}, "logical_bytes": 55309044, "agent_identity": {"project": "weknora071full", "writers": "app", "source_es": "WKNFull-elasticsearch", "source_pg": "WKNFull-postgres", "source_app": "WKNFull-app", "archive_root": "/home/zheromiku/.local/share/knowledge-governance/library", "journal_root": "/home/zheromiku/.local/share/knowledge-governance/freeze", "expectation_fingerprint": "sha256:c234a1c507e322be281571685e9ae400475379228d55109fd1387abbc7f860c9"}, "writers_stopped": true, "writers_restored": true, "knowledge_base_id": "0c84a098-d3ed-4b82-a165-e6de9691d6a8", "validation_policy": "artifact-acceptance-v1"}, "requested_by": "admin", "expectation_fingerprint": "sha256:c234a1c507e322be281571685e9ae400475379228d55109fd1387abbc7f860c9"} +(7 rows) + diff --git a/docs/library-acceptance-matrix.md b/docs/library-acceptance-matrix.md index 0bc50ee..faac8d3 100644 --- a/docs/library-acceptance-matrix.md +++ b/docs/library-acceptance-matrix.md @@ -81,6 +81,7 @@ A06(内容、问答、引用图片效果、性能报告)已由用户取消 | ID | 缺口 | 现状与影响 | | --- | --- | --- | +| R02-b | 删除型索引恢复的自动重试 | 应用期删掉了目标文档、恢复写入是独占 `_create`。持久意图已落盘而文档缺失时,服务端没有可持久、不可重用的"这份写入没落地"证据:缺失与"从未写过"同形;ES `_stats` 写计数是分片生命周期统计(官方文档:分片迁到另一节点时该分片统计会被清零),索引 uuid 不变不绑定统计生命周期,清零后重新累计到同一数值(ABA)不能排除。**现状 fail-closed**:既存 `restore-mark-intent` 一律 held(`rollback_failed`、零写入、零误归属),不自动重试,需人工按预备份核验后重新规划;本次尝试开始前不存在任何恢复意图时仍可正常重建。这是**开发缺口**(r37 反例:同 uuid 同计数 + 真实写删,恢复仍须 held),不是用户接受的能力收窄;是否引入可校验的持久 not-dispatched 状态与派发原子协议,由后续设计决定。保留的可证明路径:真实 marker 仍在且世代一致的 clean 收尾重试、文档仍是 applied 结果且世代一致的 `DELETE` 补偿重试 | | R03 | 存快/恢复快对比 | A06 性能报告已由用户取消,不作为门槛。**已记实测耗时**(小测试库,不是压测):封存 15.8s(含停写~5s)、同步 13.6s(预备份 13.4s 占主要)、恢复 13.8s;证据 `13-r03-durations.json`。没有做高负载压测,也不写没有测量的数字 | | 死信解除·真实重放演练 | 没有可解除的真实死信,也没有源侧系统管理员凭据 | 契约与执行侧已实现(见下节新增行):上游保留原行、治理侧审计+指纹绑定、未结清/变化/新死信仍阻断。**本轮没有真实死信**(`dead_letters=0`),无法演练"真实重放成功→解除→放行"整条链路;上游只有 `系统管理 runtime run_now`(需要源侧管理员权限)与整队列 purge(销毁证据,不采用)。治理平台故意不持有源侧管理员凭据(放大授权),因此这一步**阻塞在真实死信 + 重放执行方**,不伪造成功 | @@ -92,6 +93,7 @@ A06(内容、问答、引用图片效果、性能报告)已由用户取消 | 排空时序(历史结论) | 旧做法"202 之后抢时序上传"在 1faf513 上重跑 6 次全部 `Broken pipe`(`drain-task-final-1faf513*.json` 保留,不记通过) | 已被 S06-a 的确定性做法取代:先证明请求已被闸门接收,再启动维护。旧证据保留,不覆盖 | | 封存执行期身份复核(真实封存) | 期望身份随 capture 请求送进 agent,由它在操作互斥内、任何源操作之前比对(`swap_test.go` 用两个真实 agent 的 socket 替换做负例,断言错误 agent 的 capture 调用 0 次);真实封存尚未在最终构建上跑,本轮**没有**在候选栈发起真实封存(会产生新快照与停写入者窗口),因此"换 socket 被挡住"只有单测证据 | | 按版本恢复的真实执行(新构建) | `restore-availability` 真实返回、恢复投递路径有单测;真实恢复作业仍在旧构建上验过(R01),本轮未重跑,不把旧证据算作新构建证据 | +| **S04-b** | 重启接管(**不同快照**、`after:database` 真中断) | 真实作业已经证明"写链路能续完",但**脚本级验收还没拿到 exit 0**:当轮判据绑在"只有一条代码路径会打印"的文案上(`library job resumed after worker restart`),真实走的是"队列行已存在"那条,于是 worker 只留下汇总行 `takeover sweep: 1 resumed` ⇒ 脚本 exit 5。判据已改成"认领行 + 决策行 + 时间戳晚于杀点"(`scripts/takeover_log_contract.py`,含 11 条正负例自检,进 `make verify`),`prebackup` 也不再强制 `skipped`(真实是复用后重跑整条链路,记 `succeeded`),改为证明**复用同一份**(快照 id/清单字节+mtime/首次登记时刻不变 + `backup_reused=true`)。**下一轮演练(目标 `fc5955…`,4/38/31)由父在 UI 发起**,才是脚本级验收 | | U05 | 正式 8088 页面验收 | 正式栈仍是 0.1.114,本轮未替换;维护面板/逐页 Wiki 差异只在测试与候选构建里验证过 | ## 四、需授权 / 需环境 @@ -132,4 +134,29 @@ api env `LIBRARY_AGENT_SOCKET=/run/library-agent/agent.sock`,worker 挂载 3. **封存链路本轮真的打通了,而且不是放松校验**:CLI 改为实例级窗口(闸门 + 后台静默 + 目标指纹),"写者 exit=1"由闸门的 `drained/active_at_close` 证据解释,而不是被忽略;排空证明改成"先在途、再关入口"的确定性顺序,不再靠 202 之后抢时序。 4. **接线后暴露的四个真缺陷(都已修,都有用例)**:`jobs.id` 列宽 36 让封存作业根本投不进去;v0.7.1 的 app 写索引不带 `tenant_id` 导致导出 0 条;全新实例的空索引被当成"索引被改坏";恢复作业 id 带 `.` 被维护窗口拒。另有资源定位符仍写来源桶——同步过去的目标取不到图/附件。 5. **死信解除已从"缺代码"变成"有代码、真实验证了一半"**:迁移 073 记录精确解除(保留上游行、绑定实时行指纹、重放引用、源侧观测摘要、操作人);封存时每条实时死信都必须被精确解除命中,行变化/新行/未结清照旧阻断;`libraryctl dead-letters` 生成只读观测,`libraryctl -released-dead-letters` 逐字节复核。**没有演练的部分**是"真实死信→重放→解除→放行":本轮源侧 `dead_letters=0`,且重放需要源侧系统管理员权限(`/system/admin/runtime/queues/{queue}/tasks/{id}/actions/run_now`),治理平台故意不持有该凭据。不伪造成功,也不 SQL 删行冒充。 -6. **同步过去的资源"能被应用读出来"是这轮才真正验的**:资源行里既有 `physical_path` 也有独立的 `storage_backend_id` 列,两者都指向来源实例的 `storage_backends` 主键;只换桶或不换列,目标应用都 500(`code 1007 invalid MinIO file path`)。已在同一份行变换里同时改后端 id 与桶,解析不到就拒绝写入。 \ No newline at end of file +6. **同步过去的资源"能被应用读出来"是这轮才真正验的**:资源行里既有 `physical_path` 也有独立的 `storage_backend_id` 列,两者都指向来源实例的 `storage_backends` 主键;只换桶或不换列,目标应用都 500(`code 1007 invalid MinIO file path`)。已在同一份行变换里同时改后端 id 与桶,解析不到就拒绝写入。 + +## 六、2026-10-30 补录:中断接管这一轮到底验到了什么 + +**已经实测(可回看,不是推断)**:2026-10-29T19:56Z 的 `after:database` 演练 +(作业 `librestore-internal-1793303791259342087`,目标 `0d982f76…`,与中断前的生效版本不同): + +- 宿主机向 worker 容器 PID1 发 SIGKILL,`docker events` 有 `die exitCode=137`,restart policy 拉起 + (同容器、同镜像,`RestartCount 0→1`)——不是 `docker kill`、不是人工 `docker start`; +- 同一作业被启动扫描认领并续完:`database/resources/index/wiki/verify/finalize` 全 `succeeded`, + 作业终态 `succeeded`,生效版本 `source_job_id` 就是本作业,维护两把锁都已释放; +- 写集合摘要 `ec149a69…` 与预备份 `69eb5a90…` 身份在接管前后一致(预备份清单 mtime 仍是崩溃前 + 19:56:45Z,说明**没有重做备份**); +- 目标内容 `knowledges=1 / chunks=2 / wiki_pages=9`(按该快照 manifest 推导); +- 只读补验 7 项全绿(`~/.hermes/handoffs/release-takeover-evidence-next/readonly-verify-20261029.json`): + 写集合独立校验、目标/预备份逐部件字节+sha256、治理库归属与阶段、目标库逐 id+内容、 + 目标索引文档集合、目标桶对象字节+sha256。 + +**还没成立(不许当通过)**: + +- 当轮脚本判据是错的(exit 5,老文案只在一条路径打印)⇒ 这一轮**不能**算"脚本级验收通过", + FAIL 证据原样保留在 `drills/20261029T195605Z/`; +- 接管后的 `prebackup` 版本行 `created_at` 被当轮二进制重写成接管时刻(已修:预备份行取 `LEAST`, + 并写 `backup_reused=true`)——旧现场保持原样,不改写; +- `pending_final`(只差收尾)路径与 `foreign_effective`(拒绝接管)的**端到端**仍未在真实演练里跑过; +- 下一轮不同快照演练(`fc5955…` → 4/38/31)待父在 UI 发起。 diff --git a/docs/library-capture.md b/docs/library-capture.md index 5972a0d..3ee2579 100644 --- a/docs/library-capture.md +++ b/docs/library-capture.md @@ -56,8 +56,16 @@ LIBRARY_TARGET_INGRESS_URL 入口地址(恢复后要能 200) LIBRARY_TARGET_INGRESS_SERVICE Compose 里的入口闸门服务名 LIBRARY_TARGET_INGRESS_DRAIN_FILE 闸门写排空证据的宿主机文件 LIBRARY_TARGET_REDIS_ADDR/_PASSWORD/_DB 后台队列(asynq)地址 +LIBRARY_TARGET_INGRESS_MODE gate(缺省)或 none;none 只给没有闸门的测试栈 +LIBRARY_NO_INGRESS_ACK mode=none 时必须逐字符等于 test-only +LIBRARY_TARGET_HEALTH_URL mode=none 时的健康探针(恢复后必须 200) ``` +`none` 是显式降档,不是默认:整栈(如 0.9.0 测试栈)没有入口闸门时,`none` + 确认串 +才允许缺入口三项,窗口里不调用任何闸门动作,`gate` 证据位置写 +`{"mode":"none","reason":"stack has no ingress gate (test-only)"}`;恢复以 +`LIBRARY_TARGET_HEALTH_URL` 返回 200 为准。缺省 `gate` 的行为与文案不变。 + 另外 `-source-s3-endpoint ` 用来覆盖"源对象存储的访问入口":容器里写的 `MINIO_ENDPOINT` 往往是服务名(`langfuse-minio:9000`),封存跑在宿主机上时解析不到, 资源导出会失败(`read library resource`)。覆盖只换入口,桶与对象键不变;`status` diff --git a/docs/library-data-contract.md b/docs/library-data-contract.md new file mode 100644 index 0000000..231dcb8 --- /dev/null +++ b/docs/library-data-contract.md @@ -0,0 +1,89 @@ +# v0.7.1 整库发布的数据契约与覆盖边界 + +这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关按限定 key 工作,不要求整桶独占审核;B22 控制读取角色是真实 SELECT-only PG 角色。 + +## 1. 源 schema、历史身份与准入 + +- 新 `ExportLibraryWithReleases` 在读取内容的同一 REPEATABLE READ / READ ONLY 事务中读取 columns、constraints、indexes、triggers、relations、sequences;非普通表、RLS/继承/分区、自定义触发器或未知入边 FK 拒绝。 +- 新归档增加一个内容寻址的 `schema/migration-catalog` 部件。归档核 JSON 目录结构、计数、大小和 SHA256;来源清单摘要绑定该部件。PlanWriteSet 在分配序列或执行任何业务写前要求其摘要与当前目标目录一致。序列定义属于目录,last_value/is_called 不属于 DDL 指纹。 +- 旧快照没有该部件:不追加字段、不重新 seal、不改历史 hash;继续走原目标 catalog 和逐行字段/身份检查。它不能被称为“原捕获时已有 schema 证明”。旧V1台账的 canonical 规则不变。 +- 目录严格一致不是自动迁移方案。源/目标定义不同会拒绝,需要单独评审兼容性,不能在业务库上临时 DDL 绕过。 +- 实际 stack 准入读取目标模型、维度、schema 和 graph 状态。同维不同模型、模型行缺失、空模型名、graph 开启、schema dirty 均拒绝;不重算 embedding、不关闭 graph。正例和负例都比较 PG、ES正文/CAS、对象精确版本与网关 journal,证明准入无业务副作用。 + +## 2. 逐表身份、闭包和保真规则 + +|表|身份及本轮已执行的边界|保真/未闭合范围| +|---|---|---| +|knowledges|稳定字符串 ID;租户与KB按计划映射;正文/file_path/metadata 中规范资源引用进入闭包|其余原始列保留;模型/存储定位只按已冻结目标策略改写。不声称已穷尽全部业务 metadata 中非资源ID的语义| +|chunks|稳定 ID;knowledge_id 必须存在且同租户同KB;源 scoped 孤儿不能被 JOIN 静默丢掉;seq_id 使用固定数值映射|chunk_index 排序、按tenant+seq_id查询实跑;规范pre_chunk_id/next_chunk_id/parent_chunk_id要求同knowledge;tag_id及relation_chunks/indirect_relation_chunks要求在范围内,父树拒绝环;不把任意metadata数字猜成seq引用| +|knowledge_tags|稳定 ID;租户/KB必须匹配;seq_id按源数值大小分配并固定|sort_order ASC、created_at DESC、seq_id DESC 的并列排序实跑;原数值在恢复时回原,不回拨共享序列| +|knowledge_tag_relations|精确(knowledge_id,tag_id)元组;任一父可证明范围;缺knowledge、缺tag、跨KB/租户在源、入站及目标规划处拒绝|不通过内连接删除异常关系、不把元组拼成单列。非空正常/既存元组由完整隔离套件执行| +|resources|稳定 ID/22字符handle;引用资源必须存在,原对象字节、精确版本保真;目标正文引用也进入before-image和验证范围|共享资源仍按原不可变before-image/来源证明判断复用,不放宽成“字节相同即认领”。无本次归属的历史孤儿保持不动| +|resource_bindings|稳定 ID;resource_id必须在来源闭包;owner仅knowledge/chunk,必须可解析且租户一致|未知owner_type、NULL owner_type、缺owner及跨租户拒绝。被本次引用资源上的所有绑定都核验,包括指向其它KB的共享绑定;合法共享允许、未知共享归属拒绝| +|wiki_folders|稳定 ID、tenant/KB保真;整行JSON的规范资源字符串参与识别|parent_id必须在本次目录闭包且无环;目录ID碰撞写前拒绝;未知外部持久路径仍不声明支持| +|wiki_pages|稳定 ID;正文和嵌套metadata资源在无binding时也捕获/备份/发布/恢复|页面内容原样保留;按真实字段source_refs(含knowledgeID|title旧形状)、chunk_refs、folder_id检查闭包;不按不存在的source_knowledge_ids字段推断支持| +|wiki_page_issues|稳定 ID、tenant/KB保真;整行资源字符串参与识别|原v071按slug引用/展示的问题记录原样保留;未知扩展字段不自动映射数值ID,不能当作任意插件引用支持| +|wiki_log_entries|BIGINT正整数,不经float64;按源数值大小映射(2在100之前),映射绑定原计划|id DESC和cursor id<实际SQL实跑;恢复原id。旧外部持久游标不能跨映射直接复用,原A04此项仍需决策/验收| +|resource_access_grants(非迁移表)|唯一已审核的resources外部FK入边;不搬运、不删除授权|新建资源清理/Restore前若出现授权,持父键锁拒绝删除;恢复入口另核未知绑定/计划外绑定和外库正文metadata引用,有引用时在ES/对象/PG写前held,锁内再次核全部正文/绑定;当前完整隔离测试读回grant、PG、ES、原对象版本均未变。其它未知入边/触发器拒绝| + +既有目标历史软删除行按原 destructive predicate 进入 before-image,不用来源活跃行过滤规则裁剪恢复数据。来源导出只包含活跃内容;可归属于本库的异常边在过滤前检查。完全没有任何父或范围锚的历史记录不能猜成属于本库:不全局扫出后删除、不自动迁移;这不是“所有历史孤儿已修复”。 + +## 3. 资源引用的实际格式 + +只读参考源码:`WeKnora-v0.7.1-dev/internal/types/resource.go` 中 `ResourceHandleLength=22` 与 `ParseResourcePath`;本轮没有修改WeKnora源码。 + +支持并真实执行: + +- knowledge或Wiki正文里的 `resource://` 加22个URL-safe字符,包含Markdown图片语法; +- 嵌套JSON对象/数组字符串值里的同一规范引用,例如metadata.image_info[].url; +- 无binding的上述四种组合:源捕获、目标before-image、发布、恢复;完整PG及精确对象版本含历史孤儿比对。 + +实现先解码JSON再递归扫描字符串,不将JSON数字转为float64,也不重写正文。所有迁移行的字符串参与资源发现。目标 SQL 选择覆盖所有带tenant/KB的迁移表整行JSON,并与严格解析/完整引用存在性检查配合,不再只认chunk.content。 + +明确拒绝本轮实测的未知表示:短handle、过长handle、URI query/path/fragment后缀、再次转义的resource协议串;不截取22字符前缀冒充合法引用。未知owner独立拒绝。 + +覆盖边界:这不是任意富文本、任意编码或所有插件格式解析器。不承诺识别不含规范协议标识的opaque/base64内容、插件自定义裸UUID引用或全部非资源语义ID。新增格式需给出真实生产/读消费者契约、负例与保真证据后再支持;当前总体验收保持INCOMPLETE。 + +## 4. 数值序列与消费者 + +- chunks.seq_id、knowledge_tags.seq_id、wiki_log_entries.id:正常分配、落后于已占值、耗尽、源显式NULL分别真实执行。后3类在业务阶段前拒绝;所有序列的last_value/is_called、PG全文、ES正文/CAS、S3版本/删除标记不变。 +- 正常分配是明确副作用,会推进序列;必须先固化P0/预备份,不能称只读。新target接管同一WriteSet再Apply不再取号;恢复原行但不rewind序列,合法空洞不等于身份丢失。 +- v071消费者位置:repository/tag.go(sort_order/created_at/seq_id排序)、repository/chunk.go(seq_id读取及chunk_index排序)、repository/wiki_log_entry.go(id DESC、cursor id<)。本轮执行其SQL语义,不声称启动了完整WeKnora UI或所有外部消费者。 + +## 5. 后续门与安全边界 + +- 真实v071历史catalog镜像对照及UUID/自然键矩阵在r11执行,隔离结论与外部当前目录采样分开。A04已识别嵌套引用有有限支持,旧外部cursor仍不自动转换,不因内部结构正例而升级整项。 +- r8/r9进程恢复历史证据只在原发送协议、不可变计划/receipt及相应场景前提不变时复用。本轮对schema/引用准入有收紧,不能把历史执行日志称为当前源码正式进程全链重跑;完整当前隔离适配器回归单列。 +- clean-finalization unknown保持held是安全行为,但未满足全部自动收敛要求。若要求自动完成,需要能绑定原写入、完整内容和代次的充分服务端证据;相同干净正文、人工猜测归属或放宽共享规则均不可替代。 +- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。网关真实 OSS 业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。 + +## 6. 目录与唯一键的有限支持矩阵 + +`testdata/catalog-v071-r11.json` 来自既存只读取证 `source-schema-live-r3b.json`,不是当前线上目录新采样。隔离镜像按原列、约束、索引、关系和触发器定义重建并逐项比较;sequence定义和OWNED BY归属独立绑定,不将last_value伪装成只读DDL。未知外部入边、外部出边、迁移表内部数值FK扩展不能因为源/目标同样扩展就默认放行。 + +稳定主键:knowledges、chunks、knowledge_tags、resources、resource_bindings、wiki_folders、wiki_pages、wiki_page_issues按同租户异KB/异租户碰撞检查;knowledge_tag_relations使用父身份元组;三个本地数值身份按固定WriteSet映射而非稳定UUID处理。资源共享的合法同ID复用仍依赖原before-image和所有权证明。 + +自然键以实际catalog的unique/partial indexes为基准:资源handle、有效tenant/location_hash、资源绑定复合键、tag tenant/KB/name、目录KB/parent/name、wiki KB/slug,以及provider/physical_path的应用层排他。wiki_page_issues在该目录中只有主键,没有额外自然唯一键。partial predicate按有效/软删除判定,并验证不同parent的正常目录;不能无差别拒绝全部正常资料。具体逐键DDL、正负例对应表见交付 `data-contract-r11.md`。 + +Wiki日志pages_affected仅支持消费者已有的字符串slug数组和{slug,title}对象数组;已删除页面/knowledge的历史日志是展示事实,不以缺现存父强删/拒绝历史日志。数字数组、对象中新增log_id等未知结构拒绝。普通metadata数字原样保存,不推断为日志ID。 + +旧外部cursor是明确剩余风险:目标新游标可正确分页,但源数字cursor或发布前旧cursor不能直接带入目标新映射。原A04“改本地ID不破坏引用/语义”没有豁免条款,所以仍未整项通过;本模块不擅改上游WeKnora,也不把“刷新页面即可”当作已经实现的自动失效协议。 + +授权以执行时真实时钟为准;完成预备份及持久计划登记后均再验。目标实现 `GrantRevalidator` 时按治理库授权行回读:`ActiveLibraryAuthorization` 只返回未撤销、未过期且参数摘要一致的记录,撤销后连写集合都不计算(避免序列分配),预备份保留待重新授权。真实发布 wrapper 无条件接线;未接线不等于安全,只是本机历史证据的边界。 + +## 7. r12 追加的真实边界 + +- **软删除 before-image**:destructive predicate 能碰到的 7 张带 `deleted_at` 的表(knowledges/chunks/knowledge_tags/resources/wiki_folders/wiki_page_issues/wiki_pages)逐表核对备份行数与删除谓词命中数;晚阶段失败后的恢复把这些行连同 `deleted_at` 原值一起放回(r12 真实 PG)。 +- **索引独立 oracle**:发布成功后,正文、向量(同维不同值)、metadata(knowledge_id)任一被改都会让校验变红;改回后必须重新通过,说明合法本地列映射没有被这项收紧误杀。 +- **外部索引文档**:同 `_id` 属于其它知识库时整轮在写前拒绝,且那份文档的 `_source`、`_seq_no`、`_primary_term` 与对象版本逐字节不变。 +- **共享资源差异**:同 ID 共享资源在 handle / 定位 / 字节三类差异下都写前拒绝,共享对象版本不变;完全相同的共享资源按 no-op 复用,行 `xmin`/整行 JSON 与对象精确版本均不变。 +- **晚阶段失败与对象**:Wiki 阶段失败回滚后,本次新建对象不残留,**已有对象的精确版本**(versionId + SHA256 + 字节数)不变。 +- **clean 归属能力(实测)**:两个不同操作写入完全相同的字节后,索引侧只剩同一份 `_source`;`_seq_no`/`_version` 是分片提交计数,不绑定原 operation。因此"相同正文"或"seq_no+1"都不能证明是同一次 clean,缺服务端归属证据时继续 held(探针:`b19-capability-probe.json`)。 +- **旧外部游标**:游标是裸数字 id(`next_cursor` → `id < cursor`),发布按源数值升序重排本地 id。目标自己发出的游标在同代内正确;发布前或来自其它实例的游标没有代次信息,无法自动翻译,会静默错位而非报错。详见交付 `a04-cursor-semantics-r12.md` 的 A/B 决策。 + +## 8. 已接受的可用性边界(r13,用户明确接受) + +- **旧分页游标跨发布失效**:`next_cursor` 是裸数字 id(`id < cursor`),发布按源数值升序重排本地 id,请求里没有代次信息。发布前/跨实例游标无法翻译,回传会静默错位而非报错。已接受做法:发布或恢复后刷新页面、重新从第一页分页;不改 WeKnora 源码/Schema。同代内游标与引用重映射仍然正确。 +- **clean-finalization 缺归属证据时保持 held**:真实 ES 探针显示两个不同操作写入相同字节后只剩同一份 `_source`,`_seq_no`/`_version` 是分片提交计数、不绑定 operation。此分支保持维护锁定并走人工核验/恢复,不承诺自动收敛;**不允许**凭相同正文或 seq_no+1 推断归属、补写 receipt、跳过校验、强制开门或删除未知内容。带原 marker/before-image/CAS/不可变 receipt 的 unknown 仍走既有自动补偿,不因本边界回退。 + +配套只读诊断:`GET /api/v1/library/jobs/{id}` 在作业失败且目标仍被本作业持有时返回 `maintenance`(held/owner/state/ingress/target_identity/note)与 `next_step` 文本,明确"按预备份与校验证据人工核验后再放行",且不提供任何强制成功入口;作业本身仍带 operation_id/attempt_epoch/backup/target 快照与错误、恢复说明。 diff --git a/docs/library-migration-contract.md b/docs/library-migration-contract.md new file mode 100644 index 0000000..16ed2b4 --- /dev/null +++ b/docs/library-migration-contract.md @@ -0,0 +1,43 @@ +# 发布身份与不可变计划:开发检查点 + +本批是统一修复的未完成检查点,不是发布就绪版本。不得依据本地门禁通过开启发布写门或部署云执行器。 + +## 已实现边界 + +- 显式逐表身份解析:字符串稳定身份、关系二元组、Wiki bigint;未知非空表、缺身份、错误整数类型和重复身份拒绝。 +- chunks.seq_id、knowledge_tags.seq_id、wiki_log_entries.id 使用目标 sequence 分配并落入不可变写集合。接管校验来源 manifest、映射覆盖及 Wiki 写身份;回滚保留原始编号,不回退共享 sequence。 +- 原始目标 before-image 与源候选导出分离,保留范围谓词内的软删除行和关联。resource_access_grants 外部级联入边已保护;尚未证明全部 FK/trigger 级联闭包。 +- worker 包装器转发 AdoptWriteSet。不可变证据先同步文件,再同步目录;并发写者不能替换已存在的不同字节。 +- ES 写前按全索引 ID 查归属,冻结逐 ID before/after/CAS 并持久化不可变 effect。维护窗口内使用既有 content 字段的暂态操作归属标记,不新增业务 mapping;确认归属后按 CAS 写入干净正文。标记写入成功但响应丢失时,新进程可从计划、完整内容、标记和 CAS 自动确认并补偿。无归属标记、内容或代次不符、清除标记后的未知结果、删除/补偿的未知结果仍拒绝,不能据此宣布完成恢复。 +- 同 ID 资源即使在 before-image 内也必须证明等价才能只读复用;差异拒绝。已有 catalog 驱动自然唯一键预检及物理键绑定;完整负例矩阵仍未齐。 +- 内容 canonicalization 保留大整数及失效期;孤儿查询错误向上传播。 + +## 兼容与回退 + +不修改旧 manifest/blob,也不改变其 hash。本批未增加或修改业务 schema、治理迁移。 + +新执行计划使用 V2,历史 V1 canonical 字节保持不变,并拒绝在 V1 中添加新执行字段;旧 V1 仅可读取诊断,不能把缺失副作用证据的旧计划当作安全执行计划。V2 当前仍不是完整跨存储协议:带归属标记的 ES unknown 已有真实跨进程补偿证据,所有无充分证据的分支仍保持维护,原生 OSS 条件创建协议仍未闭合。复用证据的 V2 before-image 等价证明与写集合版本独立。 + +一旦新计划被用于真实副作用,不得直接降级旧执行器消费新计划;须先证明没有在飞操作并完成原备份恢复和验证。当前没有部署,也未启动任何云作业。 + +## 阻止发布的剩余项 + +1. D0 完整源/目标 schema 指纹、FK 入出边、trigger、应用引用和序列消费者闭合。 +2. 对象精确计划/intent/归属回执及版本化 MinIO 清理已局部实现并运行;MinIO 忽略 Delete IfMatch 的反例已记录,改用精确 versionId。业务桶不自动启用版本控制,无版本桶/未经验证的 OSS 适配写前拒绝。对象计划绑定与完整 adapter 隔离回归已复验;原生 OSS 版本协议已在明确授权测试前缀完成两个真实版本的精确写/读/清理,并列举确认版本与删除标记均无残留;严格条件创建与业务集成仍未闭合,不能放行。 +3. ES 未记录的干净 finalization、删除与恢复网络结果不明时的进一步对账;不得将 fail-closed 状态算作完成。 +4. 自然唯一键、resource_access_grants 与未知引用闭包。 +5. 完整执行权续租、失权取消并等待写结束、跨执行域 fencing,以及队列提交补偿。 +6. source candidate 精确查询与 API/UI 提交接线已测;旧 seal 显式证据关联已接管理员API/UI:核验原捕获响应/期望指纹与原manifest后只追加治理证据,不改快照hash;四种模式及真实页面闭环仍缺。 +7. 两次连续真实 worker 中断,55 项完整验收、最终提交/远端 CI 与父独立复核。 + +已授权的云专用 KB 发布/恢复及测试 App 短停仍属于父独立审查后的后续阶段,无需重复索要开发授权;宿主重启与生产不在本批范围。 + +## 原生 OSS 的具体差异 + +原生版本协议实现提供 versioning 只读确认、带归属 metadata 的显式 append、精确 versionId 读取、完整回执比对后精确删除及再次读取验证。它不是 conditionalObjectStore 的替代,未接成生产 CreateObject。官方 PutObject 文档说明:桶启用/暂停版本控制时,x-oss-forbid-overwrite 无效。因此不能把版本 append 包装成原子仅新建,也不能用 S3 If-None-Match 的本机 MinIO 测试代替 OSS 证明。 + +真实测试只在 KG_OSS_VERSION_TEST_ALLOW=1、明确获准的 KG_OSS_VERSION_TEST_PREFIX、私有持久证据目录及测试凭据齐全时运行。默认不发云写;允许的测试桶固定为 dobot-weknora-test,端点固定深圳 OSS,只操作随机子键及精确版本,不改桶配置。未知 append 留下 intent,不盲扫桶猜测孤儿。限定前缀 kg-library-test-r4/ 已获明确授权并完成真实协议测试;生产条件创建的安全协议仍是实现缺口,不以版本 append 冒充严格仅新建,也不请求降低既有保护。 + +### 证据目录持久性边界 + +不可变 sidecar 的目录创建逐级检查真实目录,拒绝祖先软链接,逐级 fsync 父目录并传播错误;文件与最终目录仍同步。已验证祖先软链接写前拒绝、逐级同步调用覆盖和同步错误传播。这不是实际断电/文件系统崩溃测试,也不等于完整 F12:归档初始化现同步根目录及其父目录,任一fsync失败即拒绝返回可用归档,已做故障注入;PG锚点失败和跨节点介质策略仍需单独验收。 diff --git a/docs/library-target-id-mapping.md b/docs/library-target-id-mapping.md new file mode 100644 index 0000000..69af73e --- /dev/null +++ b/docs/library-target-id-mapping.md @@ -0,0 +1,48 @@ +# 目标库隔离 ID 映射 + +同一 WeKnora 实例里可以有多个知识库。同步把源快照写进目标库时,如果沿用源库的 UUID 主键, +第二个目标库会与实例里已有库的行撞主键(真实证据:2 knowledges / 2 chunks / 23 wiki_pages / +17 wiki_folders 已存在于旧库),写入前的跨范围检查会拒绝整次同步。关闭检查等于让两个库共享身份, +删除/恢复/校验会互相误伤,因此身份必须在目标侧派生。 + +## 映射规则 + +``` +digest = sha256("knowledge-governance/target-identity/v1" || tenant || kb || table || source_id) +target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 variant/version 位) +``` + +这是**本产品自定义的稳定 ID 算法**(`target_id_mode=scoped-sha256-v1`),只保证确定性与目标隔离; +它不是标准 RFC 4122 UUIDv5(UUIDv5 用 SHA-1 + 标准 namespace),不要按 UUIDv5 互操作。 + +- 只绑定**稳定目标身份**(目标 tenant、目标 KB)与源身份,表名参与命名空间; +- 不绑定 job、时间、快照版本等瞬态值:同一目标重复同步/重试/跨版本得到同一 ID; +- 不同目标 KB、不同表得到不同 ID; +- 源归档字节不变,映射只存在于目标侧派生视图(写集合、写入行、索引文档、校验预期); +- 计划把策略持久化为 `target_id_mode=scoped-sha256-v1`:新进程按该字段重建映射,旧计划/写前镜像 + 没有该字段则按原 ID 回放,绝不二次映射。 + +## 参与映射的表与字段 + +| 表 | 身份 | 引用字段 | +|---|---|---| +| knowledges | id | — | +| chunks | id | knowledge_id, tag_id, parent_chunk_id, pre_chunk_id, next_chunk_id, relation_chunks, indirect_relation_chunks, metadata(仅精确匹配) | +| knowledge_tags | id | — | +| knowledge_tag_relations | (knowledge_id, tag_id) | 两个分量分别映射 | +| wiki_folders | id | parent_id | +| wiki_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) | +| wiki_page_issues | id | page_id, knowledge_id, chunk_id | +| resource_bindings | id | owner_id(按 owner_type) | +| resources | **不映射** | resource_id 保持共享身份 | +| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id | + +正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列 +(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。 + +## 一致性边界 + +- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算; +- 索引计划的目标文档 ID 与 `_source` 引用同步映射,before-image(目标写前镜像)保持原样; +- 恢复重放写前镜像时映射关闭,避免把目标原始 ID 再映射一次; +- 资源对象路径/location_hash 仍由既有资源改写逻辑处理,不因 ID 映射而变化。 diff --git a/docs/library-target-identity.md b/docs/library-target-identity.md new file mode 100644 index 0000000..a2d0c73 --- /dev/null +++ b/docs/library-target-identity.md @@ -0,0 +1,31 @@ +# 发布目标身份隔离与迁移 077 + +## 身份与可见性 + +API 与 worker 使用同一 `appconfig.Config.LibraryTargetIdentity`:实例、Compose 项目、数据库名、租户、对内/对外 KB、索引、对象存储 provider/endpoint/bucket 的 SHA-256。凭据、数据库连接的主机/端口、Docker socket、归档目录不参与,避免本机 SSH 转发与云端直连生成不同身份。 + +实例/项目是部署身份,不得把相同名字重新指给另一物理部署;执行器现有实时身份/拓扑准入仍必须通过。本变更不是跨环境凭据授权边界,也不代替目标健康与维护验证。 + +- 当前版本按 `(scope, target_id)` 保存;某目标的新版本不顶替另一目标的 current 或 superseded 元数据。 +- 预备份、历史生效、恢复候选、复用来源和回传引用都只取当前目标证据。 +- 作业、授权、意图持久绑定目标。切换目标后旧作业不可被新执行器准入、续作或自动接管;旧授权不生效。 +- `test_sealed` 和 `seal` 是源侧事实,保持可见;切换发布目标不删除或冒充源封存。 +- 原有事件/作业/授权/意图保留,新增列为空表示“目标归属未证明”,不推断回填。它们不成为任何新目标的运行证据;归档保护仍跨全部历史,避免清理器误删旧恢复材料。 +- 目标绑定是部署级(包含两个 KB);修改其中任一 KB 会建立新的证据上下文。旧记录保存在治理库,不在新目标的发布列表中混显。需要恢复旧目标时必须确认真实配置及证据归属,禁止把空身份批量改成当前身份。 + +## 升级顺序 + +1. 保持写门关闭,检查无在飞发布/恢复/封存、维护锁和未结束执行代次;不能仅凭一次空队列采样。 +2. 备份治理库并在隔离库实际恢复,保留旧运行镜像、Compose 配置链与版本证据摘要。 +3. 停止旧 API/worker/云发布消费者后迁移,防止旧的 `ON CONFLICT(scope)` 与新主键并行使用。**只迁移治理库,不修改 WeKnora schema。** +4. 先启动新 API 完成迁移 077,再启动使用同一配置身份的新 worker;读回版本、schema、身份配置、健康与禁写门。 +5. 页面应显示目标尚无权威版本,不能沿用旧本机演练的“已生效/0 变化”。真实空基线仍由目标逐表只读探测回答。 +6. 在独立目标备份/恢复和正式授权条件满足后执行实际发布及恢复,再确认新 target_id 下的 current。 + +## 回退边界 + +077 的 down 只允许没有任何非空目标绑定记录时执行,避免把已分离的历史合并回一个 scope。产生新记录后不要直接降级;使用经过恢复验证的控制面备份,先核对目标内容与在飞窗口,不能只回旧镜像。源封存、历史事件和快照均不得为了通过验收而清空。 + +## 验证范围 + +真实 PostgreSQL 用例覆盖旧无归属 current、新目标 A/B current 相互独立、外目标预备份/授权/作业/意图不可复用、跨目标事件 ID 冲突拒绝、源封存可共享,以及真实 worker 入口在维护前拒绝旧目标作业。默认 CI 无测试库时显式跳过这部分;本机必须另行实跑。单测通过不代表真实发布/恢复或页面验收已完成。 diff --git a/docs/object-write-gateway.md b/docs/object-write-gateway.md new file mode 100644 index 0000000..e2ca7bc --- /dev/null +++ b/docs/object-write-gateway.md @@ -0,0 +1,105 @@ +# 对象写入网关(开发候选,尚不可部署业务) + +## 协议与持久化 + +`cmd/object-gateway` 提供 `kg-object-gateway-v1`,只监听 loopback;外部接入需要另行审核的 TLS 终结与网络隔离。治理 PG 保存不可变计划、grant、intent、逐版本 receipt 和 attempt→grant delivery。部署迁移身份显式应用 `internal/objectgateway/schema.sql`;启动不自动迁移。运行身份只授必要 SELECT/INSERT 和 scope 行 UPDATE,不授 DDL/TRUNCATE/证据修改或业务库写权限。 + +scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶在本网关内只使用一个 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。这不要求整桶只有本网关一个写者:别的服务可以在同一桶的其它 key 上正常读写。 + +数据认证端点:`POST /v1/acquire`、`/v1/resolve`、`/v1/execute`、`/v1/reconcile`、`/v1/observe`,以及 `GET /v1/capabilities`。所有请求核验协议和 scope。`capabilities.automatic_grants` 必须为真,正式 stack 才接受自动授权能力;未接控制源、只读角色权限异常、协议不符或不可达均拒绝,无直写回退。 + +PG 行锁负责原子准入,不是远端存储 fence。intent 必须持久提交后才发送一次请求;连接死亡、租约过期不清除未知 intent。任何未终态 intent 均阻止 scope 换 epoch。重复 operation 只读回执或精确对账,不重发 PUT;暂时查不到版本仍 held。删除必须绑定已确认 create 的精确 VersionID,不删 latest、不生成删除标记。 + +同 key 竞争按 key 判定,不按桶判定:create 前已存在任何版本 → 回执 `rejected` 且不修改该对象;PUT 后除精确版本读回外还核对当前 latest,若并发写者已产生更新的当前版本,则只按精确 VersionID 撤回本次写入,保留对方版本并返回冲突;读不到当前版本时保持 held,不删除、不猜测。版本化存储的 PUT 不是原子 create-if-absent,因此“本 key 多数情况下归本计划”不是存储层保证。 + +不可变证据表拒绝 UPDATE/DELETE/TRUNCATE。Ready 核 fsync、synchronous_commit、full_page_writes、主库可写及必要表/触发器;管理员与迁移身份仍是可信边界,触发器不能抵御 DBA 的 DDL。 + +## 正式控制交付路径 + +生产代码路径已接入,并已在专属本机隔离栈运行正式 worker 的两次 SIGKILL 接管;这不是生产部署验收: + +`cmd/worker.runOwnedLibraryAttempt → attempt context → librarystack → GatewayObjectStore(Automatic) → ProductionLibraryTarget.Apply → EnsureObjectGrant → /v1/acquire → GatewayGovernanceAuthority → 原持久 WriteSet → journal delivery → 数据 execute`。 + +冻结/采用计划时只保存自校验后的 WriteSet,不提前索取 grant;observer 先把摘要锚定到原预备份事件,首笔业务 PG Apply 前才请求授权。worker 只提交 job/operation/attempt epoch/owner/plan digest,不提交可替换的 key/body allowlist,也不能选择网关 epoch。 + +可信控制域使用独立 SELECT-only 治理连接,核对目标身份、job/operation、当前 attempt、owner、有效租约、running 状态和原预备份事件中的摘要、job、backup、目标快照;再从归档加载并验 hash、范围、provider/bucket。客户端自述不能替代这些持久事实。控制读角色不得是 superuser、CREATEDB、CREATEROLE,不能写/截断/建触发器到这些治理表。每次加载和能力查询重验角色。 + +网关在 scope 锁内再次核对授权事实,原子写入 grant、当前 epoch、不可变 delivery。同一 attempt 重试返回原 grant;owner/operation/plan 替换拒绝;同一 job 的后续 attempt 必须沿用原 operation 和 plan。旧发送未终态时,新 attempt 可先只读对账,但无充分证据仍 held,不能交接。 + +控制服务配置了治理 authority 后,旧 `/v1/plans`、`/v1/advance` 手动控制端点关闭,控制 token 也不能绕过原计划绑定。旧 `cmd/object-gateway-control` 仅保留离线/协议兼容路径,不是正式 worker 的交付方案。 + +## 独立恢复请求 + +`library.recover` 的队列ID由原窗口job确定;它具有独立恢复operation与request digest,绑定scope、queue、原window/operation、target、source、backup和原WriteSet。原计划的job、operation和摘要不改写。Claim中的`recovery_job_id`与`recovery_operation_id`仅为独立授权上下文,原`job_id`/`operation_id`仍是发送域。网关重新读取持久队列payload、running状态、当前owner/attempt/有效租约与恢复operation,不信任worker自行声明。可选显式来源/目标/backup/plan字段只能收紧原绑定,不能覆盖它。 + +SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`library_attempts`、`library_versions`、`jobs`,均不能INSERT/UPDATE/DELETE/TRUNCATE/TRIGGER。已有原窗口恢复请求时不自动重启原发布;过期running恢复队列只在相同target、未释放维护窗口、原业务租约也过期时重新投递,业务attempt/epoch仍重新申请。 + +## 索引unknown恢复边界 + +原冻结before-image非空时,恢复先持久化`restore-mark-intent`,再以原CAS(或确认缺失的create)写入包含原计划/index/id归属标记的完整before-image。丢响应后仅匹配完整标记正文及有效CAS才能登记`restore-claimed`并CAS去标记;已知回执的代次不一致拒绝。恢复完成的`restored`回执仍须匹配正文和CAS,不能接受同正文的新代次。 + +去标记前持久化`restore-finalize-intent`。发布clean-finalization或恢复clean-finalization已提交但响应丢失时,当前干净正文并非充分归属证据;继续held,不盲删、不重发、不把相同外观当回执。旧unknown缺少写前标记intent亦不自动升级认领。本候选没有服务端可验证的clean提交关联凭证,因此这部分自动收敛仍是明确缺口,不是可部署完整恢复保证。 + +## 跨 epoch 的不可变发送身份 + +`Request.Grant` 继续代表首次发送的不可变身份,后端 claim、intent 和 receipt 都不改。新 `ExecuteRequest.authorization` 仅代表本次准入权限。`/v1/resolve` 根据相同 operation/key/action/hash/length/owner/plan 取回旧请求;只允许 epoch 差异,不能换内容。 + +新 attempt 获得新 grant 后,已发送 key 沿用旧 request/claim,未发送 key 使用新授权 epoch 建立首次 intent。当前授权必须匹配 journal 的当前 epoch;旧 epoch 的新写拒绝。新 epoch 补偿删除仍使用原 create 回执和精确版本,删除本身有独立不可变发送身份。 + +## 配置与凭据归属 + +网关进程环境: + +- `OBJECT_GATEWAY_LISTEN`:仅 `127.0.0.1:` 或 `[::1]:`。 +- `OBJECT_GATEWAY_DATABASE_URL`:独立 journal 连接,迁移与运行角色分离。 +- `OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL`:仅可信网关持有的 SELECT-only 治理读连接;独立于 journal 运行身份和普通 worker 身份。 +- `OBJECT_GATEWAY_ARCHIVE_ROOT`:原持久计划所在归档绝对路径,部署只读挂载。 +- `OBJECT_GATEWAY_TARGET_ID`:与正式 worker `LibraryTargetIdentity()` 完全相同的逻辑目标身份;不能用另一个环境的值。 +- `OBJECT_GATEWAY_PROVIDER`、`OBJECT_GATEWAY_ENDPOINT`、`OBJECT_GATEWAY_BUCKET`、`OBJECT_GATEWAY_REGION`:精确存储身份。 +- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:网关持有的对象凭据,需在目标桶 PUT/GET/按版本 DELETE/列举版本。沿用现有 AK 即可,不要求另建独立只读或独占写凭据。 +- `OBJECT_GATEWAY_DATA_TOKEN`、`OBJECT_GATEWAY_CONTROL_TOKEN`:不同且至少 32 字节;普通 worker 仅持有 data token。 +- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:**已退役**。旧部署残留的值被忽略,不参与启动、Ready、每次 Execute 或能力判断;不需要管理员签发整桶独占证明,也不会因过期文件拒绝发布。 + +秘密只经服务环境/私有文件注入,不进 argv、URL 或日志。所有调用端错误都使用固定原因码。 + +正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,可继续使用现有凭据,不再要求独立只读 OSS AK。 + +## 已关闭的本仓旁路 + +- `ObjectImporter.Stage/Promote` 无条件拒绝,不留配置开关,不执行 PUT/COPY。 +- legacy `release-worker` runtime/route 在读凭据及连接目标前拒绝。 +- `release-diag`、`release-channel-e2e` 旧写型入口启动即非零退出,避免 probe PUT 或文档级旁路。 +- `librarystack` 不再为缺网关的 MinIO/S3 返回直写 writer。 +- `libraryctl` capture 的 S3 构造与读取保留;未把读取当作写入口禁用。 + +这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;共享桶不要求撤除其它写者,跨写者的同 key 竞争按冲突/held 处理。 + +## 实测与未完成边界 + +已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证,以及共享桶下“无整桶证明启动 + 其它 key 并发写入 + 同 key 既有对象拒绝”的真实 PG/MinIO 用例。历史隔离审计 authority/故障注入是当时的测试设施,不是当前部署前置。 + +正式 worker 隔离进程证据:真实 Docker 入口闸门/队列、只读 worker 对象身份、独立治理读取角色、网关与业务 PG/ES/MinIO;首次 PG 后和对象提交后两次 SIGKILL,同一原 job/operation/plan 的三代 attempt 完成发布,原对象发送 epoch 与回执不变。隔离构建标签 `kg_isolated_drill` 仅把真实租约缩短至4秒,并拒绝非 loopback 一次性 r8 库;正常构建仍为10分钟。维护上游是无业务凭据的独立 HTTP 夹具,不是运行中的 WeKnora;签名证据绑定本次真实拒写/排空材料,不代表生产独占审核。 + +已补独立 `library.recover` 正式worker链、恢复中再次SIGKILL、完整before-image/CAS/精确版本读回,以及来源/目标/原job/计划/operation/任意队列身份拒绝。ES故障代理只转发真实ES并丢弃已提交响应,未伪造服务响应。 + +尚未完成:clean-finalization unknown的充分归属与自动收敛;网关真实 OSS 端到端与真实部署验收(父执行);原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署分列。 + +整桶独占审核、全部 writer 排空、独立只读对象凭据已不再是发布前置;维护窗口内停目标写入容器并读回确认即可更新。网关按 key 拒绝冲突、精确版本回滚,但不承诺无关写者同时修改同一 key 时仍能自动完成——那种情况会明确冲突或 held,需要人工按回执处理。未改生产权限或上游 WeKnora 源码/Schema。 + +## 维护式更新(已采用) + +目标测试 KB 的更新走维护窗口,不再要求证明整桶只有一个写者: + +1. 停目标测试 WeKnora 的写入应用容器(只停该服务,不停机器人、适配器、共享 PG/ES 或其它 KB 的服务),并由容器状态/健康读回确认已停止。这是本轮文档化的运维步骤;代码侧没有新增停容器实现。 +2. 用既有维护/预备份链记录本次目标 KB/对象范围:实例级维护窗口与写者停写证据由 `internal/libraryfreeze` + `internal/librarymaintenance` 采集,`libraryctl capture`(页面入口 `POST /api/v1/library/captures`)完成闸门排空→停写者→导出快照并保留 `post_stop_digest`;不把通用主机备份当作 KB 预备份的替代。 +3. 用原 plan、原 WriteSet 摘要和限定对象清单走既有 `ProductionLibraryTarget.Apply`(经正式 worker owned attempt 与网关 grant)更新资源;网关沿用现有 AK,不换凭据、不签独占证明。 +4. 启动原容器,健康检查与页面业务验收;失败走既有 `library.recover`/`RestoreDrill` 恢复链按原预备份回放并启动原服务,不无限留停机。 +5. 无关服务与无关 key 全程不需要停;同 key 若仍有外部写者,按上节的冲突/held 处理:双方版本都保留,由人按证据处置,不自动合并。 + +部署需变更的组件:`object-gateway`(本候选镜像)、`worker`(同提交镜像),以及两者 env 中移除/留空已退役的 `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`。`api`、`web` 无协议变更,可不同步。journal、治理 PG 只读 authority、archive 与 target identity 配置保持不变。 + +## 部署与回退(未执行) + +测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准;本候选未在任一主机执行停机、备份、更新或启动。r5 的已完成 OSS 测试授权不能重复使用。 + +按“停目标写入容器→读回确认→备份目标 KB 范围→更新资源→启动→健康/页面验收”执行;失败按原备份恢复并启动原服务。回退先关新写准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。当前整模块仍未完成真实 OSS 端到端与 clean-finalization 收敛,禁止把本候选当作完整生产就绪。 diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go index 48d0f44..990fbb6 100644 --- a/internal/appconfig/config.go +++ b/internal/appconfig/config.go @@ -3,6 +3,7 @@ package appconfig import ( "errors" "fmt" + "net/url" "path/filepath" "strconv" "strings" @@ -23,8 +24,11 @@ type Config struct { ReleaseConfigFile string ProductionReleaseRequestsEnabled bool ProductionBackupRestoreVerified bool - ProductionReleaseAuthorizerRef string - ProductionReleaseAuthTokenFile string + // LibraryRestoreDispatchEnabled 允许 worker 装配 DS01 派发台账;默认 false。 + // 它不能单独证明独占:治理库里的目标激活登记同样必需。 + LibraryRestoreDispatchEnabled bool + ProductionReleaseAuthorizerRef string + ProductionReleaseAuthTokenFile string // Production WeKnora endpoint: the release target itself stays declared in // the release runtime config (RELEASE_CONFIG_FILE); these settings only let // the API probe that endpoint so the console can show its real state. @@ -81,14 +85,20 @@ type Config struct { LibraryProductionExternalKB string // LibraryProductionS3Provider 必须与生产库 resources.provider 的取值一致: // 对象路径按 provider 路由,写错会在上传时被拒绝(而不是写错桶)。 - LibraryProductionS3Provider string - LibraryProductionS3Endpoint string - LibraryProductionS3Region string - LibraryProductionS3Bucket string - LibraryProductionS3AccessKey string - LibraryProductionS3SecretKey string - LibraryEmbeddingModel string - LibraryEmbeddingDimension int + LibraryProductionS3Provider string + LibraryProductionS3Endpoint string + LibraryProductionS3Region string + LibraryProductionS3Bucket string + LibraryProductionS3AccessKey string + LibraryProductionS3SecretKey string + LibraryObjectGatewayURL string + LibraryObjectGatewayToken string + LibraryObjectGatewayGrantDirectory string + // LibraryEmbeddingModel 是整库发布使用的向量模型声明(快照契约缺失时的回落值)。 + LibraryEmbeddingModel string + // LibraryWorkerRole 决定这个进程消费哪一段队列(见 LibraryWorkerRole 说明)。 + LibraryWorkerRole LibraryWorkerRole + LibraryEmbeddingDimension int // LibraryCapacityBudgetBytes 是整库归档容量预算;0 表示未设置(容量门禁不放行)。 LibraryCapacityBudgetBytes int64 // LibraryRetentionVersions / Days 是保留策略;都为 0 表示未设置(不生成清理候选)。 @@ -105,7 +115,13 @@ type Config struct { LibrarySourceProject string // LibrarySourceApp 是封存源容器名(agent -source-app)。project 可能同名而源接线 // 不同,所以配了就一起绑定进"期望执行器身份"。 - LibrarySourceApp string + LibrarySourceApp string + // 源绑定的知识库身份:封存快照的清单里写的是**源**的 tenant/KB,和目标知识库 + // 本来就不是同一个(云测试验收用专用 KB)。搬运必须拿这份独立注入的源绑定去核对, + // 不能拿目标绑定去对,更不能信快照自报。 + LibrarySourceTenantID uint64 + LibrarySourceInternalKB string + LibrarySourceExternalKB string LibraryTargetProject string LibraryTargetWriters []string LibraryTargetNonWriters map[string]string @@ -114,6 +130,11 @@ type Config struct { // 入口闸门:关入口与排空在它身上做(被代理服务自己不排空)。 LibraryTargetIngressService string LibraryTargetIngressDrainFile string + // 入口形态:gate(默认)或 none。none 只给整栈没有入口闸门的测试环境用, + // 必须同时给 LibraryTargetNoIngressAck,且证据等级降一档并如实记录。 + LibraryTargetIngressMode string + LibraryTargetNoIngressAck string + LibraryTargetHealthURL string // 后台静默检查:目标队列 + 目标库(HTTP 排空不等于后台任务排空)。 LibraryTargetRedisAddr string LibraryTargetRedisPassword string @@ -150,6 +171,11 @@ func Load(getenv func(string) string) (Config, error) { return Config{}, errors.New("LIBRARY_PRODUCTION_TENANT_ID must be a positive integer") } tenantID := uint64(tenantID64) + sourceTenant64, err := positiveInt64OrDefault(strings.TrimSpace(getenv("LIBRARY_SOURCE_TENANT_ID")), 0) + if err != nil { + return Config{}, errors.New("LIBRARY_SOURCE_TENANT_ID must be a positive integer") + } + sourceTenantID := uint64(sourceTenant64) embeddingDimension64, err := positiveInt64OrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_DIMENSION")), 1024) if err != nil { return Config{}, errors.New("LIBRARY_EMBEDDING_DIMENSION must be a positive integer") @@ -189,55 +215,69 @@ func Load(getenv func(string) string) (Config, error) { TestAcceptancePolicyVersion: valueOrDefault(getenv("TEST_ACCEPTANCE_POLICY_VERSION"), "structural-v1"), TestAutoReviewPolicy: valueOrDefault(getenv("TEST_AUTO_REVIEW_POLICY"), string(governance.AutoReviewInternal)), // 整库逻辑备份的目标主机:三项同时给出才接线(脚本目录/备份根有默认值)。 - BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")), - BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")), - BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"), - BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"), - VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")), - VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"), - VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")), - LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")), - LibraryAgentSocket: strings.TrimSpace(getenv("LIBRARY_AGENT_SOCKET")), - LibraryProductionDatabaseURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_DATABASE_URL")), - LibraryProductionElasticURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_ELASTIC_URL")), - LibraryProductionIndex: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_INDEX")), "weknora_full_chunks"), - LibraryProductionTenantID: uint64(tenantID), - LibraryProductionInternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_INTERNAL")), - LibraryProductionExternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_EXTERNAL")), - LibraryProductionS3Provider: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_PROVIDER")), "s3"), - LibraryProductionS3Endpoint: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ENDPOINT")), - LibraryProductionS3Region: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_REGION")), "us-east-1"), - LibraryProductionS3Bucket: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_BUCKET")), - LibraryProductionS3AccessKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ACCESS_KEY")), - LibraryProductionS3SecretKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_SECRET_KEY")), - LibraryTargetInstance: strings.TrimSpace(getenv("LIBRARY_TARGET_INSTANCE")), - LibrarySourceInstance: strings.TrimSpace(getenv("LIBRARY_SOURCE_INSTANCE")), - LibrarySourceProject: strings.TrimSpace(getenv("LIBRARY_SOURCE_PROJECT")), - LibrarySourceApp: strings.TrimSpace(getenv("LIBRARY_SOURCE_APP")), - LibraryTargetProject: strings.TrimSpace(getenv("LIBRARY_TARGET_PROJECT")), - LibraryTargetWriters: splitList(getenv("LIBRARY_TARGET_WRITERS")), - LibraryTargetNonWriters: splitDeclarations(getenv("LIBRARY_TARGET_NON_WRITERS")), - LibraryTargetDockerSocket: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_TARGET_DOCKER_SOCKET")), "/var/run/docker.sock"), - LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")), - LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")), - LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")), - LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")), - LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")), - LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0), - LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")), - LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"), - LibraryEmbeddingDimension: embeddingDimension, - LibraryCapacityBudgetBytes: capacityBudget, - LibraryRetentionVersions: retentionVersions, - LibraryRetentionDays: retentionDays, - LibraryExecutorStatusMaxAge: 2 * time.Minute, - VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")), - VersionHistoryHTTPTimeout: 15 * time.Second, - VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200), + BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")), + BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")), + BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"), + BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"), + VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")), + VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"), + VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")), + LibraryArchiveRoot: strings.TrimSpace(getenv("LIBRARY_ARCHIVE_ROOT")), + LibraryAgentSocket: strings.TrimSpace(getenv("LIBRARY_AGENT_SOCKET")), + LibraryProductionDatabaseURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_DATABASE_URL")), + LibraryProductionElasticURL: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_ELASTIC_URL")), + LibraryProductionIndex: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_INDEX")), "weknora_full_chunks"), + LibraryProductionTenantID: uint64(tenantID), + LibraryProductionInternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_INTERNAL")), + LibraryProductionExternalKB: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_KB_EXTERNAL")), + LibraryProductionS3Provider: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_PROVIDER")), "s3"), + LibraryProductionS3Endpoint: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ENDPOINT")), + LibraryProductionS3Region: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_REGION")), "us-east-1"), + LibraryProductionS3Bucket: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_BUCKET")), + LibraryProductionS3AccessKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_ACCESS_KEY")), + LibraryProductionS3SecretKey: strings.TrimSpace(getenv("LIBRARY_PRODUCTION_S3_SECRET_KEY")), + LibraryObjectGatewayURL: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_URL")), + LibraryObjectGatewayToken: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_TOKEN")), + LibraryObjectGatewayGrantDirectory: strings.TrimSpace(getenv("LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY")), + LibraryTargetInstance: strings.TrimSpace(getenv("LIBRARY_TARGET_INSTANCE")), + LibrarySourceInstance: strings.TrimSpace(getenv("LIBRARY_SOURCE_INSTANCE")), + LibrarySourceProject: strings.TrimSpace(getenv("LIBRARY_SOURCE_PROJECT")), + LibrarySourceApp: strings.TrimSpace(getenv("LIBRARY_SOURCE_APP")), + LibrarySourceTenantID: uint64(sourceTenantID), + LibrarySourceInternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_INTERNAL")), + LibrarySourceExternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_EXTERNAL")), + LibraryTargetProject: strings.TrimSpace(getenv("LIBRARY_TARGET_PROJECT")), + LibraryTargetWriters: splitList(getenv("LIBRARY_TARGET_WRITERS")), + LibraryTargetNonWriters: splitDeclarations(getenv("LIBRARY_TARGET_NON_WRITERS")), + LibraryTargetDockerSocket: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_TARGET_DOCKER_SOCKET")), "/var/run/docker.sock"), + LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")), + LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")), + LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")), + LibraryTargetIngressMode: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_MODE")), + // 确认串不 Trim:必须逐字符相等,多一个空格都算没确认。 + LibraryTargetNoIngressAck: getenv("LIBRARY_NO_INGRESS_ACK"), + LibraryTargetHealthURL: strings.TrimSpace(getenv("LIBRARY_TARGET_HEALTH_URL")), + LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")), + LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")), + LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0), + LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")), + LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"), + LibraryEmbeddingDimension: embeddingDimension, + LibraryCapacityBudgetBytes: capacityBudget, + LibraryRetentionVersions: retentionVersions, + LibraryRetentionDays: retentionDays, + LibraryExecutorStatusMaxAge: 2 * time.Minute, + VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")), + VersionHistoryHTTPTimeout: 15 * time.Second, + VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200), } if config.DatabaseURL == "" { return Config{}, errors.New("DATABASE_URL is required") } + // 角色非法必须在启动时失败:一个拼错的角色会让进程悄悄回到"什么都消费"。 + if config.LibraryWorkerRole, err = parseLibraryWorkerRole(getenv("LIBRARY_WORKER_ROLE")); err != nil { + return Config{}, err + } if config.PollInterval, err = durationOrDefault(getenv("WORKER_POLL_INTERVAL"), config.PollInterval); err != nil { return Config{}, fmt.Errorf("WORKER_POLL_INTERVAL: %w", err) } @@ -277,6 +317,14 @@ func Load(getenv func(string) string) (Config, error) { return Config{}, fmt.Errorf("PRODUCTION_BACKUP_RESTORE_VERIFIED: %w", err) } } + // DS01 恢复标记派发协议:默认关闭。开关只是"允许装配"的意思,不是独占证明—— + // 真正发放许可还要求治理库里对该目标存在未撤销的激活登记。 + if raw := getenv("LIBRARY_RESTORE_DISPATCH_V2"); raw != "" { + config.LibraryRestoreDispatchEnabled, err = strconv.ParseBool(raw) + if err != nil { + return Config{}, fmt.Errorf("LIBRARY_RESTORE_DISPATCH_V2: %w", err) + } + } if raw := getenv("PRODUCTION_WEKNORA_ALLOW_DOCKER_HTTP"); raw != "" { config.ProductionWeKnoraAllowDockerHTTP, err = strconv.ParseBool(raw) if err != nil { @@ -349,9 +397,35 @@ func Load(getenv func(string) string) (Config, error) { if config.LibraryAgentSocket != "" && !filepath.IsAbs(config.LibraryAgentSocket) { return Config{}, errors.New("LIBRARY_AGENT_SOCKET 必须是绝对路径(unix socket 由主机侧 agent 持有)") } + // 入口形态:缺省 gate,行为与之前完全一致。none 只给整栈没有入口闸门的 + // 测试环境用,必须显式确认;确认串逐字符相等,多一个空格都算没确认。 + if config.LibraryTargetIngressMode == "" { + config.LibraryTargetIngressMode = "gate" + } + switch config.LibraryTargetIngressMode { + case "gate", "none": + default: + return Config{}, fmt.Errorf("LIBRARY_TARGET_INGRESS_MODE 无效(%q):只能是 gate 或 none", + config.LibraryTargetIngressMode) + } + noGate := config.LibraryTargetIngressMode == "none" + if noGate && config.LibraryTargetNoIngressAck != "test-only" { + return Config{}, errors.New("no-gate 维护必须显式确认:LIBRARY_NO_INGRESS_ACK 必须逐字符等于 test-only,拒绝启动") + } + if !noGate && config.LibraryTargetNoIngressAck != "" { + return Config{}, errors.New("LIBRARY_NO_INGRESS_ACK 只在 LIBRARY_TARGET_INGRESS_MODE=none 下有效") + } + if config.LibraryTargetHealthURL != "" { + parsed, err := url.Parse(config.LibraryTargetHealthURL) + if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || + parsed.Host == "" || parsed.User != nil { + return Config{}, errors.New("LIBRARY_TARGET_HEALTH_URL 必须是 http(s) 地址且不带凭据") + } + } // 目标维护要么完整配置,要么完全不配;半配置会让窗口"看起来存在"却挡不住目标。 targetSet := config.LibraryTargetInstance != "" || config.LibraryTargetProject != "" || - len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != "" + len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != "" || + noGate || config.LibraryTargetHealthURL != "" if targetSet { missing := make([]string, 0, 4) if config.LibraryTargetInstance == "" { @@ -363,16 +437,21 @@ func Load(getenv func(string) string) (Config, error) { if len(config.LibraryTargetWriters) == 0 { missing = append(missing, "LIBRARY_TARGET_WRITERS") } - if config.LibraryTargetIngressURL == "" { + if noGate { + // 没有闸门可声明:健康探针是唯一能证明"目标回来了"的必需项。 + if config.LibraryTargetHealthURL == "" { + missing = append(missing, "LIBRARY_TARGET_HEALTH_URL") + } + } else if config.LibraryTargetIngressURL == "" { missing = append(missing, "LIBRARY_TARGET_INGRESS_URL") } if config.LibraryTargetJournalRoot == "" { missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT") } - if config.LibraryTargetIngressService == "" { + if !noGate && config.LibraryTargetIngressService == "" { missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE") } - if config.LibraryTargetIngressDrainFile == "" { + if !noGate && config.LibraryTargetIngressDrainFile == "" { missing = append(missing, "LIBRARY_TARGET_INGRESS_DRAIN_FILE") } if config.LibraryTargetRedisAddr == "" { @@ -381,13 +460,17 @@ func Load(getenv func(string) string) (Config, error) { if len(missing) > 0 { return Config{}, fmt.Errorf("目标维护配置不完整:缺少 %s", strings.Join(missing, "、")) } + if noGate && (config.LibraryTargetIngressURL != "" || config.LibraryTargetIngressService != "" || + config.LibraryTargetIngressDrainFile != "") { + return Config{}, errors.New("no-gate 维护不得同时配置入口地址/闸门服务/排空文件:要么有闸门,要么明确没有") + } if !filepath.IsAbs(config.LibraryTargetJournalRoot) { return Config{}, errors.New("LIBRARY_TARGET_JOURNAL_ROOT 必须是绝对路径") } if !filepath.IsAbs(config.LibraryTargetDockerSocket) { return Config{}, errors.New("LIBRARY_TARGET_DOCKER_SOCKET 必须是绝对路径") } - if !filepath.IsAbs(config.LibraryTargetIngressDrainFile) { + if !noGate && !filepath.IsAbs(config.LibraryTargetIngressDrainFile) { return Config{}, errors.New("LIBRARY_TARGET_INGRESS_DRAIN_FILE 必须是绝对路径") } if len(config.LibraryTargetNonWriters) == 0 { diff --git a/internal/appconfig/library_role.go b/internal/appconfig/library_role.go new file mode 100644 index 0000000..6e0a254 --- /dev/null +++ b/internal/appconfig/library_role.go @@ -0,0 +1,85 @@ +package appconfig + +import ( + "fmt" + "strings" + + "knowledge-governance/internal/governance" +) + +// LibraryWorkerRole 是这个进程在整库发布链上的角色(LIBRARY_WORKER_ROLE)。 +// +// 为什么要有显式角色,而不是"配了目标就算这个进程能发布":一条 release 作业 +// 只带 scope 与快照 ID,**目标实例来自本进程的部署配置**(LIBRARY_TARGET_* / +// LIBRARY_PRODUCTION_*)。两个执行器同时消费同一队列时,谁抢到就按谁自己的 +// 配置执行——本机执行器会把"发往云测试"的作业按本机 kgseal 的维护窗口去停本机 +// 容器、往本机目标写。这不是权限问题,是身份问题,只能靠"谁消费哪段队列" +// 在启动时定死。 +type LibraryWorkerRole string + +const ( + // LibraryWorkerRoleFull 是历史行为:本进程消费全部队列(单机部署)。 + LibraryWorkerRoleFull LibraryWorkerRole = "full" + // LibraryWorkerRoleReleaseExecutor 只消费整库发布(sync / restore / recover / + // baseline)与它们的接管扫描。不起 scheduler、不接封存 agent、不消费 QA/测试/ + // 目录刷新等作业:那些队列归本机那个源侧执行器。 + LibraryWorkerRoleReleaseExecutor LibraryWorkerRole = "release-executor" + // LibraryWorkerRoleCapture 消费除整库发布以外的全部队列(封存、QA、测试、 + // 目录刷新…),并且**不接管** release 作业。与 release-executor 互斥。 + LibraryWorkerRoleCapture LibraryWorkerRole = "capture" +) + +func parseLibraryWorkerRole(raw string) (LibraryWorkerRole, error) { + value := LibraryWorkerRole(strings.TrimSpace(raw)) + switch value { + case "": + return LibraryWorkerRoleFull, nil + case LibraryWorkerRoleFull, LibraryWorkerRoleReleaseExecutor, LibraryWorkerRoleCapture: + return value, nil + default: + return "", fmt.Errorf("LIBRARY_WORKER_ROLE 只能是 full/release-executor/capture,当前是 %q", string(value)) + } +} + +func (r LibraryWorkerRole) String() string { + if r == "" { + return string(LibraryWorkerRoleFull) + } + return string(r) +} + +// ExecutesRelease:本进程注册整库发布 handler,并接管中断的发布作业。 +func (r LibraryWorkerRole) ExecutesRelease() bool { + return r == "" || r == LibraryWorkerRoleFull || r == LibraryWorkerRoleReleaseExecutor +} + +// ExecutesSourceWork:本进程注册封存/QA/测试/目录刷新等非发布队列,并起后台调度。 +func (r LibraryWorkerRole) ExecutesSourceWork() bool { + return r == "" || r == LibraryWorkerRoleFull || r == LibraryWorkerRoleCapture +} + +// ExecutesMigrations:只有控制面所在的那个进程才做 DDL。 +// +// 发布执行器是"目标旁边的一个消费者",不是控制面:让它去改治理库 schema, +// 等于把"谁有权决定治理库结构"扩散到第二台机器。云侧只读校验版本,落后就拒绝启动。 +func (r LibraryWorkerRole) ExecutesMigrations() bool { + return r == "" || r == LibraryWorkerRoleFull || r == LibraryWorkerRoleCapture +} + +// LibraryJobKinds 是这个角色负责收拾孤儿/接管的 library_jobs.kind。 +// 分开是因为"收拾"会写终态和恢复责任文案:seal 的恢复责任在封存 agent, +// release 的恢复责任在目标与预备份,混着写会把责任指错人。 +func (r LibraryWorkerRole) LibraryJobKinds() []string { + switch r { + case LibraryWorkerRoleReleaseExecutor: + return []string{string(governance.LibraryJobSync), string(governance.LibraryJobRestore), + string(governance.LibraryJobRecover), string(governance.LibraryJobBaseline), + string(governance.LibraryJobVerify)} + case LibraryWorkerRoleCapture: + return []string{string(governance.LibraryJobSeal)} + default: + return []string{string(governance.LibraryJobSeal), string(governance.LibraryJobSync), + string(governance.LibraryJobRestore), string(governance.LibraryJobRecover), + string(governance.LibraryJobBaseline), string(governance.LibraryJobVerify)} + } +} diff --git a/internal/appconfig/library_role_test.go b/internal/appconfig/library_role_test.go new file mode 100644 index 0000000..ef64b15 --- /dev/null +++ b/internal/appconfig/library_role_test.go @@ -0,0 +1,84 @@ +package appconfig + +import "testing" + +func TestParseLibraryWorkerRole(t *testing.T) { + cases := []struct { + raw string + want LibraryWorkerRole + release bool + source bool + wantFail bool + }{ + {raw: "", want: LibraryWorkerRoleFull, release: true, source: true}, + {raw: "full", want: LibraryWorkerRoleFull, release: true, source: true}, + {raw: " release-executor ", want: LibraryWorkerRoleReleaseExecutor, release: true, source: false}, + {raw: "capture", want: LibraryWorkerRoleCapture, release: false, source: true}, + {raw: "release", wantFail: true}, + {raw: "worker", wantFail: true}, + } + for _, test := range cases { + got, err := parseLibraryWorkerRole(test.raw) + if test.wantFail { + if err == nil { + t.Fatalf("parseLibraryWorkerRole(%q) accepted an unknown role", test.raw) + } + continue + } + if err != nil { + t.Fatalf("parseLibraryWorkerRole(%q) error = %v", test.raw, err) + } + if got != test.want { + t.Fatalf("parseLibraryWorkerRole(%q) = %q, want %q", test.raw, got, test.want) + } + if got.ExecutesRelease() != test.release || got.ExecutesSourceWork() != test.source { + t.Fatalf("role %q release=%t source=%t, want release=%t source=%t", + got, got.ExecutesRelease(), got.ExecutesSourceWork(), test.release, test.source) + } + if got.ExecutesRelease() && got.ExecutesSourceWork() && got != LibraryWorkerRoleFull { + t.Fatalf("role %q claims both domains without being full", got) + } + } +} + +// 非法角色必须让进程起不来:静默回到 full 会让两套执行器抢同一批 release 作业。 +func TestLoadRejectsUnknownLibraryWorkerRole(t *testing.T) { + env := map[string]string{ + "DATABASE_URL": "postgres://user:pass@127.0.0.1:5432/governance?sslmode=disable", + "LIBRARY_WORKER_ROLE": "release", + } + if _, err := Load(func(key string) string { return env[key] }); err == nil { + t.Fatal("Load() accepted LIBRARY_WORKER_ROLE=release") + } + env["LIBRARY_WORKER_ROLE"] = "release-executor" + config, err := Load(func(key string) string { return env[key] }) + if err != nil { + t.Fatalf("Load() error = %v", err) + } + if !config.LibraryWorkerRole.ExecutesRelease() || config.LibraryWorkerRole.ExecutesSourceWork() { + t.Fatalf("release-executor role mapping is wrong: %#v", config.LibraryWorkerRole) + } +} + +// 每个角色收拾哪些 kind、谁拥有 DDL,都必须互斥且覆盖完整。 +func TestLibraryWorkerRoleOwnershipMaps(t *testing.T) { + release := LibraryWorkerRoleReleaseExecutor + if got := release.LibraryJobKinds(); len(got) != 5 || got[0] != "sync" || got[1] != "restore" || + got[2] != "recover" || got[3] != "baseline" || got[4] != "verify" { + t.Fatalf("release-executor kinds = %v", got) + } + if got := LibraryWorkerRoleCapture.LibraryJobKinds(); len(got) != 1 || got[0] != "seal" { + t.Fatalf("capture kinds = %v", got) + } + if got := LibraryWorkerRoleFull.LibraryJobKinds(); len(got) != 6 { + t.Fatalf("full kinds = %v", got) + } + for _, role := range []LibraryWorkerRole{LibraryWorkerRoleFull, LibraryWorkerRoleCapture} { + if !role.ExecutesMigrations() { + t.Fatalf("role %q must own DDL", role) + } + } + if release.ExecutesMigrations() { + t.Fatal("release-executor must not own governance DDL") + } +} diff --git a/internal/appconfig/library_target.go b/internal/appconfig/library_target.go new file mode 100644 index 0000000..a915bdc --- /dev/null +++ b/internal/appconfig/library_target.go @@ -0,0 +1,41 @@ +package appconfig + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// LibraryTargetIdentity binds control-plane evidence to the logical deployment +// and data scope, not credentials or the caller's transport. API may use an SSH +// forward while the executor uses the private DB address. Instance/project are +// deployment identities, verified independently by executor admission; reusing +// them for another physical deployment is not a supported target switch. +func (c Config) LibraryTargetIdentity() string { + database := "unconfigured" + if c.LibraryProductionDatabaseURL != "" { + if parsed, err := pgxpool.ParseConfig(c.LibraryProductionDatabaseURL); err == nil { + database = parsed.ConnConfig.Database + } else { + database = "invalid" + } + } + raw, _ := json.Marshal(struct { + Instance string + Project string + Database string + Tenant uint64 + InternalKB string + ExternalKB string + Index string + Provider string + ObjectEndpoint string + Bucket string + }{c.LibraryTargetInstance, c.LibraryTargetProject, database, c.LibraryProductionTenantID, + c.LibraryProductionInternalKB, c.LibraryProductionExternalKB, c.LibraryProductionIndex, + c.LibraryProductionS3Provider, c.LibraryProductionS3Endpoint, c.LibraryProductionS3Bucket}) + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/appconfig/library_target_test.go b/internal/appconfig/library_target_test.go new file mode 100644 index 0000000..4ddfb62 --- /dev/null +++ b/internal/appconfig/library_target_test.go @@ -0,0 +1,48 @@ +package appconfig + +import "testing" + +func identityForTest(c Config) string { + return c.LibraryTargetIdentity() +} + +func TestLibraryTargetIdentityIgnoresTransportButBindsData(t *testing.T) { + a := Config{LibraryTargetInstance: "cloud-test", LibraryTargetProject: "weknora-test", + LibraryProductionDatabaseURL: "postgres://local@127.0.0.1:5433/target_db", LibraryProductionTenantID: 10000, + LibraryProductionInternalKB: "internal-a", LibraryProductionExternalKB: "external-a", + LibraryProductionIndex: "index-a", LibraryProductionS3Bucket: "bucket-a", LibraryProductionS3Provider: "s3", LibraryProductionS3Endpoint: "https://objects.example"} + want := identityForTest(a) + if want == "" { + t.Fatal("live services must never bind the empty legacy namespace") + } + transport := a + transport.LibraryProductionDatabaseURL = "postgres://remote@database:5432/target_db" + transport.LibraryTargetDockerSocket = "/other/docker.sock" + transport.LibraryArchiveRoot = "/other/archive" + if got := identityForTest(transport); got != want { + t.Fatal("SSH routing must not change logical identity") + } + cases := map[string]func(*Config){ + "instance": func(c *Config) { c.LibraryTargetInstance = "other" }, + "project": func(c *Config) { c.LibraryTargetProject = "other" }, + "database": func(c *Config) { c.LibraryProductionDatabaseURL = "postgres://local@127.0.0.1:5433/other_db" }, + "tenant": func(c *Config) { c.LibraryProductionTenantID = 20000 }, + "internal": func(c *Config) { c.LibraryProductionInternalKB = "other" }, + "external": func(c *Config) { c.LibraryProductionExternalKB = "other" }, + "index": func(c *Config) { c.LibraryProductionIndex = "other" }, + "bucket": func(c *Config) { c.LibraryProductionS3Bucket = "other" }, + "object_endpoint": func(c *Config) { c.LibraryProductionS3Endpoint = "https://other.example" }, + } + for name, change := range cases { + t.Run(name, func(t *testing.T) { + c := a + change(&c) + if identityForTest(c) == want { + t.Fatal("changed data target reused old identity") + } + }) + } + if identityForTest(Config{}) == "" { + t.Fatal("unconfigured service must not adopt unbound historical evidence") + } +} diff --git a/internal/backuphost/runner.go b/internal/backuphost/runner.go index afe3a9d..46c71be 100644 --- a/internal/backuphost/runner.go +++ b/internal/backuphost/runner.go @@ -10,6 +10,8 @@ import ( "encoding/json" "errors" "fmt" + "net" + "os" "os/exec" "regexp" "strconv" @@ -127,12 +129,81 @@ func (r *Runner) runRemote(ctx context.Context, timeout time.Duration, remote st if ctx.Err() != nil { return text, fmt.Errorf("ssh %s 超时(%s)", r.config.Target, timeout) } - // 主机侧脚本会用退出码表达"参数非法/有库失败",把输出带回去便于页面展示。 - return text, fmt.Errorf("ssh %s 执行失败: %s", r.config.Target, firstLines(text, 6)) + // 连接层失败与主机侧命令失败必须分开说:前者连脚本都没跑, + // 任何"脚本缺失/计划未下发"都是把未观测当成事实。 + return text, hostFailure(r.config.Target, text) } return text, nil } +// hostFailure 把 ssh 的非零退出分成两类:连不上,和连上了但远端命令失败。 +func hostFailure(target, text string) error { + if connectionFailurePattern.MatchString(text) { + return fmt.Errorf("目标主机 %s 不可达(%s);未执行任何主机侧脚本,脚本与计划状态未知", + target, firstLines(text, 3)) + } + // 主机侧脚本会用退出码表达"参数非法/有库失败",把输出带回去便于页面展示。 + return fmt.Errorf("已连上 %s,但主机侧命令失败: %s", target, firstLines(text, 6)) +} + +// connectionFailurePattern 是 OpenSSH 客户端在"根本没建立连接"时打的原文。 +// 只有命中它才允许说"不可达";其余非零退出属于远端命令自己的失败。 +var connectionFailurePattern = regexp.MustCompile(`(?i)ssh: connect to host|Operation timed out|Connection timed out|Connection refused|Connection reset by peer|No route to host|Network is unreachable|Could not resolve hostname|Host key verification failed|Permission denied|Connection closed by`) + +// Endpoint 读回挂载的 ssh 配置里本别名真实拨号的 host:port。 +// 页面必须能说清"现在连的是哪个地址"——只显示别名时,改错文件也看不出来。 +func (r *Runner) Endpoint() string { + if r == nil || r.config.SSHConfig == "" || r.config.Target == "" { + return "" + } + raw, err := os.ReadFile(r.config.SSHConfig) + if err != nil { + return "" + } + host, port := sshConfigEndpoint(string(raw), r.config.Target) + if host == "" { + return "" + } + if port == "" { + port = "22" + } + return net.JoinHostPort(host, port) +} + +// sshConfigEndpoint 解析 `Host ` 段的 HostName/Port(首个匹配段生效)。 +// 只做"页面显示用"的最小解析,不替代 ssh 自己的配置语义。 +func sshConfigEndpoint(config, alias string) (string, string) { + host, port := "", "" + active := false + for _, line := range strings.Split(config, "\n") { + fields := strings.Fields(strings.TrimSpace(line)) + if len(fields) == 0 || strings.HasPrefix(fields[0], "#") { + continue + } + key := strings.ToLower(fields[0]) + if key == "host" { + active = false + for _, pattern := range fields[1:] { + if pattern == alias { + active = true + break + } + } + continue + } + if !active || len(fields) < 2 { + continue + } + switch key { + case "hostname": + host = strings.Trim(fields[1], `"`) + case "port": + port = strings.Trim(fields[1], `"`) + } + } + return host, port +} + var scheduleAppliedPattern = regexp.MustCompile( `SCHEDULE_APPLIED enabled=(\d)(?: time=(\S+))?(?: days=(\d+))?(?: months=(\d+))?(?: next=(\S+))?(?: cron=(\S+))?`) diff --git a/internal/backuphost/runner_test.go b/internal/backuphost/runner_test.go index 5794158..3e538d9 100644 --- a/internal/backuphost/runner_test.go +++ b/internal/backuphost/runner_test.go @@ -3,6 +3,8 @@ package backuphost import ( "context" "errors" + "os" + "path/filepath" "strings" "testing" "time" @@ -188,6 +190,41 @@ func TestRunnerSurfacesHostFailure(t *testing.T) { } } +// 现场原错:ssh: connect to host 120.76.217.51 port 22: Operation timed out。 +// 连不上时脚本根本没跑,只能说"不可达";断言配对的反面:不能说脚本缺失。 +func TestHostFailureSeparatesUnreachableFromRemoteCommand(t *testing.T) { + unreachable := hostFailure("weknora-test", "ssh: connect to host 120.76.217.51 port 22: Operation timed out") + if !strings.Contains(unreachable.Error(), "不可达") || !strings.Contains(unreachable.Error(), "Operation timed out") { + t.Fatalf("连接超时应报不可达并带原错: %v", unreachable) + } + if strings.Contains(unreachable.Error(), "主机侧命令失败") || strings.Contains(unreachable.Error(), "脚本缺失") { + t.Fatalf("连接失败不能报成远端命令/脚本问题: %v", unreachable) + } + remote := hostFailure("weknora-test", "bash: /opt/weknora-test/logical-backup.sh: No such file or directory") + if !strings.Contains(remote.Error(), "已连上") || !strings.Contains(remote.Error(), "No such file") { + t.Fatalf("已连接但脚本失败时应原样带回原因: %v", remote) + } + if strings.Contains(remote.Error(), "不可达") { + t.Fatalf("已连上就不能说不可达: %v", remote) + } +} + +// 页面要能说清"实际拨号的地址",否则改错 ssh_config 也看不出来。 +func TestRunnerEndpointReadsDialedHostPort(t *testing.T) { + path := filepath.Join(t.TempDir(), "ssh_config") + config := "Host other\n HostName 10.0.0.9\n Port 2222\n\nHost weknora-test\n HostName 100.85.111.121\n HostKeyAlias 120.76.217.51\n" + if err := os.WriteFile(path, []byte(config), 0o600); err != nil { + t.Fatal(err) + } + runner := New(Config{SSHConfig: path, Target: "weknora-test", ScriptDir: "/opt/weknora-test"}) + if got := runner.Endpoint(); got != "100.85.111.121:22" { + t.Fatalf("应报真实拨号地址(默认 22),得到 %q", got) + } + if got := New(Config{SSHConfig: filepath.Join(t.TempDir(), "missing"), Target: "weknora-test"}).Endpoint(); got != "" { + t.Fatalf("配置文件不可读时应返回空,不猜地址,得到 %q", got) + } +} + func TestRunnerRunNowReadsBackLastRun(t *testing.T) { calls := 0 runner := testRunner(func(_ context.Context, _ time.Duration, remote string) (string, error) { diff --git a/internal/dingtalkdiscovery/credentials.go b/internal/dingtalkdiscovery/credentials.go index c3ea3c4..3e9acaa 100644 --- a/internal/dingtalkdiscovery/credentials.go +++ b/internal/dingtalkdiscovery/credentials.go @@ -2,16 +2,22 @@ package dingtalkdiscovery import ( "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" ) // CredentialStatus contains metadata only, never credential values. type CredentialStatus struct { + Identity string `json:"identity,omitempty"` Authenticated bool `json:"authenticated"` RefreshTokenValid bool `json:"refresh_token_valid"` ExpiresAt string `json:"expires_at,omitempty"` RefreshExpiresAt string `json:"refresh_expires_at,omitempty"` + CorpName string `json:"corp_name,omitempty"` + UserName string `json:"user_name,omitempty"` + StatusKnown bool `json:"status_known"` } func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, error) { @@ -20,13 +26,23 @@ func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, return CredentialStatus{}, errors.New("could not read DWS credential status") } var decoded struct { - Authenticated *bool `json:"authenticated"` - RefreshTokenValid bool `json:"refresh_token_valid"` - ExpiresAt string `json:"expires_at"` - RefreshExpiresAt string `json:"refresh_expires_at"` + CorpID json.RawMessage `json:"corp_id"` + UserID json.RawMessage `json:"user_id"` + Authenticated *bool `json:"authenticated"` + RefreshTokenValid bool `json:"refresh_token_valid"` + ExpiresAt string `json:"expires_at"` + RefreshExpiresAt string `json:"refresh_expires_at"` + CorpName string `json:"corp_name"` + UserName string `json:"user_name"` + Reason string `json:"reason"` } if json.Unmarshal(raw, &decoded) != nil || decoded.Authenticated == nil { return CredentialStatus{}, errors.New("invalid DWS credential status") } - return CredentialStatus{*decoded.Authenticated, decoded.RefreshTokenValid, decoded.ExpiresAt, decoded.RefreshExpiresAt}, nil + identity := "" + if len(decoded.CorpID) > 0 && len(decoded.UserID) > 0 && string(decoded.CorpID) != "null" && string(decoded.UserID) != "null" { + sum := sha256.Sum256(append(append(decoded.CorpID, 0), decoded.UserID...)) + identity = hex.EncodeToString(sum[:]) + } + return CredentialStatus{Identity: identity, Authenticated: *decoded.Authenticated, RefreshTokenValid: decoded.RefreshTokenValid, ExpiresAt: decoded.ExpiresAt, RefreshExpiresAt: decoded.RefreshExpiresAt, CorpName: decoded.CorpName, UserName: decoded.UserName, StatusKnown: decoded.Reason == ""}, nil } diff --git a/internal/dingtalkdiscovery/device_login.go b/internal/dingtalkdiscovery/device_login.go new file mode 100644 index 0000000..11a3a05 --- /dev/null +++ b/internal/dingtalkdiscovery/device_login.go @@ -0,0 +1,243 @@ +package dingtalkdiscovery + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "io" + "net/url" + "regexp" + "strconv" + "strings" + "sync" + "time" +) + +var ErrLoginBusy = errors.New("another DWS authorization is active") +var ErrLoginNotFound = errors.New("DWS authorization not found") + +// DeviceLoginView contains only the user-facing challenge. Tokens remain in the +// CLI's shared credential store; command output is never logged or returned. +type DeviceLoginView struct { + ID string `json:"id"` + State string `json:"state"` + VerificationURL string `json:"verification_url,omitempty"` + UserCode string `json:"user_code,omitempty"` + ExpiresAt time.Time `json:"expires_at"` + Error string `json:"error,omitempty"` +} + +type deviceLogin struct { + view DeviceLoginView + owner string + cancel context.CancelFunc + done chan struct{} +} + +type DeviceLoginManager struct { + ctx context.Context + runner ExecRunner + mu sync.Mutex + sessions map[string]*deviceLogin +} + +func NewDeviceLoginManager(ctx context.Context, runner ExecRunner) *DeviceLoginManager { + return &DeviceLoginManager{ctx: ctx, runner: runner, sessions: make(map[string]*deviceLogin)} +} + +func loginActive(state string) bool { + return state == "starting" || state == "waiting" || state == "verifying" +} + +func (m *DeviceLoginManager) Start(owner string) (DeviceLoginView, error) { + if owner == "" { + return DeviceLoginView{}, ErrLoginNotFound + } + m.mu.Lock() + defer m.mu.Unlock() + for id, s := range m.sessions { + if s.view.State == "cancelled" || s.view.State == "expired" { + select { + case <-s.done: + default: + return DeviceLoginView{}, ErrLoginBusy + } + } + if loginActive(s.view.State) { + if s.owner == owner { + return s.view, nil + } + return DeviceLoginView{}, ErrLoginBusy + } + if time.Since(s.view.ExpiresAt) > 30*time.Minute || len(m.sessions) >= 16 { + delete(m.sessions, id) + } + } + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return DeviceLoginView{}, err + } + ctx, cancel := context.WithTimeout(m.ctx, 20*time.Minute) + s := &deviceLogin{view: DeviceLoginView{ID: hex.EncodeToString(b[:]), State: "starting", ExpiresAt: time.Now().UTC().Add(20 * time.Minute)}, owner: owner, cancel: cancel, done: make(chan struct{})} + m.sessions[s.view.ID] = s + go m.run(ctx, s) + return s.view, nil +} + +func (m *DeviceLoginManager) Get(owner, id string) (DeviceLoginView, error) { + m.mu.Lock() + defer m.mu.Unlock() + s := m.sessions[id] + if s == nil || s.owner != owner { + return DeviceLoginView{}, ErrLoginNotFound + } + if loginActive(s.view.State) && !time.Now().Before(s.view.ExpiresAt) { + s.cancel() + finishLogin(s, "expired", "授权已过期,请重新发起。") + } + return s.view, nil +} + +func (m *DeviceLoginManager) Cancel(owner, id string) (DeviceLoginView, error) { + m.mu.Lock() + s := m.sessions[id] + if s == nil || s.owner != owner { + m.mu.Unlock() + return DeviceLoginView{}, ErrLoginNotFound + } + if loginActive(s.view.State) { + s.cancel() + finishLogin(s, "cancelled", "") + } + m.mu.Unlock() + // Do not acknowledge cancellation while the old CLI could still write tokens. + timer := time.NewTimer(7 * time.Second) + defer timer.Stop() + select { + case <-s.done: + case <-timer.C: + return DeviceLoginView{}, ErrLoginBusy + } + m.mu.Lock() + defer m.mu.Unlock() + return s.view, nil +} + +func finishLogin(s *deviceLogin, state, message string) { + s.view.State = state + s.view.Error = message + s.view.VerificationURL = "" + s.view.UserCode = "" +} + +var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;]*[A-Za-z]`) +var challengeCode = regexp.MustCompile(`(?:授权码|User code|User Code)\s*[::]\s*([A-Za-z0-9-]{4,32})`) +var challengeExpiry = regexp.MustCompile(`(?:将在\s*|expires in\s*)([0-9]+)\s*(?:秒|seconds)`) + +func safeDeviceURL(raw string) bool { + u, err := url.Parse(raw) + return err == nil && u.Scheme == "https" && u.Host == "login.dingtalk.com" && u.User == nil && u.Fragment == "" && u.Path == "/oauth2/device/verify.htm" +} + +func (m *DeviceLoginManager) observe(s *deviceLogin, line string) { + line = strings.TrimSpace(ansiEscape.ReplaceAllString(line, "")) + m.mu.Lock() + defer m.mu.Unlock() + if !loginActive(s.view.State) { + return + } + if match := challengeCode.FindStringSubmatch(line); len(match) == 2 { + s.view.UserCode = match[1] + } + if match := challengeExpiry.FindStringSubmatch(line); len(match) == 2 { + seconds, _ := strconv.Atoi(match[1]) + if seconds > 0 && seconds <= 1800 { + s.view.ExpiresAt = time.Now().UTC().Add(time.Duration(seconds) * time.Second) + } + } + if safeDeviceURL(line) { + u, _ := url.Parse(line) + if s.view.VerificationURL == "" || u.Query().Get("user_code") != "" { + s.view.VerificationURL = line + } + } + if s.view.State == "starting" && s.view.UserCode != "" && s.view.VerificationURL != "" { + s.view.State = "waiting" + } + if strings.Contains(line, "Step 3:") { + s.view.State = "verifying" + } +} + +func (m *DeviceLoginManager) run(ctx context.Context, s *deviceLogin) { + defer close(s.done) + defer s.cancel() + command, err := m.runner.command(ctx, "auth", "login", "--device", "--no-browser", "--format", "json") + if err != nil { + m.failed(s, "DWS 登录程序不可用,请联系管理员检查服务配置。") + return + } + command.Env = append(command.Env, "DWS_LANG=zh", "NO_COLOR=1", "TERM=dumb") + command.Stdout = io.Discard + stderr, err := command.StderrPipe() + if err != nil { + m.failed(s, "无法启动 DWS 授权,请重试。") + return + } + if err = command.Start(); err != nil { + m.failed(s, "无法启动 DWS 授权,请检查凭据目录权限。") + return + } + scanner := bufio.NewScanner(stderr) + scanner.Buffer(make([]byte, 4096), 64*1024) + for scanner.Scan() { + m.observe(s, scanner.Text()) + } + if scanner.Err() != nil { + s.cancel() + } + err = command.Wait() + m.mu.Lock() + active := loginActive(s.view.State) + m.mu.Unlock() + if !active { + return + } + if err != nil || ctx.Err() != nil { + m.mu.Lock() + defer m.mu.Unlock() + if !loginActive(s.view.State) { + return + } + if errors.Is(ctx.Err(), context.DeadlineExceeded) || !time.Now().Before(s.view.ExpiresAt) { + finishLogin(s, "expired", "授权已过期,请重新发起。") + } else { + finishLogin(s, "failed", "DWS 授权未完成,请重试;若组织未开通 CLI 数据权限,请联系钉钉管理员。") + } + return + } + // A process exit alone is not proof that usable credentials were persisted. + checkCtx, cancel := context.WithTimeout(m.ctx, 5*time.Second) + defer cancel() + status, statusErr := ReadCredentialStatus(checkCtx, m.runner) + m.mu.Lock() + defer m.mu.Unlock() + if !loginActive(s.view.State) { + return + } + if statusErr != nil || !status.Authenticated || !status.RefreshTokenValid || !status.StatusKnown { + finishLogin(s, "failed", "授权结束,但未读到有效 DWS 凭据,请重新授权。") + } else { + finishLogin(s, "succeeded", "") + } +} + +func (m *DeviceLoginManager) failed(s *deviceLogin, message string) { + m.mu.Lock() + defer m.mu.Unlock() + if loginActive(s.view.State) { + finishLogin(s, "failed", message) + } +} diff --git a/internal/dingtalkdiscovery/device_login_test.go b/internal/dingtalkdiscovery/device_login_test.go new file mode 100644 index 0000000..eaea06e --- /dev/null +++ b/internal/dingtalkdiscovery/device_login_test.go @@ -0,0 +1,160 @@ +package dingtalkdiscovery + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func deviceFixture(t *testing.T) (*DeviceLoginManager, string) { + t.Helper() + root := t.TempDir() + binary := filepath.Join(root, "dws") + script := `#!/usr/bin/env python3 +import sys,time,pathlib,json,os +root=pathlib.Path(` + strconv.Quote(root) + `) +a=sys.argv[1:] +if a==['auth','login','--device','--no-browser','--format','json']: + (root/'pid').write_text(str(os.getpid())) + print(' 授权码: TEST-CODE',file=sys.stderr,flush=True) + print('授权码将在 900 秒后过期。',file=sys.stderr,flush=True) + print('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE',file=sys.stderr,flush=True) + print('https://login.dingtalk.com/oauth2/device/verify.htm',file=sys.stderr,flush=True) + print('never-expose-this-marker',file=sys.stderr,flush=True) + while not (root/'finish').exists(): time.sleep(.01) + if (root/'fail').exists(): sys.exit(1) +elif a==['auth','status','--readonly','--format','json']: + print(json.dumps({'authenticated':not (root/'invalid').exists(),'refresh_token_valid':True,'corp_name':'测试组织','user_name':'测试账号','access_token':'never-expose-this-marker'})) +else: sys.exit(9) +` + if err := os.WriteFile(binary, []byte(script), 0700); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + return NewDeviceLoginManager(ctx, ExecRunner{Binary: binary}), root +} +func awaitDevice(t *testing.T, m *DeviceLoginManager, id, state string) DeviceLoginView { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + v, e := m.Get("owner", id) + if e != nil { + t.Fatal(e) + } + if v.State == state { + return v + } + time.Sleep(10 * time.Millisecond) + } + v, _ := m.Get("owner", id) + t.Fatalf("state=%s want=%s error=%s", v.State, state, v.Error) + return v +} +func TestDeviceLoginUsesOfficialChallengeAndSharedCLI(t *testing.T) { + m, root := deviceFixture(t) + initial, err := m.Start("owner") + if err != nil { + t.Fatal(err) + } + if initial.State != "starting" { + t.Fatal(initial) + } + waiting := awaitDevice(t, m, initial.ID, "waiting") + if waiting.UserCode != "TEST-CODE" || !strings.Contains(waiting.VerificationURL, "user_code=TEST-CODE") { + t.Fatal("missing complete official challenge") + } + if _, err = m.Start("other"); !errors.Is(err, ErrLoginBusy) { + t.Fatal("parallel logins may overwrite shared credentials") + } + duplicate, _ := m.Start("owner") + if duplicate.ID != initial.ID { + t.Fatal("duplicate start was not idempotent") + } + if _, err = m.Get("other", initial.ID); !errors.Is(err, ErrLoginNotFound) { + t.Fatal("challenge leaked to another owner") + } + if _, err = m.Cancel("other", initial.ID); !errors.Is(err, ErrLoginNotFound) { + t.Fatal("foreign cancellation permitted") + } + if err = os.WriteFile(filepath.Join(root, "finish"), nil, 0600); err != nil { + t.Fatal(err) + } + done := awaitDevice(t, m, initial.ID, "succeeded") + raw, _ := json.Marshal(done) + if done.UserCode != "" || done.VerificationURL != "" || strings.Contains(string(raw), "never-expose") { + t.Fatal("completed session retained sensitive output") + } +} +func TestDeviceLoginCancellationClearsChallenge(t *testing.T) { + m, root := deviceFixture(t) + v, _ := m.Start("owner") + awaitDevice(t, m, v.ID, "waiting") + closed, err := m.Cancel("owner", v.ID) + if err != nil || closed.State != "cancelled" || closed.UserCode != "" || closed.VerificationURL != "" { + t.Fatal(closed, err) + } + pidBytes, err := os.ReadFile(filepath.Join(root, "pid")) + if err != nil { + t.Fatal(err) + } + pid, _ := strconv.Atoi(string(pidBytes)) + if syscall.Kill(pid, 0) == nil { + t.Fatal("cancel returned while credential-writing process was still running") + } + again, _ := m.Get("owner", v.ID) + if again.State != "cancelled" { + t.Fatal("late process exit overwrote cancellation") + } +} +func TestDeviceLoginRejectsExitWithoutPersistedCredentials(t *testing.T) { + m, root := deviceFixture(t) + os.WriteFile(filepath.Join(root, "invalid"), nil, 0600) + os.WriteFile(filepath.Join(root, "finish"), nil, 0600) + v, _ := m.Start("owner") + done := awaitDevice(t, m, v.ID, "failed") + if !strings.Contains(done.Error, "未读到有效") { + t.Fatal("successful exit was treated as authenticated") + } +} +func TestDeviceLoginFailureIsRedactedAndRetryable(t *testing.T) { + m, root := deviceFixture(t) + os.WriteFile(filepath.Join(root, "fail"), nil, 0600) + os.WriteFile(filepath.Join(root, "finish"), nil, 0600) + v, _ := m.Start("owner") + done := awaitDevice(t, m, v.ID, "failed") + if strings.Contains(done.Error, "never-expose") || done.Error == "" { + t.Fatal("raw CLI output or missing error") + } + retry, e := m.Start("owner") + if e != nil || retry.ID == v.ID { + t.Fatal("cannot retry failed authorization") + } +} +func TestDeviceChallengeRejectsUntrustedLinksAndExpires(t *testing.T) { + m, root := deviceFixture(t) + _ = root + s := &deviceLogin{view: DeviceLoginView{State: "starting", ExpiresAt: time.Now().Add(time.Minute)}, cancel: func() {}} + m.observe(s, "授权码: TEST-CODE") + for _, link := range []string{"http://login.dingtalk.com/oauth2/device/verify.htm", "https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm", "https://user:pass@login.dingtalk.com/oauth2/device/verify.htm", "javascript:alert(1)", "https://login.dingtalk.com/other"} { + m.observe(s, link) + } + if s.view.State != "starting" || s.view.VerificationURL != "" { + t.Fatal("untrusted link accepted") + } + s.view.ID = "test-expired" + s.owner = "owner" + s.view.ExpiresAt = time.Now().Add(-time.Second) + m.sessions[s.view.ID] = s + got, e := m.Get("owner", s.view.ID) + if e != nil || got.State != "expired" || got.UserCode != "" { + t.Fatal("expired challenge retained") + } +} diff --git a/internal/dingtalkdiscovery/discovery.go b/internal/dingtalkdiscovery/discovery.go index 9bf4d7d..7394068 100644 --- a/internal/dingtalkdiscovery/discovery.go +++ b/internal/dingtalkdiscovery/discovery.go @@ -21,6 +21,7 @@ import ( // KnowledgeBase 是一个钉钉知识库(wiki 空间)。URL 是 alidocs 空间链接,直接可用于登记来源。 type KnowledgeBase struct { + Registered bool `json:"registered"` Name string `json:"name"` SpaceID string `json:"space_id"` SpaceType string `json:"space_type"` @@ -30,6 +31,7 @@ type KnowledgeBase struct { // DriveSpace 是一个钉盘空间(我的文件 = mySpace;组织空间 = orgSpace)。 type DriveSpace struct { + Registered bool `json:"registered"` Name string `json:"name"` SpaceID string `json:"space_id"` RootFolderID string `json:"root_folder_id,omitempty"` @@ -38,6 +40,7 @@ type DriveSpace struct { // Result 是一次发现的结果。 type Result struct { + Identity string `json:"identity,omitempty"` KnowledgeBases []KnowledgeBase `json:"knowledge_bases"` DriveSpaces []DriveSpace `json:"drive_spaces"` // KnowledgeNotice / DriveNotice 说明「这一类为什么不全」:权限不足、未登录、或被上限截断。 @@ -70,21 +73,26 @@ func SpaceListArgs(spaceType string) []string { // 知识库整体列不出来 → 返回 ErrUnavailable(页面必须提示「列不出来」,不能装成空列表)。 // 单独一类失败、钉盘失败、或结果被上限截断 → 只丢那一部分,把原因写进对应的 Notice。 func Discover(ctx context.Context, runner Runner) (Result, error) { - result := Result{FetchedAt: time.Now().UTC()} + result := Result{FetchedAt: time.Now().UTC(), KnowledgeBases: []KnowledgeBase{}, DriveSpaces: []DriveSpace{}} + successful := 0 + causes := []error{} failures := make([]string, 0, len(knowledgeSpaceTypes)) seenKnowledge := map[string]bool{} for _, spaceType := range knowledgeSpaceTypes { raw, err := runner.RunDWS(ctx, SpaceListArgs(spaceType)...) if err != nil { - failures = append(failures, describe(spaceType, err)) + failures = append(failures, describe(spaceType, failureCause(raw, err))) + causes = append(causes, failureCause(raw, err)) continue } bases, notice, err := parseKnowledgeBases(raw, spaceType) if err != nil { - failures = append(failures, describe(spaceType, err)) + failures = append(failures, describe(spaceType, failureCause(raw, err))) + causes = append(causes, failureCause(raw, err)) continue } + successful++ if notice != "" { result.KnowledgeNotice = notice } @@ -96,9 +104,6 @@ func Discover(ctx context.Context, runner Runner) (Result, error) { result.KnowledgeBases = append(result.KnowledgeBases, base) } } - if len(result.KnowledgeBases) == 0 && len(failures) > 0 { - return result, fmt.Errorf("%w: %s", ErrUnavailable, strings.Join(failures, ";")) - } if len(failures) > 0 { result.KnowledgeNotice = strings.Join(append([]string{result.KnowledgeNotice}, failures...), ";") } @@ -107,14 +112,17 @@ func Discover(ctx context.Context, runner Runner) (Result, error) { for _, spaceType := range []string{"mySpace", "orgSpace"} { raw, err := runner.RunDWS(ctx, "wiki", "space", "list", "--type", spaceType) if err != nil { - result.DriveNotice = err.Error() + result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限" + causes = append(causes, failureCause(raw, err)) continue } spaces, err := parseDriveSpaces(raw, spaceType) if err != nil { - result.DriveNotice = err.Error() + result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限" + causes = append(causes, failureCause(raw, err)) continue } + successful++ for _, space := range spaces { if seenDrive[space.SpaceType+":"+space.SpaceID] { continue @@ -123,11 +131,21 @@ func Discover(ctx context.Context, runner Runner) (Result, error) { result.DriveSpaces = append(result.DriveSpaces, space) } } + if successful == 0 && len(causes) > 0 { + return result, fmt.Errorf("%w: %w", ErrUnavailable, errors.Join(causes...)) + } return result, nil } func describe(scope string, err error) string { - return scope + ":" + err.Error() + reason := "读取失败,请重试" + if errors.Is(err, ErrCredentials) { + reason = "DWS 授权已失效" + } + if errors.Is(err, ErrPermission) { + reason = "当前范围权限不足" + } + return scope + ":" + reason } // parseKnowledgeBases 解析 `dws wiki +space-list`: diff --git a/internal/dingtalkdiscovery/discovery_test.go b/internal/dingtalkdiscovery/discovery_test.go index 35f326c..8163b55 100644 --- a/internal/dingtalkdiscovery/discovery_test.go +++ b/internal/dingtalkdiscovery/discovery_test.go @@ -127,7 +127,7 @@ func TestDiscoverKeepsKnowledgeBasesWhenDriveIsDenied(t *testing.T) { if len(result.DriveSpaces) != 0 { t.Fatalf("drive spaces = %d, want 0", len(result.DriveSpaces)) } - if !strings.Contains(result.DriveNotice, "permission denied") { + if !strings.Contains(result.DriveNotice, "权限") { t.Fatalf("drive notice = %q", result.DriveNotice) } } diff --git a/internal/dingtalkdiscovery/exec_runner.go b/internal/dingtalkdiscovery/exec_runner.go index 7f75f88..7bc7324 100644 --- a/internal/dingtalkdiscovery/exec_runner.go +++ b/internal/dingtalkdiscovery/exec_runner.go @@ -19,8 +19,8 @@ type ExecRunner struct { Timeout time.Duration } -// RunDWS 运行 `dws ` 并返回 stdout。 -func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) { +// command keeps device login and source reads on one credential environment. +func (r ExecRunner) command(ctx context.Context, args ...string) (*exec.Cmd, error) { binary := r.Binary if binary == "" { binary = os.Getenv("DWS_BIN") @@ -32,14 +32,24 @@ func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) } binary = found } + command := exec.CommandContext(ctx, binary, args...) + command.Env = dwsEnv() + command.WaitDelay = 2 * time.Second + return command, nil +} + +// RunDWS uses the same executable and credential environment as device login. +func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) { timeout := r.Timeout if timeout <= 0 { timeout = 25 * time.Second } runCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() - command := exec.CommandContext(runCtx, binary, args...) - command.Env = dwsEnv() + command, err := r.command(runCtx, args...) + if err != nil { + return nil, err + } var stdout, stderr bytes.Buffer command.Stdout = &stdout command.Stderr = &stderr diff --git a/internal/dingtalkdiscovery/failure.go b/internal/dingtalkdiscovery/failure.go new file mode 100644 index 0000000..953f11d --- /dev/null +++ b/internal/dingtalkdiscovery/failure.go @@ -0,0 +1,40 @@ +package dingtalkdiscovery + +import ( + "encoding/json" + "errors" + "fmt" + "strings" +) + +var ErrCredentials = errors.New("DWS authorization required") +var ErrPermission = errors.New("DWS directory permission denied") + +// failureCause inspects only structured CLI errors; no upstream text is returned. +func failureCause(raw []byte, cause error) error { + var v struct { + Error struct { + Type string `json:"type"` + Code any `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if json.Unmarshal(raw, &v) != nil { + return ErrUnavailable + } + text := strings.ToLower(v.Error.Type + " " + fmt.Sprint(v.Error.Code) + " " + v.Error.Message) + for _, key := range []string{"permission", "forbidden", "scope", "access denied", "权限", "403"} { + if strings.Contains(text, key) { + return ErrPermission + } + } + for _, key := range []string{"unauth", "not_logged_in", "not logged", "login_required", "login required", "authentication", "auth_required", "credential", "token_expired", "invalid_token", "token expired", "invalid_grant", "未登录", "授权已过期", "授权失效"} { + if strings.Contains(text, key) { + return ErrCredentials + } + } + if errors.Is(cause, ErrCredentials) || errors.Is(cause, ErrPermission) { + return cause + } + return ErrUnavailable +} diff --git a/internal/governance/development_notes.go b/internal/governance/development_notes.go index 9431f0f..7047296 100644 --- a/internal/governance/development_notes.go +++ b/internal/governance/development_notes.go @@ -16,9 +16,8 @@ func developmentNotes(changelog, version, sha string) string { return "" } lines := strings.Split(changelog, "\n") - prefix := "## 开发快照 snapshot/v" + version + " - " for i, line := range lines { - if strings.HasPrefix(line, prefix) { + if developmentHeadingMatches(line, version) { end := len(lines) for j := i + 1; j < len(lines); j++ { if strings.HasPrefix(lines[j], "## ") { @@ -39,3 +38,33 @@ func developmentNotes(changelog, version, sha string) string { } return "" } + +// developmentHeadingMatches 接受两种真实标题: +// - 旧格式:## 开发快照 snapshot/v0.1.1 - 2026-10-18 +// - 开发快照:## 开发快照 0.1.351(索引预检使用目标映射 ID) +// +// 版本号后必须是字符串结束或分隔符,避免 0.1.35 命中 0.1.351; +// 只读取到下一个二级标题,不跨版本吞正文。 +func developmentHeadingMatches(line, version string) bool { + prefixes := []string{ + "## 开发快照 snapshot/v" + version, + "## 开发快照 " + version, + } + for _, prefix := range prefixes { + if !strings.HasPrefix(line, prefix) { + continue + } + rest := line[len(prefix):] + if rest == "" { + return true + } + if strings.HasPrefix(rest, "—") || strings.HasPrefix(rest, "(") { + return true + } + switch rest[0] { + case ' ', '\t', '-', '(': + return true + } + } + return false +} diff --git a/internal/governance/library_dispatch.go b/internal/governance/library_dispatch.go new file mode 100644 index 0000000..034be0b --- /dev/null +++ b/internal/governance/library_dispatch.go @@ -0,0 +1,16 @@ +package governance + +import "encoding/json" + +func LibraryQueueRequest(handoff bool, jobID, scope, snapshotID, releaseType string) (string, string, []byte, error) { + payload := map[string]string{"library_job_id": jobID, "scope": scope, "target_snapshot_id": snapshotID} + queueID := QueueJobIDFor(jobID) + queueType := releaseType + if handoff { + payload["next_type"] = releaseType + queueID = LibraryHandoffQueueJobID(jobID) + queueType = "library.snapshot.handoff" + } + raw, err := json.Marshal(payload) + return queueID, queueType, raw, err +} diff --git a/internal/governance/library_flow.go b/internal/governance/library_flow.go index 7e6b440..3773f6f 100644 --- a/internal/governance/library_flow.go +++ b/internal/governance/library_flow.go @@ -22,6 +22,10 @@ const ( LibraryVersionProductionEffective LibraryVersionKind = "production_effective" // LibraryVersionProductionPrebackup 是每次生产写入前的独立预备份。 LibraryVersionProductionPrebackup LibraryVersionKind = "production_prebackup" + // LibraryVersionRecoveryVerified 是"按预备份恢复并逐类校验通过"的恢复事实: + // 它让 current 指向恢复出来的内容身份,而不是继续宣称已经失败的新版本生效(F06)。 + // 它不是测试封存,也不代表生产发布授权。 + LibraryVersionRecoveryVerified LibraryVersionKind = "recovery_verified" ) type LibraryJobKind string @@ -31,10 +35,19 @@ const ( LibraryJobSync LibraryJobKind = "sync" // LibraryJobRestore 是按指定整库版本恢复:与同步分开,授权与阶段也独立。 LibraryJobRestore LibraryJobKind = "restore" + // LibraryJobRecover 是"按预备份恢复这个失败窗口"这一次**新意图**。 + // 它必须是一条独立意图:恢复要把 current 指回更早发布的快照,而 current 的次序按 + // 意图的创建时间排序(见 CurrentOrderKey),拿旧失败作业的身份去写就会被判成"迟到的 + // 旧意图"而拒绝——那正是 F06 不能解决的形状。 + LibraryJobRecover LibraryJobKind = "recover" // LibraryJobBaseline 建立首次发布目标的权威基线:在维护隔离下把目标整库 // 读出来封存成快照并逐类校验,再登记成 production_effective。 // 它不写目标内容、不清空目标、不猜版本——基线只能来自真实捕获与校验。 LibraryJobBaseline LibraryJobKind = "baseline" + // LibraryJobVerify 是"恢复验证":在维护窗口内捕获目标 → 校验基线一致 → + // 写一个 canary 证明校验能发现差异 → 按预备份恢复 → 复核完全一致。 + // 它是唯一能产生"生产可恢复"证据的作业,页面不再接受手填开关。 + LibraryJobVerify LibraryJobKind = "verify" ) type LibraryJobState string @@ -67,25 +80,30 @@ type LibraryStage struct { } type LibraryJob struct { - ID string `json:"id"` - Scope string `json:"scope"` - Kind LibraryJobKind `json:"kind"` - State LibraryJobState `json:"state"` - Stage string `json:"stage"` - IdempotencyKey string `json:"-"` - RequestDigest string `json:"request_digest"` - QueueJobID string `json:"queue_job_id"` - SnapshotID string `json:"snapshot_id"` - TargetSnapshotID string `json:"target_snapshot_id"` - Actor string `json:"actor"` - Error string `json:"error"` - Recovery string `json:"recovery"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - FinishedAt *time.Time `json:"finished_at"` - Stages []LibraryStage `json:"stages"` + ID string `json:"id"` + Scope string `json:"scope"` + Kind LibraryJobKind `json:"kind"` + State LibraryJobState `json:"state"` + Stage string `json:"stage"` + IdempotencyKey string `json:"-"` + // OperationID 让"同一个意图的多次执行"有稳定谱系;AttemptEpoch 是本次执行代次。 + OperationID string `json:"operation_id"` + AttemptEpoch int `json:"attempt_epoch"` + RequestDigest string `json:"request_digest"` + QueueJobID string `json:"queue_job_id"` + SnapshotID string `json:"snapshot_id"` + TargetSnapshotID string `json:"target_snapshot_id"` + Actor string `json:"actor"` + Error string `json:"error"` + Recovery string `json:"recovery"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + FinishedAt *time.Time `json:"finished_at"` + Stages []LibraryStage `json:"stages"` } +// LibraryVersion 是一条**不可变版本事件**。同一 operation 重放幂等(同 id 不重写), +// 不同 operation 引用同一快照是不同事件,谁也不覆盖谁的证据与作业归属。 type LibraryVersion struct { ID string `json:"id"` Scope string `json:"scope"` @@ -93,10 +111,16 @@ type LibraryVersion struct { SnapshotID string `json:"snapshot_id"` VersionLabel string `json:"version_label"` SourceJobID string `json:"source_job_id"` - Evidence map[string]any `json:"evidence"` - CreatedBy string `json:"created_by"` - CreatedAt time.Time `json:"created_at"` - SupersededAt *time.Time `json:"superseded_at"` + // OperationID/AttemptEpoch 是这条事件的执行身份:登记时用它做 epoch 守卫, + // 保证失租的旧代次不能写事件,也不能推进 current。 + OperationID string `json:"operation_id"` + AttemptEpoch int `json:"attempt_epoch"` + // AttemptOwner 只用于 epoch 守卫(不落库、不展示):写入时必须与作业行租约一致。 + AttemptOwner string `json:"-"` + Evidence map[string]any `json:"evidence"` + CreatedBy string `json:"created_by"` + CreatedAt time.Time `json:"created_at"` + SupersededAt *time.Time `json:"superseded_at"` } // LibraryRequestDigest 绑定一次请求的确切含义:同键不同体必须被拒绝,而不是 @@ -116,6 +140,15 @@ func QueueJobIDFor(libraryJobID string) string { return "q" + hex.EncodeToString(sum[:])[:32] } +// LibraryHandoffQueueJobID 是"先搬运"这一步的队列作业号。 +// +// 为什么单独一个函数:API(投递)与 capture worker(认所有权/幂等重放)必须算出同一个 +// 值,否则重放会被判成"另一个执行者"。jobs.id 是 varchar(36),所以对带后缀的键再哈希, +// 而不是直接在 33 字符 ID 后面拼字符串。 +func LibraryHandoffQueueJobID(libraryJobID string) string { + return QueueJobIDFor(libraryJobID + ":handoff") +} + func LibraryRequestDigest(scope string, kind LibraryJobKind, payload map[string]any) (string, error) { canonical := map[string]any{"scope": scope, "kind": string(kind), "payload": payload} raw, err := json.Marshal(canonical) @@ -144,6 +177,12 @@ func BaselineStages() []string { return []string{"capture", "verify", "finalize"} } +// VerifyStages 是恢复验证的阶段:捕获 → 基线校验 → 写 canary(证明校验有效) +// → 按预备份恢复 → 恢复后复核。canary 与 restore 都是真实写入,失败必须可见。 +func VerifyStages() []string { + return []string{"capture", "verify", "canary", "restore", "finalize"} +} + // LibraryReleaseAuthorization 是生产发布授权:绑定目标、快照、参数摘要与有效期。 type LibraryReleaseAuthorization struct { ID string `json:"id"` diff --git a/internal/governance/library_operation.go b/internal/governance/library_operation.go new file mode 100644 index 0000000..f258db1 --- /dev/null +++ b/internal/governance/library_operation.go @@ -0,0 +1,155 @@ +package governance + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" +) + +// 发布执行身份:operation / attempt 与版本事件、current 指针的唯一约定。 +// +// 为什么必须把这几件事分开: +// - operation 是**用户的一次明确意图**(发布到这个快照 / 恢复到这个快照)。它不该被 +// "这个快照已经成功过"吞掉——用户再次要求同一个目标状态是一次新意图,必须真的执行并 +// 留下自己的记录(F01)。 +// - attempt 是这次意图的**执行代次**(epoch)。崩溃、接管只新增代次,不新造意图, +// 否则维护窗口、预备份、写集合的谱系就断了(F15)。旧代次一旦失租就不能再写(F13)。 +// - 版本事件是**不可变事实**,同一快照被两个 operation 引用是两条事件,谁也不能覆盖谁 +// (F02/F09)。current 只是一个"现在生效的是哪条事件"的指针,用单调次序做条件更新, +// 不反过来修改历史。 + +// ErrLibraryEpochStale:这次写入来自已经失租/被接管的执行代次。 +// 调用方必须停止副作用并把控制权交给当前代次,不能用"重试"掩盖。 +var ErrLibraryEpochStale = errors.New("library attempt epoch is stale: another attempt owns this operation") + +// ErrLibraryCurrentStale:这条事件不是当前该生效的事实(有更晚的真相已登记)。 +var ErrLibraryCurrentStale = errors.New("library current pointer already advanced past this event") + +// ErrLibraryOperationConflict:同一 operation 键被用在了不同的请求内容上。 +var ErrLibraryOperationConflict = errors.New("library operation key reused with a different request") + +// LibraryAttemptState 是一次执行代次的状态。 +type LibraryAttemptState string + +const ( + // LibraryAttemptClaimed:已被某个 worker 认领,尚未进入维护窗口。 + LibraryAttemptClaimed LibraryAttemptState = "claimed" + // LibraryAttemptRunning:正在执行(持有目标执行域)。 + LibraryAttemptRunning LibraryAttemptState = "running" + LibraryAttemptCompleted LibraryAttemptState = "completed" + LibraryAttemptFailed LibraryAttemptState = "failed" + LibraryAttemptAbandoned LibraryAttemptState = "abandoned" +) + +// LibraryOperation 是一次明确意图。字段一旦写入就不再改变(锚点另见 LibraryAnchors)。 +type LibraryOperation struct { + ID string `json:"id"` + Scope string `json:"scope"` + Kind LibraryJobKind `json:"kind"` + TargetSnapshotID string `json:"target_snapshot_id"` + RequestDigest string `json:"request_digest"` + OperationKey string `json:"operation_key"` + Actor string `json:"actor"` + CreatedAt time.Time `json:"created_at"` +} + +// LibraryAnchors 是 operation 的**不可变首次锚点**:预备份身份/字节、写集合摘要、 +// 目标指纹。所有 attempt 继承它;接管不许"再拍一份",也不许用新值覆盖它(F07/F09)。 +type LibraryAnchors struct { + FirstBackupSnapshotID string `json:"first_backup_snapshot_id,omitempty"` + FirstBackupBytes *int64 `json:"first_backup_bytes,omitempty"` + FirstBackupAt *time.Time `json:"first_backup_at,omitempty"` + WriteSetDigest string `json:"writeset_digest,omitempty"` + WriteSetRows *int64 `json:"writeset_rows,omitempty"` + TargetFingerprint string `json:"target_fingerprint,omitempty"` + RecordedAt *time.Time `json:"recorded_at,omitempty"` +} + +// LibraryAttempt 是 operation 的一次执行代次。 +type LibraryAttempt struct { + OperationID string `json:"operation_id"` + Epoch int `json:"epoch"` + JobID string `json:"job_id"` + QueueJobID string `json:"queue_job_id"` + Owner string `json:"owner"` + State LibraryAttemptState `json:"state"` + StartedAt time.Time `json:"started_at"` + HeartbeatAt *time.Time `json:"heartbeat_at,omitempty"` + LeaseUntil *time.Time `json:"lease_until,omitempty"` + FinishedAt *time.Time `json:"finished_at,omitempty"` + Outcome string `json:"outcome,omitempty"` +} + +// LibraryOperationID 由 (scope, kind, operation 键) 决定:同一个客户端重放键永远得到 +// 同一个 operation(幂等),换一个键就是一次新意图(不是"历史成功")。 +func LibraryOperationID(scope string, kind LibraryJobKind, operationKey string) string { + sum := sha256.Sum256([]byte(string(kind) + "|" + scope + "|" + operationKey)) + return "libop-" + hex.EncodeToString(sum[:])[:24] +} + +// LibraryVersionEventID 生成一条**不可变版本事件**的 ID:同一个 operation 对同一快照 +// 同一类别只产生一条事件(重放幂等);不同 operation 即使引用同一快照也是不同事件, +// 因此 `source_job_id`/`evidence`/`created_at` 不会被后来的执行覆盖(F02)。 +// operationID 为空时退回旧形状,供历史行/旧调用方保持同一身份。 +func LibraryVersionEventID(kind LibraryVersionKind, scope, snapshotID, operationID string) string { + identity := string(kind) + "|" + scope + "|" + snapshotID + if operationID != "" { + identity += "|" + operationID + } + sum := sha256.Sum256([]byte(identity)) + return "libver-" + hex.EncodeToString(sum[:])[:16] +} + +// CurrentOrderKey 给"这条事实是什么时候被记录为真相的"一个**单调可比较**的键。 +// +// 用它做 current 指针的条件更新:后来登记的事实可以推进指针,更早的不能把指针拉回历史。 +// 旧执行代次"迟到 finalize 反转 current"在写边界就被拦住了(epoch 守卫), +// 所以这里不需要也不该再拿 operation 的创建时间当次序——恢复回滚必须能把指针指回更早发布的 +// 快照,那个事件的**登记时间**是新的。 +func CurrentOrderKey(recordedAt time.Time, operationID string, epoch int) string { + return fmt.Sprintf("%020d|%s|%09d", recordedAt.UTC().UnixNano(), operationID, epoch) +} + +// CanAdvanceCurrent 判断一条新事实能否推进 current 指针(纯函数,供写入路径与测试共用)。 +// 返回 false 表示"这条事件只能确认自己的历史",调用方必须拒绝把它登记成当前状态。 +func CanAdvanceCurrent(currentOrderKey, nextOrderKey string) bool { + if nextOrderKey == "" { + return false + } + if currentOrderKey == "" { + return true + } + return nextOrderKey > currentOrderKey +} + +// LibraryJobTypePrefix 是所有整库发布相关队列作业的类型前缀。 +// +// 这些类型的准入条件(生产闸口、精确授权、维护互斥、目标身份核验)只在发布管理专用 +// 入口里判断,所以它们对通用 queue 入口是**保留类型**:通用入口的通用 engineer 角色 +// 检查替代不了准入,允许它造一个 library.* 作业就是绕过整条准入链(F14)。 +const LibraryJobTypePrefix = "library." + +// IsReservedLibraryJobType 按前缀整类判断,而不是逐个列举类型: +// 以后新增一种 library 作业类型时不会漏掉准入。 +func IsReservedLibraryJobType(jobType string) bool { + return strings.HasPrefix(strings.TrimSpace(jobType), LibraryJobTypePrefix) +} + +// ValidateLibraryOperation 只做结构校验:缺字段就拒绝,不猜默认值。 +func ValidateLibraryOperation(op LibraryOperation) error { + if op.ID == "" || op.OperationKey == "" || op.RequestDigest == "" || op.CreatedAt.IsZero() { + return errors.New("library operation requires id, key, digest and created_at") + } + if op.Scope != "internal" && op.Scope != "external" { + return errors.New("library operation requires internal or external scope") + } + switch op.Kind { + case LibraryJobSeal, LibraryJobSync, LibraryJobRestore, LibraryJobBaseline, LibraryJobRecover, LibraryJobVerify: + default: + return fmt.Errorf("unsupported library operation kind %q", op.Kind) + } + return nil +} diff --git a/internal/governance/library_recovery_identity.go b/internal/governance/library_recovery_identity.go new file mode 100644 index 0000000..53c12a1 --- /dev/null +++ b/internal/governance/library_recovery_identity.go @@ -0,0 +1,52 @@ +package governance + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "strings" +) + +// The recovery request has its own queue identity and stable operation. It +// borrows the original window's fence, never its immutable sending identity. +func LibraryRecoveryQueueID(windowJob string) string { + sum := sha256.Sum256([]byte(windowJob)) + return "lrec-" + hex.EncodeToString(sum[:14]) +} + +func LibraryRecoveryDigest(scope, queue, window, operation, target, source, backup, plan string) (string, error) { + return LibraryRequestDigest(scope, LibraryJobRecover, map[string]any{ + "recovery_queue": queue, "window_job": window, "original_operation": operation, + "target_id": target, "source_snapshot": source, "backup_snapshot": backup, "writeset_digest": plan, + }) +} + +// LibraryDeliveryOwner 是队列投递 + 业务 attempt 的合成 owner: +// +// ## +// +// 它就是 library_attempts.owner,也决定了"这次派发属于哪一次真实投递"。worker 与 +// 派发台账必须用同一份格式,否则"当前 owner"会变成两处各自解释的字符串。 +func LibraryDeliveryOwner(workerID, queueID string, attempt int) string { + if queueID == "" { + queueID = "-" + } + if workerID == "" { + workerID = "worker" + } + return fmt.Sprintf("%s#%s#%d", workerID, queueID, attempt) +} + +// ParseLibraryDeliveryOwner 把 owner 拆回 (worker, ok);queue/attempt 必须逐位相同, +// 不能靠后缀匹配把别的投递混进来。 +func ParseLibraryDeliveryOwner(owner, queueID string, attempt int) (string, bool) { + suffix := fmt.Sprintf("#%s#%d", queueID, attempt) + if queueID == "" || !strings.HasSuffix(owner, suffix) { + return "", false + } + worker := strings.TrimSuffix(owner, suffix) + if worker == "" || strings.Contains(worker, "#") { + return "", false + } + return worker, true +} diff --git a/internal/governance/library_source_identity.go b/internal/governance/library_source_identity.go new file mode 100644 index 0000000..2e29a4c --- /dev/null +++ b/internal/governance/library_source_identity.go @@ -0,0 +1,30 @@ +package governance + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" +) + +// SourceIdentity binds an immutable capture to its configured origin, not to a +// target or a page of mixed version history. It does not modify snapshot hashes. +type LibrarySourceIdentity struct { + Project string `json:"project"` + App string `json:"app"` + Scope string `json:"scope"` + TenantID uint64 `json:"tenant_id"` + KnowledgeBaseID string `json:"knowledge_base_id"` +} + +func (s LibrarySourceIdentity) ID() (string, error) { + if s.Project == "" || s.App == "" || (s.Scope != "internal" && s.Scope != "external") || s.TenantID == 0 || s.KnowledgeBaseID == "" { + return "", errors.New("source project/app/scope/tenant/knowledge base binding incomplete") + } + raw, err := json.Marshal(s) + if err != nil { + return "", err + } + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]), nil +} diff --git a/internal/governance/library_verification.go b/internal/governance/library_verification.go new file mode 100644 index 0000000..306285b --- /dev/null +++ b/internal/governance/library_verification.go @@ -0,0 +1,51 @@ +package governance + +import ( + "strings" + "time" +) + +// LibraryRestoreVerification 是一次**真实**恢复验证(备份 → canary → 恢复 → 复核)的登记。 +// +// 为什么不能继续用环境变量 PRODUCTION_BACKUP_RESTORE_VERIFIED:那是一个可以手填的开关, +// 它既证明不了"有人真跑过恢复",也证明不了"跑的是当前目标"。这里的每条记录由 worker +// 在真实演练结束后写入,绑定 target_id(实例+库+索引+桶)与 scope,失败也照实留痕。 +type LibraryRestoreVerification struct { + ID string `json:"id"` + Scope string `json:"scope"` + Status string `json:"status"` // passed | failed + SnapshotID string `json:"snapshot_id"` + JobID string `json:"job_id"` + Failure string `json:"failure,omitempty"` + Report map[string]any `json:"report,omitempty"` + StartedAt time.Time `json:"started_at"` + FinishedAt time.Time `json:"finished_at"` +} + +const ( + LibraryVerificationPassed = "passed" + LibraryVerificationFailed = "failed" +) + +// LibraryVerificationSatisfied 只回答一件事:这条证据能不能支撑"当前目标的恢复验证已通过"。 +// 通过的条件必须是全部成立——状态 passed、scope 相同、快照非空、完成时间有效。 +// target_id 的匹配由查询层(按当前 target_id 过滤)保证,这里不重复比较。 +func LibraryVerificationSatisfied(verification LibraryRestoreVerification, scope string) (bool, string) { + if verification.Status != LibraryVerificationPassed { + reason := "最近一次恢复验证没有通过" + if detail := strings.TrimSpace(verification.Failure); detail != "" { + reason += ":" + detail + } + return false, reason + } + if verification.Scope != scope { + return false, "恢复验证证据属于另一个 scope(" + verification.Scope + ")" + } + if strings.TrimSpace(verification.SnapshotID) == "" { + return false, "恢复验证证据没有绑定快照,不能作为备份可恢复的证明" + } + if verification.FinishedAt.IsZero() { + return false, "恢复验证证据没有完成时间" + } + return true, "" +} diff --git a/internal/governance/library_verification_test.go b/internal/governance/library_verification_test.go new file mode 100644 index 0000000..97e2709 --- /dev/null +++ b/internal/governance/library_verification_test.go @@ -0,0 +1,59 @@ +package governance + +import ( + "testing" + "time" +) + +// 证据能不能支撑"当前目标可恢复"只由这四个条件回答: +// 状态 passed、scope 相同、绑定了快照、有完成时间。少任何一条都不算。 +func TestLibraryVerificationSatisfied(t *testing.T) { + now := time.Now().UTC() + cases := []struct { + name string + verification LibraryRestoreVerification + scope string + want bool + reason string + }{ + {name: "passed with snapshot", scope: "internal", want: true, + verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal", + SnapshotID: "snap-1", FinishedAt: now}}, + {name: "failed carries failure", scope: "internal", want: false, reason: "canary 后校验仍通过", + verification: LibraryRestoreVerification{Status: LibraryVerificationFailed, Scope: "internal", + SnapshotID: "snap-1", Failure: "canary 后校验仍通过", FinishedAt: now}}, + {name: "wrong scope", scope: "internal", want: false, reason: "另一个 scope", + verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "external", + SnapshotID: "snap-1", FinishedAt: now}}, + {name: "no snapshot", scope: "internal", want: false, reason: "没有绑定快照", + verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal", + FinishedAt: now}}, + {name: "no finish time", scope: "internal", want: false, reason: "没有完成时间", + verification: LibraryRestoreVerification{Status: LibraryVerificationPassed, Scope: "internal", + SnapshotID: "snap-1"}}, + } + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + ok, reason := LibraryVerificationSatisfied(testCase.verification, testCase.scope) + if ok != testCase.want { + t.Fatalf("satisfied=%v want=%v reason=%q", ok, testCase.want, reason) + } + if !testCase.want && testCase.reason != "" && !containsText(reason, testCase.reason) { + t.Fatalf("reason=%q want contains %q", reason, testCase.reason) + } + }) + } +} + +func containsText(haystack, needle string) bool { + return len(haystack) >= len(needle) && (haystack == needle || indexOf(haystack, needle) >= 0) +} + +func indexOf(haystack, needle string) int { + for i := 0; i+len(needle) <= len(haystack); i++ { + if haystack[i:i+len(needle)] == needle { + return i + } + } + return -1 +} diff --git a/internal/governance/monitor.go b/internal/governance/monitor.go index 940d3e1..3d1c6aa 100644 --- a/internal/governance/monitor.go +++ b/internal/governance/monitor.go @@ -36,8 +36,11 @@ type ServiceHealth struct { ObservedAt time.Time `json:"observed_at"` LastSuccessAt *time.Time `json:"last_success_at"` ConsecutiveFailures int `json:"consecutive_failures"` - Configured bool `json:"configured"` - Applicable bool `json:"applicable"` + // ProbeTarget names the object being probed (instance + short binding id), + // never credentials or full UUIDs, so a red light can be attributed. + ProbeTarget string `json:"probe_target"` + Configured bool `json:"configured"` + Applicable bool `json:"applicable"` } type KnowledgeBaseProgress struct { diff --git a/internal/governance/source_catalog.go b/internal/governance/source_catalog.go index 123c113..1157505 100644 --- a/internal/governance/source_catalog.go +++ b/internal/governance/source_catalog.go @@ -116,6 +116,7 @@ type CatalogRouteRequest struct { // fulfillment path needs to materialize and fetch it later. type CatalogRouteFile struct { NodeID string + ParentNodeID string Name string RelativePath string SizeBytes *int64 diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go index a9f4aec..a94541b 100644 --- a/internal/httpapi/auth.go +++ b/internal/httpapi/auth.go @@ -99,7 +99,7 @@ func isAuthEndpoint(method, path string) bool { // classify maps a request to the minimum role required. func classifyRole(method, path string) string { - if path == "/api/v1/source-connections/audit" { + if path == "/api/v1/source-connections/audit" || path == "/api/v1/library/source-associations" { return roleAdmin } // The member roster exposes account identities and roles: admin-only for @@ -107,6 +107,9 @@ func classifyRole(method, path string) string { if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") { return roleAdmin } + if strings.HasPrefix(path, "/api/v1/dws-login") || strings.HasPrefix(path, "/api/v1/pp-connection") || strings.HasPrefix(path, "/api/v1/dingtalk-spaces") || strings.HasPrefix(path, "/api/v1/dingtalk-session") { + return roleAdmin + } if method == http.MethodGet { return roleViewer } @@ -148,6 +151,11 @@ func classifyRole(method, path string) string { if strings.HasPrefix(path, "/api/v1/backup-schedule") && method != http.MethodGet { return roleAdmin } + // 核对封存结果会把一个 pending 业务作业修成 succeeded;只允许管理员, + // 且 handler 仍要求 completed queue、精确版本和归档复核。 + if strings.HasPrefix(path, "/api/v1/library/jobs/") && strings.HasSuffix(path, "/reconcile-capture") { + return roleAdmin + } // 版本记录的同步会拉起一次对远端仓库的抓取(消耗网络与数据库写入), // 与"谁能改生产绑定"同级:读任何角色可看,同步只能管理员。 if strings.HasPrefix(path, "/api/v1/version-history") && method != http.MethodGet { diff --git a/internal/httpapi/backup_schedule.go b/internal/httpapi/backup_schedule.go index 72e9572..11918c4 100644 --- a/internal/httpapi/backup_schedule.go +++ b/internal/httpapi/backup_schedule.go @@ -24,6 +24,9 @@ type BackupScheduleStore interface { type BackupHost interface { Available() bool Target() string + // Endpoint 是挂载的 ssh 配置里该别名真实拨号的 host:port;页面据此证明 + // "连的是哪条通道",而不是只显示一个别名。 + Endpoint() string Show(context.Context) (backuphost.ShowResult, error) Apply(context.Context, bool, string, int, int) (backuphost.ApplyResult, error) RunNow(context.Context) (backuphost.RunResult, error) @@ -82,8 +85,11 @@ type backupScheduleView struct { // HostConfigured/HostReachable 区分"没接线"与"接线了但连不上"。 HostConfigured bool `json:"host_configured"` HostTarget string `json:"host_target"` - HostReachable bool `json:"host_reachable"` - HostError string `json:"host_error"` + // HostEndpoint 是这条别名真实拨号的 host:port(来自挂载的 ssh 配置)。 + // 连接失败时它就是"到底往哪连"的唯一证据,不能只给一个别名让人猜。 + HostEndpoint string `json:"host_endpoint"` + HostReachable bool `json:"host_reachable"` + HostError string `json:"host_error"` HostScheduleEnabled bool `json:"host_schedule_enabled"` HostScheduleTime string `json:"host_schedule_time"` @@ -92,6 +98,8 @@ type backupScheduleView struct { HostCronLines []string `json:"host_cron_lines"` HostCronService string `json:"host_cron_service"` HostScriptPresent bool `json:"host_script_present"` + // HostCheckedAt 是本次真实主机探测时间;没有探测(只读库)时为空。 + HostCheckedAt string `json:"host_checked_at,omitempty"` LastRunStamp string `json:"last_run_stamp"` LastRunCreatedAt string `json:"last_run_created_at"` @@ -281,6 +289,7 @@ func (config Config) backupSchedulePayload(ctx context.Context, probeHost bool) } view.HostConfigured = config.BackupHost.Available() view.HostTarget = config.BackupHost.Target() + view.HostEndpoint = config.BackupHost.Endpoint() if !view.HostConfigured { view.InSync = false view.HostError = "目标主机凭据未挂载(BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET)" @@ -289,10 +298,14 @@ func (config Config) backupSchedulePayload(ctx context.Context, probeHost bool) if !probeHost { return view, nil } + view.HostCheckedAt = formatTime(config.Now().UTC()) show, err := config.BackupHost.Show(ctx) if err != nil { view.HostReachable = false view.HostError = err.Error() + if view.HostEndpoint != "" { + view.HostError += "(拨号地址 " + view.HostEndpoint + ")" + } view.InSync = false } else { view.HostReachable = true diff --git a/internal/httpapi/backup_schedule_test.go b/internal/httpapi/backup_schedule_test.go index 01e4e79..8d08bef 100644 --- a/internal/httpapi/backup_schedule_test.go +++ b/internal/httpapi/backup_schedule_test.go @@ -46,6 +46,7 @@ func (store *fakeBackupScheduleStore) MarkBackupScheduleApplied(_ context.Contex type fakeBackupHost struct { available bool target string + endpoint string show backuphost.ShowResult showErr error apply backuphost.ApplyResult @@ -59,6 +60,9 @@ type fakeBackupHost struct { func (host *fakeBackupHost) Available() bool { return host.available } func (host *fakeBackupHost) Target() string { return host.target } +func (host *fakeBackupHost) Endpoint() string { + return host.endpoint +} func (host *fakeBackupHost) Show(context.Context) (backuphost.ShowResult, error) { return host.show, host.showErr } @@ -166,6 +170,48 @@ func TestHandleBackupScheduleHostFlagsDrift(t *testing.T) { } } +func TestHandleBackupScheduleHostUnreachableSeparatesConnectionFromHostState(t *testing.T) { + // 现场原错:ssh connect to host 120.76.217.51 port 22 Operation timed out。 + // 连接没建立 ⇒ 既不能报"脚本缺失",也不能报"计划未下发",只能报不可达 + 拨号地址。 + host := &fakeBackupHost{ + available: true, target: "weknora-test", endpoint: "100.85.111.121:22", + showErr: errors.New("目标主机 weknora-test 不可达(ssh: connect to host 120.76.217.51 port 22: Operation timed out);未执行任何主机侧脚本,脚本与计划状态未知"), + } + config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, host) + recorder := httptest.NewRecorder() + config.handleBackupScheduleHost(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/host", nil)) + data := decodeData(t, recorder) + if data["host_reachable"] != false || data["in_sync"] != false { + t.Fatalf("连不上时不能报告可达或已同步: %+v", data) + } + message := data["host_error"].(string) + if !strings.Contains(message, "不可达") || !strings.Contains(message, "100.85.111.121:22") { + t.Fatalf("应报不可达并给出真实拨号地址: %q", message) + } + if strings.Contains(message, "脚本缺失") || strings.Contains(message, "未下发") { + t.Fatalf("未观测到的脚本/计划状态不能当成结论: %q", message) + } +} + +func TestHandleBackupScheduleHostReportsMissingScriptOnlyAfterConnecting(t *testing.T) { + // 真正的脚本缺失:ssh 已连上,主机回的是脚本不存在 ⇒ 这时才允许说脚本缺失。 + host := &fakeBackupHost{ + available: true, target: "weknora-test", endpoint: "100.85.111.121:22", + showErr: errors.New("已连上 weknora-test,但主机侧命令失败: bash: /opt/weknora-test/install_backup_schedule.sh: No such file or directory"), + } + config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, host) + recorder := httptest.NewRecorder() + config.handleBackupScheduleHost(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/host", nil)) + data := decodeData(t, recorder) + message := data["host_error"].(string) + if !strings.Contains(message, "已连上") || !strings.Contains(message, "No such file") { + t.Fatalf("已连接但脚本缺失时应原样带回主机原因: %q", message) + } + if strings.Contains(message, "不可达") { + t.Fatalf("已连上就不能说不可达: %q", message) + } +} + func TestHandleBackupScheduleHostUnconfiguredDegrades(t *testing.T) { config := backupConfig(&fakeBackupScheduleStore{schedule: goldenSchedule}, &fakeBackupHost{available: false}) recorder := httptest.NewRecorder() diff --git a/internal/httpapi/credential_audit.go b/internal/httpapi/credential_audit.go new file mode 100644 index 0000000..151a84c --- /dev/null +++ b/internal/httpapi/credential_audit.go @@ -0,0 +1,63 @@ +package httpapi + +import ( + "context" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/ppauth" + "sort" +) + +// Credential events are committed with their secret revision in one atomic file. +// Merge them into the existing audit view without copying secrets into SQL. +func combinedSourceAudit(ctx context.Context, reader sourceAuditReader, manager *ppauth.Manager, limit, offset int) (postgresstore.SourceAuditPage, error) { + if manager == nil { + return reader.ListSourceAudit(ctx, limit, offset) + } + events, err := manager.Events(ctx) + if err != nil { + return postgresstore.SourceAuditPage{}, err + } + if len(events) == 0 { + return reader.ListSourceAudit(ctx, limit, offset) + } + start := offset - len(events) + if start < 0 { + start = 0 + } + rows := make([]postgresstore.SourceAuditItem, 0, limit+len(events)) + total := 0 + for next := start; len(rows) < limit+len(events); { + take := limit + len(events) - len(rows) + if take > 100 { + take = 100 + } + page, e := reader.ListSourceAudit(ctx, take, next) + if e != nil { + return postgresstore.SourceAuditPage{}, e + } + total = page.Total + rows = append(rows, page.Items...) + next += len(page.Items) + if next >= total || len(page.Items) == 0 { + break + } + } + for _, e := range events { + rows = append(rows, postgresstore.SourceAuditItem{ID: e.ID, ConnectionID: "", SourceName: e.SourceName, Action: e.Action, Actor: e.Actor, CreatedAt: e.CreatedAt, Detail: e.Detail}) + } + sort.SliceStable(rows, func(i, j int) bool { + if rows[i].CreatedAt.Equal(rows[j].CreatedAt) { + return rows[i].ID > rows[j].ID + } + return rows[i].CreatedAt.After(rows[j].CreatedAt) + }) + skip := offset - start + if skip > len(rows) { + skip = len(rows) + } + end := skip + limit + if end > len(rows) { + end = len(rows) + } + return postgresstore.SourceAuditPage{Items: rows[skip:end], Total: total + len(events), Limit: limit, Offset: offset}, nil +} diff --git a/internal/httpapi/dingtalk_discovery.go b/internal/httpapi/dingtalk_discovery.go index f988ebe..fd1c552 100644 --- a/internal/httpapi/dingtalk_discovery.go +++ b/internal/httpapi/dingtalk_discovery.go @@ -2,7 +2,6 @@ package httpapi import ( "context" - "errors" "net/http" "time" @@ -25,25 +24,16 @@ func listDingtalkSources(w http.ResponseWriter, r *http.Request, config Config) if _, ok := requireSessionIdentity(w, r); !ok { return } - lister := config.DingtalkSources - if lister == nil { - writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"}) + identity, _ := requireSessionIdentity(w, r) + if identity.Role != roleAdmin { + writeJSON(w, 403, map[string]string{"error": "需要管理员身份列举数据源"}) return } ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() - result, err := lister.ListAvailableDingtalkSources(ctx) + result, err := availableDWS(ctx, config) if err != nil { - if errors.Is(err, dingtalkdiscovery.ErrUnavailable) { - // 环境问题(dws 未登录 / 权限不足 / 二进制缺失):页面显示"暂时列不出来", - // 不是平台故障,也不该把内部错误细节当 500 抛出去。 - writeJSON(w, http.StatusServiceUnavailable, map[string]string{ - "error": "dingtalk_discovery_unavailable", - "hint": "dws 未登录或缺少租户目录读权限;请先刷新钉钉会话,或让管理员检查 dws 凭据。", - }) - return - } - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list dingtalk sources"}) + writeDWSSourceError(w, err) return } writeJSON(w, http.StatusOK, map[string]any{"data": result}) diff --git a/internal/httpapi/dingtalk_discovery_test.go b/internal/httpapi/dingtalk_discovery_test.go index 845b87b..c85003f 100644 --- a/internal/httpapi/dingtalk_discovery_test.go +++ b/internal/httpapi/dingtalk_discovery_test.go @@ -53,7 +53,7 @@ func TestListDingtalkSourcesReportsEnvironmentProblemsAsUnavailable(t *testing.T if rec.Code != http.StatusServiceUnavailable { t.Fatalf("unavailable = %d, want 503 body=%s", rec.Code, rec.Body.String()) } - if !strings.Contains(rec.Body.String(), "dingtalk_discovery_unavailable") { + if !strings.Contains(rec.Body.String(), "dws_unavailable") { t.Fatalf("body = %s", rec.Body.String()) } } diff --git a/internal/httpapi/dingtalk_register_dws_test.go b/internal/httpapi/dingtalk_register_dws_test.go index 01e5b32..2dcb82a 100644 --- a/internal/httpapi/dingtalk_register_dws_test.go +++ b/internal/httpapi/dingtalk_register_dws_test.go @@ -2,59 +2,42 @@ package httpapi import ( "context" + "knowledge-governance/internal/dingtalkdiscovery" postgresstore "knowledge-governance/internal/platform/postgres" - "net/http" "net/http/httptest" "testing" "time" - - "knowledge-governance/internal/dingtalkdiscovery" ) func TestDWSNameConflictIsNotASuccessfulRegistration(t *testing.T) { store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: postgresstore.ErrDingtalkSpaceNameTaken} lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "wiki", SpaceID: "testspace"}}}} rec := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-spaces", nil) - registerSpaceThroughDWS(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op") - if rec.Code != http.StatusConflict { + req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", nil) + registerDWSOnlySpace(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op") + if rec.Code != 409 { t.Fatalf("name conflict must not claim success: %d", rec.Code) } } - -// 登记走 dws 不是侧车:解析出来的键、名称、根节点直接决定新来源的确定性 id。 func TestResolveSpaceViaDWSUsesTheSpaceCredentialsAlreadyHeld(t *testing.T) { - lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{ - KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{ - {Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"}, - {Name: "视觉文档", SpaceID: "9JOGO9EEOMLMWX4Q"}, - }, - DriveSpaces: []dingtalkdiscovery.DriveSpace{ - {Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a"}, - }, - }} - rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS( - context.Background(), lister, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")) - if !ok || rootKey != "space-9JOGOLBQndOyaz4Q" || name != "国内技术支持管理" || rootID != "9JOGOLBQndOyaz4Q" || spaceID != "9JOGOLBQndOyaz4Q" { - t.Fatalf("knowledge base resolved as key=%q name=%q root=%q space=%q ok=%v", rootKey, name, rootID, spaceID, ok) + result := dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"}}, DriveSpaces: []dingtalkdiscovery.DriveSpace{{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "drive-root"}}} + input, err := resolveDWS(result, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")) + if err != nil || input.RootKey != "space-9JOGOLBQndOyaz4Q" || input.Name != "国内技术支持管理" || input.RootID != "9JOGOLBQndOyaz4Q" || input.SpaceID != "9JOGOLBQndOyaz4Q" { + t.Fatalf("wiki resolution=%+v %v", input, err) } - - // 钉盘的根是 rootFolderId,不是空间 id:抓取侧按它遍历。 - rootKey, _, rootID, _, ok = resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("102571304")) - if !ok || rootID != "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a" || rootKey != "space-102571304" { - t.Fatalf("drive space resolved as key=%q root=%q ok=%v", rootKey, rootID, ok) + input, err = resolveDWS(result, dingtalkdiscovery.SpaceURL("102571304")) + if err != nil || input.RootID != "drive-root" || input.RootKey != "space-102571304" { + t.Fatalf("drive resolution=%+v %v", input, err) } } - -func TestResolveSpaceViaDWSLeavesUnknownSpacesToTheFallback(t *testing.T) { - lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{}} - if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("unknownspace1")); ok { - t.Fatal("an unknown space must not resolve") +func TestResolveDWSRejectsUnknownAndUnwiredWithoutBrowserFallback(t *testing.T) { + if _, err := resolveDWS(dingtalkdiscovery.Result{}, dingtalkdiscovery.SpaceURL("unknownspace1")); err == nil { + t.Fatal("unknown space resolved") } - if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), nil, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")); ok { - t.Fatal("without a lister nothing can resolve") + if _, err := availableDWS(context.Background(), Config{}); err == nil { + t.Fatal("unwired service resolved") } - if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, "not-a-space-url"); ok { - t.Fatal("a URL without a space id must not resolve") + if _, err := resolveDWS(dingtalkdiscovery.Result{}, "not-a-space-url"); err == nil { + t.Fatal("invalid space resolved") } } diff --git a/internal/httpapi/dingtalk_session.go b/internal/httpapi/dingtalk_session.go index d86946d..c1c864e 100644 --- a/internal/httpapi/dingtalk_session.go +++ b/internal/httpapi/dingtalk_session.go @@ -2,9 +2,7 @@ package httpapi import ( "bytes" - "context" "encoding/json" - "errors" "io" "log" "net/http" @@ -12,10 +10,6 @@ import ( "regexp" "strings" "time" - - "knowledge-governance/internal/governance" - "knowledge-governance/internal/jobs" - postgresstore "knowledge-governance/internal/platform/postgres" ) // DingTalk login proxy. The scan-code login itself lives in the @@ -102,86 +96,15 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config writeJSON(w, http.StatusBadRequest, map[string]string{"error": "url is required"}) return } - // dws 已经持有有效凭据(access 自动续期、refresh 一个月),登记也该走它: - // 只有 dws 解析不出这个空间时,才回落到老的扫码侧车。 - if registered, ok := registerSpaceThroughDWS(w, r, config, strings.TrimSpace(input.URL), operationID); ok || registered { - return - } - payload, _ := json.Marshal(map[string]string{"url": strings.TrimSpace(input.URL)}) - status, data := proxyDingtalk(http.MethodPost, "/spaces/add", payload) - if status != http.StatusOK { - if status == 0 { - writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "dingtalk_login_unavailable"}) - return - } - // Relay the sidecar's error (login_required / space_not_found / - // name_conflict) verbatim; bodies are machine codes, no secrets. - writeProxyResult(w, status, data) - return - } - var resolved struct { - Key string `json:"key"` - Name string `json:"name"` - Root string `json:"root"` - } - if err := json.Unmarshal(data, &resolved); err != nil || resolved.Key == "" || resolved.Name == "" || resolved.Root == "" { - writeJSON(w, http.StatusBadGateway, map[string]string{"error": "invalid sidecar registration response"}) - return - } - store, ok := config.Store.(interface { - RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error) - }) - if !ok { - writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"}) - return - } - spaceID := extractDingtalkSpaceID(input.URL) - if spaceID == "" { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid space url"}) - return - } - connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{ - RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(), Actor: actorFor(r), - }) - switch { - case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken): - writeJSON(w, http.StatusConflict, map[string]string{ - "error": "space_name_conflict", - "hint": "已有同名来源仍在使用(未下架):请先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间。", - }) - return - case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict): - writeJSON(w, http.StatusConflict, map[string]string{ - "error": "space_identity_conflict", - "hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试;若仍失败,把该来源「去掉来源」后再登记。", - }) - return - case err != nil: - // 真正的数据库/内部故障不能伪装成"冲突":换个 500 才有人去查日志。 - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"}) - return - } - // First scan is enqueued right away: the new connection has no catalog - // head yet, so the generic sources/{id}/refresh endpoint would 404 until - // the first snapshot exists. - if enqueuer, ok := config.Store.(interface { - EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error) - }); ok { - if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(r.Context(), governance.CatalogSource{ - ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: resolved.Name, - }, operationID+":first", config.Now().UTC()); enqueueErr != nil { - log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr) - } - } - log.Printf("dingtalk space %q registered as connection %s by %s", resolved.Name, connectionID, actorFor(r)) - writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{ - "connection_id": connectionID, "name": resolved.Name, - }}) + registerDWSOnlySpace(w, r, config, strings.TrimSpace(input.URL), operationID) } var dingtalkSpacePattern = regexp.MustCompile(`/spaces/([A-Za-z0-9_-]+)`) func extractDingtalkSpaceID(raw string) string { + if !validDingtalkURL(raw) { + return "" + } match := dingtalkSpacePattern.FindStringSubmatch(raw) if len(match) == 2 { return match[1] @@ -244,76 +167,3 @@ func proxyDingtalk(method, path string, body []byte) (int, []byte) { } return resp.StatusCode, data } - -// resolveSpaceViaDWS 用 dws 列举结果定位一个空间:返回确定性登记键、名称与根节点。 -// 认不出就 ok=false,调用方回落到老的扫码侧车(历史空间仍能被登记)。 -func resolveSpaceViaDWS(ctx context.Context, lister dingtalkSourcesLister, rawURL string) (rootKey, name, rootID, spaceID string, ok bool) { - spaceID = extractDingtalkSpaceID(rawURL) - if lister == nil || spaceID == "" { - return "", "", "", "", false - } - discovered, err := lister.ListAvailableDingtalkSources(ctx) - if err != nil { - return "", "", "", "", false - } - for _, base := range discovered.KnowledgeBases { - if base.SpaceID == spaceID { - // 知识库:URL 里的 id 就是空间 id,抓取侧按 spaces/ 匹配。 - return "space-" + spaceID, base.Name, spaceID, spaceID, true - } - } - for _, space := range discovered.DriveSpaces { - if space.SpaceID == spaceID && space.RootFolderID != "" { - return "space-" + spaceID, space.Name, space.RootFolderID, spaceID, true - } - } - return "", "", "", "", false -} - -// registerSpaceThroughDWS 用 dws 凭据直接登记来源,不再要求扫码会话。 -func registerSpaceThroughDWS(w http.ResponseWriter, r *http.Request, config Config, rawURL, operationID string) (bool, bool) { - ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) - defer cancel() - rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(ctx, config.DingtalkSources, rawURL) - if !ok { - return false, false - } - store, wired := config.Store.(interface { - RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error) - }) - if !wired { - writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"}) - return true, false - } - connectionID, err := store.RegisterDingtalkSpace(ctx, postgresstore.RegisterDingtalkSpaceInput{ - RootKey: rootKey, Name: name, SpaceID: spaceID, RootID: rootID, Now: config.Now(), Actor: actorFor(r), - }) - switch { - case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken): - writeJSON(w, http.StatusConflict, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源,但空间标识不一致;请核对已有来源,不能按名称判定添加成功。"}) - return true, false - case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict): - writeJSON(w, http.StatusConflict, map[string]string{ - "error": "space_identity_conflict", - "hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试。", - }) - return true, false - case err != nil: - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"}) - return true, false - } - if enqueuer, wired := config.Store.(interface { - EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error) - }); wired { - if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{ - ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: name, - }, operationID+":first", config.Now().UTC()); enqueueErr != nil { - log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr) - } - } - log.Printf("dingtalk space %q registered as connection %s by %s (dws)", name, connectionID, actorFor(r)) - writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{ - "connection_id": connectionID, "name": name, - }}) - return true, true -} diff --git a/internal/httpapi/dingtalk_session_test.go b/internal/httpapi/dingtalk_session_test.go index 27de453..4dce962 100644 --- a/internal/httpapi/dingtalk_session_test.go +++ b/internal/httpapi/dingtalk_session_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "knowledge-governance/internal/dingtalkdiscovery" postgresstore "knowledge-governance/internal/platform/postgres" ) @@ -123,7 +124,7 @@ func TestDingtalkSpaceRegistrationErrorClassification(t *testing.T) { call := func(storeErr error) (int, string) { store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: storeErr} - handler, err := NewHandler(Config{Store: store}) + handler, err := NewHandler(Config{Store: store, DingtalkSources: fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "公司级技术支持知识库", SpaceID: "9JOK9EEOMLMWX4Q"}}}}}) if err != nil { t.Fatalf("NewHandler() error = %v", err) } diff --git a/internal/httpapi/dws_login.go b/internal/httpapi/dws_login.go new file mode 100644 index 0000000..cd30445 --- /dev/null +++ b/internal/httpapi/dws_login.go @@ -0,0 +1,83 @@ +package httpapi + +import ( + "errors" + "log" + "net/http" + "net/url" + + "knowledge-governance/internal/dingtalkdiscovery" +) + +func registerDWSLoginRoutes(mux *http.ServeMux, config Config) { + mux.HandleFunc("POST /api/v1/dws-login", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "start") }) + mux.HandleFunc("GET /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "get") }) + mux.HandleFunc("DELETE /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "cancel") }) +} + +func handleDWSLogin(w http.ResponseWriter, r *http.Request, config Config, action string) { + w.Header().Set("Cache-Control", "no-store") + identity, ok := requireSessionIdentity(w, r) + if !ok { + return + } + if identity.Role != roleAdmin { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "需要管理员身份才能管理 DWS 授权"}) + return + } + if action != "get" { + originOK := true + if raw := r.Header.Get("Origin"); raw != "" { + origin, err := url.Parse(raw) + originOK = err == nil && origin.Host == r.Host && (origin.Scheme == "http" || origin.Scheme == "https") + } + if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != "dws-login" { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "请从本平台的数据源配置页发起授权"}) + return + } + } + if config.DWSLogin == nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "DWS 登录服务未接通,请联系管理员"}) + return + } + // Bind the challenge to this authenticated administrator and browser session. + owner := identity.UserID + "/" + identity.SessionID + var view dingtalkdiscovery.DeviceLoginView + var err error + switch action { + case "start": + view, err = config.DWSLogin.Start(owner) + case "get": + view, err = config.DWSLogin.Get(owner, r.PathValue("id")) + case "cancel": + view, err = config.DWSLogin.Cancel(owner, r.PathValue("id")) + } + if err != nil { + switch { + case errors.Is(err, dingtalkdiscovery.ErrLoginNotFound): + writeJSON(w, http.StatusNotFound, map[string]string{"error": "授权会话已结束或服务已重启,请重新发起"}) + case errors.Is(err, dingtalkdiscovery.ErrLoginBusy): + writeJSON(w, http.StatusConflict, map[string]string{"error": "另一位管理员正在授权,请稍后再试"}) + default: + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "无法发起 DWS 授权,请重试"}) + } + return + } + if config.PPConnection != nil && (action != "get" || view.State == "succeeded" || view.State == "failed" || view.State == "expired") { + if err := config.PPConnection.AuditOnce(r.Context(), "dws-"+view.ID+"-"+string(view.State), "钉钉账号(DWS)", "dws_authorization", identity.Username, "DWS 授权状态:"+string(view.State)); err != nil { + if action == "start" { + _, _ = config.DWSLogin.Cancel(owner, view.ID) + } + writeJSON(w, 503, map[string]string{"error": "授权审计写入失败,请重试"}) + return + } + } + if action != "get" { + log.Printf("DWS authorization action=%s id=%s actor=%s", action, view.ID, identity.Username) + } + status := http.StatusOK + if action == "start" { + status = http.StatusAccepted + } + writeJSON(w, status, map[string]any{"data": view}) +} diff --git a/internal/httpapi/dws_login_test.go b/internal/httpapi/dws_login_test.go new file mode 100644 index 0000000..675544e --- /dev/null +++ b/internal/httpapi/dws_login_test.go @@ -0,0 +1,82 @@ +package httpapi + +import ( + "context" + "encoding/json" + "knowledge-governance/internal/dingtalkdiscovery" + "net/http" + "net/http/httptest" + "testing" +) + +func TestDWSLoginHTTPAuthenticationOwnershipAndOrigin(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + manager := dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{Binary: "/nonexistent/dws"}) + h, err := NewHandler(Config{Store: &fakeJobStore{}, DWSLogin: manager}) + if err != nil { + t.Fatal(err) + } + call := func(method, path, role, session, origin, intent string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, nil) + if role != "" { + r = r.WithContext(context.WithValue(r.Context(), sessionKey{}, sessionIdentity{UserID: "admin-user", Username: "tester", Role: role, SessionID: session})) + } + r.Header.Set("Origin", origin) + r.Header.Set("X-Governance-Action", intent) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + for _, role := range []string{"", roleViewer, roleEngineer} { + w := call("POST", "/api/v1/dws-login", role, "s1", "", "dws-login") + if w.Code != 401 && w.Code != 403 { + t.Fatalf("role=%q status=%d", role, w.Code) + } + } + for _, input := range [][2]string{{"", ""}, {"https://foreign.invalid", "dws-login"}} { + w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", input[0], input[1]) + if w.Code != 403 { + t.Fatalf("origin/intent not enforced: %d", w.Code) + } + } + w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", "", "dws-login") + if w.Code != 202 || w.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("start=%d body=%s", w.Code, w.Body) + } + var body struct { + Data dingtalkdiscovery.DeviceLoginView `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Data.ID == "" { + t.Fatal("missing session", err) + } + path := "/api/v1/dws-login/" + body.Data.ID + for _, method := range []string{"GET", "DELETE"} { + w = call(method, path, roleAdmin, "other-session", "", "dws-login") + if w.Code != 404 { + t.Fatalf("foreign session %s=%d", method, w.Code) + } + w = call(method, path, roleEngineer, "s1", "", "dws-login") + if w.Code != 403 { + t.Fatalf("engineer %s=%d", method, w.Code) + } + } + w = call("GET", path, roleAdmin, "s1", "", "") + if w.Code != 200 { + t.Fatalf("get=%d", w.Code) + } + w = call("DELETE", path, roleAdmin, "s1", "", "dws-login") + if w.Code != 200 { + t.Fatalf("cancel=%d", w.Code) + } +} + +func TestDWSLoginRoutesAreAdminOnly(t *testing.T) { + for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} { + for _, path := range []string{"/api/v1/dws-login", "/api/v1/dws-login/session-id"} { + if got := classifyRole(method, path); got != roleAdmin { + t.Errorf("%s %s role=%s; authorization artifacts must be admin-only", method, path, got) + } + } + } +} diff --git a/internal/httpapi/dws_registration.go b/internal/httpapi/dws_registration.go new file mode 100644 index 0000000..ff8a2ea --- /dev/null +++ b/internal/httpapi/dws_registration.go @@ -0,0 +1,212 @@ +package httpapi + +import ( + "context" + "errors" + "knowledge-governance/internal/dingtalkdiscovery" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + postgresstore "knowledge-governance/internal/platform/postgres" + "net/http" + "net/url" + "strings" + "time" +) + +type dwsSourceError struct { + Status int + Code, Hint string +} + +func (e *dwsSourceError) Error() string { return e.Hint } +func writeDWSSourceError(w http.ResponseWriter, err error) { + var e *dwsSourceError + if errors.As(err, &e) { + writeJSON(w, e.Status, map[string]string{"error": e.Code, "hint": e.Hint}) + return + } + writeJSON(w, 500, map[string]string{"error": "dws_source_failed", "hint": "读取钉钉来源失败,请重试"}) +} +func availableDWS(ctx context.Context, config Config) (dingtalkdiscovery.Result, error) { + identity := "" + if config.DingtalkSources == nil { + return dingtalkdiscovery.Result{}, &dwsSourceError{501, "dws_unwired", "DWS 来源服务未接通"} + } + if reader, ok := config.DingtalkSources.(interface { + ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error) + }); ok { + status, err := reader.ReadDWSMetadata(ctx) + if err != nil || !status.StatusKnown { + return dingtalkdiscovery.Result{}, &dwsSourceError{503, "dws_status_unavailable", "暂时无法读取 DWS 授权状态,请重试"} + } + identity = status.Identity + if !status.Authenticated && !status.RefreshTokenValid { + return dingtalkdiscovery.Result{}, &dwsSourceError{401, "dws_login_required", "DWS 未登录或授权已失效,请重新授权"} + } + } + result, err := config.DingtalkSources.ListAvailableDingtalkSources(ctx) + if err != nil { + if errors.Is(err, dingtalkdiscovery.ErrCredentials) { + return result, &dwsSourceError{401, "dws_login_required", "DWS 授权已失效,请重新授权"} + } + if errors.Is(err, dingtalkdiscovery.ErrPermission) { + return result, &dwsSourceError{403, "dws_permission_denied", "当前 DWS 账号缺少目录读取权限"} + } + if errors.Is(err, dingtalkdiscovery.ErrUnavailable) { + return result, &dwsSourceError{503, "dws_unavailable", "DWS 目录暂时无法读取,请检查连接后重试"} + } + return result, err + } + if identity != "" { + reader := config.DingtalkSources.(interface { + ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error) + }) + fresh, e := reader.ReadDWSMetadata(ctx) + if e != nil { + return result, &dwsSourceError{503, "dws_status_unavailable", "无法确认当前账号,请重试"} + } + if fresh.Identity != identity { + return result, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"} + } + } + result.Identity = identity + if config.Store != nil { + if page, e := config.Store.ListSourceConnections(ctx); e == nil { + seen := map[string]bool{} + for _, c := range page.Items { + seen[c.ID] = true + } + for i, kb := range result.KnowledgeBases { + in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + kb.SpaceID} + result.KnowledgeBases[i].Registered = seen[in.ConnectionID()] + } + for i, space := range result.DriveSpaces { + in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + space.SpaceID} + result.DriveSpaces[i].Registered = seen[in.ConnectionID()] + } + } + } + if registry, ok := config.Store.(interface { + RegisteredDingtalkSpaceIDs(context.Context) (map[string]bool, error) + }); ok { + ids, e := registry.RegisteredDingtalkSpaceIDs(ctx) + if e != nil { + return result, &dwsSourceError{503, "dws_registration_state_unavailable", "无法核对已接入空间,请重试"} + } + for i, kb := range result.KnowledgeBases { + result.KnowledgeBases[i].Registered = ids[kb.SpaceID] + } + for i, space := range result.DriveSpaces { + result.DriveSpaces[i].Registered = ids[space.SpaceID] + } + } + return result, nil +} +func resolveDWS(result dingtalkdiscovery.Result, raw string) (postgresstore.RegisterDingtalkSpaceInput, error) { + spaceID := extractDingtalkSpaceID(raw) + if spaceID == "" { + return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"} + } + for _, base := range result.KnowledgeBases { + if base.SpaceID == spaceID { + return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: base.Name, RootID: spaceID, SpaceID: spaceID}, nil + } + } + for _, space := range result.DriveSpaces { + if space.SpaceID == spaceID && space.RootFolderID != "" { + return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: space.Name, RootID: space.RootFolderID, SpaceID: spaceID}, nil + } + } + if result.KnowledgeNotice != "" || result.DriveNotice != "" { + return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{503, "dws_scope_incomplete", "当前目录结果不完整,无法确认所选空间;请检查相应目录权限后重试"} + } + return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{409, "dws_space_not_visible", "当前 DWS 账号已看不到所选空间,请刷新范围或核对账号权限"} +} +func registerDWSOnlySpace(w http.ResponseWriter, r *http.Request, config Config, raw, operationID string) { + if extractDingtalkSpaceID(raw) == "" { + writeDWSSourceError(w, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"}) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + result, err := availableDWS(ctx, config) + if err != nil { + writeDWSSourceError(w, err) + return + } + if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity { + writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"}) + return + } + input, err := resolveDWS(result, raw) + if err != nil { + writeDWSSourceError(w, err) + return + } + input.Now = config.Now() + input.Actor = actorFor(r) + store, ok := config.Store.(interface { + RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error) + }) + if !ok { + writeJSON(w, 503, map[string]string{"error": "registration_unavailable"}) + return + } + connectionID, err := store.RegisterDingtalkSpace(ctx, input) + switch { + case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken): + writeJSON(w, 409, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源仍在使用:请核对空间身份,必要时先移除旧连接(原去掉来源操作)"}) + return + case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict): + writeJSON(w, 409, map[string]string{"error": "space_identity_conflict", "hint": "登记键已指向另一个空间,请刷新后核对来源"}) + return + case err != nil: + writeJSON(w, 500, map[string]string{"error": "space_registration_failed"}) + return + } + queued := false + if queue, ok := config.Store.(interface { + EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error) + }); ok { + _, _, err = queue.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: input.Name}, "dws-source-first:"+connectionID, config.Now().UTC()) + queued = err == nil + } + writeJSON(w, 201, map[string]any{"data": map[string]any{"connection_id": connectionID, "name": input.Name, "first_scan_queued": queued}}) +} +func validateDWSSpace(w http.ResponseWriter, r *http.Request, config Config) { + if !credentialAdmin(w, r, "dingtalk-space") { + return + } + var input struct { + URLs []string `json:"urls"` + } + if decodeJSONStrict(r, &input) != nil || len(input.URLs) == 0 || len(input.URLs) > 100 { + writeJSON(w, 400, map[string]string{"error": "请选择有效的空间范围"}) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + result, err := availableDWS(ctx, config) + if err != nil { + writeDWSSourceError(w, err) + return + } + if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity { + writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"}) + return + } + for _, raw := range input.URLs { + if _, err := resolveDWS(result, raw); err != nil { + writeDWSSourceError(w, err) + return + } + } + writeJSON(w, 200, map[string]any{"data": map[string]any{"valid": true, "checked_at": config.Now().UTC(), "count": len(input.URLs)}}) +} +func validDingtalkURL(raw string) bool { + if !strings.Contains(raw, "://") { + return true + } + u, err := url.Parse(raw) + return err == nil && u.Scheme == "https" && u.Host == "alidocs.dingtalk.com" && u.User == nil && u.Fragment == "" +} diff --git a/internal/httpapi/dws_registration_test.go b/internal/httpapi/dws_registration_test.go new file mode 100644 index 0000000..8757a79 --- /dev/null +++ b/internal/httpapi/dws_registration_test.go @@ -0,0 +1,30 @@ +package httpapi + +import ( + "context" + "knowledge-governance/internal/dingtalkdiscovery" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestDWSRegistrationNeverFallsBackToBrowserSession(t *testing.T) { + calls := 0 + sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(401) })) + defer sidecar.Close() + t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL) + h, err := NewHandler(Config{Store: &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}}, DingtalkSources: fakeDingtalkSources{err: dingtalkdiscovery.ErrUnavailable}}) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", strings.NewReader(`{"url":"https://alidocs.dingtalk.com/i/spaces/valid-space-id/overview"}`)) + req.Header.Set("Idempotency-Key", "op-dws-only") + req.Header.Set("X-Governance-Action", "dingtalk-space") + req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if calls != 0 || rec.Code != 503 || !strings.Contains(rec.Body.String(), "dws_unavailable") { + t.Fatalf("DWS failed: legacy calls=%d status=%d body=%s", calls, rec.Code, rec.Body.String()) + } +} diff --git a/internal/httpapi/library_baseline.go b/internal/httpapi/library_baseline.go index 01acebe..128916e 100644 --- a/internal/httpapi/library_baseline.go +++ b/internal/httpapi/library_baseline.go @@ -9,7 +9,6 @@ import ( "time" "knowledge-governance/internal/governance" - "knowledge-governance/internal/jobs" postgresstore "knowledge-governance/internal/platform/postgres" ) @@ -52,18 +51,18 @@ func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Confi "error": "版本登记存储不可用"}) return } - versions, err := store.LibraryVersions(r.Context(), request.Scope, 50) + // 建基线的前提是"这个目标还没有生效版本"。这是创建判据,必须精确查当前生效版本: + // 用"最近 N 条"会在窗口满时把已生效读成没有,放行一次会覆盖他人版本的基线捕获。 + current, hasCurrent, err := store.LibraryCurrentVersion(r.Context(), request.Scope) if err != nil { - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"}) + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read current library version"}) return } - for _, item := range versions { - if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil { - writeJSON(w, http.StatusConflict, map[string]any{"code": "library_baseline_exists", - "error": "该目标已有生效版本,不需要再建基线;换版本请走同步或恢复", - "snapshot_id": item.SnapshotID}) - return - } + if hasCurrent { + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_baseline_exists", + "error": "该目标已有生效版本,不需要再建基线;换版本请走同步或恢复", + "snapshot_id": current.SnapshotID}) + return } // 目标必须真的读得到:读不到就不是"非空无权威版本",而是另一个问题, // 不允许用建基线去掩盖连接/配置故障。 @@ -107,12 +106,12 @@ func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Confi return } now := time.Now().UTC() - job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{ + job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{ ID: fmt.Sprintf("libbase-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope, Kind: governance.LibraryJobBaseline, IdempotencyKey: "library.baseline:" + request.Scope + ":" + now.Format("20060102T150405.000000000"), RequestDigest: digest, Actor: identity.Username, - }, governance.BaselineStages(), now) + }, governance.BaselineStages(), false, now) if errors.Is(err, governance.ErrLibraryJobActive) { writeJSON(w, http.StatusConflict, map[string]any{"code": "library_write_active", "error": "该目标已有在飞的写作业(同步/恢复/基线互斥),等它结束再发起"}) @@ -131,26 +130,6 @@ func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Confi writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true}) return } - payload, err := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": request.Scope}) - if err != nil { - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build baseline payload"}) - return - } - queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ - ID: governance.QueueJobIDFor(job.ID), Type: libraryBaselineJobType, Payload: payload, - AvailableAt: now, MaxAttempts: 1, IdempotencyKey: "library.baseline.queue:" + job.ID, - }, now) - if err != nil || queueJob == nil { - // 作业先落库、队列投递失败就把作业取消:不留下"看起来在跑"的空作业, - // 否则它会一直占着该 scope 的写互斥。 - _ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始建立基线", now) - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue baseline job"}) - return - } - if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil { - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach baseline job"}) - return - } writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false, "target_counts": counts}) } diff --git a/internal/httpapi/library_baseline_mutex_test.go b/internal/httpapi/library_baseline_mutex_test.go index 842afc2..512a1ac 100644 --- a/internal/httpapi/library_baseline_mutex_test.go +++ b/internal/httpapi/library_baseline_mutex_test.go @@ -45,6 +45,21 @@ func (s *baselineMutexStore) CreateLibraryJob(ctx context.Context, job governanc return s.fakeLibraryStore.CreateLibraryJob(ctx, job, stages, now) } +func (s *baselineMutexStore) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) { + if s.activeByScope == nil { + s.activeByScope = map[string]string{} + } + if s.activeByScope[job.Scope] != "" { + return governance.LibraryJob{}, false, governance.ErrLibraryJobActive + } + created, reused, err := s.fakeLibraryStore.CreateLibraryDispatch(ctx, job, stages, handoff, now) + if err == nil { + s.activeByScope[job.Scope] = created.ID + s.enqueues++ + } + return created, reused, err +} + func (s *baselineMutexStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) { s.enqueues++ return s.fakeLibraryStore.fakeJobStore.Enqueue(ctx, request, now) diff --git a/internal/httpapi/library_baseline_test.go b/internal/httpapi/library_baseline_test.go index ce83293..f5ceabe 100644 --- a/internal/httpapi/library_baseline_test.go +++ b/internal/httpapi/library_baseline_test.go @@ -3,6 +3,7 @@ package httpapi import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "strings" @@ -160,3 +161,32 @@ func TestLibraryMaintenanceCapabilityReportsWiringInsteadOfOneVagueSentence(t *t t.Fatalf("missing=%v", broken["missing"]) } } + +// 建基线的存在性判断同样不能靠展示窗口:生效版本可能在"最近 N 条"之外。 +// 读不到(而不是"没有")时也必须 fail closed,不许当成可以建基线。 +func TestLibraryBaselineUsesExactCurrentVersionBeyondWindow(t *testing.T) { + store := &fakeLibraryStore{current: &governance.LibraryVersion{ID: "libver-1", Scope: "internal", + Kind: governance.LibraryVersionProductionEffective, SnapshotID: "snap-effective", + CreatedAt: time.Now().UTC().Add(-96 * time.Hour)}} + recorder := httptest.NewRecorder() + libraryBaselineEnqueue(recorder, baselineRequest(`{"scope":"internal"}`, roleAdmin, "admin"), Config{Store: store}) + if recorder.Code != http.StatusConflict { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if body := decodeBody(t, recorder); body["code"] != "library_baseline_exists" || body["snapshot_id"] != "snap-effective" { + t.Fatalf("body=%v", body) + } + if store.createN != 0 { + t.Fatal("must not create a baseline job when an effective version exists") + } + + failing := &fakeLibraryStore{currentErr: errors.New("version storage down")} + recorder = httptest.NewRecorder() + libraryBaselineEnqueue(recorder, baselineRequest(`{"scope":"internal"}`, roleAdmin, "admin"), Config{Store: failing}) + if recorder.Code != http.StatusInternalServerError { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if failing.createN != 0 { + t.Fatal("must not create a baseline job while the current version is unreadable") + } +} diff --git a/internal/httpapi/library_capture_reconcile.go b/internal/httpapi/library_capture_reconcile.go new file mode 100644 index 0000000..7686527 --- /dev/null +++ b/internal/httpapi/library_capture_reconcile.go @@ -0,0 +1,246 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "knowledge-governance/internal/librarysnapshot" +) + +// libraryCaptureReconciler is deliberately narrow: it repairs one business +// seal job only after the completed capture queue, the successful export stage, +// the exact test-sealed version and the archived bytes all agree. It never +// captures, freezes writers, creates snapshots, writes source/target content or +// changes historical failure evidence. +type libraryCaptureReconciler interface { + LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error) + LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error) + LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) + EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error) + ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error) + ReconcileMisclassifiedLibraryCapture(ctx context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, auditID, actor, reason string, evidence map[string]any, now time.Time) (bool, error) +} + +const ( + legacyOrphanError = "队列中已无对应作业,业务作业未收到结果" + legacyOrphanRecovery = "封存作业由 agent 恢复来源;确认来源 healthy 后可重发" +) + +type libraryCaptureQueueReader interface { + QueueJob(ctx context.Context, id string) (jobs.Job, bool, error) +} + +func libraryCaptureReconcile(w http.ResponseWriter, r *http.Request, config Config) { + if r.Method != http.MethodPost { + writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"}) + return + } + store, ok := config.Store.(libraryCaptureReconciler) + if !ok { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, + "reason": "封存作业核对存储不可用"}) + return + } + queueStore, ok := config.Store.(libraryCaptureQueueReader) + if !ok { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, + "reason": "队列精确读取不可用"}) + return + } + jobID := strings.TrimSpace(r.PathValue("id")) + if jobID == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "job id required"}) + return + } + job, err := store.LibraryJob(r.Context(), jobID) + if err != nil { + writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"}) + return + } + if job.Kind != governance.LibraryJobSeal { + conflict(w, "只有封存作业可以核对封存结果") + return + } + systemMisclassified := job.State == governance.LibraryJobFailed && job.Stage == "" && + job.Error == legacyOrphanError && job.Recovery == legacyOrphanRecovery && job.SnapshotID == "" + if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning && + job.State != governance.LibraryJobSucceeded && !systemMisclassified { + conflict(w, "作业是真实失败/取消终态,不能改写成成功") + return + } + if job.QueueJobID == "" { + conflict(w, "作业没有关联队列号,不能证明封存完成") + return + } + captureJob := strings.TrimPrefix(job.ID, "libseal-") + if captureJob == "" || captureJob == job.ID { + conflict(w, "作业号不是封存作业身份") + return + } + queue, found, err := queueStore.QueueJob(r.Context(), job.QueueJobID) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture queue"}) + return + } + if !found { + conflict(w, "队列作业不存在,不能证明封存完成") + return + } + if queue.Type != libraryCaptureJobType || queue.State != jobs.StateCompleted { + conflict(w, "队列作业不是 completed 的 library.capture") + return + } + var payload struct { + Scope string `json:"scope"` + CaptureJob string `json:"capture_job"` + } + if err := json.Unmarshal(queue.Payload, &payload); err != nil || + payload.Scope != job.Scope || payload.CaptureJob != captureJob || + queue.IdempotencyKey != "library.capture:"+captureJob { + conflict(w, "队列作业的 scope/capture_job/幂等键与业务作业不一致") + return + } + stageState, _, err := store.LibraryCaptureExportEvidence(r.Context(), job.ID) + if err != nil || stageState != "succeeded" { + conflict(w, "导出阶段没有成功证据,不能修复终态") + return + } + version, found, err := store.LibraryTestSealedVersionForJob(r.Context(), job.Scope, job.ID) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read exact test-sealed version"}) + return + } + if !found || version.Kind != governance.LibraryVersionTestSealed || + version.Scope != job.Scope || version.SourceJobID != job.ID || version.SnapshotID == "" { + conflict(w, "没有与作业/scope 精确绑定的测试封存版本") + return + } + source := configuredLibrarySource(config, job.Scope) + sourceID, err := source.ID() + if err != nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, + "reason": "来源身份配置不完整,无法核对封存来源"}) + return + } + evidenceSource, _ := version.Evidence["source_id"].(string) + evidenceCapture, _ := version.Evidence["capture_job"].(string) + if evidenceSource != sourceID || evidenceCapture != captureJob { + conflict(w, "版本来源或 capture_job 与当前作业不一致") + return + } + if config.LibraryArchiveRoot == "" { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, + "reason": "未接线归档根,无法复核归档完整性"}) + return + } + archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024) + if err != nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, + "reason": "归档不可读,不能确认封存完整"}) + return + } + defer archive.Close() + manifest, err := archive.Load(version.SnapshotID) + if err != nil { + conflict(w, "归档字节复核失败,不能修复作业") + return + } + if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID || + manifest.KnowledgeBaseID != source.KnowledgeBaseID { + conflict(w, "归档清单来源身份与当前来源不一致") + return + } + if job.SnapshotID != "" && job.SnapshotID != version.SnapshotID { + conflict(w, "作业已有不同快照,不能覆盖") + return + } + if job.State == governance.LibraryJobSucceeded { + if job.SnapshotID != version.SnapshotID { + conflict(w, "作业已成功但快照与精确版本不一致") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "repaired": false, "already_succeeded": true, "job_id": job.ID, + "snapshot_id": version.SnapshotID, "queue_job_id": queue.ID, + "version_id": version.ID, + }) + return + } + actor := "" + if identity, ok := sessionFrom(r.Context()); ok { + actor = identity.Username + } + now := time.Now().UTC() + digest, err := governance.LibraryRequestDigest(job.Scope, governance.LibraryJobRecover, map[string]any{ + "kind": "capture_reconcile", "job_id": job.ID, "queue_job_id": queue.ID, + "snapshot_id": version.SnapshotID, "capture_job": captureJob, "stage": "export", + }) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build reconcile audit digest"}) + return + } + if systemMisclassified { + auditID := "librepair-" + digest[:16] + updated, repairErr := store.ReconcileMisclassifiedLibraryCapture(r.Context(), job.ID, job.Scope, + job.QueueJobID, version.SnapshotID, job.Stage, legacyOrphanError, legacyOrphanRecovery, + job.FinishedAt, auditID, actor, "completed capture queue + export succeeded + exact version + archive verified; legacy orphan misclassification", map[string]any{ + "original_state": job.State, "original_error": job.Error, "original_recovery": job.Recovery, + "original_finished_at": job.FinishedAt, "queue_job_id": queue.ID, + "snapshot_id": version.SnapshotID, "version_id": version.ID, "archive_verified": true, + }, now) + if repairErr != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot persist misclassification repair"}) + return + } + if !updated { + conflict(w, "原误判行状态/错误/完成时间已变化,拒绝覆盖") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "repaired": true, "already_succeeded": false, "misclassification_repaired": true, + "job_id": job.ID, "snapshot_id": version.SnapshotID, "queue_job_id": queue.ID, + "stage": "export", "version_id": version.ID, "audit_repair_id": auditID, + }) + return + } + opID := "libop-capture-reconcile-" + digest[:16] + op, _, err := store.EnsureLibraryOperation(r.Context(), governance.LibraryOperation{ + ID: opID, Scope: job.Scope, Kind: governance.LibraryJobRecover, + TargetSnapshotID: version.SnapshotID, RequestDigest: digest, + OperationKey: "capture-reconcile:" + job.ID, Actor: actor, CreatedAt: now, + }) + if errors.Is(err, governance.ErrLibraryOperationConflict) { + conflict(w, "同一核对键对应了不同证据,拒绝修复") + return + } + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot record reconcile audit"}) + return + } + updated, err := store.ReconcileLibraryCaptureTerminal(r.Context(), job.ID, job.Scope, job.QueueJobID, version.SnapshotID, now) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]any{ + "error": "cannot persist reconciled job terminal", "audit_operation_id": op.ID, + }) + return + } + if !updated { + conflict(w, "作业状态/身份在核对期间变化,拒绝覆盖") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "repaired": true, "already_succeeded": false, "job_id": job.ID, + "snapshot_id": version.SnapshotID, "queue_job_id": queue.ID, + "stage": "export", "version_id": version.ID, "audit_operation_id": op.ID, + }) +} + +func conflict(w http.ResponseWriter, reason string) { + writeJSON(w, http.StatusConflict, map[string]any{"available": false, "repaired": false, "reason": reason}) +} diff --git a/internal/httpapi/library_capture_reconcile_test.go b/internal/httpapi/library_capture_reconcile_test.go new file mode 100644 index 0000000..7ccd1be --- /dev/null +++ b/internal/httpapi/library_capture_reconcile_test.go @@ -0,0 +1,361 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "knowledge-governance/internal/librarysnapshot" +) + +func (f *fakeLibraryStore) QueueJob(_ context.Context, id string) (jobs.Job, bool, error) { + if f.queue == nil || f.queue.ID != id { + return jobs.Job{}, false, nil + } + return *f.queue, true, nil +} + +func (f *fakeLibraryStore) LibraryCaptureExportEvidence(_ context.Context, _ string) (string, string, error) { + return f.stageState, "", f.stageErr +} + +func (f *fakeLibraryStore) LibraryJobStage(_ context.Context, _, stage string) (string, string, error) { + if f.stageErr != nil { + return "", "", f.stageErr + } + if stage != "export" { + return "", "", errors.New("unexpected stage") + } + return f.stageState, "", nil +} + +func (f *fakeLibraryStore) LibraryTestSealedVersionForJob(_ context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) { + if f.versionErr != nil { + return governance.LibraryVersion{}, false, f.versionErr + } + if f.sealedVersion == nil || f.sealedVersion.Scope != scope || f.sealedVersion.SourceJobID != jobID { + return governance.LibraryVersion{}, false, nil + } + return *f.sealedVersion, true, nil +} + +func reconcileFixture(t *testing.T) (*fakeLibraryStore, Config, governance.LibraryJob, []byte) { + t.Helper() + root := libraryFixtureRoot(t) + snapshotID := sealSharedVersions(t, root, 1, 4)[0] + archive, err := librarysnapshot.Open(root, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + manifest, err := archive.Load(snapshotID) + archive.Close() + if err != nil { + t.Fatal(err) + } + config := Config{LibraryArchiveRoot: root, + LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app", + LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID} + source := configuredLibrarySource(config, "internal") + sourceID, err := source.ID() + if err != nil { + t.Fatal(err) + } + job := governance.LibraryJob{ID: "libseal-cap-1", Scope: "internal", Kind: governance.LibraryJobSeal, + State: governance.LibraryJobPending, QueueJobID: "libcap-1"} + payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "cap-1"}) + store := &fakeLibraryStore{ + jobs: []governance.LibraryJob{job}, + stageState: "succeeded", + queue: &jobs.Job{ID: "libcap-1", Type: libraryCaptureJobType, State: jobs.StateCompleted, + Payload: payload, IdempotencyKey: "library.capture:cap-1"}, + sealedVersion: &governance.LibraryVersion{ID: "libver-1", Scope: "internal", + Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshotID, SourceJobID: job.ID, + Evidence: map[string]any{"source_id": sourceID, "capture_job": "cap-1"}}, + } + config.Store = store + return store, config, job, payload +} + +func (f *fakeLibraryStore) ReconcileLibraryCaptureTerminal(_ context.Context, jobID, scope, queueJobID, snapshotID string, _ time.Time) (bool, error) { + if f.reconcileDenied { + return false, nil + } + for index := range f.jobs { + if f.jobs[index].ID != jobID || f.jobs[index].Scope != scope || f.jobs[index].Kind != governance.LibraryJobSeal || + f.jobs[index].QueueJobID != queueJobID || (f.jobs[index].State != governance.LibraryJobPending && f.jobs[index].State != governance.LibraryJobRunning) || + (f.jobs[index].SnapshotID != "" && f.jobs[index].SnapshotID != snapshotID) { + return false, nil + } + f.jobs[index].State = governance.LibraryJobSucceeded + f.jobs[index].SnapshotID = snapshotID + f.lastState = governance.LibraryJobSucceeded + return true, nil + } + return false, nil +} + +func (f *fakeLibraryStore) ReconcileMisclassifiedLibraryCapture(_ context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, _ string, _ string, _ string, _ map[string]any, _ time.Time) (bool, error) { + if f.reconcileDenied { + return false, nil + } + for index := range f.jobs { + j := &f.jobs[index] + if j.ID != jobID || j.Scope != scope || j.Kind != governance.LibraryJobSeal || j.QueueJobID != queueJobID || + j.State != governance.LibraryJobFailed || j.Stage != expectedStage || j.Error != expectedError || + j.Recovery != expectedRecovery || j.SnapshotID != "" || (j.FinishedAt == nil) != (expectedFinished == nil) || + (j.FinishedAt != nil && expectedFinished != nil && !j.FinishedAt.Equal(*expectedFinished)) { + return false, nil + } + j.State = governance.LibraryJobSucceeded + j.SnapshotID = snapshotID + j.Stage = "export" + f.lastState = governance.LibraryJobSucceeded + return true, nil + } + return false, nil +} + +var _ libraryCaptureReconciler = (*fakeLibraryStore)(nil) + +func runReconcile(t *testing.T, config Config, jobID string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+jobID+"/reconcile-capture", nil) + req.SetPathValue("id", jobID) + rec := httptest.NewRecorder() + libraryCaptureReconcile(rec, req, config) + return rec +} + +func TestLibraryCaptureReconcileRepairsExactCompletedCapture(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String()) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body["repaired"] != true || body["snapshot_id"] == "" || body["audit_operation_id"] == "" { + t.Fatalf("body=%v", body) + } + if store.lastState != governance.LibraryJobSucceeded { + t.Fatalf("advanced state=%s", store.lastState) + } + if len(store.operations) != 1 { + t.Fatalf("audit operations=%v", store.operations) + } +} + +func TestLibraryCaptureReconcileAlreadySucceededIsReadOnly(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + job.State = governance.LibraryJobSucceeded + job.SnapshotID = store.sealedVersion.SnapshotID + store.jobs[0] = job + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String()) + } + var body map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &body) + if body["already_succeeded"] != true || body["repaired"] != false || store.lastState != "" { + t.Fatalf("body=%v advanced=%q", body, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsQueueNotCompleted(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.queue.State = jobs.StateRunning + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String()) + } +} + +func TestLibraryCaptureReconcileRejectsStageNotSucceeded(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.stageState = "failed" + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsWrongVersionSource(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.sealedVersion.Evidence["source_id"] = "other-source" + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsWrongCaptureJob(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.sealedVersion.Evidence["capture_job"] = "other-capture" + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsBadArchive(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.sealedVersion.SnapshotID = "missing-snapshot" + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String()) + } +} + +func TestLibraryCaptureReconcileRejectsFailedJob(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + job.State = governance.LibraryJobFailed + store.jobs[0] = job + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} + +func TestLibraryCaptureReconcileIsIdempotent(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + first := runReconcile(t, config, job.ID) + if first.Code != http.StatusOK { + t.Fatalf("first code=%d body=%s", first.Code, first.Body.String()) + } + second := runReconcile(t, config, job.ID) + if second.Code != http.StatusOK { + t.Fatalf("second code=%d body=%s", second.Code, second.Body.String()) + } + var body map[string]any + _ = json.Unmarshal(second.Body.Bytes(), &body) + if body["already_succeeded"] != true || len(store.operations) != 1 { + t.Fatalf("body=%v ops=%v", body, store.operations) + } +} + +func TestLibraryCaptureReconcileRejectsMissingQueue(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.queue = nil + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsQueueScope(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.queue.Payload, _ = json.Marshal(map[string]string{"scope": "external", "capture_job": "cap-1"}) + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsMissingVersion(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.sealedVersion = nil + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsWrongScopeVersion(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.sealedVersion.Scope = "external" + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsDifferentExistingSnapshot(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + job.SnapshotID = "other-snapshot" + store.jobs[0] = job + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String()) + } +} + +func TestLibraryCaptureReconcileConditionalWriteRejectsConcurrentState(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + store.reconcileDenied = true + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String()) + } +} + +func TestLibraryCaptureReconcileRepairsExactLegacyMisclassification(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + finished := time.Now().UTC() + job.State = governance.LibraryJobFailed + job.Stage = "" + job.Error = legacyOrphanError + job.Recovery = legacyOrphanRecovery + job.FinishedAt = &finished + store.jobs[0] = job + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String()) + } + var body map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &body) + if body["misclassification_repaired"] != true || store.lastState != governance.LibraryJobSucceeded { + t.Fatalf("body=%v advanced=%q", body, store.lastState) + } +} + +func TestLibraryCaptureReconcileRejectsOtherFailedError(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + finished := time.Now().UTC() + job.State = governance.LibraryJobFailed + job.Stage = "" + job.Error = "capture export failed" + job.Recovery = legacyOrphanRecovery + job.FinishedAt = &finished + store.jobs[0] = job + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String()) + } +} + +func TestLibraryCaptureReconcileRejectsRealFailureAndCancel(t *testing.T) { + for _, state := range []governance.LibraryJobState{governance.LibraryJobFailed, governance.LibraryJobCancelled} { + store, config, job, _ := reconcileFixture(t) + job.State = state + job.Error = "real failure" + store.jobs[0] = job + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("state=%s code=%d advanced=%q", state, rec.Code, store.lastState) + } + } +} + +func TestLibraryCaptureReconcileMisclassificationCASRejectsChange(t *testing.T) { + store, config, job, _ := reconcileFixture(t) + finished := time.Now().UTC() + job.State = governance.LibraryJobFailed + job.Stage = "" + job.Error = legacyOrphanError + job.Recovery = legacyOrphanRecovery + job.FinishedAt = &finished + store.jobs[0] = job + store.reconcileDenied = true + rec := runReconcile(t, config, job.ID) + if rec.Code != http.StatusConflict || store.lastState != "" { + t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState) + } +} diff --git a/internal/httpapi/library_capture_reconcile_vertical_pg_test.go b/internal/httpapi/library_capture_reconcile_vertical_pg_test.go new file mode 100644 index 0000000..848f4d8 --- /dev/null +++ b/internal/httpapi/library_capture_reconcile_vertical_pg_test.go @@ -0,0 +1,204 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// Vertical PostgreSQL path: the real worker startup reconciliation must leave +// a pending seal with a completed capture queue intact, then the actual HTTP +// handler must verify archive/version/stage and repair it. This is not a fake +// store or a direct helper test. +func verticalReconcileFixture(t *testing.T) (*postgresstore.Store, Config, string, *pgxpool.Pool) { + t.Helper() + dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database") + } + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + t.Fatal("isolated database required") + } + cfg.MaxConns = 1 + cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp" + ctx := context.Background() + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + if _, err := pool.Exec(ctx, ` +CREATE TEMP TABLE library_jobs( + id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL, + state varchar(16) NOT NULL, stage varchar(32) NOT NULL DEFAULT '', + idempotency_key varchar(255) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL DEFAULT '', + queue_job_id varchar(64) NOT NULL DEFAULT '', snapshot_id varchar(64) NOT NULL DEFAULT '', + target_snapshot_id varchar(64) NOT NULL DEFAULT '', actor varchar(128) NOT NULL DEFAULT '', + error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '', + operation_id varchar(64) NOT NULL DEFAULT '', attempt_epoch integer NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL, finished_at timestamptz, + target_id text NOT NULL DEFAULT ''); +CREATE TEMP TABLE library_job_stages( + job_id varchar(64) NOT NULL, stage varchar(32) NOT NULL, state varchar(16) NOT NULL, + total bigint, completed bigint, bytes_total bigint, bytes_done bigint, + detail text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, PRIMARY KEY(job_id,stage)); +CREATE TEMP TABLE library_versions( + id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(24) NOT NULL, + snapshot_id varchar(64) NOT NULL DEFAULT '', version_label varchar(64) NOT NULL DEFAULT '', + source_job_id varchar(64) NOT NULL DEFAULT '', operation_id varchar(64) NOT NULL DEFAULT '', + attempt_epoch integer NOT NULL DEFAULT 0, evidence jsonb NOT NULL DEFAULT '{}'::jsonb, + created_by varchar(128) NOT NULL DEFAULT '', created_at timestamptz NOT NULL, superseded_at timestamptz); +CREATE TEMP TABLE library_job_repairs( + id varchar(64) PRIMARY KEY, job_id varchar(64) NOT NULL, scope varchar(16) NOT NULL, + kind varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL, snapshot_id varchar(64) NOT NULL, + original_state varchar(16) NOT NULL, original_stage varchar(32) NOT NULL DEFAULT '', + original_error text NOT NULL DEFAULT '', original_recovery varchar(255) NOT NULL DEFAULT '', + original_finished_at timestamptz, reason varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '', + evidence jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL); +CREATE TEMP TABLE library_operations( + id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL, + target_snapshot_id varchar(64) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL, + operation_key varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '', + created_at timestamptz NOT NULL, target_id text NOT NULL DEFAULT '', + first_backup_snapshot_id varchar(64), first_backup_bytes bigint, first_backup_at timestamptz, + writeset_digest varchar(64), writeset_rows bigint, target_fingerprint varchar(128), anchors_at timestamptz); +CREATE UNIQUE INDEX library_operations_key_test ON library_operations(scope,kind,operation_key); +CREATE TEMP TABLE jobs( + id varchar(64) PRIMARY KEY, type varchar(64) NOT NULL, payload jsonb NOT NULL, + state varchar(16) NOT NULL, priority integer NOT NULL DEFAULT 0, available_at timestamptz NOT NULL, + lease_owner varchar(128), lease_until timestamptz, attempt integer NOT NULL DEFAULT 0, + max_attempts integer NOT NULL DEFAULT 1, last_error text, idempotency_key varchar(255) NOT NULL, + created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL);`); err != nil { + t.Fatal(err) + } + root := libraryFixtureRoot(t) + snapshotID := sealSharedVersions(t, root, 1, 4)[0] + archive, err := librarysnapshot.Open(root, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + manifest, err := archive.Load(snapshotID) + archive.Close() + if err != nil { + t.Fatal(err) + } + config := Config{LibraryArchiveRoot: root, + LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app", + LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID} + source := configuredLibrarySource(config, "internal") + sourceID, err := source.ID() + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical"}) + if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at) + VALUES('q-vertical','library.capture',$1,'completed',$2,'library.capture:vertical',$2,$2)`, payload, now); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at) + VALUES('ver-vertical','internal','test_sealed',$1,'libseal-vertical',$2,$3)`, snapshotID, + map[string]any{"source_id": sourceID, "capture_job": "vertical"}, now); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at) + VALUES('libseal-vertical','export','succeeded','已封存快照', $1)`, now); err != nil { + t.Fatal(err) + } + store := postgresstore.NewStore(pool) + config.Store = store + if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,created_at,updated_at) + VALUES('libseal-vertical','internal','seal','pending','k','d','q-vertical',$1,$1)`, now); err != nil { + t.Fatal(err) + } + return store, config, snapshotID, pool +} + +func TestStartupReconcileThenHandlerRepairsPendingCapture(t *testing.T) { + store, config, _, _ := verticalReconcileFixture(t) + ctx := context.Background() + now := time.Now().UTC() + if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 { + t.Fatalf("startup reconcile n=%d err=%v", n, err) + } + job, err := store.LibraryJob(ctx, "libseal-vertical") + if err != nil || job.State != governance.LibraryJobPending { + t.Fatalf("startup changed job: %+v err=%v", job, err) + } + req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical/reconcile-capture", nil) + req.SetPathValue("id", "libseal-vertical") + rec := httptest.NewRecorder() + libraryCaptureReconcile(rec, req, config) + if rec.Code != http.StatusOK { + t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String()) + } + job, err = store.LibraryJob(ctx, "libseal-vertical") + if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID == "" { + t.Fatalf("handler did not repair: %+v err=%v", job, err) + } +} + +func TestStartupReconcilePreservesFailedCapturesForExactReconcile(t *testing.T) { + store, config, snapshotID, pool := verticalReconcileFixture(t) + ctx := context.Background() + now := time.Now().UTC() + source := configuredLibrarySource(config, "internal") + sourceID, err := source.ID() + if err != nil { + t.Fatal(err) + } + payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical-failed"}) + if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at) + VALUES('q-failed','library.capture',$1,'completed',$2,'library.capture:vertical-failed',$2,$2)`, payload, now); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at) + VALUES('ver-failed','internal','test_sealed',$1,'libseal-vertical-failed',$2,$3)`, + snapshotID, map[string]any{"source_id": sourceID, "capture_job": "vertical-failed"}, now); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at) + VALUES('libseal-vertical-failed','export','succeeded','已封存快照', $1)`, now); err != nil { + t.Fatal(err) + } + finished := now.Truncate(time.Microsecond) + if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,error,recovery,created_at,updated_at,finished_at) + VALUES('libseal-vertical-failed','internal','seal','failed','kf','df','q-failed',$1,$2,$3,$3,$3)`, + "队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", finished); err != nil { + t.Fatal(err) + } + if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 { + t.Fatalf("startup reconcile n=%d err=%v", n, err) + } + req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical-failed/reconcile-capture", nil) + req.SetPathValue("id", "libseal-vertical-failed") + rec := httptest.NewRecorder() + libraryCaptureReconcile(rec, req, config) + if rec.Code != http.StatusOK { + t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String()) + } + job, err := store.LibraryJob(ctx, "libseal-vertical-failed") + if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID != snapshotID { + t.Fatalf("failed misclassification not repaired: %+v err=%v", job, err) + } + var originalState, originalError string + if err := pool.QueryRow(ctx, `SELECT original_state, original_error FROM library_job_repairs WHERE job_id='libseal-vertical-failed'`). + Scan(&originalState, &originalError); err != nil { + t.Fatal(err) + } + if originalState != "failed" || originalError == "" { + t.Fatalf("audit missing original: state=%q error=%q", originalState, originalError) + } +} diff --git a/internal/httpapi/library_dispatch_fixture_test.go b/internal/httpapi/library_dispatch_fixture_test.go new file mode 100644 index 0000000..b7a54f9 --- /dev/null +++ b/internal/httpapi/library_dispatch_fixture_test.go @@ -0,0 +1,33 @@ +package httpapi + +import ( + "context" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "time" +) + +// In-memory API fixture mirrors dispatch shape; atomicity is tested against PG. +func (s *fakeLibraryStore) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) { + created, reused, err := s.CreateLibraryJob(ctx, job, stages, now) + if err != nil { + return created, reused, err + } + if reused && (created.State != governance.LibraryJobPending || created.QueueJobID != "") { + return created, reused, nil + } + id, kind, payload, err := governance.LibraryQueueRequest(handoff, created.ID, created.Scope, created.TargetSnapshotID, "library."+string(created.Kind)) + if err != nil { + return created, reused, err + } + queued, err := s.Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: kind, Payload: payload, AvailableAt: now, MaxAttempts: 1, IdempotencyKey: kind + ".queue:" + created.ID}, now) + if err != nil { + s.lastJob = governance.LibraryJob{} + return governance.LibraryJob{}, false, err + } + if err = s.AttachLibraryQueueJob(ctx, created.ID, queued.ID, now); err != nil { + return created, reused, err + } + created.QueueJobID = queued.ID + return created, reused, nil +} diff --git a/internal/httpapi/library_flow.go b/internal/httpapi/library_flow.go index 191b427..af8e9da 100644 --- a/internal/httpapi/library_flow.go +++ b/internal/httpapi/library_flow.go @@ -2,12 +2,9 @@ package httpapi import ( "context" - "crypto/sha256" - "encoding/hex" "encoding/json" "errors" "fmt" - "log" "net/http" "strings" "time" @@ -45,6 +42,10 @@ type libraryVersionView struct { // librarySyncJobType 与 worker 的处理器类型一致;单独定义避免 API 依赖 worker 包。 const librarySyncJobType = "library.sync" +// libraryHandoffJobType 是"先把快照送到执行器"的队列类型(capture 角色消费)。 +// 与发布作业分开:搬运失败时发布作业根本不会入队,目标不会进入维护窗口。 +const libraryHandoffJobType = "library.snapshot.handoff" + // libraryRecoverJobType 是"按预备份恢复并校验"的队列类型(同一份定义也在 worker 里)。 const libraryRecoverJobType = "library.recover" @@ -55,6 +56,10 @@ type libraryKnownView struct { // EmptyBaseline 表示"没有生效版本记录,但生产目标可读且确实是空的": // 这是首次发布的合法起点,和"生产非空却没有权威版本"必须区分。 EmptyBaseline bool `json:"empty_baseline,omitempty"` + // BoundToTarget 只对预备份有意义:这份备份的内容是否就是当前待发布目标。 + // 最近一次生产写入前的备份可能**不是**本次目标(例如刚按版本恢复过), + // 页面必须照实说是哪一次作业的备份,而不是一句"尚未创建"。 + BoundToTarget bool `json:"bound_to_target,omitempty"` } // productionScopeState 只读探测生产目标:真正连库数一遍,不用缓存或推断。 @@ -82,8 +87,27 @@ func productionScopeState(ctx context.Context, config Config, scope string) (boo v071.ProductionScope{TenantID: config.LibraryProductionTenantID, KnowledgeBaseID: kb}) } -// productionScopeEmpty 保留"只问空不空"的调用形状;逐表行数在需要举证时用 -// productionScopeState 取。 +// unknownLibraryTarget distinguishes an empty target from unreadable state. +// Overview and enqueue share this probe; neither may infer nonempty from failure. +func unknownLibraryTarget(ctx context.Context, config Config, scope string) libraryKnownView { + probe := config.LibraryScopeProbe + if probe == nil { + probe = func(ctx context.Context, scope string) (bool, map[string]int64, error) { + return productionScopeState(ctx, config, scope) + } + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + empty, _, err := probe(ctx, scope) + if err != nil { + return libraryKnownView{State: "unreachable", Reason: "无法读取目标整库状态:请检查目标连接后重试,不能据此判定空库或建立基线"} + } + if empty { + return libraryKnownView{State: "unknown", EmptyBaseline: true, Reason: "生产目标可读且为空:本次是首次发布,写入前仍会生成完整预备份"} + } + return libraryKnownView{State: "unknown", Reason: "目标非空且尚无权威版本"} +} + func productionScopeEmpty(ctx context.Context, config Config, scope string) (bool, error) { empty, _, err := productionScopeState(ctx, config, scope) return empty, err @@ -302,11 +326,14 @@ type libraryGateView struct { } type libraryOverview struct { - Scope string `json:"scope"` - TestSealed *librarySnapshotView `json:"test_sealed,omitempty"` - TestSealedReason string `json:"test_sealed_reason,omitempty"` - Production libraryKnownView `json:"production"` - Prebackup libraryKnownView `json:"prebackup"` + Scope string `json:"scope"` + TestSealed *librarySnapshotView `json:"test_sealed,omitempty"` + TestSealedReason string `json:"test_sealed_reason,omitempty"` + Production libraryKnownView `json:"production"` + Prebackup libraryKnownView `json:"prebackup"` + // Versions 是已登记版本的轻量清单(不含 evidence):页面要按快照判断 + // "这份归档是哪一类版本",不能把所有归档都写成测试封存。 + Versions []libraryVersionRef `json:"versions"` Diff libraryDiffView `json:"diff"` Job *governance.LibraryJob `json:"job,omitempty"` Jobs []governance.LibraryJob `json:"jobs"` @@ -315,19 +342,46 @@ type libraryOverview struct { CaptureAvailable bool `json:"capture_available"` CaptureReason string `json:"capture_reason,omitempty"` Executor libraryExecutorView `json:"executor"` - Now time.Time `json:"now"` + // 实际目标身份:页面不能只显示"weknora-test"或旧文档级绑定名称。 + TargetInstance string `json:"target_instance,omitempty"` + TargetProject string `json:"target_project,omitempty"` + TargetKnowledgeBaseID string `json:"target_knowledge_base_id,omitempty"` + Now time.Time `json:"now"` +} + +// libraryVersionRef 只回答"这个快照被登记成哪一类版本、由哪个作业登记"。 +type libraryVersionRef struct { + ID string `json:"id"` + Kind string `json:"kind"` + SnapshotID string `json:"snapshot_id"` + VersionLabel string `json:"version_label"` + SourceJobID string `json:"source_job_id"` + CreatedAt time.Time `json:"created_at"` + SupersededAt *time.Time `json:"superseded_at,omitempty"` } type libraryJobStore interface { + CreateLibraryDispatch(context.Context, governance.LibraryJob, []string, bool, time.Time) (governance.LibraryJob, bool, error) CreateLibraryJob(ctx context.Context, job governance.LibraryJob, stages []string, now time.Time) (governance.LibraryJob, bool, error) + // EnsureLibraryOperation 幂等登记"一次明确意图":同键+同摘要 ⇒ 同一次意图(客户端重放), + // 换键 ⇒ 新意图。作业是意图的执行代次,不能反过来用"历史成功作业"回答新意图(F01)。 + EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error) LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error) ListLibraryJobs(ctx context.Context, scope string, limit int) ([]governance.LibraryJob, error) RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error LibraryVersions(ctx context.Context, scope string, limit int) ([]governance.LibraryVersion, error) + // 当前生效版本与"某快照自己的登记"必须是精确查询:LibraryVersions 是分页展示窗口, + // 窗口一满就会把"已生效"读成"没有",同步闸口/基线入口就会放行一次不必要的重写。 + LibraryCurrentVersion(ctx context.Context, scope string) (governance.LibraryVersion, bool, error) + LibraryVersionOfSnapshot(ctx context.Context, scope string, kind governance.LibraryVersionKind, + snapshotID string) (governance.LibraryVersion, bool, error) UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error AttachLibraryQueueJob(ctx context.Context, jobID, queueJobID string, now time.Time) error CancelLibraryJob(ctx context.Context, jobID, reason string, now time.Time) error + // 续作走**原业务作业**(维护窗口/journal/预备份都按它落盘),只新增执行代次。 + PrepareLibraryJobResume(ctx context.Context, jobID string, now time.Time) (governance.LibraryJob, bool, error) + ResetQueueJobForResume(ctx context.Context, queueJobID string, now time.Time) error } func libraryStore(config Config) (libraryJobStore, bool) { @@ -418,8 +472,7 @@ func libraryMaintenanceRecoverHandler(w http.ResponseWriter, r *http.Request, co } // 队列作业 id 与幂等键都按窗口固定:重复点击只会得到同一个恢复作业。 // 队列 id 有长度上限(36),窗口作业 id 比它还长,所以按窗口摘要取短 id。 - sum := sha256.Sum256([]byte(held.OwnerJobID)) - queueID := "lrec-" + hex.EncodeToString(sum[:14]) + queueID := governance.LibraryRecoveryQueueID(held.OwnerJobID) queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ ID: queueID, Type: libraryRecoverJobType, Payload: payload, AvailableAt: now, MaxAttempts: 1, IdempotencyKey: "library.recover:" + held.OwnerJobID, @@ -546,6 +599,11 @@ func testSealedOf(versions []governance.LibraryVersion, byID map[string]libraryS // 它刻意只说配置:能停写入者/关入口/证明排空的真实能力在 worker 侧(docker socket、 // 闸门、排空文件),API 若声称"能力可用"就是拿配置字符串冒充执行证据。 func libraryMaintenanceCapability(config Config) map[string]any { + mode := strings.TrimSpace(config.LibraryTargetIngressMode) + if mode == "" { + mode = "gate" + } + noGate := mode == "none" missing := make([]string, 0, 6) if config.LibraryTargetInstance == "" { missing = append(missing, "LIBRARY_TARGET_INSTANCE") @@ -556,11 +614,18 @@ func libraryMaintenanceCapability(config Config) map[string]any { if len(config.LibraryTargetWriters) == 0 { missing = append(missing, "LIBRARY_TARGET_WRITERS") } - if config.LibraryTargetIngressURL == "" { - missing = append(missing, "LIBRARY_TARGET_INGRESS_URL") - } - if config.LibraryTargetIngressService == "" { - missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE") + if noGate { + // 没有闸门:页面必须如实说"无闸门(测试模式)",不能显示"打开"。 + if config.LibraryTargetHealthURL == "" { + missing = append(missing, "LIBRARY_TARGET_HEALTH_URL") + } + } else { + if config.LibraryTargetIngressURL == "" { + missing = append(missing, "LIBRARY_TARGET_INGRESS_URL") + } + if config.LibraryTargetIngressService == "" { + missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE") + } } if config.LibraryTargetJournalRoot == "" { missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT") @@ -568,12 +633,18 @@ func libraryMaintenanceCapability(config Config) map[string]any { if config.LibraryTargetDockerSocket == "" { missing = append(missing, "LIBRARY_TARGET_DOCKER_SOCKET") } + ingressState := "闸门" + if noGate { + ingressState = "无闸门(测试模式)" + } return map[string]any{ "configured": len(missing) == 0, "missing": missing, "instance": config.LibraryTargetInstance, "project": config.LibraryTargetProject, "writers": config.LibraryTargetWriters, + "ingress_mode": mode, + "ingress_state": ingressState, "ingress_service": config.LibraryTargetIngressService, "note": "配置齐全只说明治理侧接线完整;停写入者、关入口与排空由 worker 在作业内校验并执行", } @@ -593,9 +664,7 @@ func librarySyncGateWithGrant(config Config, production libraryKnownView, prebac if !config.ProductionReleaseRequestsEnabled { gate.Reasons = append(gate.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)") } - if !config.ProductionBackupRestoreVerified { - gate.Reasons = append(gate.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)") - } + gate.Reasons = append(gate.Reasons, restoreGateReasons(config)...) // 生产端点以"整库目标是否配置"为准:整库同步直接写 PG/ES/对象, // 不依赖 WeKnora 的 HTTP 端,所以不能拿它是否配置当门禁。 if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" { @@ -605,7 +674,9 @@ func librarySyncGateWithGrant(config Config, production libraryKnownView, prebac // 这就是一个合法的"空基线",不应该被永久挡住。非空但无权威版本仍然阻断, // 指向真实可行的入口(在维护隔离下捕获目标整库并校验后登记基线), // 而不是让人去手写版本或清空目标。 - if production.State != "known" && !production.EmptyBaseline { + if production.State == "unreachable" { + gate.Reasons = append(gate.Reasons, production.Reason) + } else if production.State != "known" && !production.EmptyBaseline { gate.Reasons = append(gate.Reasons, "目标非空且没有生效版本记录:先建立目标权威基线(维护隔离下捕获整库并逐类校验),或确认目标确实是空库") } if target == "" { @@ -637,10 +708,16 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi } now := time.Now().UTC() overview := libraryOverview{Scope: scope, Jobs: []governance.LibraryJob{}, Now: now, + TargetInstance: config.LibraryTargetInstance, TargetProject: config.LibraryTargetProject, Gate: libraryGateView{Reasons: []string{}}, Diff: libraryDiffView{State: "unknown", Reason: "生产与测试的文档级差异读取未接线", Added: []any{}, Updated: []any{}, Removed: []any{}}} // 可发起封存 = worker 真实探测到执行器可用且指向本实例;原因逐条给全。 overview.CaptureAvailable, overview.CaptureReason, overview.Executor = libraryExecutorAvailability(r.Context(), config) + if scope == "internal" { + overview.TargetKnowledgeBaseID = config.LibraryProductionInternalKB + } else { + overview.TargetKnowledgeBaseID = config.LibraryProductionExternalKB + } // 测试封存来自归档 + 版本登记:归档里**不止**测试封存——生产预备份与目标基线 // 快照同样带 scope,如果只按"这个 scope 最新一份"挑,页面就会把目标自己的内容 @@ -660,16 +737,33 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi } // 生产生效 / 预备份 / 作业来自持久登记。 + // 历史列表仍是分页展示(窗口),但"当前生效版本"必须精确查:窗口一满, + // 生效版本会掉出列表,页面就会显示成"没有生效版本",与真实状态不符。 versions, err := store.LibraryVersions(r.Context(), scope, 50) if err != nil { writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"}) return } + current, hasCurrent, currentErr := store.LibraryCurrentVersion(r.Context(), scope) + if currentErr != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read current library version"}) + return + } if archiveReadable { - overview.TestSealed, overview.TestSealedReason = testSealedOf(versions, byID) + var candidateErr error + overview.TestSealed, candidateErr = currentSourceCandidate(r.Context(), config, scope) + if candidateErr != nil { + overview.TestSealedReason = candidateErr.Error() + } } overview.Production = libraryKnownView{State: "unknown", Reason: "还没有生产验证通过的生效版本记录"} - overview.Prebackup = libraryKnownView{State: "unknown", Reason: "本次目标快照还没有生产预备份"} + overview.Prebackup = libraryKnownView{State: "unknown", Reason: "这个范围还没有任何生产预备份"} + if hasCurrent { + view := libraryVersionViewOf(current) + overview.Production = libraryKnownView{State: "known", Version: &view} + } else { + overview.Production = unknownLibraryTarget(r.Context(), config, scope) + } target := "" if overview.TestSealed != nil { target = overview.TestSealed.SnapshotID @@ -677,15 +771,21 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi for index := range versions { item := versions[index] view := libraryVersionViewOf(item) + overview.Versions = append(overview.Versions, libraryVersionRef{ + ID: item.ID, Kind: string(item.Kind), SnapshotID: item.SnapshotID, VersionLabel: item.VersionLabel, + SourceJobID: item.SourceJobID, CreatedAt: item.CreatedAt, SupersededAt: item.SupersededAt, + }) switch item.Kind { case governance.LibraryVersionProductionEffective: - if item.SupersededAt == nil { - overview.Production = libraryKnownView{State: "known", Version: &view} - } + // 生效状态只认上面那条精确查询;这里只负责把历史行放进列表。 case governance.LibraryVersionProductionPrebackup: - // 只有与目标快照绑定的预备份才算"这次同步前的备份"。 - if target != "" && item.SnapshotID == target { - overview.Prebackup = libraryKnownView{State: "known", Version: &view} + // 页面要显示"最近一次生产写入前的备份",不是"与拟发布快照同内容的那一份": + // 恢复作业登记的是**恢复前**的备份,它和测试封存快照本来就不同; + // 只按目标匹配会让真登记过的预备份显示成"尚未创建"。 + // versions 已按时间倒序,第一份就是最近一次;是否与本次目标同快照另给标志。 + if overview.Prebackup.State != "known" { + overview.Prebackup = libraryKnownView{State: "known", Version: &view, + BoundToTarget: target != "" && item.SnapshotID == target} } } } @@ -740,7 +840,8 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi grant, hasGrant := activeGrantFor(r.Context(), config, scope, target) overview.Authorization = authorizationViewOf(grant, hasGrant) - overview.Gate = librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, target, hasGrant) + // 闸口按当前目标的真实恢复证据判断(没有证据时也接受历史 env 覆盖)。 + overview.Gate = librarySyncGateWithGrant(config.withRestoreEvidence(r.Context(), scope), overview.Production, overview.Prebackup, target, hasGrant) writeJSON(w, http.StatusOK, overview) } @@ -779,7 +880,38 @@ func libraryJobDetailHandler(w http.ResponseWriter, r *http.Request, config Conf writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"}) return } - writeJSON(w, http.StatusOK, map[string]any{"available": true, "job": job}) + detail := map[string]any{"available": true, "job": job} + // 只读诊断:明确"目标现在被谁按着、入口是什么状态、下一步该怎么做"。 + // 这里刻意不提供任何"强制成功/强制开门"的入口:缺归属证据的作业必须停在 + // held,由人工按预备份与校验证据处置(已接受的可用性边界)。 + if maintenanceStore, ok := config.Store.(interface { + LibraryMaintenanceOf(ctx context.Context, scope string) (*postgresstore.LibraryMaintenance, error) + }); ok { + maintenance, maintenanceErr := maintenanceStore.LibraryMaintenanceOf(r.Context(), job.Scope) + if maintenanceErr != nil || maintenance == nil { + writeJSON(w, http.StatusOK, detail) + return + } + held := maintenance.ReleasedAt == nil + detail["maintenance"] = map[string]any{ + "held": held, + "owner_job_id": maintenance.OwnerJobID, + "owner_is_job": maintenance.OwnerJobID == job.ID, + "state": maintenance.State, + "ingress": maintenance.IngressState, + "target_identity": maintenance.TargetIdentity, + "note": maintenance.Note, + "acquired_at": maintenance.AcquiredAt, + "released": !held, + } + if held && job.State == governance.LibraryJobFailed { + detail["next_step"] = "内容可能已写入并通过校验,但收尾未完成:目标仍处于维护、入口未开。按本作业的预备份与校验证据人工核验后再放行;本接口不提供强制成功。" + } + } + if _, ok := detail["next_step"]; !ok && job.State == governance.LibraryJobFailed && job.Recovery != "" { + detail["next_step"] = job.Recovery + } + writeJSON(w, http.StatusOK, detail) } // librarySyncEnqueue 是生产同步的唯一入口:闸口未齐时**不建作业**,直接说明缺项。 @@ -797,6 +929,10 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) { var request struct { Scope string `json:"scope"` Target string `json:"target_snapshot_id"` + // OperationKey 是客户端重放键:同一次意图重发要命中同一个 operation。 + // 不传就是一次新意图(同一个快照再发布一次也必须真的执行)。 + OperationKey string `json:"operation_key"` + SourceID string `json:"source_id"` } if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"}) @@ -807,23 +943,30 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) { return } overview := libraryOverview{Scope: request.Scope} + // 闸口依赖"生产是否已有生效版本":这是**创建**判据,必须精确查。 + // 用窗口列表会把它读成"没有",于是把一次不必要的覆盖当成合法首发; + // 查询失败同样拒绝(fail closed),不猜。 + current, hasCurrent, currentErr := store.LibraryCurrentVersion(r.Context(), request.Scope) + if currentErr != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read current library version"}) + return + } versions, err := store.LibraryVersions(r.Context(), request.Scope, 50) if err != nil { writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"}) return } overview.Production = libraryKnownView{State: "unknown"} + if hasCurrent { + view := libraryVersionViewOf(current) + overview.Production = libraryKnownView{State: "known", Version: &view} + } overview.Prebackup = libraryKnownView{State: "unknown"} - if empty, probeErr := productionScopeEmpty(r.Context(), config, request.Scope); probeErr == nil && empty { - overview.Production = libraryKnownView{State: "unknown", EmptyBaseline: true, - Reason: "生产目标可读且为空:本次是首次发布,写入前仍会生成完整预备份"} + if !hasCurrent { + overview.Production = unknownLibraryTarget(r.Context(), config, request.Scope) } for index := range versions { item := versions[index] - if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil { - view := libraryVersionViewOf(item) - overview.Production = libraryKnownView{State: "known", Version: &view} - } if item.Kind == governance.LibraryVersionProductionPrebackup && request.Target != "" && item.SnapshotID == request.Target { view := libraryVersionViewOf(item) overview.Prebackup = libraryKnownView{State: "known", Version: &view} @@ -847,7 +990,7 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) { return } } - gate := librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, request.Target, hasGrant) + gate := librarySyncGateWithGrant(config.withRestoreEvidence(r.Context(), request.Scope), overview.Production, overview.Prebackup, request.Target, hasGrant) if !gate.SyncAllowed { writeJSON(w, http.StatusServiceUnavailable, map[string]any{ "code": "library_sync_blocked", "reasons": gate.Reasons, @@ -856,6 +999,11 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) { return } + candidate, candidateErr := currentSourceCandidate(r.Context(), config, request.Scope) + if candidateErr != nil || request.SourceID == "" || candidate == nil || candidate.SourceID != request.SourceID || candidate.SnapshotID != request.Target { + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_source_candidate_changed", "error": "来源候选已变化或身份未绑定,请刷新后重试", "detail": errString(candidateErr)}) + return + } // 走到这里说明闸口与证据都齐了才真正建作业;互斥与幂等由数据库索引保证。 digest, err := governance.LibraryRequestDigest(request.Scope, governance.LibraryJobSync, map[string]any{"target_snapshot_id": request.Target}) @@ -869,11 +1017,24 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) { } now := time.Now().UTC() jobID := fmt.Sprintf("libsync-%s-%d", request.Scope, now.UnixNano()) - job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{ + // 意图身份:同一个 operation 的重复请求复用作业;新意图即使目标快照与历史成功相同 + // 也会建新作业并真的执行(F01)。 + intent, intentErr := ensureLibraryIntent(r.Context(), store, request.Scope, governance.LibraryJobSync, + request.Target, digest, actor, request.OperationKey, now) + if intentErr != nil { + if isIntentConflict(intentErr) { + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_intent_conflict", + "error": "同一 operation_key 对应了不同的请求内容:换一个键表示新意图"}) + return + } + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register library intent"}) + return + } + job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{ ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobSync, - IdempotencyKey: "library.sync:" + request.Scope + ":" + request.Target, RequestDigest: digest, + IdempotencyKey: intent.JobKey, RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.Target, Actor: actor, - }, governance.SyncStages(), now) + }, governance.SyncStages(), config.LibraryHandoffEnabled, now) if errors.Is(err, governance.ErrLibraryJobActive) { writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_active", "error": "该目标已有在飞的生产写作业(同步与恢复互斥)"}) @@ -887,15 +1048,16 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) { writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library sync job"}) return } - // 上一次同参数请求失败/被取消后,幂等键不能再把新请求塞回那个死作业里: - // 换一个"重试代次"键重新建作业,旧作业保留为审计记录。 + // 上一次同意图请求失败/被取消后,幂等键不能再把新请求塞回那个死作业里: + // 在**同一个 operation** 下开一个新的执行作业(重试代次),旧作业保留为审计记录。 if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) { - job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{ - ID: fmt.Sprintf("libsync-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope, + job, reused, err = store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{ + ID: fmt.Sprintf("libsync-%s-%d", request.Scope, time.Now().UTC().UnixNano()), Scope: request.Scope, Kind: governance.LibraryJobSync, - IdempotencyKey: "library.sync:" + request.Scope + ":" + request.Target + ":retry:" + now.Format("20060102T150405.000000000"), - RequestDigest: digest, TargetSnapshotID: request.Target, Actor: actor, - }, governance.SyncStages(), now) + IdempotencyKey: intent.JobKey + ":retry:" + now.Format("20060102T150405.000000000"), + RequestDigest: digest, OperationID: intent.Operation.ID, + TargetSnapshotID: request.Target, Actor: actor, + }, governance.SyncStages(), config.LibraryHandoffEnabled, now) if err != nil || reused { writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_retry_conflict", "error": "无法为重试创建新作业", "detail": errString(err)}) @@ -906,27 +1068,14 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) { writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true}) return } - // 业务作业先落库,再投递队列:投递失败就把作业标失败,不留下"看起来在跑"的空作业。 - payload, err := json.Marshal(map[string]string{ - "library_job_id": job.ID, "scope": request.Scope, "target_snapshot_id": request.Target, - }) - if err != nil { - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build sync payload"}) - return - } - queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ - ID: governance.QueueJobIDFor(job.ID), Type: librarySyncJobType, Payload: payload, AvailableAt: now, - MaxAttempts: 1, IdempotencyKey: "library.sync.queue:" + job.ID, - }, now) - if err != nil || queueJob == nil { - log.Printf("library sync enqueue failed job=%s: %v", job.ID, err) - _ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始同步", now) - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue sync job"}) - return - } - if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil { - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach sync job"}) - return - } writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false}) } + +// libraryQueueRequest 决定"这份作业先入哪个队列"。 +// +// 搬运接线时先入 library.snapshot.handoff(capture 角色把快照送到执行器并校验), +// 由它在成功后再入 releaseType;搬运未接线时保持原样。两种情况下 releaseType +// 作业的 ID 都是 QueueJobIDFor(jobID),所以接管/续作的既有路径不受影响。 +func libraryQueueRequest(handoff bool, jobID, scope, snapshotID, releaseType string) (string, string, []byte, error) { + return governance.LibraryQueueRequest(handoff, jobID, scope, snapshotID, releaseType) +} diff --git a/internal/httpapi/library_flow_test.go b/internal/httpapi/library_flow_test.go index b7130b0..352232d 100644 --- a/internal/httpapi/library_flow_test.go +++ b/internal/httpapi/library_flow_test.go @@ -3,6 +3,7 @@ package httpapi import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "strings" @@ -10,6 +11,7 @@ import ( "time" "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" ) // 生产闸口与整库状态契约的针对性测试:不做数据库集成,只验证 @@ -17,6 +19,7 @@ import ( // 复用既有 fakeJobStore 提供 Store 的其余方法,只覆盖整库作业这几个。 type fakeLibraryStore struct { + sourceCandidate *governance.LibraryVersion fakeJobStore grant *governance.LibraryReleaseAuthorization versions []governance.LibraryVersion @@ -24,6 +27,24 @@ type fakeLibraryStore struct { createN int lastJob governance.LibraryJob lastState governance.LibraryJobState + // current 让用例表达"窗口列表里看不到、但精确查询能查到当前生效版本"这一现场形状; + // currentErr 表达"读不到"(调用方必须 fail closed,不许当成没有生效版本)。 + current *governance.LibraryVersion + currentErr error + // operations/lastOperation 记录"意图身份":重放与换键的差别在这里表达(F01)。 + operations map[string]governance.LibraryOperation + lastOperation governance.LibraryOperation + // 续作:resumeOK/resumeErr 驱动存储层结果,resumeCalls 记录每次调用(断言不重复投递)。 + resumeOK bool + resumeErr error + resumeCalls []string + // capture reconciliation fixtures + queue *jobs.Job + stageState string + stageErr error + sealedVersion *governance.LibraryVersion + versionErr error + reconcileDenied bool } func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) { @@ -32,7 +53,29 @@ func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.Li return job, false, nil } +// EnsureLibraryOperation 在 fake 里就是"同键同摘要 ⇒ 同一条意图":测试用例靠它表达 +// "重放命中同意图 / 换键是新意图"(F01),不需要真实库。 +func (f *fakeLibraryStore) EnsureLibraryOperation(_ context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error) { + if f.operations == nil { + f.operations = map[string]governance.LibraryOperation{} + } + if existing, ok := f.operations[op.OperationKey]; ok { + if existing.RequestDigest != op.RequestDigest { + return existing, false, governance.ErrLibraryOperationConflict + } + return existing, false, nil + } + f.operations[op.OperationKey] = op + f.lastOperation = op + return op, true, nil +} + func (f *fakeLibraryStore) LibraryJob(_ context.Context, id string) (governance.LibraryJob, error) { + for _, job := range f.jobs { + if job.ID == id { + return job, nil + } + } return governance.LibraryJob{ID: id}, nil } @@ -61,12 +104,47 @@ func (f *fakeLibraryStore) LibraryVersions(_ context.Context, scope string, _ in return result, nil } +// 当前生效版本是精确查询:这里刻意只按 (scope, kind, 未顶替) 过滤,不模拟分页窗口, +// 与真实 Store 的契约一致(窗口只用于展示列表)。 +func (f *fakeLibraryStore) LibraryCurrentVersion(_ context.Context, scope string) (governance.LibraryVersion, bool, error) { + if f.currentErr != nil { + return governance.LibraryVersion{}, false, f.currentErr + } + if f.current != nil { + return *f.current, true, nil + } + for _, version := range f.versions { + if version.Scope == scope && version.Kind == governance.LibraryVersionProductionEffective && version.SupersededAt == nil { + return version, true, nil + } + } + return governance.LibraryVersion{}, false, nil +} + +func (f *fakeLibraryStore) LibraryVersionOfSnapshot(_ context.Context, scope string, kind governance.LibraryVersionKind, + snapshotID string) (governance.LibraryVersion, bool, error) { + for _, version := range f.versions { + if version.Scope == scope && version.Kind == kind && version.SnapshotID == snapshotID { + return version, true, nil + } + } + return governance.LibraryVersion{}, false, nil +} + func (f *fakeLibraryStore) UpdateLibraryStage(_ context.Context, _, _, _ string, _, _, _, _ *int64, _ string, _ time.Time) error { return nil } -func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState, _, _, _, _, _ string, _ time.Time) error { +func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, _, _, _, snapshotID, _ string, _ time.Time) error { f.lastState = state + for index := range f.jobs { + if f.jobs[index].ID == jobID { + f.jobs[index].State = state + if snapshotID != "" { + f.jobs[index].SnapshotID = snapshotID + } + } + } return nil } @@ -105,6 +183,43 @@ func (f *fakeLibraryStore) CancelLibraryJob(_ context.Context, _, _ string, _ ti return nil } +// 续作走原作业:只有 failed/cancelled 才能回到 pending。 +func (f *fakeLibraryStore) PrepareLibraryJobResume(_ context.Context, jobID string, + _ time.Time) (governance.LibraryJob, bool, error) { + for index, job := range f.jobs { + if job.ID != jobID { + continue + } + if job.State != governance.LibraryJobFailed && job.State != governance.LibraryJobCancelled { + return job, false, nil + } + f.jobs[index].State = governance.LibraryJobPending + return f.jobs[index], true, nil + } + return governance.LibraryJob{}, false, nil +} + +func (f *fakeLibraryStore) ResetQueueJobForResume(_ context.Context, _ string, _ time.Time) error { + return nil +} + +// ResumeLibraryJob 模拟存储层事务语义:结果由 resumeResult 驱动,调用次数可断言"重复请求不重复投递"。 +func (f *fakeLibraryStore) ResumeLibraryJob(_ context.Context, jobID, queueType string, _ time.Time) (governance.LibraryJob, bool, error) { + f.resumeCalls = append(f.resumeCalls, jobID+"/"+queueType) + if f.resumeErr != nil { + return governance.LibraryJob{}, false, f.resumeErr + } + if !f.resumeOK { + return governance.LibraryJob{}, false, nil + } + for _, job := range f.jobs { + if job.ID == jobID { + return job, true, nil + } + } + return governance.LibraryJob{}, false, nil +} + func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) { known := libraryKnownView{State: "known", Version: &libraryVersionView{ID: "v1"}} cases := []struct { @@ -273,8 +388,11 @@ func TestLibrarySyncEnqueueCreatesJobOnlyWithGrant(t *testing.T) { store.enqueueEchoRequestedID = true config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", LibraryCapacityBudgetBytes: 1 << 40} + sourceID := bindSourceFixture(t, &config, store, &target) + digest, _ = librarySyncParamsDigest("internal", target) body := `{"scope":"internal","target_snapshot_id":"` + target + `"}` + body = sourceRequestBody(t, body, sourceID) // 先没有授权 recorder := httptest.NewRecorder() librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config) @@ -305,6 +423,63 @@ func TestLibrarySyncEnqueueCreatesJobOnlyWithGrant(t *testing.T) { } } +// 真实现场(2026-10-29 16:59 的按版本恢复):恢复作业登记了"恢复前备份", +// 但那份备份的内容就是**恢复前**的生产状态,永远不可能等于测试封存快照。 +// 旧逻辑只认"与测试封存同快照的预备份",于是刚备份完就显示"尚未创建/无记录"。 +func TestLibraryOverviewShowsLatestPrebackupWhenTargetDiffers(t *testing.T) { + root := libraryFixtureRoot(t) + sealed := sealSharedVersions(t, root, 1, 4)[0] + now := time.Now().UTC() + store := &fakeLibraryStore{versions: []governance.LibraryVersion{ + {ID: "ver-effective", Scope: "internal", Kind: governance.LibraryVersionProductionEffective, + SnapshotID: "prod-restored-snapshot", CreatedAt: now}, + {ID: "ver-prebackup", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup, + SnapshotID: "snap-before-restore", SourceJobID: "librestore-internal-1", CreatedAt: now.Add(-time.Second)}, + {ID: "ver-sealed", Scope: "internal", Kind: governance.LibraryVersionTestSealed, + SnapshotID: sealed, CreatedAt: now.Add(-2 * time.Hour)}, + }} + config := Config{Store: store, LibraryArchiveRoot: root, LibraryCapacityBudgetBytes: 1 << 30} + bindSourceFixture(t, &config, store, &sealed) + request := httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil) + recorder := httptest.NewRecorder() + libraryOverviewHandler(recorder, request, config) + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d: %s", recorder.Code, recorder.Body.String()) + } + var body struct { + Production libraryKnownView `json:"production"` + Prebackup libraryKnownView `json:"prebackup"` + Versions []libraryVersionRef `json:"versions"` + TestSealed *librarySnapshotView `json:"test_sealed"` + Gate struct { + SyncAllowed bool `json:"sync_allowed"` + Reasons []string `json:"reasons"` + } `json:"gate"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil { + t.Fatalf("decode overview: %v", err) + } + if body.TestSealed == nil || body.TestSealed.SnapshotID != sealed { + t.Fatalf("test sealed candidate must be the registered one: %+v", body.TestSealed) + } + if body.Prebackup.State != "known" || body.Prebackup.Version == nil || + body.Prebackup.Version.ID != "ver-prebackup" || body.Prebackup.Version.SourceJobID != "librestore-internal-1" { + t.Fatalf("latest registered prebackup must be visible with its job: %+v", body.Prebackup) + } + if body.Prebackup.BoundToTarget { + t.Fatal("a restore prebackup is not the publish target snapshot") + } + // 三类版本都要出现在轻量清单里,页面才能给每份归档写对类型。 + if len(body.Versions) != 3 { + t.Fatalf("versions = %+v", body.Versions) + } + for _, reason := range body.Gate.Reasons { + if strings.Contains(reason, "预备份") { + t.Fatalf("a registered prebackup must not be reported as missing: %q", reason) + } + } +} + // 三类版本必须分开读:production_effective 才是生产当前,测试封存不能顶替。 func TestLibraryOverviewKeepsVersionKindsSeparate(t *testing.T) { now := time.Now().UTC() @@ -323,8 +498,9 @@ func TestLibraryOverviewKeepsVersionKindsSeparate(t *testing.T) { t.Fatalf("status = %d: %s", recorder.Code, recorder.Body.String()) } var body struct { - Production libraryKnownView `json:"production"` - Prebackup libraryKnownView `json:"prebackup"` + Production libraryKnownView `json:"production"` + Prebackup libraryKnownView `json:"prebackup"` + Versions []libraryVersionRef `json:"versions"` Diff struct { State string `json:"state"` } `json:"diff"` @@ -338,9 +514,17 @@ func TestLibraryOverviewKeepsVersionKindsSeparate(t *testing.T) { if body.Production.State != "known" || body.Production.Version == nil || body.Production.Version.ID != "ver-prod" { t.Fatalf("production must be the effective version, got %+v", body.Production) } - // 预备份只对匹配目标快照的那一份生效;这里目标为空(归档不可用),所以是未知。 - if body.Prebackup.State != "unknown" { - t.Fatalf("prebackup must stay unknown without a matching target snapshot: %+v", body.Prebackup) + // 预备份按"最近一次生产写入前的备份"显示:归档不可用时没有可匹配的目标, + // 但登记过的预备份必须仍然可见(否则真备份了却显示"尚未创建"), + // 并且明确标出它并不是本次拟发布快照。 + if body.Prebackup.State != "known" || body.Prebackup.Version == nil || body.Prebackup.Version.ID != "ver-backup-other" { + t.Fatalf("registered prebackup must stay visible: %+v", body.Prebackup) + } + if body.Prebackup.BoundToTarget { + t.Fatalf("prebackup must not claim to be the publish target without one: %+v", body.Prebackup) + } + if len(body.Versions) != 3 { + t.Fatalf("overview must expose every registered version kind, got %+v", body.Versions) } if body.Diff.State != "unknown" { t.Fatalf("diff must be unknown until the comparison is wired, got %q", body.Diff.State) @@ -349,3 +533,65 @@ func TestLibraryOverviewKeepsVersionKindsSeparate(t *testing.T) { t.Fatal("gate must stay closed") } } + +// 现场形状:历史把生效版本挤出了展示窗口(LibraryVersions 返回空),但"当前生效版本" +// 精确查询仍读得到它。同步闸口必须据此认为生产已有权威版本: +// 读成"没有"会把一次不必要的覆盖放行,并把人推向"重新建基线"。 +func TestLibrarySyncEnqueueUsesExactCurrentVersionBeyondWindow(t *testing.T) { + target := "snap-1" + digest, err := librarySyncParamsDigest("internal", target) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + store := &fakeLibraryStore{ + // 窗口:故意什么都不返回(模拟生效版本掉出"最近 N 条")。 + versions: []governance.LibraryVersion{}, + current: &governance.LibraryVersion{ID: "ver-prod", Scope: "internal", + Kind: governance.LibraryVersionProductionEffective, SnapshotID: "prod-snap", + VersionLabel: "prod-2026.10", CreatedAt: now.Add(-72 * time.Hour)}, + } + store.enqueueEchoRequestedID = true + store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target, + ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(30 * time.Minute), CreatedAt: now} + config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, + LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", + LibraryCapacityBudgetBytes: 1 << 40} + sourceID := bindSourceFixture(t, &config, store, &target) + digest, _ = librarySyncParamsDigest("internal", target) + body := `{"scope":"internal","target_snapshot_id":"` + target + `"}` + body = sourceRequestBody(t, body, sourceID) + recorder := httptest.NewRecorder() + librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config) + if recorder.Code != http.StatusAccepted { + t.Fatalf("status=%d body=%s(窗口外读到生效版本时闸口不该拒绝)", recorder.Code, recorder.Body.String()) + } + if store.createN != 1 { + t.Fatalf("created=%d, want 1", store.createN) + } +} + +// 读不到当前生效版本时不许猜:fail closed(500)且不创建作业。 +func TestLibrarySyncEnqueueFailsClosedWhenCurrentVersionUnreadable(t *testing.T) { + target := "snap-1" + digest, err := librarySyncParamsDigest("internal", target) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + store := &fakeLibraryStore{currentErr: errors.New("version storage down")} + store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target, + ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(30 * time.Minute), CreatedAt: now} + config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, + LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", + LibraryCapacityBudgetBytes: 1 << 40} + recorder := httptest.NewRecorder() + librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", + strings.NewReader(`{"scope":"internal","target_snapshot_id":"`+target+`"}`)), config) + if recorder.Code != http.StatusInternalServerError { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if store.createN != 0 { + t.Fatalf("created %d jobs while the current version was unreadable", store.createN) + } +} diff --git a/internal/httpapi/library_handoff_queue_test.go b/internal/httpapi/library_handoff_queue_test.go new file mode 100644 index 0000000..85ee73b --- /dev/null +++ b/internal/httpapi/library_handoff_queue_test.go @@ -0,0 +1,52 @@ +package httpapi + +import ( + "encoding/json" + "testing" + + "knowledge-governance/internal/governance" +) + +// 搬运接线时,发布作业必须"先搬运":队列类型换成 handoff,释放作业的 ID 仍是基础 ID。 +func TestLibraryQueueRequestGatesReleaseOnHandoff(t *testing.T) { + jobID := "libsync-internal-1" + snapshot := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + + id, queueType, payload, err := libraryQueueRequest(true, jobID, "internal", snapshot, librarySyncJobType) + if err != nil { + t.Fatal(err) + } + if queueType != libraryHandoffJobType { + t.Fatalf("queue type = %q, want %q", queueType, libraryHandoffJobType) + } + if id != governance.LibraryHandoffQueueJobID(jobID) { + t.Fatalf("handoff queue id = %q", id) + } + // jobs.id 是 varchar(36):交接用的队列作业号必须能真正插进去(曾因拼后缀超长而必失败)。 + if len(id) > 36 { + t.Fatalf("handoff queue id 长度 %d 超过 jobs.id 上限 36", len(id)) + } + var decoded map[string]string + if err := json.Unmarshal(payload, &decoded); err != nil { + t.Fatal(err) + } + if decoded["next_type"] != librarySyncJobType || decoded["target_snapshot_id"] != snapshot { + t.Fatalf("handoff payload = %#v", decoded) + } + + // 未接线:行为与今天完全一致(直接投递发布作业,ID 是基础 ID)。 + id, queueType, payload, err = libraryQueueRequest(false, jobID, "internal", snapshot, libraryRestoreJobType) + if err != nil { + t.Fatal(err) + } + if queueType != libraryRestoreJobType || id != governance.QueueJobIDFor(jobID) { + t.Fatalf("unconfigured queue request = %q %q", queueType, id) + } + decoded = map[string]string{} + if err := json.Unmarshal(payload, &decoded); err != nil { + t.Fatal(err) + } + if _, present := decoded["next_type"]; present { + t.Fatal("release payload must not carry next_type when handoff is off") + } +} diff --git a/internal/httpapi/library_held_detail_r13_test.go b/internal/httpapi/library_held_detail_r13_test.go new file mode 100644 index 0000000..c91c98c --- /dev/null +++ b/internal/httpapi/library_held_detail_r13_test.go @@ -0,0 +1,75 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "knowledge-governance/internal/governance" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +type r13HeldDetailStore struct { + fakeLibraryStore + maintenance *postgresstore.LibraryMaintenance + job governance.LibraryJob +} + +func (s *r13HeldDetailStore) LibraryJob(_ context.Context, id string) (governance.LibraryJob, error) { + job := s.job + job.ID = id + return job, nil +} + +func (s *r13HeldDetailStore) LibraryMaintenanceOf(context.Context, string) (*postgresstore.LibraryMaintenance, error) { + return s.maintenance, nil +} + +// 已接受的边界:缺归属证据的作业停在 held,页面/接口必须给出可核对的 job/operation/目标 +// 与阻断原因,并且**不能**提供"强制成功/强制开门"的动作。 +func TestR13HeldJobDetailExplainsManualRecovery(t *testing.T) { + store := &r13HeldDetailStore{maintenance: &postgresstore.LibraryMaintenance{ + Scope: "internal", OwnerJobID: "job-held", State: "needs_restore", + IngressState: "open", TargetIdentity: "scope=internal", Note: "内容已验证,但收尾未完成", + Services: []string{"app"}, + }} + store.job = governance.LibraryJob{ + Scope: "internal", Kind: governance.LibraryJobSync, State: governance.LibraryJobFailed, + Stage: "finalize", OperationID: "op-r13", AttemptEpoch: 2, + SnapshotID: "backup-r13", TargetSnapshotID: "target-r13", + Error: "内容已验证,但收尾未完成", Recovery: "预备份保留;按归档人工核验", + } + request := httptest.NewRequest(http.MethodGet, "/api/v1/library/jobs/job-held", nil) + request.SetPathValue("id", "job-held") + recorder := httptest.NewRecorder() + libraryJobDetailHandler(recorder, request, Config{Store: store}) + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d body=%s", recorder.Code, recorder.Body.String()) + } + var body map[string]any + if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + job, _ := body["job"].(map[string]any) + if job["operation_id"] != "op-r13" || job["attempt_epoch"] != float64(2) || + job["snapshot_id"] != "backup-r13" || job["target_snapshot_id"] != "target-r13" { + t.Fatalf("作业身份/证据不完整:%v", job) + } + maintenance, _ := body["maintenance"].(map[string]any) + if maintenance["held"] != true || maintenance["owner_is_job"] != true || maintenance["state"] != "needs_restore" { + t.Fatalf("维护状态没有暴露:%v", maintenance) + } + step, _ := body["next_step"].(string) + if !strings.Contains(step, "维护") || !strings.Contains(step, "人工") { + t.Fatalf("下一步没有指向人工核验:%q", step) + } + raw := strings.ToLower(recorder.Body.String()) + for _, banned := range []string{"force_success", "force-open", "force_open", "ignore_unknown", "skip_verify"} { + if strings.Contains(raw, banned) { + t.Fatalf("诊断接口出现了强制动作:%s", banned) + } + } +} diff --git a/internal/httpapi/library_intent.go b/internal/httpapi/library_intent.go new file mode 100644 index 0000000..0293179 --- /dev/null +++ b/internal/httpapi/library_intent.go @@ -0,0 +1,63 @@ +package httpapi + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + + "knowledge-governance/internal/governance" +) + +// libraryIntent 是"用户这一次明确意图"的不可变身份。 +// +// 为什么不能再拿 `library.sync::` 当终身幂等键:那是把**意图**和 +// **目标状态**混成一体。成功同步 B 之后改成 A、再要求同步 B 时,第二次 B 拿到的是第一次 +// 的历史成功作业,什么都不做——用户要的状态没实现,页面还显示成功(F01)。 +// +// 现在:客户端可以用 `operation_key` 重放同一次意图(双击/网络重试 ⇒ 同一个 operation ⇒ +// 同一个作业);不带或换一个键 ⇒ 新意图 ⇒ 新 operation ⇒ 真的执行一遍,并留下自己的 +// 事件与 current 变更。 +type libraryIntent struct { + Operation governance.LibraryOperation + // JobKey 是作业幂等键:同一意图重放得到同一个作业行(不会重复建)。 + JobKey string +} + +// intentCacheKey 把"目标快照 + 客户端意图键"拼成 operation 键: +// 快照参与是因为 operation 的身份必须绑定它发布的是什么;客户端键参与是因为 +// 同一次重放要命中同一条意图。 +func intentCacheKey(snapshotID, clientKey string, now time.Time) string { + base := strings.TrimSpace(snapshotID) + if client := strings.TrimSpace(clientKey); client != "" { + return base + "#" + client + } + // 没有客户端键:每次请求都是一次新意图。用纳秒而不是随机数,便于从日志里回溯。 + return base + "#" + strconv.FormatInt(now.UnixNano(), 10) +} + +// ensureLibraryIntent 幂等登记意图。摘要不一致 ⇒ 冲突(同一个键不许换内容)。 +func ensureLibraryIntent(ctx context.Context, store libraryJobStore, scope string, kind governance.LibraryJobKind, + snapshotID, digest, actor, clientKey string, now time.Time) (libraryIntent, error) { + key := intentCacheKey(snapshotID, clientKey, now) + op, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ + ID: governance.LibraryOperationID(scope, kind, key), Scope: scope, Kind: kind, + TargetSnapshotID: snapshotID, RequestDigest: digest, OperationKey: key, Actor: actor, CreatedAt: now.UTC(), + }) + if err != nil { + return libraryIntent{}, err + } + return libraryIntent{Operation: op, JobKey: "library.job:" + op.ID}, nil +} + +// isIntentConflict 区分"同一个意图键换了内容"(409,调用方应换键)与内部错误。 +func isIntentConflict(err error) bool { + return errors.Is(err, governance.ErrLibraryOperationConflict) +} + +// libraryOperationView 是响应里给前端的意图身份(可复用于重放)。 +func libraryOperationView(intent libraryIntent) map[string]any { + return map[string]any{"operation_id": intent.Operation.ID, "operation_key": intent.Operation.OperationKey, + "target_snapshot_id": intent.Operation.TargetSnapshotID, "kind": string(intent.Operation.Kind)} +} diff --git a/internal/httpapi/library_intent_test.go b/internal/httpapi/library_intent_test.go new file mode 100644 index 0000000..c563884 --- /dev/null +++ b/internal/httpapi/library_intent_test.go @@ -0,0 +1,134 @@ +package httpapi + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +// F01:同一个目标快照的**新意图**必须真的执行,不能被"这个快照曾经成功过"吞掉。 +// +// 现场形状:同步 B 成功 → 恢复 A → 再次同步 B。第三次请求是一次合法意图, +// 旧实现返回第一次的成功作业(202, 不再并入队),用户要的状态没实现。 +// +// 判据:换 operation_key ⇒ 新 operation(ID 不同、作业幂等键不同); +// 同一个 operation_key ⇒ 同一 operation(重放)。 +func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) { + root := libraryFixtureRoot(t) + target := sealSharedVersions(t, root, 1, 4)[0] + digest, err := librarySyncParamsDigest("internal", target) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + newStore := func() *fakeLibraryStore { + store := &fakeLibraryStore{ + current: &governance.LibraryVersion{ID: "ver-prod", Scope: "internal", + Kind: governance.LibraryVersionProductionEffective, SnapshotID: "prod-snap", + VersionLabel: "prod-2026.10", CreatedAt: now.Add(-72 * time.Hour)}, + } + store.enqueueEchoRequestedID = true + store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target, + ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(30 * time.Minute), CreatedAt: now} + return store + } + config := func(store *fakeLibraryStore) Config { + c := Config{Store: store, LibraryArchiveRoot: root, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, + LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", + LibraryCapacityBudgetBytes: 1 << 40} + bindSourceFixture(t, &c, store, &target) + return c + } + post := func(store *fakeLibraryStore, body string) *httptest.ResponseRecorder { + c := config(store) + id, _ := configuredLibrarySource(c, "internal").ID() + body = sourceRequestBody(t, body, id) + recorder := httptest.NewRecorder() + librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", + strings.NewReader(body)), c) + return recorder + } + withKey := `{"scope":"internal","target_snapshot_id":"` + target + `","operation_key":"%s"}` + + // 第一次意图:建作业。 + first := newStore() + if recorder := post(first, strings.Replace(withKey, "%s", "intent-1", 1)); recorder.Code != http.StatusAccepted { + t.Fatalf("首次发布会话 status=%d body=%s", recorder.Code, recorder.Body.String()) + } + firstOperation := first.lastOperation.ID + if firstOperation == "" || first.lastJob.OperationID != firstOperation { + t.Fatalf("作业必须挂在意图上:job.operation=%q intent=%q", first.lastJob.OperationID, firstOperation) + } + + // 同一次意图重放(双击/超时重发):同一个 operation,不产生第二条意图。 + replay := newStore() + if recorder := post(replay, strings.Replace(withKey, "%s", "intent-1", 1)); recorder.Code != http.StatusAccepted { + t.Fatalf("重放 status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if replay.lastOperation.ID != firstOperation { + t.Fatalf("同一意图键得到了不同 operation:%q vs %q", replay.lastOperation.ID, firstOperation) + } + + // 新意图(同一快照、不同键):必须是新 operation ⇒ 新作业幂等键 ⇒ 真的执行。 + second := newStore() + if recorder := post(second, strings.Replace(withKey, "%s", "intent-2", 1)); recorder.Code != http.StatusAccepted { + t.Fatalf("新意图 status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if second.lastOperation.ID == firstOperation { + t.Fatal("同一快照的新意图必须得到新 operation:否则历史成功会吞掉本次请求(F01)") + } + if second.lastJob.IdempotencyKey == first.lastJob.IdempotencyKey { + t.Fatal("新意图的作业幂等键与历史作业相同:CreateLibraryJob 会返回旧作业,什么也不执行") + } + if second.createN != 1 { + t.Fatalf("新意图必须建作业并执行,created=%d", second.createN) + } +} + +// 同一个意图键配上不同快照 = 冲突,不能悄悄共享谱系。 +func TestLibrarySyncIntentKeyReusedWithAnotherSnapshotConflicts(t *testing.T) { + root := libraryFixtureRoot(t) + target := sealSharedVersions(t, root, 1, 4)[0] + digest, _ := librarySyncParamsDigest("internal", target) + now := time.Now().UTC() + store := &fakeLibraryStore{current: &governance.LibraryVersion{ID: "ver-prod", Scope: "internal", + Kind: governance.LibraryVersionProductionEffective, SnapshotID: "prod-snap", CreatedAt: now.Add(-time.Hour)}} + store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target, + ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now} + // 预先登记一条"同键但不同快照"的意图。 + if _, _, err := store.EnsureLibraryOperation(nil, governance.LibraryOperation{ + ID: "libop-x", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: "other-snap", + RequestDigest: "different", OperationKey: target + "#intent-1", CreatedAt: now}); err != nil { + t.Fatal(err) + } + config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, + LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", + LibraryCapacityBudgetBytes: 1 << 40} + config.LibraryArchiveRoot = root + sourceID := bindSourceFixture(t, &config, store, &target) + body := sourceRequestBody(t, `{"scope":"internal","target_snapshot_id":"`+target+`","operation_key":"intent-1"}`, sourceID) + recorder := httptest.NewRecorder() + librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config) + if recorder.Code != http.StatusConflict { + t.Fatalf("同键不同内容必须 409,status=%d body=%s", recorder.Code, recorder.Body.String()) + } +} + +// F14:通用 queue 入口不许创建整库保留类型——那里的角色检查替代不了发布准入。 +func TestCreateJobRejectsReservedLibraryTypes(t *testing.T) { + store := &fakeJobStore{} + config := Config{Store: store} + body := `{"type":"library.baseline","payload":{"scope":"internal"},"idempotency_key":"k-1"}` + recorder := httptest.NewRecorder() + createJob(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/jobs", strings.NewReader(body)), config) + if recorder.Code != http.StatusBadRequest { + t.Fatalf("保留类型必须被通用入口拒绝:status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), "发布管理专用入口") { + t.Fatalf("拒绝原因必须指向专用入口:%s", recorder.Body.String()) + } +} diff --git a/internal/httpapi/library_legacy_source.go b/internal/httpapi/library_legacy_source.go new file mode 100644 index 0000000..1beedcd --- /dev/null +++ b/internal/httpapi/library_legacy_source.go @@ -0,0 +1,48 @@ +package httpapi + +import ( + "context" + "encoding/json" + "io" + "knowledge-governance/internal/governance" + "net/http" + "time" +) + +type libraryLegacySourceBinder interface { + BindLegacyLibrarySource(context.Context, string, string, governance.LibrarySourceIdentity, string, time.Time) error +} + +func libraryLegacySourceBind(w http.ResponseWriter, r *http.Request, config Config) { + identity, ok := sessionFrom(r.Context()) + if !ok || identity.Role != roleAdmin || identity.Username == "" { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "administrator session required"}) + return + } + var input struct { + Scope string `json:"scope"` + SnapshotID string `json:"snapshot_id"` + } + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)) + decoder.DisallowUnknownFields() + if decoder.Decode(&input) != nil || decoder.Decode(new(any)) != io.EOF || (input.Scope != "internal" && input.Scope != "external") || input.SnapshotID == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "exact snapshot and scope required"}) + return + } + source := configuredLibrarySource(config, input.Scope) + sourceID, err := source.ID() + if err != nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": err.Error()}) + return + } + store, ok := config.Store.(libraryLegacySourceBinder) + if !ok { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "source association store unavailable"}) + return + } + if err = store.BindLegacyLibrarySource(r.Context(), input.SnapshotID, config.LibraryArchiveRoot, source, identity.Username, time.Now().UTC()); err != nil { + writeJSON(w, http.StatusConflict, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"snapshot_id": input.SnapshotID, "source_id": sourceID, "source_identity": source, "associated": true, "published": false}) +} diff --git a/internal/httpapi/library_legacy_source_test.go b/internal/httpapi/library_legacy_source_test.go new file mode 100644 index 0000000..9fef8ab --- /dev/null +++ b/internal/httpapi/library_legacy_source_test.go @@ -0,0 +1,67 @@ +package httpapi + +import ( + "context" + "errors" + "knowledge-governance/internal/governance" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +type legacySourceAPIStore struct { + fakeLibraryStore + calls int + actor string + source governance.LibrarySourceIdentity + err error +} + +func (s *legacySourceAPIStore) BindLegacyLibrarySource(_ context.Context, _ string, _ string, source governance.LibrarySourceIdentity, actor string, _ time.Time) error { + s.calls++ + s.actor = actor + s.source = source + return s.err +} +func TestContractLegacySourceAssociationAPI(t *testing.T) { + for _, role := range []string{roleViewer, roleEngineer, roleAdmin} { + store := &legacySourceAPIStore{} + config := Config{Store: store, LibrarySourceProject: "configured-project", LibrarySourceApp: "configured-app", LibrarySourceTenantID: 10000, LibrarySourceInternalKB: "configured-kb"} + request := httptest.NewRequest(http.MethodPost, "/api/v1/library/source-associations", strings.NewReader(`{"scope":"internal","snapshot_id":"exact-snapshot"}`)) + request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "real-session-actor", Role: role})) + response := httptest.NewRecorder() + libraryLegacySourceBind(response, request, config) + if role == roleAdmin { + if response.Code != 200 || store.calls != 1 || store.actor != "real-session-actor" || store.source.Project != "configured-project" || store.source.KnowledgeBaseID != "configured-kb" { + t.Fatal("association contract", response.Code, response.Body.String()) + } + } else if response.Code != 403 || store.calls != 0 { + t.Fatal("non-admin associated source") + } + } + if classifyRole("POST", "/api/v1/library/source-associations") != roleAdmin { + t.Fatal("route is not administrator only") + } +} +func TestContractLegacySourceAssociationAPIRejectsSpoofAndEvidenceFailure(t *testing.T) { + for _, body := range []string{`{"scope":"internal","snapshot_id":"x","actor":"forged"}`, `{"scope":"internal","snapshot_id":"x","source_identity":{"project":"forged"}}`, `{"scope":"internal","snapshot_id":"x"} {}`} { + store := &legacySourceAPIStore{} + req := httptest.NewRequest("POST", "/", strings.NewReader(body)) + req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "admin", Role: roleAdmin})) + out := httptest.NewRecorder() + libraryLegacySourceBind(out, req, Config{Store: store}) + if out.Code != 400 || store.calls != 0 { + t.Fatal("spoofed or trailing payload accepted") + } + } + store := &legacySourceAPIStore{err: errors.New("original proof mismatch")} + req := httptest.NewRequest("POST", "/", strings.NewReader(`{"scope":"internal","snapshot_id":"x"}`)) + req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "admin", Role: roleAdmin})) + out := httptest.NewRecorder() + libraryLegacySourceBind(out, req, Config{Store: store, LibrarySourceProject: "p", LibrarySourceApp: "app", LibrarySourceTenantID: 1, LibrarySourceInternalKB: "kb"}) + if out.Code != 409 { + t.Fatal("unproven association reported success") + } +} diff --git a/internal/httpapi/library_overview_empty_test.go b/internal/httpapi/library_overview_empty_test.go new file mode 100644 index 0000000..104660b --- /dev/null +++ b/internal/httpapi/library_overview_empty_test.go @@ -0,0 +1,102 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "knowledge-governance/internal/governance" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestEmptyTargetOverviewAndEnqueueAgree(t *testing.T) { + for _, failed := range []bool{false, true} { + root := libraryFixtureRoot(t) + target := sealSharedVersions(t, root, 1, 4)[0] + digest, err := librarySyncParamsDigest("internal", target) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + store := &fakeLibraryStore{versions: []governance.LibraryVersion{{ID: "seal", Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: target, CreatedAt: now}}} + store.enqueueEchoRequestedID = true + store.grant = &governance.LibraryReleaseAuthorization{ID: "grant", Scope: "internal", SnapshotID: target, ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now} + config := Config{Store: store, LibraryArchiveRoot: root, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, LibraryProductionDatabaseURL: "postgres://unused.invalid/test", LibraryProductionInternalKB: "kb", LibraryCapacityBudgetBytes: 1 << 40, LibraryScopeProbe: func(context.Context, string) (bool, map[string]int64, error) { + if failed { + return false, nil, errors.New("offline") + } + return true, nil, nil + }} + sourceID := bindSourceFixture(t, &config, store, &target) + rec := httptest.NewRecorder() + libraryOverviewHandler(rec, httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil), config) + var overview libraryOverview + if err := json.Unmarshal(rec.Body.Bytes(), &overview); err != nil { + t.Fatal(err) + } + if overview.Gate.SyncAllowed == failed { + t.Fatalf("failed=%v gate=%+v", failed, overview.Gate) + } + rec = httptest.NewRecorder() + librarySyncEnqueue(rec, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(sourceRequestBody(t, `{"scope":"internal","target_snapshot_id":"`+target+`"}`, sourceID))), config) + if failed { + if rec.Code != http.StatusServiceUnavailable || store.createN != 0 { + t.Fatalf("unreachable target enqueued: %d %s", rec.Code, rec.Body.String()) + } + } else if rec.Code != http.StatusAccepted || store.createN != 1 { + t.Fatalf("empty target rejected: %d %s", rec.Code, rec.Body.String()) + } + } +} + +func TestLibraryOverviewProbesUnknownTarget(t *testing.T) { + for _, tc := range []struct { + name string + empty bool + err error + want string + }{ + {name: "empty", empty: true}, + {name: "nonempty", want: "目标非空"}, + {name: "unreachable", err: errors.New("connection unavailable"), want: "无法读取目标整库状态"}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + config := Config{Store: &fakeLibraryStore{}, LibraryArchiveRoot: t.TempDir(), LibraryScopeProbe: func(ctx context.Context, scope string) (bool, map[string]int64, error) { + calls++ + if scope != "internal" { + t.Fatalf("scope=%s", scope) + } + return tc.empty, nil, tc.err + }} + recorder := httptest.NewRecorder() + libraryOverviewHandler(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil), config) + if recorder.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + var body libraryOverview + if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if calls != 1 { + t.Fatalf("target probe calls=%d, want 1", calls) + } + if body.Production.EmptyBaseline != tc.empty { + t.Fatalf("production=%+v", body.Production) + } + reasons := strings.Join(body.Gate.Reasons, "|") + if tc.want != "" && !strings.Contains(reasons, tc.want) { + t.Fatalf("reasons=%s", reasons) + } + if (tc.empty || tc.err != nil) && strings.Contains(reasons, "目标非空") { + t.Fatalf("not proven nonempty: %s", reasons) + } + if body.Gate.SyncAllowed { + t.Fatal("empty target must not bypass authorization and write gates") + } + }) + } +} diff --git a/internal/httpapi/library_read_paths_test.go b/internal/httpapi/library_read_paths_test.go index 0944c5f..f54d3c9 100644 --- a/internal/httpapi/library_read_paths_test.go +++ b/internal/httpapi/library_read_paths_test.go @@ -266,3 +266,25 @@ func TestLibraryReadPathsRejectTamperedManifest(t *testing.T) { t.Fatalf("storage must fail closed: status=%d body=%s", recorder.Code, recorder.Body.String()) } } + +// F11: the HTTP projection must include binding and Wiki log counts; the +// previous projection silently omitted them and the UI turned absence into 0. +func TestLibrarySnapshotTotalsIncludeBindingsAndWikiLogs(t *testing.T) { + view := librarySnapshotViewOfNoUsage("snap-totals", librarysnapshot.Manifest{ + Scope: "internal", KnowledgeBaseID: "kb", TenantID: 10000, + Parts: []librarysnapshot.Part{ + {Kind: "database", Name: "knowledges", Count: 4}, + {Kind: "database", Name: "chunks", Count: 38}, + {Kind: "database", Name: "resources", Count: 21}, + {Kind: "database", Name: "resource_bindings", Count: 4}, + {Kind: "wiki", Name: "wiki_pages", Count: 31}, + {Kind: "wiki", Name: "wiki_folders", Count: 21}, + {Kind: "wiki", Name: "wiki_log_entries", Count: 11}, + }, + }) + for key, want := range map[string]int64{"documents": 4, "chunks": 38, "resources": 21, "bindings": 4, "wiki_pages": 31, "wiki_folders": 21, "wiki_log_entries": 11} { + if view.Totals[key] != want { + t.Fatalf("totals[%s]=%d want=%d (%v)", key, view.Totals[key], want, view.Totals) + } + } +} diff --git a/internal/httpapi/library_restore.go b/internal/httpapi/library_restore.go index 3e1239f..3b40884 100644 --- a/internal/httpapi/library_restore.go +++ b/internal/httpapi/library_restore.go @@ -4,13 +4,13 @@ import ( "context" "encoding/json" "errors" + "knowledge-governance/internal/platform/postgres" "net/http" "strconv" "strings" "time" "knowledge-governance/internal/governance" - "knowledge-governance/internal/jobs" ) // 按指定整库版本恢复:与同步分开的作业类型,需要**单独的管理员授权**, @@ -25,6 +25,8 @@ func libraryRestoreParamsDigest(scope, snapshotID string) (string, error) { type libraryRestoreRequest struct { Scope string `json:"scope"` SnapshotID string `json:"snapshot_id"` + // OperationKey 是客户端重放键;不传就是一次新意图(同一快照再恢复一次也要真的执行)。 + OperationKey string `json:"operation_key"` } func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config) { @@ -69,9 +71,7 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config if !config.ProductionReleaseRequestsEnabled { reasons = append(reasons, "生产写入闸口关闭") } - if !config.ProductionBackupRestoreVerified { - reasons = append(reasons, "没有已核验的生产恢复演练证据") - } + reasons = append(reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), request.Scope))...) authorizationOK := false if storeWithAuth, ok := config.Store.(interface { ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, digest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error) @@ -91,11 +91,23 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config // [A-Za-z0-9_-]:带 "." 的时间戳会让恢复在开窗口时被拒(真跑报 invalid freeze request), // 所以用纳秒整数,和同步作业保持一致。 jobID := "librestore-" + request.Scope + "-" + strconv.FormatInt(now.UnixNano(), 10) - job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{ + intent, intentErr := ensureLibraryIntent(r.Context(), store, request.Scope, governance.LibraryJobRestore, + request.SnapshotID, digest, identity.Username, request.OperationKey, now) + if intentErr != nil { + if isIntentConflict(intentErr) { + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_intent_conflict", + "error": "同一 operation_key 对应了不同的请求内容:换一个键表示新意图"}) + return + } + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register restore intent"}) + return + } + job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{ ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobRestore, - IdempotencyKey: "library.restore:" + request.Scope + ":" + request.SnapshotID, - RequestDigest: digest, TargetSnapshotID: request.SnapshotID, Actor: identity.Username, - }, governance.SyncStages(), now) + IdempotencyKey: intent.JobKey, + RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.SnapshotID, + Actor: identity.Username, + }, governance.SyncStages(), config.LibraryHandoffEnabled, now) if errors.Is(err, governance.ErrLibraryJobActive) { writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_active", "error": "该目标已有在飞作业"}) return @@ -109,11 +121,12 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config return } if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) { - job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{ + job, reused, err = store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{ ID: jobID + "-retry", Scope: request.Scope, Kind: governance.LibraryJobRestore, - IdempotencyKey: "library.restore:" + request.Scope + ":" + request.SnapshotID + ":retry:" + strconv.FormatInt(now.UnixNano(), 10), - RequestDigest: digest, TargetSnapshotID: request.SnapshotID, Actor: identity.Username, - }, governance.SyncStages(), now) + IdempotencyKey: intent.JobKey + ":retry:" + strconv.FormatInt(now.UnixNano(), 10), + RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.SnapshotID, + Actor: identity.Username, + }, governance.SyncStages(), config.LibraryHandoffEnabled, now) if err != nil || reused { writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_retry_conflict", "error": "无法为重试创建新作业"}) return @@ -123,26 +136,6 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true}) return } - payload, err := json.Marshal(map[string]string{ - "library_job_id": job.ID, "scope": request.Scope, "target_snapshot_id": request.SnapshotID, - }) - if err != nil { - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build restore payload"}) - return - } - queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ - ID: governance.QueueJobIDFor(job.ID), Type: libraryRestoreJobType, Payload: payload, AvailableAt: now, - MaxAttempts: 1, IdempotencyKey: "library.restore.queue:" + job.ID, - }, now) - if err != nil || queueJob == nil { - _ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始恢复", now) - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue restore job"}) - return - } - if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil { - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach restore job"}) - return - } writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false}) } @@ -174,9 +167,7 @@ func libraryRestoreAvailability(w http.ResponseWriter, r *http.Request, config C if !config.ProductionReleaseRequestsEnabled { view.Reasons = append(view.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)") } - if !config.ProductionBackupRestoreVerified { - view.Reasons = append(view.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)") - } + view.Reasons = append(view.Reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), scope))...) digest, err := libraryRestoreParamsDigest(scope, snapshotID) if err != nil { writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest params"}) @@ -233,9 +224,7 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) { if !config.ProductionReleaseRequestsEnabled { reasons = append(reasons, "生产写入闸口关闭") } - if !config.ProductionBackupRestoreVerified { - reasons = append(reasons, "没有已核验的生产恢复演练证据") - } + reasons = append(reasons, restoreGateReasons(config.withRestoreEvidence(r.Context(), source.Scope))...) var digest string switch source.Kind { case governance.LibraryJobSync: @@ -260,61 +249,63 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) { } now := time.Now().UTC() - // 幂等键按源作业固定:重复点击返回同一个续作作业,而不是每次新建。 - jobID := sourceID + "-resume" - var kind governance.LibraryJobKind queueType := "" switch source.Kind { case governance.LibraryJobSync: - kind, queueType = governance.LibraryJobSync, librarySyncJobType + queueType = librarySyncJobType case governance.LibraryJobRestore: - kind, queueType = governance.LibraryJobRestore, libraryRestoreJobType + queueType = libraryRestoreJobType default: writeJSON(w, http.StatusConflict, map[string]any{"error": "封存作业由封存入口重发,不走续作"}) return } - job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{ - ID: jobID, Scope: source.Scope, Kind: kind, - IdempotencyKey: "library.resume:" + sourceID, - RequestDigest: digest, TargetSnapshotID: source.TargetSnapshotID, Actor: identity.Username, - }, governance.SyncStages(), now) - if errors.Is(err, governance.ErrLibraryJobActive) { - writeJSON(w, http.StatusConflict, map[string]any{"error": "该目标已有在飞作业"}) + // R3:续作沿用**原业务作业**,只新增执行代次。 + // + // 维护窗口 owner_job_id、freeze journal 文件名、预备份与写集合的身份全部按业务作业 + // id 落盘。另建 `-resume` 作业只能继承 operation,其它所有者仍指向旧作业: + // AcquireInstanceMaintenance 会拒绝它、journal 与预备份也查不到——那样"续作"只是 + // 一个漂亮的新行,接不上原窗口。原作业 + 新 attempt 才是批准协议的形状。 + // 阶段/状态/执行权与载荷全部在存储层的事务里校验并构造:handler 手里的 source 只用于 + // 授权与闸口判断,不参与续作决策,避免用过期快照复活一个已经变化的作业。 + resumer, ok := config.Store.(interface { + ResumeLibraryJob(ctx context.Context, jobID, queueType string, now time.Time) (governance.LibraryJob, bool, error) + }) + if !ok { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "作业存储不支持续作"}) return } - if errors.Is(err, governance.ErrLibraryJobIdempotencyConflict) { - writeJSON(w, http.StatusConflict, map[string]any{"error": "同一续作请求参数不一致"}) + prepared, resumed, err := resumer.ResumeLibraryJob(r.Context(), sourceID, queueType, now) + switch { + case errors.Is(err, postgres.ErrLibraryResumeBusy): + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_busy", + "error": "该作业已有执行在跑(租约仍有效),等它结束再续作"}) + return + case errors.Is(err, postgres.ErrLibraryResumeRequiresRecover): + // 窗口是否仍被持有由维护记录决定:已释放的回滚作业说"窗口已释放",不能一律宣称仍持有。 + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_requires_recover", + "error": "作业停在回滚阶段,请走维护恢复而不是续作", + "maintenance_held": maintenanceHeldFor(r.Context(), config, source)}) + return + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot resume job"}) + return + case !resumed: + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_state_changed", + "error": "作业已不在可续作状态(可能已被接管或完成)"}) return } - if err != nil { - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create resumed job"}) - return - } - if reused { - writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "resumed_from": sourceID, "reused": true}) - return - } - // 写入已完成、只差登记版本的情况:续作只做幂等收尾,不重写生产。 - body := map[string]any{"library_job_id": job.ID, "scope": source.Scope, - "target_snapshot_id": source.TargetSnapshotID} - if source.Stage == "finalize" && source.SnapshotID != "" { - body["finalize_only"] = true - } - payload, _ := json.Marshal(body) - queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ - ID: governance.QueueJobIDFor(job.ID), Type: queueType, Payload: payload, AvailableAt: now, - MaxAttempts: 1, IdempotencyKey: "library.resume.queue:" + job.ID, - }, now) - if err != nil || queueJob == nil { - _ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败", now) - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue resumed job"}) - return - } - // 附不上队列号就等于作业没人跑:必须显式失败并取消,不能静默返回 202。 - if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil { - _ = store.CancelLibraryJob(r.Context(), job.ID, "队列归属写入失败", now) - writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach resumed job"}) - return - } - writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "resumed_from": sourceID, "reused": false}) + writeJSON(w, http.StatusAccepted, map[string]any{"job": prepared, "resumed_from": sourceID, + "resumed": true, "next_attempt_epoch": prepared.AttemptEpoch + 1}) +} + +// maintenanceHeldFor 只回答"这个作业现在是否仍持有维护窗口",用于给回滚作业的拒绝文案定性。 +func maintenanceHeldFor(ctx context.Context, config Config, job governance.LibraryJob) bool { + reader, ok := config.Store.(interface { + LibraryMaintenanceOf(ctx context.Context, scope string) (*postgres.LibraryMaintenance, error) + }) + if !ok { + return false + } + m, err := reader.LibraryMaintenanceOf(ctx, job.Scope) + return err == nil && m != nil && m.OwnerJobID == job.ID && m.ReleasedAt == nil } diff --git a/internal/httpapi/library_resume_r26_test.go b/internal/httpapi/library_resume_r26_test.go new file mode 100644 index 0000000..b570d50 --- /dev/null +++ b/internal/httpapi/library_resume_r26_test.go @@ -0,0 +1,118 @@ +package httpapi + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/platform/postgres" +) + +func resumeRequest(id string) *http.Request { + request := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+id+"/resume", nil) + request.SetPathValue("id", id) + return request.WithContext(context.WithValue(request.Context(), sessionKey{}, + sessionIdentity{Username: "admin", Role: roleAdmin})) +} + +func resumableStore(job governance.LibraryJob) *fakeLibraryStore { + now := time.Now().UTC() + digest, _ := librarySyncParamsDigest(job.Scope, job.TargetSnapshotID) + if job.Kind == governance.LibraryJobRestore { + digest, _ = libraryRestoreParamsDigest(job.Scope, job.TargetSnapshotID) + } + store := &fakeLibraryStore{ + jobs: []governance.LibraryJob{job}, + grant: &governance.LibraryReleaseAuthorization{ID: "a", Scope: job.Scope, + SnapshotID: job.TargetSnapshotID, ParamsDigest: digest, ExpiresAt: now.Add(time.Hour), CreatedAt: now}, + } + store.resumeOK = true + return store +} + +func resumeConfig(store *fakeLibraryStore) Config { + return Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true} +} + +// 合法续作:202,并且只投递一次。 +func TestR26ResumeAcceptedDeliversOnce(t *testing.T) { + job := governance.LibraryJob{ID: "job-ok", Scope: "internal", Kind: governance.LibraryJobSync, + State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"} + store := resumableStore(job) + recorder := httptest.NewRecorder() + libraryJobResume(recorder, resumeRequest("job-ok"), resumeConfig(store)) + if recorder.Code != http.StatusAccepted { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if len(store.resumeCalls) != 1 || store.resumeCalls[0] != "job-ok/library.sync" { + t.Fatalf("resume calls=%v", store.resumeCalls) + } +} + +// 回滚阶段的作业:409,且文案不能一律宣称"仍持有维护窗口"(窗口可能已释放)。 +func TestR26ResumeRollbackStageRequiresRecover(t *testing.T) { + job := governance.LibraryJob{ID: "job-rb", Scope: "internal", Kind: governance.LibraryJobRestore, + State: governance.LibraryJobFailed, Stage: "rollback", TargetSnapshotID: "snap-1"} + store := resumableStore(job) + store.resumeErr = postgres.ErrLibraryResumeRequiresRecover + recorder := httptest.NewRecorder() + libraryJobResume(recorder, resumeRequest("job-rb"), resumeConfig(store)) + if recorder.Code != http.StatusConflict || !strings.Contains(recorder.Body.String(), "library_resume_requires_recover") { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if strings.Contains(recorder.Body.String(), "保留维护窗口") { + t.Fatalf("must not always claim the window is held: %s", recorder.Body.String()) + } +} + +// 租约仍有效:409 busy,不是 500。 +func TestR26ResumeBusyIsConflict(t *testing.T) { + job := governance.LibraryJob{ID: "job-busy", Scope: "internal", Kind: governance.LibraryJobSync, + State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"} + store := resumableStore(job) + store.resumeErr = postgres.ErrLibraryResumeBusy + recorder := httptest.NewRecorder() + libraryJobResume(recorder, resumeRequest("job-busy"), resumeConfig(store)) + if recorder.Code != http.StatusConflict || !strings.Contains(recorder.Body.String(), "library_resume_busy") { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } +} + +// 入队失败(存储层事务回滚):500,且不得把作业当成已续作。 +func TestR26ResumeEnqueueFailureIsServerError(t *testing.T) { + job := governance.LibraryJob{ID: "job-fail", Scope: "internal", Kind: governance.LibraryJobRestore, + State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"} + store := resumableStore(job) + store.resumeErr = errors.New("enqueue resumed job: injected") + recorder := httptest.NewRecorder() + libraryJobResume(recorder, resumeRequest("job-fail"), resumeConfig(store)) + if recorder.Code != http.StatusInternalServerError { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if strings.Contains(recorder.Body.String(), "resumed") { + t.Fatalf("failed enqueue must not claim success: %s", recorder.Body.String()) + } +} + +// 重复请求:第二次被存储层拒绝(状态已推进),不会重复投递。 +func TestR26ResumeDuplicateRequestDoesNotRedeliver(t *testing.T) { + job := governance.LibraryJob{ID: "job-dup", Scope: "internal", Kind: governance.LibraryJobSync, + State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"} + store := resumableStore(job) + first := httptest.NewRecorder() + libraryJobResume(first, resumeRequest("job-dup"), resumeConfig(store)) + store.resumeOK = false // 第二次:业务作业已不是 failed + second := httptest.NewRecorder() + libraryJobResume(second, resumeRequest("job-dup"), resumeConfig(store)) + if first.Code != http.StatusAccepted || second.Code != http.StatusConflict { + t.Fatalf("first=%d second=%d body=%s", first.Code, second.Code, second.Body.String()) + } + if len(store.resumeCalls) != 2 { + t.Fatalf("expected 2 store calls, got %v", store.resumeCalls) + } +} diff --git a/internal/httpapi/library_snapshots.go b/internal/httpapi/library_snapshots.go index bbdab31..096bd3d 100644 --- a/internal/httpapi/library_snapshots.go +++ b/internal/httpapi/library_snapshots.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "knowledge-governance/internal/governance" "knowledge-governance/internal/librarysnapshot" ) @@ -28,19 +29,21 @@ type librarySnapshotPart struct { } type librarySnapshotView struct { - SnapshotID string `json:"snapshot_id"` - Scope string `json:"scope"` - KnowledgeBaseID string `json:"knowledge_base_id"` - TenantID uint64 `json:"tenant_id"` - CreatedAt time.Time `json:"created_at"` - ValidationPolicy string `json:"validation_policy"` - Format string `json:"format"` - Compatibility librarysnapshot.Compatibility `json:"compatibility"` - Parts []librarySnapshotPart `json:"parts"` - LogicalBytes int64 `json:"logical_bytes"` - UniqueBytes int64 `json:"unique_bytes"` - SharedBytes int64 `json:"shared_bytes"` - Totals map[string]int64 `json:"totals"` + SourceID string `json:"source_id,omitempty"` + SourceIdentity *governance.LibrarySourceIdentity `json:"source_identity,omitempty"` + SnapshotID string `json:"snapshot_id"` + Scope string `json:"scope"` + KnowledgeBaseID string `json:"knowledge_base_id"` + TenantID uint64 `json:"tenant_id"` + CreatedAt time.Time `json:"created_at"` + ValidationPolicy string `json:"validation_policy"` + Format string `json:"format"` + Compatibility librarysnapshot.Compatibility `json:"compatibility"` + Parts []librarySnapshotPart `json:"parts"` + LogicalBytes int64 `json:"logical_bytes"` + UniqueBytes int64 `json:"unique_bytes"` + SharedBytes int64 `json:"shared_bytes"` + Totals map[string]int64 `json:"totals"` // Verified 只在这一份版本的每个部件都被重新哈希并核对通过时为 true。 // 列表口径下它恒为 false:枚举只证明清单可读,不是"完整性已验证"。 Verified bool `json:"verified"` @@ -258,10 +261,14 @@ func librarySnapshotViewOfNoUsage(id string, manifest librarysnapshot.Manifest) } case "resources": snapshot.Totals["resources"] = part.Count + case "resource_bindings": + snapshot.Totals["bindings"] = part.Count case "wiki_pages": snapshot.Totals["wiki_pages"] = part.Count case "wiki_folders": snapshot.Totals["wiki_folders"] = part.Count + case "wiki_log_entries": + snapshot.Totals["wiki_log_entries"] = part.Count } } sort.Slice(snapshot.Parts, func(i, j int) bool { diff --git a/internal/httpapi/library_source_candidate.go b/internal/httpapi/library_source_candidate.go new file mode 100644 index 0000000..23189bc --- /dev/null +++ b/internal/httpapi/library_source_candidate.go @@ -0,0 +1,58 @@ +package httpapi + +import ( + "context" + "errors" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" +) + +type librarySourceCandidateStore interface { + LibrarySourceCandidate(context.Context, string, string) (governance.LibraryVersion, bool, error) +} + +func configuredLibrarySource(config Config, scope string) governance.LibrarySourceIdentity { + kb := config.LibrarySourceInternalKB + if scope == "external" { + kb = config.LibrarySourceExternalKB + } + return governance.LibrarySourceIdentity{Project: config.LibrarySourceProject, App: config.LibrarySourceApp, Scope: scope, TenantID: config.LibrarySourceTenantID, KnowledgeBaseID: kb} +} + +func currentSourceCandidate(ctx context.Context, config Config, scope string) (*librarySnapshotView, error) { + source := configuredLibrarySource(config, scope) + id, err := source.ID() + if err != nil { + return nil, err + } + store, ok := config.Store.(librarySourceCandidateStore) + if !ok { + return nil, errors.New("source candidate exact query unavailable") + } + candidate, found, err := store.LibrarySourceCandidate(ctx, scope, id) + if err != nil { + return nil, err + } + if !found { + return nil, errors.New("当前来源没有已绑定封存;旧快照须以原捕获证据核验关联,不能继承其他来源") + } + if candidate.Kind != governance.LibraryVersionTestSealed || candidate.Scope != scope || candidate.Evidence["source_id"] != id { + return nil, errors.New("candidate source binding mismatch") + } + archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024) + if err != nil { + return nil, err + } + defer archive.Close() + manifest, err := archive.Load(candidate.SnapshotID) + if err != nil { + return nil, err + } + if manifest.Scope != scope || manifest.TenantID != source.TenantID || manifest.KnowledgeBaseID != source.KnowledgeBaseID { + return nil, errors.New("candidate manifest differs from configured source") + } + view := librarySnapshotViewOfNoUsage(candidate.SnapshotID, manifest) + view.SourceID = id + view.SourceIdentity = &source + return &view, nil +} diff --git a/internal/httpapi/library_source_contract_test.go b/internal/httpapi/library_source_contract_test.go new file mode 100644 index 0000000..afee0f9 --- /dev/null +++ b/internal/httpapi/library_source_contract_test.go @@ -0,0 +1,23 @@ +package httpapi + +import ( + "knowledge-governance/internal/governance" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestContractSyncRejectsUnboundSourceBeforeCreatingJob(t *testing.T) { + store := &fakeLibraryStore{current: &governance.LibraryVersion{SnapshotID: "current"}, grant: &governance.LibraryReleaseAuthorization{Scope: "internal", SnapshotID: "foreign", ExpiresAt: time.Now().Add(time.Hour)}} + digest, _ := librarySyncParamsDigest("internal", "foreign") + store.grant.ParamsDigest = digest + config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, LibraryProductionDatabaseURL: "postgres://unreachable.invalid/db", LibraryCapacityBudgetBytes: 1 << 40} + request := httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(`{"scope":"internal","target_snapshot_id":"foreign"}`)) + response := httptest.NewRecorder() + librarySyncEnqueue(response, request, config) + if store.createN != 0 { + t.Fatalf("unbound foreign source created %d jobs; response=%s", store.createN, response.Body.String()) + } +} diff --git a/internal/httpapi/library_source_fixture_test.go b/internal/httpapi/library_source_fixture_test.go new file mode 100644 index 0000000..705a188 --- /dev/null +++ b/internal/httpapi/library_source_fixture_test.go @@ -0,0 +1,63 @@ +package httpapi + +import ( + "context" + "encoding/json" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" + "testing" +) + +func (f *fakeLibraryStore) LibrarySourceCandidate(_ context.Context, scope, sourceID string) (governance.LibraryVersion, bool, error) { + if f.sourceCandidate != nil && f.sourceCandidate.Scope == scope && f.sourceCandidate.Evidence["source_id"] == sourceID { + return *f.sourceCandidate, true, nil + } + return governance.LibraryVersion{}, false, nil +} + +// These fixtures now contain the same capture identity and real immutable +// manifest required by the production admission path. No production bypass. +func bindSourceFixture(t *testing.T, config *Config, store *fakeLibraryStore, target *string) string { + t.Helper() + if config.LibraryArchiveRoot == "" { + config.LibraryArchiveRoot = libraryFixtureRoot(t) + *target = sealSharedVersions(t, config.LibraryArchiveRoot, 1, 4)[0] + } + archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + manifest, err := archive.Load(*target) + if err != nil { + t.Fatal(err) + } + config.LibrarySourceProject = "fixture-project" + config.LibrarySourceApp = "fixture-app" + config.LibrarySourceTenantID = manifest.TenantID + config.LibrarySourceInternalKB = manifest.KnowledgeBaseID + source := configuredLibrarySource(*config, "internal") + id, err := source.ID() + if err != nil { + t.Fatal(err) + } + store.sourceCandidate = &governance.LibraryVersion{Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: *target, Evidence: map[string]any{"source_id": id}} + if store.grant != nil { + store.grant.SnapshotID = *target + store.grant.ParamsDigest, _ = librarySyncParamsDigest("internal", *target) + } + return id +} +func sourceRequestBody(t *testing.T, body, id string) string { + t.Helper() + var v map[string]any + if err := json.Unmarshal([]byte(body), &v); err != nil { + t.Fatal(err) + } + v["source_id"] = id + raw, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + return string(raw) +} diff --git a/internal/httpapi/library_storage.go b/internal/httpapi/library_storage.go index a802db1..a8a3b86 100644 --- a/internal/httpapi/library_storage.go +++ b/internal/httpapi/library_storage.go @@ -1,6 +1,7 @@ package httpapi import ( + "context" "net/http" "sort" "strings" @@ -96,36 +97,47 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config // 版本类型与保护依据来自持久登记与在飞作业,不靠文件时间猜。 kinds := map[string]governance.LibraryVersion{} protectedBy := map[string][]string{} + protectionUnknown := false store, storeOK := libraryStore(config) if storeOK { + // 类型与保护依据只认**持久登记**的精确查询:分页窗口(最近 100 个版本/20 个作业) + // 一旦被历史挤满,需要恢复的旧预备份与 failed-but-held 作业就会被读成"可删除候选"(F10)。 for _, scope := range []string{"internal", "external"} { versions, listErr := store.LibraryVersions(r.Context(), scope, 100) - if listErr == nil { - for _, item := range versions { - kinds[item.SnapshotID] = item - if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil { - protectedBy[item.SnapshotID] = append(protectedBy[item.SnapshotID], "生产生效版本") - } - if item.Kind == governance.LibraryVersionProductionPrebackup { - protectedBy[item.SnapshotID] = append(protectedBy[item.SnapshotID], "生产预备份") - } - } + if listErr != nil { + protectionUnknown = true + continue } - jobs, jobErr := store.ListLibraryJobs(r.Context(), scope, 20) - if jobErr == nil { - for _, job := range jobs { - if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning { - continue - } - for _, id := range []string{job.SnapshotID, job.TargetSnapshotID} { - if id != "" { - protectedBy[id] = append(protectedBy[id], "在飞作业引用") - } - } + for _, item := range versions { + kinds[item.SnapshotID] = item + } + if current, found, currentErr := store.LibraryCurrentVersion(r.Context(), scope); currentErr == nil && found { + if _, seen := kinds[current.SnapshotID]; !seen { + kinds[current.SnapshotID] = current } + } else if currentErr != nil { + protectionUnknown = true } } + if protector, ok := config.Store.(interface { + LibraryProtection(ctx context.Context) (map[string][]string, error) + }); ok { + if reasons, protectErr := protector.LibraryProtection(r.Context()); protectErr == nil { + for snapshot, items := range reasons { + for _, reason := range items { + protectedBy[snapshot] = appendUnique(protectedBy[snapshot], reason) + } + } + } else { + protectionUnknown = true + response.Notes = append(response.Notes, "保护依据读取失败("+protectErr.Error()+"):本次不生成可删除候选") + } + } else { + protectionUnknown = true + response.Notes = append(response.Notes, "存储不支持全量保护查询:本次不生成可删除候选") + } } else { + protectionUnknown = true response.Notes = append(response.Notes, "版本登记存储不可用:只按归档文件统计,无法识别受保护版本") } @@ -143,11 +155,11 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config } for index, id := range ids { manifest := manifests[index] + // 备份类型只能来自显式登记:非空 ValidationPolicy 也被生产预备份使用, + // 拿它猜类型会把生产预备份显示成测试封存(F10)。 kind := "unregistered" if record, ok := kinds[id]; ok { kind = string(record.Kind) - } else if manifest.ValidationPolicy != "" { - kind = "test_sealed" } if kind == "test_sealed" { // 每库最近一次封存受保护:它是最新可发布的测试版本。 @@ -165,14 +177,19 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config // 用与上面相同的清单再定位一次最新测试封存,避免把时间映射回 ID 时出错。 for index, id := range ids { manifest := manifests[index] - if kindOf := kinds[id].Kind; kindOf == governance.LibraryVersionTestSealed || - (kindOf == "" && manifest.ValidationPolicy != "") { + if kindOf := kinds[id].Kind; kindOf == governance.LibraryVersionTestSealed { if manifest.CreatedAt.Equal(latestSealed[manifest.Scope]) { - protectedBy[id] = append(protectedBy[id], "最近测试封存("+manifest.Scope+")") + protectedBy[id] = appendUnique(protectedBy[id], "最近测试封存("+manifest.Scope+")") } } } + if protectionUnknown { + // 保护依据未知 ⇒ 不许产出"可删除候选":不确定的东西不能按可删处理(fail closed)。 + for index := range versions { + protectedBy[versions[index].ID] = appendUnique(protectedBy[versions[index].ID], "保护依据未知(拒绝生成可删候选)") + } + } for index := range versions { if reasons := protectedBy[versions[index].ID]; len(reasons) > 0 { versions[index].Protected = true @@ -205,3 +222,14 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config response.Capacity = libraryretention.CheckCapacity(total.ContentBytes, requiredBytes, config.LibraryCapacityBudgetBytes) writeJSON(w, http.StatusOK, response) } + +// appendUnique 只追加还没出现过的标签:同一条版本可能同时被展示窗口与精确查询命中, +// 重复标签会让"保护依据"看起来像两条不同理由。 +func appendUnique(labels []string, value string) []string { + for _, item := range labels { + if item == value { + return labels + } + } + return append(labels, value) +} diff --git a/internal/httpapi/library_verify.go b/internal/httpapi/library_verify.go new file mode 100644 index 0000000..3ffdff7 --- /dev/null +++ b/internal/httpapi/library_verify.go @@ -0,0 +1,328 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "knowledge-governance/internal/governance" +) + +// 恢复验证:页面点一次"跑恢复验证",后端建一个持久作业,worker 用与 CLI 同一份实现 +// (internal/libraryverify)真实执行:捕获目标 → 基线校验 → 写 canary 证明校验有效 → +// 按预备份恢复 → 恢复后复核。通过与否只由这条证据表回答,页面不接受手填开关。 +const libraryVerifyJobType = "library.verify" + +type libraryVerifyRequest struct { + Scope string `json:"scope"` +} + +// libraryVerificationView 是页面需要的全部事实:当前目标是谁、最近一次验证结果、 +// 证据是否对当前目标成立、以及同步闸口能不能据此放行。 +type libraryVerificationView struct { + Scope string `json:"scope"` + Target libraryVerificationTarget `json:"target"` + Verified bool `json:"verified"` + Reason string `json:"reason"` + Latest *governance.LibraryRestoreVerification `json:"latest,omitempty"` + // SnapshotLatest 只在请求显式带 snapshot_id 时返回:快照报告不能拿 scope + // 最近一条代替。 + SnapshotLatest *governance.LibraryRestoreVerification `json:"snapshot_latest,omitempty"` + History []governance.LibraryRestoreVerification `json:"history"` + Running bool `json:"running"` + JobID string `json:"job_id,omitempty"` + State string `json:"state,omitempty"` + Stage string `json:"stage,omitempty"` +} + +type libraryVerificationTarget struct { + Instance string `json:"instance"` + Project string `json:"project"` + InternalKB string `json:"internal_kb"` + ExternalKB string `json:"external_kb"` + Index string `json:"index"` + S3Bucket string `json:"s3_bucket"` + TenantID uint64 `json:"tenant_id"` + DatabaseSet bool `json:"database_configured"` +} + +// libraryVerifyEnqueue 投递一次恢复验证作业(管理员)。 +// +// 它不签发发布授权、不改版本:验证只回答"当前目标的预备份能不能恢复"。 +// 目标是部署配置,不接受请求体指定——否则一次点击就能验证别的库并把证据挂到当前目标上。 +func libraryVerifyEnqueue(w http.ResponseWriter, r *http.Request, config Config) { + if r.Method != http.MethodPost { + writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"}) + return + } + identity, ok := sessionFrom(r.Context()) + if !ok || roleRank(identity.Role) < roleRank(roleAdmin) { + writeJSON(w, http.StatusForbidden, map[string]any{"error": "恢复验证仅管理员可发起"}) + return + } + var request libraryVerifyRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"}) + return + } + if request.Scope != "internal" && request.Scope != "external" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "scope must be internal or external"}) + return + } + store, ok := libraryStore(config) + if !ok { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{"code": "library_verify_unavailable", + "error": "恢复验证存储不可用"}) + return + } + // 验证要停写入者并在目标上写 canary:维护中或闸口关闭时直接拒绝, + // 不让页面投一个 worker 必然失败的作业。 + if body, held := instanceMaintenanceGuard(r.Context(), config, request.Scope); held { + writeJSON(w, http.StatusConflict, body) + return + } + if !config.ProductionReleaseRequestsEnabled { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{ + "code": "library_verify_blocked", + "reasons": []string{ + "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false):恢复验证要停写入者并在目标上写 canary", + }, + }) + return + } + digest, err := governance.LibraryRequestDigest(request.Scope, governance.LibraryJobVerify, + map[string]any{"scope": request.Scope}) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest request"}) + return + } + now := time.Now().UTC() + // 验证作业必须有和同步/恢复同一套不可变 operation:worker 的 owned attempt 从 + // job.operation_id 取身份,恢复派发闸口和对象网关都按它核验。没有 operation 的 + // verify 作业在真实恢复时会被 fail closed(审核 B2-R1)。 + intent, intentErr := ensureLibraryIntent(r.Context(), store, request.Scope, governance.LibraryJobVerify, + "", digest, identity.Username, "", now) + if intentErr != nil { + if isIntentConflict(intentErr) { + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_verify_conflict", + "error": "同一幂等键对应了不同的请求"}) + return + } + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library verify operation"}) + return + } + job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{ + ID: fmt.Sprintf("libverify-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope, + Kind: governance.LibraryJobVerify, + IdempotencyKey: intent.JobKey, + RequestDigest: digest, OperationID: intent.Operation.ID, Actor: identity.Username, + }, governance.VerifyStages(), false, now) + if errors.Is(err, governance.ErrLibraryJobActive) { + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_write_active", + "error": "该目标已有在飞的写作业(同步/恢复/基线/验证互斥),等它结束再发起"}) + return + } + if errors.Is(err, governance.ErrLibraryJobIdempotencyConflict) { + writeJSON(w, http.StatusConflict, map[string]any{"code": "library_verify_conflict", + "error": "同一幂等键对应了不同的请求"}) + return + } + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library verify job"}) + return + } + writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": reused}) +} + +// libraryVerifications 读当前目标的恢复验证证据(页面轮询用)。 +func libraryVerifications(w http.ResponseWriter, r *http.Request, config Config) { + scope, err := scopeFromQuery(r) + if err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) + return + } + view := libraryVerificationView{ + Scope: scope, + History: []governance.LibraryRestoreVerification{}, + Target: libraryVerificationTarget{ + Instance: config.LibraryTargetInstance, + Project: config.LibraryTargetProject, + InternalKB: config.LibraryProductionInternalKB, + ExternalKB: config.LibraryProductionExternalKB, + Index: config.LibraryProductionIndex, + S3Bucket: config.LibraryProductionS3Bucket, + TenantID: config.LibraryProductionTenantID, + DatabaseSet: config.LibraryProductionDatabaseURL != "", + }, + } + store, ok := config.Store.(interface { + LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) + LibraryRestoreVerifications(context.Context, string, int) ([]governance.LibraryRestoreVerification, error) + }) + if !ok { + view.Reason = "当前部署没有恢复验证存储:无法读取证据" + writeJSON(w, http.StatusServiceUnavailable, view) + return + } + latest, found, err := store.LatestLibraryRestoreVerification(r.Context(), scope) + if err != nil { + view.Reason = "读取恢复验证证据失败:" + err.Error() + writeJSON(w, http.StatusServiceUnavailable, view) + return + } + if found { + view.Latest = &latest + view.JobID = latest.JobID + } + if history, err := store.LibraryRestoreVerifications(r.Context(), scope, 10); err == nil { + view.History = history + } + if snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id")); snapshotID != "" { + if exact, ok := config.Store.(interface { + LibraryRestoreVerificationForSnapshot(context.Context, string, string) (governance.LibraryRestoreVerification, bool, error) + }); ok { + item, found, exactErr := exact.LibraryRestoreVerificationForSnapshot(r.Context(), scope, snapshotID) + if exactErr != nil { + view.Reason = "读取该快照的恢复验证记录失败" + writeJSON(w, http.StatusServiceUnavailable, view) + return + } + if found { + view.SnapshotLatest = &item + } + } + } + view.Verified, view.Reason = governance.LibraryVerificationSatisfied(latest, scope) + if !found { + view.Verified = false + view.Reason = "还没有对当前目标做过恢复验证:点「跑一次恢复验证」(真实备份 → canary → 恢复 → 复核)" + } + if snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id")); snapshotID != "" { + // 显式按快照查询时,verified 只回答该快照;不能让 scope 最新通过记录 + // 把另一个未演练的快照染绿。 + view.Verified = false + if view.SnapshotLatest == nil { + view.Reason = "该快照没有真实恢复验证记录(未验证;不是读取失败)" + } else if view.SnapshotLatest.Status == governance.LibraryVerificationPassed { + view.Verified = true + view.Reason = "" + } else { + view.Reason = "该快照最近一次恢复验证未通过" + } + } + // 在飞作业必须从真实业务行读出来:旧实现只构造 running 字段却从不赋值, + // 页面因此在验收里看不到"已接受/正在执行",按钮也不会进入执行态(审核 B4)。 + if jobs, ok := config.Store.(interface { + ListLibraryJobs(context.Context, string, int) ([]governance.LibraryJob, error) + }); ok { + if items, err := jobs.ListLibraryJobs(r.Context(), scope, 20); err == nil { + var active *governance.LibraryJob + for index := range items { + item := items[index] + if item.Kind != governance.LibraryJobVerify || string(item.State) == "" { + continue + } + if !libraryJobActiveState(item.State) { + continue + } + if active == nil || item.CreatedAt.After(active.CreatedAt) { + active = &item + } + } + if active != nil { + view.Running = true + view.JobID = active.ID + view.State = string(active.State) + view.Stage = active.Stage + view.Reason = "恢复验证作业 " + active.ID + " 正在执行(" + active.Stage + ");终态会在这里显示证据,页面会自动刷新" + } + } + } + writeJSON(w, http.StatusOK, view) +} + +// libraryJobActiveState 只认仍在执行的业务状态:终态不是"在飞"。 +func libraryJobActiveState(state governance.LibraryJobState) bool { + switch state { + case governance.LibraryJobPending, governance.LibraryJobRunning: + return true + } + return false +} + +// withRestoreEvidence 把"当前目标是否有真实恢复证据"注入 Config 的副本, +// 让同步/恢复闸口在同一个请求里按证据判断,而不是读一个可能被手填的 env。 +// +// 证据优先级是不可交换的(审核 B3):明确 failed/invalid 或读取失败都必须拒绝, +// 即使 env=true;历史 env 覆盖只在**明确没有证据行**(not-found)时兜底。 +// 把读取失败混进 not-found 等于把"不知道"说成"满足"。 +func (c Config) withRestoreEvidence(ctx context.Context, scope string) Config { + satisfied, missing, err := c.restoreEvidence(ctx, scope) + c.restoreEvidenceChecked = true + switch { + case err != nil: + c.restoreVerified = false + c.restoreEvidenceReason = err.Error() + case satisfied: + c.restoreVerified = true + c.restoreEvidenceReason = "" + case missing && c.ProductionBackupRestoreVerified: + c.restoreVerified = true + c.restoreEvidenceReason = "" + default: + c.restoreVerified = false + if missing { + c.restoreEvidenceReason = "当前目标还没有恢复演练证据:先在「生产保护与恢复」里跑一次恢复验证" + } else { + c.restoreEvidenceReason = "没有已核验的生产恢复演练证据" + } + } + return c +} + +// restoreEvidence 读当前目标的最近一条证据并给出它能不能支撑"可恢复"。 +// missing 只在"查询成功且确实没有这一行"时为 true;读取错误单独返回。 +func (c Config) restoreEvidence(ctx context.Context, scope string) (satisfied bool, missing bool, err error) { + store, ok := c.Store.(interface { + LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) + }) + if !ok { + // 存储没有证据能力(迁移前的部署形状)等同于"没有证据行": + // 历史 env 覆盖仍可兜底,但一旦读得出证据行,失败/无效/读取错误都优先拒绝。 + return false, true, nil + } + latest, found, err := store.LatestLibraryRestoreVerification(ctx, scope) + if err != nil { + return false, false, fmt.Errorf("读取恢复验证证据失败:%w", err) + } + if !found { + return false, true, nil + } + ok, reason := governance.LibraryVerificationSatisfied(latest, scope) + if !ok { + return false, false, errors.New(reason) + } + return true, false, nil +} + +// restoreGateReasons 是闸口对"恢复可验证"的统一判断:只看 withRestoreEvidence 的结论。 +// 这里不再 OR env:env 兜底只在证据缺失时、且已经在 withRestoreEvidence 里判定过。 +func restoreGateReasons(config Config) []string { + if config.restoreVerified { + return nil + } + // 没有走过证据读取的调用点(历史路径/单元夹具)保持原有 env 语义; + // 一旦读过证据,上面的 withRestoreEvidence 已经把优先级判定完毕。 + if !config.restoreEvidenceChecked && config.ProductionBackupRestoreVerified { + return nil + } + reason := config.restoreEvidenceReason + if reason == "" { + reason = "没有已核验的生产恢复演练证据" + } + return []string{reason} +} diff --git a/internal/httpapi/library_verify_test.go b/internal/httpapi/library_verify_test.go new file mode 100644 index 0000000..f873bc7 --- /dev/null +++ b/internal/httpapi/library_verify_test.go @@ -0,0 +1,309 @@ +package httpapi + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +// 恢复验证的页面契约: +// - 只有管理员能发起(它会停写入者并在目标上写 canary); +// - 闸口关闭 / 维护中时直接拒绝,不投一个 worker 必然失败的作业; +// - 证据只由真实执行写入:没有证据 ⇒ verified=false,过期/换目标 ⇒ 失效。 +// +// 这里不模拟"真跑一次恢复"(那需要真实目标);执行体本身在 internal/libraryverify, +// 由库内 CLI 与 worker 共用,属于隔离 fixture 之外的集成范围。 + +type verificationStore struct { + fakeLibraryStore + verifications []governance.LibraryRestoreVerification +} + +func (s *verificationStore) LatestLibraryRestoreVerification(_ context.Context, scope string) (governance.LibraryRestoreVerification, bool, error) { + for _, item := range s.verifications { + if item.Scope == scope { + return item, true, nil + } + } + return governance.LibraryRestoreVerification{}, false, nil +} + +func (s *verificationStore) LibraryRestoreVerificationForSnapshot(_ context.Context, scope, snapshotID string) (governance.LibraryRestoreVerification, bool, error) { + for _, item := range s.verifications { + if item.Scope == scope && item.SnapshotID == snapshotID { + return item, true, nil + } + } + return governance.LibraryRestoreVerification{}, false, nil +} + +func (s *verificationStore) LibraryRestoreVerifications(_ context.Context, scope string, limit int) ([]governance.LibraryRestoreVerification, error) { + items := make([]governance.LibraryRestoreVerification, 0, len(s.verifications)) + for _, item := range s.verifications { + if item.Scope == scope { + items = append(items, item) + } + } + if limit > 0 && len(items) > limit { + items = items[:limit] + } + return items, nil +} + +func verifyRequest(body, role, username string) *http.Request { + request := httptest.NewRequest(http.MethodPost, "/api/v1/library/verifications", strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + ctx := context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: username, Role: role}) + return request.WithContext(ctx) +} + +func TestLibraryVerifyRequiresAdmin(t *testing.T) { + store := &verificationStore{} + recorder := httptest.NewRecorder() + libraryVerifyEnqueue(recorder, verifyRequest(`{"scope":"internal"}`, roleEngineer, "eng"), + Config{Store: store, ProductionReleaseRequestsEnabled: true}) + if recorder.Code != http.StatusForbidden { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if store.createN != 0 { + t.Fatal("non-admin must not create a verify job") + } +} + +func TestLibraryVerifyRefusesWhenWriteGateClosed(t *testing.T) { + store := &verificationStore{} + recorder := httptest.NewRecorder() + libraryVerifyEnqueue(recorder, verifyRequest(`{"scope":"internal"}`, roleAdmin, "admin"), + Config{Store: store, ProductionReleaseRequestsEnabled: false}) + if recorder.Code != http.StatusServiceUnavailable { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + body := decodeBody(t, recorder) + if body["code"] != "library_verify_blocked" { + t.Fatalf("body=%v", body) + } + if store.createN != 0 { + t.Fatal("closed gate must not create a verify job") + } +} + +func TestLibraryVerifyEnqueuesVerifyJobWithCanaryStages(t *testing.T) { + store := &verificationStore{} + store.enqueueEchoRequestedID = true + recorder := httptest.NewRecorder() + libraryVerifyEnqueue(recorder, verifyRequest(`{"scope":"internal"}`, roleAdmin, "admin"), + Config{Store: store, ProductionReleaseRequestsEnabled: true}) + if recorder.Code != http.StatusAccepted { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if store.lastJob.Kind != governance.LibraryJobVerify || store.lastJob.Scope != "internal" { + t.Fatalf("job=%#v", store.lastJob) + } + if !strings.HasPrefix(store.lastJob.ID, "libverify-internal-") { + t.Fatalf("job id=%q", store.lastJob.ID) + } + // B2-R1:verify 作业必须带不可变 operation,worker 的 owned attempt / 恢复派发 + // 身份都从它取;没有 operation 的作业在真实恢复时会被 fail closed。 + if store.lastJob.OperationID == "" || store.lastJob.OperationID != store.lastOperation.ID { + t.Fatalf("verify job must carry its operation: job=%#v op=%#v", store.lastJob, store.lastOperation) + } + if store.lastOperation.Kind != governance.LibraryJobVerify || store.lastOperation.Scope != "internal" { + t.Fatalf("verify operation identity=%#v", store.lastOperation) + } + // 阶段必须包含 canary:没有"写 canary 证明校验有效"这一步,验证就只是自证。 + want := governance.VerifyStages() + if len(want) != 5 || want[2] != "canary" || want[3] != "restore" || want[4] != "finalize" { + t.Fatalf("verify stages=%v", want) + } +} + +func TestLibraryVerificationsWithoutEvidenceIsNotVerified(t *testing.T) { + store := &verificationStore{} + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil) + libraryVerifications(recorder, request, Config{Store: store}) + if recorder.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } + body := decodeBody(t, recorder) + if body["verified"] != false { + t.Fatalf("verified must be false without evidence: %v", body) + } + if reason, _ := body["reason"].(string); !strings.Contains(reason, "还没有对当前目标做过恢复验证") { + t.Fatalf("reason=%q", reason) + } +} + +// F03: the selected snapshot must resolve its own evidence, never the scope's +// newest passed record. +func TestLibraryVerificationsExactSnapshotDoesNotBorrowLatest(t *testing.T) { + store := &verificationStore{verifications: []governance.LibraryRestoreVerification{ + {ID: "verify-new", Scope: "internal", Status: governance.LibraryVerificationPassed, + SnapshotID: "snap-new", JobID: "job-new", FinishedAt: time.Now().UTC()}, + {ID: "verify-old", Scope: "internal", Status: governance.LibraryVerificationFailed, + SnapshotID: "snap-old", JobID: "job-old", Failure: "old restore mismatch", + FinishedAt: time.Now().UTC().Add(-time.Hour)}, + }} + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal&snapshot_id=snap-old", nil) + libraryVerifications(recorder, request, Config{Store: store}) + body := decodeBody(t, recorder) + exact, ok := body["snapshot_latest"].(map[string]any) + if !ok || exact["snapshot_id"] != "snap-old" || exact["status"] != "failed" { + t.Fatalf("snapshot_latest=%v body=%v", body["snapshot_latest"], body) + } + if body["verified"] != false { + t.Fatalf("old failed snapshot must not inherit latest passed: %v", body["verified"]) + } +} + +func TestLibraryVerificationsWithPassedEvidenceIsVerified(t *testing.T) { + store := &verificationStore{verifications: []governance.LibraryRestoreVerification{{ + ID: "libverify-internal-job1", Scope: "internal", Status: governance.LibraryVerificationPassed, + SnapshotID: "snap-1", JobID: "job1", StartedAt: time.Now().UTC().Add(-time.Minute), + FinishedAt: time.Now().UTC(), + }}} + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil) + libraryVerifications(recorder, request, Config{Store: store}) + body := decodeBody(t, recorder) + if body["verified"] != true { + t.Fatalf("verified must be true with passed evidence: %v", body) + } +} + +func TestLibraryVerificationsFailedEvidenceIsNotVerified(t *testing.T) { + store := &verificationStore{verifications: []governance.LibraryRestoreVerification{{ + ID: "libverify-internal-job2", Scope: "internal", Status: governance.LibraryVerificationFailed, + SnapshotID: "snap-2", JobID: "job2", Failure: "恢复后内容仍与预备份不一致", + StartedAt: time.Now().UTC().Add(-time.Minute), FinishedAt: time.Now().UTC(), + }}} + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil) + libraryVerifications(recorder, request, Config{Store: store}) + body := decodeBody(t, recorder) + if body["verified"] != false { + t.Fatalf("failed evidence must not verify: %v", body) + } + if reason, _ := body["reason"].(string); !strings.Contains(reason, "恢复后内容仍与预备份不一致") { + t.Fatalf("reason=%q", reason) + } +} + +// 同步闸口必须消费同一 target 的证据:有 passed 证据即放行, +// 只有失败证据时仍然拒绝并给出失败原因(不是笼统"没有证据")。 +// 审核 B3 反例(GPT-6 overlay)转成通过断言:env=true 不能覆盖明确失败或读取失败。 +type evidenceReadErrorStore struct{ verificationStore } + +func (*evidenceReadErrorStore) LatestLibraryRestoreVerification(context.Context, string) (governance.LibraryRestoreVerification, bool, error) { + return governance.LibraryRestoreVerification{}, false, errors.New("evidence lookup failed") +} + +func TestRestoreGateFailedEvidenceBeatsEnv(t *testing.T) { + store := &verificationStore{verifications: []governance.LibraryRestoreVerification{{ + Scope: "internal", Status: governance.LibraryVerificationFailed, Failure: "restore mismatch", + FinishedAt: time.Now().UTC(), + }}} + config := Config{Store: store, ProductionBackupRestoreVerified: true}.withRestoreEvidence(context.Background(), "internal") + reasons := restoreGateReasons(config) + if len(reasons) == 0 || !strings.Contains(strings.Join(reasons, ";"), "restore mismatch") { + t.Fatalf("failed evidence must beat env=true: %v", reasons) + } +} + +func TestRestoreGateUnreadableEvidenceBeatsEnv(t *testing.T) { + config := Config{Store: &evidenceReadErrorStore{}, ProductionBackupRestoreVerified: true}. + withRestoreEvidence(context.Background(), "internal") + reasons := restoreGateReasons(config) + if len(reasons) == 0 || !strings.Contains(strings.Join(reasons, ";"), "读取恢复验证证据失败") { + t.Fatalf("unreadable evidence must beat env=true: %v", reasons) + } +} + +// env 兜底只允许在"明确没有证据行"时生效。 +func TestRestoreGateEnvFallbackOnlyWhenEvidenceMissing(t *testing.T) { + config := Config{Store: &verificationStore{}, ProductionBackupRestoreVerified: true}. + withRestoreEvidence(context.Background(), "internal") + if reasons := restoreGateReasons(config); len(reasons) != 0 { + t.Fatalf("explicit not-found with legacy env must still allow: %v", reasons) + } +} + +// 审核 B4:GET 必须从真实业务行投影在飞验证作业,而不是永远 running=false。 +func TestLibraryVerificationsProjectsActiveVerifyJob(t *testing.T) { + store := &verificationStore{} + store.jobs = []governance.LibraryJob{{ + ID: "verify-running", Scope: "internal", Kind: governance.LibraryJobVerify, + State: governance.LibraryJobRunning, Stage: "restore", CreatedAt: time.Now().UTC(), + }} + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil) + libraryVerifications(recorder, request, Config{Store: store}) + body := decodeBody(t, recorder) + if body["running"] != true { + t.Fatalf("running verify job must be projected: %v", body) + } + if body["job_id"] != "verify-running" { + t.Fatalf("job_id=%v", body["job_id"]) + } + if body["stage"] != "restore" { + t.Fatalf("stage=%v", body["stage"]) + } +} + +// 终态作业不是"在飞":页面不能一直显示执行中。 +func TestLibraryVerificationsIgnoresTerminalVerifyJob(t *testing.T) { + store := &verificationStore{} + store.jobs = []governance.LibraryJob{{ + ID: "verify-done", Scope: "internal", Kind: governance.LibraryJobVerify, + State: governance.LibraryJobSucceeded, CreatedAt: time.Now().UTC(), + }} + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal", nil) + libraryVerifications(recorder, request, Config{Store: store}) + body := decodeBody(t, recorder) + if body["running"] != false { + t.Fatalf("terminal verify job must not be projected as running: %v", body) + } +} + +func TestLibrarySyncGateConsumesRestoreEvidence(t *testing.T) { + base := Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: false, + LibraryProductionDatabaseURL: "postgres://unused.invalid/db", LibraryCapacityBudgetBytes: 1 << 40} + base.Store = &verificationStore{verifications: []governance.LibraryRestoreVerification{{ + Scope: "internal", Status: governance.LibraryVerificationPassed, SnapshotID: "snap-1", + JobID: "job1", FinishedAt: time.Now().UTC(), + }}} + allowed := librarySyncGateWithGrant(base.withRestoreEvidence(context.Background(), "internal"), + libraryKnownView{State: "known"}, libraryKnownView{State: "unknown"}, "snap-1", true) + if !allowed.SyncAllowed { + t.Fatalf("gate should allow with passed evidence: %v", allowed.Reasons) + } + noEvidence := Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: false, + LibraryProductionDatabaseURL: "postgres://unused.invalid/db", LibraryCapacityBudgetBytes: 1 << 40, + Store: &verificationStore{}}.withRestoreEvidence(context.Background(), "internal") + blocked := librarySyncGateWithGrant(noEvidence, + libraryKnownView{State: "known"}, libraryKnownView{State: "unknown"}, "snap-1", true) + if blocked.SyncAllowed { + t.Fatalf("gate without env and without evidence must block: %v", blocked.Reasons) + } + if len(blocked.Reasons) == 0 || !strings.Contains(strings.Join(blocked.Reasons, ";"), "恢复验证") { + t.Fatalf("blocked reasons=%v", blocked.Reasons) + } + failedConfig := Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: false, + LibraryProductionDatabaseURL: "postgres://unused.invalid/db", LibraryCapacityBudgetBytes: 1 << 40, + Store: &verificationStore{verifications: []governance.LibraryRestoreVerification{{ + Scope: "internal", Status: governance.LibraryVerificationFailed, SnapshotID: "snap-2", + JobID: "job2", Failure: "canary 后校验仍通过", FinishedAt: time.Now().UTC(), + }}}} + reason := strings.Join(restoreGateReasons(failedConfig.withRestoreEvidence(context.Background(), "internal")), ";") + if !strings.Contains(reason, "canary 后校验仍通过") { + t.Fatalf("失败证据的失败原因必须出现在闸口:%q", reason) + } +} diff --git a/internal/httpapi/monitor_tasks.go b/internal/httpapi/monitor_tasks.go index 99adad7..4ad5a0f 100644 --- a/internal/httpapi/monitor_tasks.go +++ b/internal/httpapi/monitor_tasks.go @@ -97,6 +97,10 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) { writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"}) return } + // 目标同名不罕见(两侧都叫“对内知识库”):把当前生效绑定随页返回, + // 前端才能在同一口径下标注“当前绑定/历史”,而不是拿本页条目反推全局。 + internal, external := config.effectiveRoutingTargets(r.Context()) + page.Bindings = postgresstore.MonitorBindings{Internal: internal, External: external} w.Header().Set("Cache-Control", "no-store") writeJSON(w, 200, map[string]any{"data": page}) } diff --git a/internal/httpapi/monitor_tasks_test.go b/internal/httpapi/monitor_tasks_test.go index 38623a0..00a558c 100644 --- a/internal/httpapi/monitor_tasks_test.go +++ b/internal/httpapi/monitor_tasks_test.go @@ -2,6 +2,7 @@ package httpapi import ( "context" + "encoding/json" postgresstore "knowledge-governance/internal/platform/postgres" "net/http/httptest" "testing" @@ -51,3 +52,39 @@ func TestMonitorTasksRoute(t *testing.T) { t.Fatalf("viewer removal %d", removal.Code) } } + +// F15:筛选里的“当前绑定”必须来自持久化绑定(与业务同一真源),不是 env 旧值, +// 也不能让前端拿本页数据猜全局。 +func TestMonitorTasksReportsEffectiveTargetBindings(t *testing.T) { + store := &monitorTasksTestStore{} + handler, err := NewHandler(Config{ + Store: store, + InternalRoutingKnowledgeBaseID: "env-old-internal", + ExternalRoutingKnowledgeBaseID: "env-old-external", + RoutingBindings: &bindingStoreFake{internal: "current-internal", external: "current-external"}, + }) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("GET", "/api/v1/monitor/tasks?limit=20", nil) + req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleViewer})) + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, req) + if recorder.Code != 200 { + t.Fatalf("status %d: %s", recorder.Code, recorder.Body.String()) + } + var payload struct { + Data struct { + Bindings struct { + Internal string `json:"internal"` + External string `json:"external"` + } `json:"bindings"` + } `json:"data"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if payload.Data.Bindings.Internal != "current-internal" || payload.Data.Bindings.External != "current-external" { + t.Fatalf("bindings = %#v, want the persisted current bindings", payload.Data.Bindings) + } +} diff --git a/internal/httpapi/openapi_contract_test.go b/internal/httpapi/openapi_contract_test.go index 7cee0df..15e4b08 100644 --- a/internal/httpapi/openapi_contract_test.go +++ b/internal/httpapi/openapi_contract_test.go @@ -52,7 +52,7 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) { switch value := node.(type) { case map[string]any: for key, child := range value { - if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" { + if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" { t.Fatalf("unapproved endpoint exposure at %s", path) } next := key diff --git a/internal/httpapi/pp_auth.go b/internal/httpapi/pp_auth.go new file mode 100644 index 0000000..996892f --- /dev/null +++ b/internal/httpapi/pp_auth.go @@ -0,0 +1,94 @@ +package httpapi + +import ( + "context" + "errors" + "knowledge-governance/internal/ppauth" + "net/http" + "net/url" + "time" +) + +func credentialAdmin(w http.ResponseWriter, r *http.Request, action string) bool { + w.Header().Set("Cache-Control", "no-store") + identity, ok := requireSessionIdentity(w, r) + if !ok { + return false + } + if identity.Role != roleAdmin { + writeJSON(w, 403, map[string]string{"error": "需要管理员身份管理来源凭据"}) + return false + } + if r.Method != "GET" { + originOK := true + if raw := r.Header.Get("Origin"); raw != "" { + u, err := url.Parse(raw) + originOK = err == nil && u.Host == r.Host && (u.Scheme == "http" || u.Scheme == "https") + } + if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != action { + writeJSON(w, 403, map[string]string{"error": "请从本平台的数据源配置页操作"}) + return false + } + } + return true +} +func writePPError(w http.ResponseWriter, err error) { + status := http.StatusBadRequest + if errors.Is(err, ppauth.ErrConflict) { + status = http.StatusConflict + } + writeJSON(w, status, map[string]string{"error": err.Error()}) +} + +func registerPPConnectionRoutes(mux *http.ServeMux, config Config) { + for _, pattern := range []string{"GET /api/v1/pp-connection", "PUT /api/v1/pp-connection", "POST /api/v1/pp-connection/test"} { + mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { + if !credentialAdmin(w, r, "pp-connection") { + return + } + if config.PPConnection == nil { + writeJSON(w, 503, map[string]string{"error": "PP 配置服务未接通,请联系管理员"}) + return + } + if r.Method == "GET" { + v, err := config.PPConnection.View() + if err != nil { + writeJSON(w, 503, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, 200, map[string]any{"data": v}) + return + } + var draft ppauth.Draft + r.Body = http.MaxBytesReader(w, r.Body, 16384) + if decodeJSONStrict(r, &draft) != nil { + writeJSON(w, 400, map[string]string{"error": "PP 配置请求格式不正确"}) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second) + defer cancel() + if r.Method == "POST" { + result, err := config.PPConnection.Test(ctx, draft, actorFor(r)) + if err != nil { + writePPError(w, err) + return + } + writeJSON(w, 200, map[string]any{"data": result}) + return + } + result, err := config.PPConnection.Save(ctx, draft, actorFor(r)) + if err != nil { + status := 400 + if errors.Is(err, ppauth.ErrConflict) { + status = 409 + } + if errors.Is(err, ppauth.ErrRejected) { + status = 422 + } + writeJSON(w, status, map[string]any{"error": err.Error(), "data": result}) + return + } + writeJSON(w, 200, map[string]any{"data": result}) + }) + } +} diff --git a/internal/httpapi/pp_auth_roundtrip_test.go b/internal/httpapi/pp_auth_roundtrip_test.go new file mode 100644 index 0000000..c31afcc --- /dev/null +++ b/internal/httpapi/pp_auth_roundtrip_test.go @@ -0,0 +1,142 @@ +package httpapi + +import ( + "context" + "encoding/json" + "fmt" + "knowledge-governance/internal/jobs" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/ppauth" + "net/http/httptest" + "os" + "path/filepath" + "sort" + "strings" + "testing" + "time" +) + +type noPPJobStore struct { + *fakeJobStore + queued int +} + +func (s *noPPJobStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) { + s.queued++ + return s.fakeJobStore.Enqueue(ctx, request, now) +} +func TestPPHTTPRoundTripRechecksSaveAndNeverEnqueues(t *testing.T) { + probes := 0 + m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c ppauth.Credentials) ppauth.Observation { + probes++ + return ppauth.Observation{State: "valid", Message: "认证有效 · 目录可读"} + }} + store := &noPPJobStore{fakeJobStore: &fakeJobStore{}} + h, err := NewHandler(Config{Store: store, PPConnection: m}) + if err != nil { + t.Fatal(err) + } + call := func(method, path, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("X-Governance-Action", "pp-connection") + req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec + } + draft := `{"base_url":"https://api.example.invalid","username":"example","password":"example-private","revision":0}` + for _, op := range [][2]string{{"POST", "/api/v1/pp-connection/test"}, {"PUT", "/api/v1/pp-connection"}, {"GET", "/api/v1/pp-connection"}} { + rec := call(op[0], op[1], draft) + if rec.Code != 200 { + t.Fatalf("%s status=%d body=%s", op[0], rec.Code, rec.Body) + } + if strings.Contains(rec.Body.String(), "example-private") || strings.Contains(rec.Body.String(), `"password":`) { + t.Fatal("credential leaked through response") + } + } + if probes != 2 || store.queued != 0 { + t.Fatalf("save must recheck and must not enqueue: checks=%d jobs=%d", probes, store.queued) + } + rec := call("PUT", "/api/v1/pp-connection", draft) + if rec.Code != 409 { + t.Fatalf("stale revision accepted: %d", rec.Code) + } +} +func TestPPHTTPRefusesCrossOriginBeforeProbe(t *testing.T) { + probes := 0 + m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, _ ppauth.Credentials) ppauth.Observation { + probes++ + return ppauth.Observation{State: "valid"} + }} + h, _ := NewHandler(Config{Store: &fakeJobStore{}, PPConnection: m}) + req := httptest.NewRequest("POST", "/api/v1/pp-connection/test", strings.NewReader(`{}`)) + req.Header.Set("Origin", "https://foreign.example.invalid") + req.Header.Set("X-Governance-Action", "pp-connection") + req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 403 || probes != 0 { + t.Fatal("cross-origin request reached credential probe") + } +} + +type combinedAuditStore struct { + *fakeJobStore + items []postgresstore.SourceAuditItem +} + +func (s *combinedAuditStore) ListSourceAudit(_ context.Context, limit, offset int) (postgresstore.SourceAuditPage, error) { + start := offset + if start > len(s.items) { + start = len(s.items) + } + end := start + limit + if end > len(s.items) { + end = len(s.items) + } + return postgresstore.SourceAuditPage{Items: s.items[start:end], Total: len(s.items), Limit: limit, Offset: offset}, nil +} +func TestPPSourceAuditSharesTheExistingPagedView(t *testing.T) { + ctx := context.Background() + m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json"} + if err := os.Mkdir(filepath.Dir(m.Path), 0700); err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + store := &combinedAuditStore{fakeJobStore: &fakeJobStore{}} + expected := []postgresstore.SourceAuditItem{} + for i := 0; i < 8; i++ { + item := postgresstore.SourceAuditItem{ID: fmt.Sprintf("db-%02d", i), CreatedAt: now.Add(-time.Duration(i*2) * time.Minute), SourceName: "existing source"} + store.items = append(store.items, item) + expected = append(expected, item) + } + state := ppauth.State{} + for i := 0; i < 4; i++ { + event := ppauth.AuditEvent{ID: fmt.Sprintf("auth-%02d", i), CreatedAt: now.Add(-time.Duration(i*2+1) * time.Minute), SourceName: "PP", Action: "credential_test", Actor: "tester", Detail: "只读连接检查"} + state.Audit = append(state.Audit, event) + expected = append(expected, postgresstore.SourceAuditItem{ID: event.ID, CreatedAt: event.CreatedAt, SourceName: event.SourceName}) + } + raw, _ := json.Marshal(state) + if err := os.WriteFile(m.Path, raw, 0600); err != nil { + t.Fatal(err) + } + sort.Slice(expected, func(i, j int) bool { return expected[i].CreatedAt.After(expected[j].CreatedAt) }) + for offset := 0; offset <= len(expected); offset++ { + page, err := combinedSourceAudit(ctx, store, m, 3, offset) + if err != nil || page.Total != len(expected) { + t.Fatalf("offset=%d total=%d err=%v", offset, page.Total, err) + } + end := offset + 3 + if end > len(expected) { + end = len(expected) + } + if len(page.Items) != end-offset { + t.Fatalf("wrong page length at %d", offset) + } + for i, item := range page.Items { + if item.ID != expected[offset+i].ID { + t.Fatalf("audit order mismatch at offset %d", offset) + } + } + } +} diff --git a/internal/httpapi/pp_auth_test.go b/internal/httpapi/pp_auth_test.go new file mode 100644 index 0000000..5f0f8fe --- /dev/null +++ b/internal/httpapi/pp_auth_test.go @@ -0,0 +1,42 @@ +package httpapi + +import ( + "context" + "net/http/httptest" + "testing" +) + +func TestPPAuthRoutesRequireAdminAndFailClosedWhenUnwired(t *testing.T) { + h, err := NewHandler(Config{Store: &fakeJobStore{}}) + if err != nil { + t.Fatal(err) + } + for _, method := range []string{"GET", "PUT", "POST"} { + path := "/api/v1/pp-connection" + if method == "POST" { + path += "/test" + } + for _, role := range []string{"", roleViewer, roleEngineer, roleAdmin} { + req := httptest.NewRequest(method, path, nil) + if role != "" { + req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{UserID: "admin", Username: "tester", Role: role, SessionID: "session"})) + } + req.Header.Set("X-Governance-Action", "pp-connection") + res := httptest.NewRecorder() + h.ServeHTTP(res, req) + want := 403 + if role == "" { + want = 401 + } + if role == roleAdmin { + want = 503 + } + if res.Code != want { + t.Errorf("%s role=%q status=%d want=%d", method, role, res.Code, want) + } + } + if got := classifyRole(method, path); got != roleAdmin { + t.Errorf("%s classified=%q; credential metadata and tests must be admin only", method, got) + } + } +} diff --git a/internal/httpapi/production_bindings.go b/internal/httpapi/production_bindings.go index 7e72939..43756c7 100644 --- a/internal/httpapi/production_bindings.go +++ b/internal/httpapi/production_bindings.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "knowledge-governance/internal/pgdsn" "knowledge-governance/internal/platform/weknora" ) @@ -33,6 +34,55 @@ type productionBindingView struct { ProductionBaseURL string `json:"production_base_url"` ProductionConnected bool `json:"production_connected"` ProductionMessage string `json:"production_message"` + // LegacyScope 说明这条记录属于哪条发布路径。整库发布(封存/同步/恢复)不读它, + // 只读下面的 WholeTarget;页面必须把两者分开写,否则会把旧文档级目标当成整库目标。 + LegacyScope string `json:"legacy_scope"` + // WholeTarget 是整库发布真正写入的目标(来自部署环境 LIBRARY_PRODUCTION_*), + // 与上面可编辑的文档级绑定是两条独立路径。 + WholeTarget libraryPublishTargetView `json:"whole_target"` +} + +// libraryPublishTargetView 是"整库发布到底写哪儿"的只读投影。 +// 为什么由后端给出:页面上的 kb 名称/文档数来自生产端列表接口,而整库写入用的是 +// 另一组环境配置;让页面自己拼会把两条路径混成一个。 +type libraryPublishTargetView struct { + Configured bool `json:"configured"` + Source string `json:"source"` + TenantID uint64 `json:"tenant_id"` + InternalKBID string `json:"internal_kb_id"` + ExternalKBID string `json:"external_kb_id"` + Database string `json:"database"` + ElasticIndex string `json:"elastic_index"` + ObjectBucket string `json:"object_bucket"` + MissingReason string `json:"missing_reason"` +} + +// libraryPublishTarget 从 config 派生整库目标;缺项照实说缺哪一项,不猜默认值。 +func (config Config) libraryPublishTarget() libraryPublishTargetView { + view := libraryPublishTargetView{ + Source: "部署环境 LIBRARY_PRODUCTION_*", + TenantID: config.LibraryProductionTenantID, + InternalKBID: config.LibraryProductionInternalKB, + ExternalKBID: config.LibraryProductionExternalKB, + Database: pgdsn.Endpoint(config.LibraryProductionDatabaseURL), + ElasticIndex: config.LibraryProductionIndex, + ObjectBucket: config.LibraryProductionS3Bucket, + } + missing := make([]string, 0, 4) + if config.LibraryProductionDatabaseURL == "" { + missing = append(missing, "LIBRARY_PRODUCTION_DATABASE_URL") + } + if view.InternalKBID == "" { + missing = append(missing, "LIBRARY_PRODUCTION_KB_INTERNAL") + } + if config.LibraryProductionIndex == "" { + missing = append(missing, "LIBRARY_PRODUCTION_INDEX") + } + view.Configured = len(missing) == 0 + if len(missing) > 0 { + view.MissingReason = "未配置:" + strings.Join(missing, "、") + } + return view } // productionTargetBaseURL is the production endpoint the picker reads from: the @@ -79,6 +129,10 @@ func (config Config) productionBindingPayload(ctx context.Context) (productionBi InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal], UpdatedBy: updatedBy, ProductionBaseURL: config.productionTargetBaseURL(ctx), ProductionConnected: message == "", ProductionMessage: message, + // 这张表服务的是"文档级发布"(单篇文档写生产)。整库发布读的是部署环境 + // LIBRARY_PRODUCTION_*,两者不能互相顶替,所以页面必须分开显示。 + LegacyScope: "文档级发布(单篇文档写生产)· 旧路径", + WholeTarget: config.libraryPublishTarget(), }, nil } diff --git a/internal/httpapi/production_bindings_test.go b/internal/httpapi/production_bindings_test.go index db5a77f..229a597 100644 --- a/internal/httpapi/production_bindings_test.go +++ b/internal/httpapi/production_bindings_test.go @@ -178,3 +178,50 @@ func TestProductionBindingOptionsReportUnavailableReason(t *testing.T) { t.Fatalf("status = %d body %s", recorder.Code, recorder.Body.String()) } } + +// 页面必须说清"整库发布真正写哪个 KB/端点"。这条投影只能来自部署配置, +// 不能从可编辑的文档级绑定推出来,也不能把口令带进响应。 +func TestLibraryPublishTargetIsDerivedFromDeploymentConfig(t *testing.T) { + config := Config{ + // 只放形状,不放任何可用凭据:口令段是占位符,主机是 .invalid。 + LibraryProductionDatabaseURL: "postgres://governance@db.invalid:5432/weknora_test?sslmode=disable", + LibraryProductionInternalKB: "a8e9c8ad-411c-4c53-8421-599d29e9b179", + LibraryProductionExternalKB: "2e980686-2233-4c4e-b5a6-8b0069477b8e", + LibraryProductionTenantID: 10000, + LibraryProductionIndex: "weknora_test_chunks", + LibraryProductionS3Bucket: "dobot-weknora-test", + } + target := config.libraryPublishTarget() + if !target.Configured || target.MissingReason != "" { + t.Fatalf("完整配置应判为已配置: %+v", target) + } + if target.InternalKBID != "a8e9c8ad-411c-4c53-8421-599d29e9b179" || target.TenantID != 10000 { + t.Fatalf("必须回显实际整库目标而不是占位: %+v", target) + } + if target.Database != "db.invalid:5432/weknora_test" { + t.Fatalf("端点应只含 host:port/db,得到 %q", target.Database) + } + // 回显只能是端点:连接串里的用户信息(口令、账号)一个字符都不能进响应。 + if strings.Contains(target.Database, "@") || strings.Contains(target.Source, "@") || + strings.Contains(target.Source, "postgres://") { + t.Fatalf("响应里不能出现连接串用户信息: %+v", target) + } + if target.ElasticIndex != "weknora_test_chunks" || target.ObjectBucket != "dobot-weknora-test" { + t.Fatalf("索引与桶也要显示: %+v", target) + } +} + +func TestLibraryPublishTargetNamesMissingConfigInsteadOfGuessing(t *testing.T) { + target := Config{}.libraryPublishTarget() + if target.Configured { + t.Fatal("缺配置时不能报告已配置") + } + for _, key := range []string{"LIBRARY_PRODUCTION_DATABASE_URL", "LIBRARY_PRODUCTION_KB_INTERNAL"} { + if !strings.Contains(target.MissingReason, key) { + t.Fatalf("缺失说明应点名 %s,得到 %q", key, target.MissingReason) + } + } + if target.InternalKBID != "" || target.Database != "(未配置)" { + t.Fatalf("缺配置就不要编造目标: %+v", target) + } +} diff --git a/internal/httpapi/qa_weekly_mail.go b/internal/httpapi/qa_weekly_mail.go index 05a1daf..961802a 100644 --- a/internal/httpapi/qa_weekly_mail.go +++ b/internal/httpapi/qa_weekly_mail.go @@ -7,6 +7,7 @@ import ( "knowledge-governance/internal/dobotaiops" "knowledge-governance/internal/qawemail" "net/http" + "strconv" "time" ) @@ -20,6 +21,98 @@ type weeklyMailStore interface { TestSend(context.Context, string) (string, error) SaveDashboardImage(context.Context, string, []byte) error SendDue(context.Context, time.Time) (qawemail.DueResult, error) + PreviewSend(context.Context, string, int64, string, time.Time) (qawemail.SendPreview, error) + SendManual(context.Context, string, int64, string, string, time.Time) (qawemail.ManualResult, error) +} + +// weeklyMailSendError names the rule that refused a manual resend. Anything SMTP-related is +// reported by the handler itself, so an unmet precondition never looks like a mail failure. +func weeklyMailSendError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, qawemail.ErrNotCurrent): + writeJSON(w, http.StatusConflict, map[string]string{"error": "该周周报未确认,或确认后正文/版本已变化;请先确认当前版本再补发"}) + case errors.Is(err, qawemail.ErrFutureWeek): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "不能补发未来周"}) + case errors.Is(err, qawemail.ErrSlotPending): + writeJSON(w, http.StatusConflict, map[string]string{"error": "本周尚未到达设定的发送时点,暂不能补发"}) + case errors.Is(err, qawemail.ErrNotConfigured): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "未配置邮件服务器、发件人或收件人,无法补发"}) + case errors.Is(err, qawemail.ErrSendInFlight): + writeJSON(w, http.StatusConflict, map[string]string{"error": "该周该版本有一次发送结果未知(记录停在发送中),为避免重复投递未重发;请先核对已发出的邮件"}) + case errors.Is(err, qawemail.ErrDeliveryUnknown): + writeJSON(w, http.StatusConflict, map[string]string{"error": "SMTP 已提交但未收到最终确认,投递结果未知;为避免重复已停止重发,请先核对已发出的邮件"}) + case errors.Is(err, qawemail.ErrNoPassword): + writeJSON(w, http.StatusConflict, map[string]string{"error": "SMTP 授权码缺失或无法解密,无法补发"}) + case errors.Is(err, qawemail.ErrInvalid): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "补发参数无效:需要精确的周、已确认版本与正文 hash"}) + default: + weeklyMailError(w, err) + } +} + +// qaWeeklyMailSendPreview lets the confirmation dialog show the exact week, revision and +// distribution this send would use — the same settings the send path reads. +func qaWeeklyMailSendPreview(w http.ResponseWriter, r *http.Request, c Config) { + if !authorizeQAOps(w, r) { + return + } + store, ok := c.QAWeeklyMail.(weeklyMailStore) + if !ok { + weeklyMailError(w, qawemail.ErrUnavailable) + return + } + query := r.URL.Query() + revision, err := strconv.ParseInt(query.Get("revision"), 10, 64) + if err != nil { + weeklyMailSendError(w, qawemail.ErrInvalid) + return + } + preview, err := store.PreviewSend(r.Context(), r.PathValue("week"), revision, query.Get("body_sha256"), time.Now()) + if err != nil { + weeklyMailSendError(w, err) + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": preview}) +} + +// qaWeeklyMailSend is the formal resend: admin only, bound to the live confirmation, and the same +// render/claim path as the automatic slot. It is not a test send and never targets the review box. +func qaWeeklyMailSend(w http.ResponseWriter, r *http.Request, c Config) { + if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-mail") { + return + } + identity, ok := sessionFrom(r.Context()) + if !ok || identity.Role != "admin" { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "仅管理员可正式补发周报"}) + return + } + store, found := c.QAWeeklyMail.(weeklyMailStore) + if !found { + weeklyMailError(w, qawemail.ErrUnavailable) + return + } + var request struct { + Revision int64 `json:"revision"` + BodySHA256 string `json:"body_sha256"` + } + if decodeQualityJSON(w, r, &request) != nil { + weeklyMailError(w, qawemail.ErrInvalid) + return + } + result, err := store.SendManual(r.Context(), r.PathValue("week"), request.Revision, request.BodySHA256, identity.Username, time.Now()) + if err != nil { + weeklyMailSendError(w, err) + return + } + if result.Status == "failed" { + reason := result.Reason + if len(reason) > 300 { + reason = reason[:300] + } + writeJSON(w, http.StatusBadGateway, map[string]string{"error": "正式补发未送达:" + reason}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": result}) } func weeklyMailError(w http.ResponseWriter, err error) { diff --git a/internal/httpapi/qa_weekly_mail_pg_test.go b/internal/httpapi/qa_weekly_mail_pg_test.go new file mode 100644 index 0000000..2e2f210 --- /dev/null +++ b/internal/httpapi/qa_weekly_mail_pg_test.go @@ -0,0 +1,91 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/qawemail" +) + +// 页面 reload / “完成读真实发送记录”走的就是这个 handler。用真实 PG 的非空历史证明 +// 产品读回路径返回 200 且带 message_id,而不是 503——“历史行存在就整个列表不可用” +// 正是上一版 Sends() 的确定性回归。 +func TestWeeklyMailSendsHandlerReadsRealHistoryWithMessageID(t *testing.T) { + dsn := os.Getenv("KG_WEEKLY_MAIL_TEST_DSN") + if dsn == "" { + t.Skip("显式一次性周报邮件数据库未提供(KG_WEEKLY_MAIL_TEST_DSN):跳过不等于通过") + } + if !strings.Contains(dsn, "/kg_weekly_mail_test_") || strings.Contains(dsn, "/governance?") { + t.Fatal("拒绝非一次性周报测试库") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal("测试库连接参数无效(详情省略)") + } + defer pool.Close() + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + store := qawemail.NewStore(pool, "fixture-http-history", os.Getenv("KG_WEEKLY_MAIL_TEST_KEY"), nil) + for _, statement := range []string{ + `DELETE FROM qa_weekly_email_sends WHERE tenant_key=$1`, + } { + if _, err := pool.Exec(ctx, statement, "fixture-http-history"); err != nil { + t.Fatal(err) + } + } + if _, err := pool.Exec(ctx, `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,message_id,last_error,created_at,updated_at) + VALUES($1,'2026-W45',16,$2,'sent',1,'','',now(),now()), + ($1,'2026-W44',7,$2,'failed',2,'','smtp RCPT 被拒: 550',now(),now() - interval '1 hour')`, + "fixture-http-history", strings.Repeat("a", 64)); err != nil { + t.Fatal(err) + } + + request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/sends?week=2026-W45", nil) + request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + recorder := httptest.NewRecorder() + qaWeeklyMailSends(recorder, request, Config{QAWeeklyMail: store}) + if recorder.Code != http.StatusOK { + t.Fatalf("非空历史必须 200,status=%d body=%s", recorder.Code, recorder.Body.String()) + } + var payload struct { + Data struct { + Sends []qawemail.Send `json:"sends"` + } `json:"data"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if len(payload.Data.Sends) != 1 || payload.Data.Sends[0].MessageID != "" || payload.Data.Sends[0].Status != "sent" { + t.Fatalf("发送记录必须带回真实 message_id:%+v", payload.Data.Sends) + } + + // 全量历史(不带 week)同样必须可读,且 failed 行不伪造 message_id。 + all := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/sends", nil) + all = all.WithContext(context.WithValue(all.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + allRecorder := httptest.NewRecorder() + qaWeeklyMailSends(allRecorder, all, Config{QAWeeklyMail: store}) + if allRecorder.Code != http.StatusOK { + t.Fatalf("全量历史必须 200,status=%d body=%s", allRecorder.Code, allRecorder.Body.String()) + } + if err := json.Unmarshal(allRecorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if len(payload.Data.Sends) != 2 { + t.Fatalf("应返回 2 条历史,got %+v", payload.Data.Sends) + } + for _, item := range payload.Data.Sends { + if item.Status == "failed" && item.MessageID != "" { + t.Fatalf("failed 行不得有 message_id:%+v", item) + } + } +} diff --git a/internal/httpapi/qa_weekly_mail_test.go b/internal/httpapi/qa_weekly_mail_test.go new file mode 100644 index 0000000..748d57e --- /dev/null +++ b/internal/httpapi/qa_weekly_mail_test.go @@ -0,0 +1,186 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "knowledge-governance/internal/qawemail" +) + +type fakeWeeklyMailStore struct { + preview qawemail.SendPreview + previewErr error + result qawemail.ManualResult + sendErr error + calls int + lastWeek string + lastRev int64 + lastHash string + lastActor string +} + +func (f *fakeWeeklyMailStore) ReadSettings(context.Context) (qawemail.Settings, error) { + return qawemail.Settings{}, nil +} +func (f *fakeWeeklyMailStore) SaveSettings(context.Context, string, qawemail.SettingsInput) (qawemail.Settings, error) { + return qawemail.Settings{}, nil +} +func (f *fakeWeeklyMailStore) Confirm(context.Context, string, string) (qawemail.Confirmation, error) { + return qawemail.Confirmation{}, nil +} +func (f *fakeWeeklyMailStore) Unconfirm(context.Context, string) error { return nil } +func (f *fakeWeeklyMailStore) ReadConfirmation(context.Context, string) (*qawemail.Confirmation, error) { + return nil, nil +} +func (f *fakeWeeklyMailStore) Sends(context.Context, string) ([]qawemail.Send, error) { + return nil, nil +} +func (f *fakeWeeklyMailStore) TestSend(context.Context, string) (string, error) { return "", nil } +func (f *fakeWeeklyMailStore) SaveDashboardImage(context.Context, string, []byte) error { + return nil +} +func (f *fakeWeeklyMailStore) SendDue(context.Context, time.Time) (qawemail.DueResult, error) { + return qawemail.DueResult{}, nil +} +func (f *fakeWeeklyMailStore) PreviewSend(_ context.Context, week string, revision int64, hash string, _ time.Time) (qawemail.SendPreview, error) { + f.lastWeek, f.lastRev, f.lastHash = week, revision, hash + if f.previewErr != nil { + return qawemail.SendPreview{}, f.previewErr + } + out := f.preview + out.Week, out.Revision, out.BodySHA256 = week, revision, hash + return out, nil +} +func (f *fakeWeeklyMailStore) SendManual(_ context.Context, week string, revision int64, hash, actor string, _ time.Time) (qawemail.ManualResult, error) { + f.calls++ + f.lastWeek, f.lastRev, f.lastHash, f.lastActor = week, revision, hash, actor + if f.sendErr != nil { + return qawemail.ManualResult{}, f.sendErr + } + out := f.result + out.Week, out.Revision = week, revision + return out, nil +} + +func weeklyMailSendRequest(t *testing.T, role, body string, withIntent bool) *http.Request { + t.Helper() + request := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/master/weekly-mail/send/2026-W45", strings.NewReader(body)) + request.SetPathValue("week", "2026-W45") + request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role})) + if withIntent { + request.Header.Set("X-Governance-Action", "qa-weekly-mail") + } + return request +} + +// 正式补发是管理员动作:普通角色与缺少同源意图都必须被挡在 SMTP 之前。 +func TestWeeklyMailFormalSendRequiresAdminAndIntent(t *testing.T) { + store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "sent", MessageID: ""}} + config := Config{QAWeeklyMail: store} + body := `{"revision":16,"body_sha256":"` + strings.Repeat("a", 64) + `"}` + + recorder := httptest.NewRecorder() + qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, "engineer", body, true), config) + if recorder.Code != http.StatusForbidden { + t.Fatalf("非管理员必须 403,status=%d body=%s", recorder.Code, recorder.Body.String()) + } + recorder = httptest.NewRecorder() + qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, body, false), config) + if recorder.Code != http.StatusForbidden { + t.Fatalf("缺少同源操作意图必须 403,status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if store.calls != 0 { + t.Fatalf("被拒请求不得调用发送:calls=%d", store.calls) + } +} + +// 成功补发必须把 week/版本/hash/操作人原样交给 store,并回传真实 message_id 与收件人数。 +func TestWeeklyMailFormalSendPassesExactRevisionAndReturnsReceipt(t *testing.T) { + store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "sent", MessageID: "", Recipients: 119, Cc: 8}} + config := Config{QAWeeklyMail: store} + hash := strings.Repeat("b", 64) + recorder := httptest.NewRecorder() + qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+hash+`"}`, true), config) + if recorder.Code != http.StatusOK { + t.Fatalf("管理员补发应成功,status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if store.lastWeek != "2026-W45" || store.lastRev != 16 || store.lastHash != hash || store.lastActor != "tester" { + t.Fatalf("补发参数没有精确传递:week=%q rev=%d hash=%q actor=%q", store.lastWeek, store.lastRev, store.lastHash, store.lastActor) + } + var payload struct { + Data qawemail.ManualResult `json:"data"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if payload.Data.MessageID != "" || payload.Data.Recipients != 119 || payload.Data.Cc != 8 { + t.Fatalf("响应必须带回真实发送凭据与正式收件人数:%+v", payload.Data) + } +} + +// 前置条件不满足必须给出具体原因,而不是冒充 SMTP 失败。 +func TestWeeklyMailFormalSendExplainsRefusalsInsteadOfSMTPFailure(t *testing.T) { + cases := []struct { + name string + err error + status int + contains string + }{ + {"future", qawemail.ErrFutureWeek, http.StatusBadRequest, "未来周"}, + {"slot", qawemail.ErrSlotPending, http.StatusConflict, "尚未到达设定的发送时点"}, + {"stale", qawemail.ErrNotCurrent, http.StatusConflict, "正文/版本已变化"}, + {"inflight", qawemail.ErrSendInFlight, http.StatusConflict, "结果未知"}, + {"nopassword", qawemail.ErrNoPassword, http.StatusConflict, "授权码"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + store := &fakeWeeklyMailStore{sendErr: tc.err} + recorder := httptest.NewRecorder() + qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+strings.Repeat("c", 64)+`"}`, true), Config{QAWeeklyMail: store}) + if recorder.Code != tc.status || !strings.Contains(recorder.Body.String(), tc.contains) { + t.Fatalf("%s 应 %d 且说明原因 %q,status=%d body=%s", tc.name, tc.status, tc.contains, recorder.Code, recorder.Body.String()) + } + }) + } +} + +// SMTP 真实失败:必须 502 且带上真实原因,绝不能回“已发送”。 +func TestWeeklyMailFormalSendReportsDeliveryFailure(t *testing.T) { + store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "failed", Reason: "发送失败:smtp 登录失败: 535"}} + recorder := httptest.NewRecorder() + qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+strings.Repeat("d", 64)+`"}`, true), Config{QAWeeklyMail: store}) + if recorder.Code != http.StatusBadGateway || !strings.Contains(recorder.Body.String(), "535") { + t.Fatalf("未送达必须 502 并带真实原因,status=%d body=%s", recorder.Code, recorder.Body.String()) + } +} + +// 补发前预览必须给出真实 week/版本/收件人数,用于确认框;预览本身不投递。 +func TestWeeklyMailSendPreviewShowsExactDistribution(t *testing.T) { + store := &fakeWeeklyMailStore{preview: qawemail.SendPreview{Status: "ready", Recipients: 119, Cc: 8}} + hash := strings.Repeat("e", 64) + request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/send/2026-W45?revision=16&body_sha256="+hash, nil) + request.SetPathValue("week", "2026-W45") + request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) + recorder := httptest.NewRecorder() + qaWeeklyMailSendPreview(recorder, request, Config{QAWeeklyMail: store}) + if recorder.Code != http.StatusOK { + t.Fatalf("预览应成功,status=%d body=%s", recorder.Code, recorder.Body.String()) + } + var payload struct { + Data qawemail.SendPreview `json:"data"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if payload.Data.Recipients != 119 || payload.Data.Cc != 8 || payload.Data.Revision != 16 || payload.Data.Status != "ready" { + t.Fatalf("预览必须给出正式收件人数与版本:%+v", payload.Data) + } + if store.calls != 0 { + t.Fatal("预览不得触发发送") + } +} diff --git a/internal/httpapi/routing_bindings.go b/internal/httpapi/routing_bindings.go index fffe52f..c2e8b5c 100644 --- a/internal/httpapi/routing_bindings.go +++ b/internal/httpapi/routing_bindings.go @@ -41,6 +41,24 @@ type routingBindingView struct { // that had not been uploaded yet. A plain read reports zeros. Replanned int `json:"replanned"` RetiredDuplicates int `json:"retired_duplicates"` + // 整库封存源(LIBRARY_SOURCE_KB_*)与“测试入库绑定”是两套配置: + // 页面必须同时给出两者,并标明是否一致,避免改绑后名字变了、封存还是旧库。 + LibrarySourceInternalKB string `json:"library_source_internal_kb"` + LibrarySourceExternalKB string `json:"library_source_external_kb"` + InternalSourceState string `json:"internal_source_state"` + ExternalSourceState string `json:"external_source_state"` +} + +// sourceState 只回答“入库目标与封存源是不是同一个库”。 +func sourceState(binding, source string) string { + switch { + case source == "": + return "unconfigured" + case binding == source: + return "consistent" + default: + return "mismatch" + } } type routingKnowledgeBaseOption struct { @@ -101,7 +119,11 @@ func (config Config) routingBindingPayload(ctx context.Context, replan postgress InternalEnvFallback: storedInternal == "" && config.InternalRoutingKnowledgeBaseID != "", ExternalEnvFallback: storedExternal == "" && config.ExternalRoutingKnowledgeBaseID != "", InternalKBName: names[storedInternal], ExternalKBName: names[storedExternal], - UpdatedBy: updatedBy, WeKnoraConnected: connected, + LibrarySourceInternalKB: config.LibrarySourceInternalKB, + LibrarySourceExternalKB: config.LibrarySourceExternalKB, + InternalSourceState: sourceState(internal, config.LibrarySourceInternalKB), + ExternalSourceState: sourceState(external, config.LibrarySourceExternalKB), + UpdatedBy: updatedBy, WeKnoraConnected: connected, Replanned: replan.Replanned, RetiredDuplicates: replan.RetiredDuplicates, }, nil } diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index bca8f40..052e4ce 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -15,10 +15,12 @@ import ( "time" "knowledge-governance/internal/backuphost" + "knowledge-governance/internal/dingtalkdiscovery" "knowledge-governance/internal/governance" "knowledge-governance/internal/jobs" "knowledge-governance/internal/monitoring" postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/ppauth" "knowledge-governance/internal/qaopsai" "knowledge-governance/internal/qaopsmirror" "knowledge-governance/internal/qaopsorg" @@ -145,6 +147,10 @@ type Config struct { VersionHistoryRepo string // LibraryArchiveRoot 是整库封存产物的只读归档根;留空即未接线(页面降级)。 LibraryArchiveRoot string + // LibraryHandoffEnabled:快照搬运已接线时,发布/恢复作业先投递搬运作业, + // 由 capture 角色把不可变快照送到云端执行器并校验通过后才投递真正的发布作业。 + // 未接线即保持今天的行为(本机目标直接发布)。 + LibraryHandoffEnabled bool // LibraryTargetInstance 是实例级维护的目标实例名;留空即"未接线", // 页面不能发起按预备份恢复,接口返回原因而不是假装能恢复。 LibraryTargetInstance string @@ -155,15 +161,23 @@ type Config struct { LibraryTargetWriters []string LibraryTargetIngressURL string LibraryTargetIngressService string - LibraryTargetDockerSocket string - LibraryTargetJournalRoot string + // 入口形态与健康探针只用于如实展示"有没有闸门":none 显示"无闸门(测试模式)", + // 不能把没有闸门的测试栈说成"打开"。 + LibraryTargetIngressMode string + LibraryTargetHealthURL string + LibraryTargetDockerSocket string + LibraryTargetJournalRoot string // LibrarySourceInstance 是死信解除记录的来源实例名(封存源),留空回落到目标实例名。 LibrarySourceInstance string // LibraryAgentSocket 是主机侧封存 agent 的 unix socket;留空即页面不能发起封存。 LibraryAgentSocket string // LibrarySourceProject 是执行器应指向的实例名(agent -project,封存源)。 // 与它不一致时按"封错库"处理:不可发起,并说明差在哪。 - LibrarySourceProject string + LibrarySourceProject string + LibrarySourceApp string + LibrarySourceTenantID uint64 + LibrarySourceInternalKB string + LibrarySourceExternalKB string // LibraryExecutorStatusMaxAge 是执行器观测的有效期;超过即"无法确认"。 LibraryExecutorStatusMaxAge time.Duration // LibraryCapacityBudgetBytes 是整库归档容量预算;0 = 未设置(容量门禁不放行)。 @@ -173,6 +187,9 @@ type Config struct { LibraryProductionInternalKB string LibraryProductionExternalKB string LibraryProductionTenantID uint64 + // 整库发布还落在这些后端上;页面要显示"到底写哪儿",只给 KB ID 不够。 + LibraryProductionIndex string + LibraryProductionS3Bucket string // LibraryScopeProbe 让测试注入"目标整库是否为空"的探测;留空即用真实连接。 // 它不是运行时开关:生产部署不设置它,那次探测仍然直连目标库逐表计数。 LibraryScopeProbe func(ctx context.Context, scope string) (bool, map[string]int64, error) @@ -190,8 +207,16 @@ type Config struct { RequireWeKnoraReady bool ProductionReleaseRequestsEnabled bool // TestAutoReviewPolicy 只用于展示:让运维在界面上看到"现在自动批准到什么程度"。 - TestAutoReviewPolicy string - ProductionBackupRestoreVerified bool + TestAutoReviewPolicy string + ProductionBackupRestoreVerified bool + // restoreVerified / restoreEvidenceReason 由请求期的证据读取填入(withRestoreEvidence): + // 闸口按"当前目标是否有真实恢复验证证据"判断,而不是按可手填的 env。 + // 它们不可由配置注入,避免把证据变成另一个开关。 + restoreVerified bool + restoreEvidenceReason string + // restoreEvidenceChecked 表示这个请求真的读过证据行:只有读过之后才适用 + // "失败/读取错误优先于 env"。从未读过证据的旧调用点仍按历史 env 语义兜底。 + restoreEvidenceChecked bool ProductionReleaseAuthorizerRef string ProductionReleaseAuthorizationToken string // DingtalkSources 枚举「我账号下能看到」的钉钉知识库与钉盘空间(只读,dws)。 @@ -199,6 +224,8 @@ type Config struct { DingtalkSources dingtalkSourcesLister // DingtalkDocuments 列在线文档/表格并校验可读(只读,dws)。 DingtalkDocuments dingtalkDocLister + DWSLogin *dingtalkdiscovery.DeviceLoginManager + PPConnection *ppauth.Manager NewID func() (string, error) Auth *AuthConfig } @@ -233,6 +260,9 @@ func NewHandler(config Config) (http.Handler, error) { config.NewID = newID } mux := http.NewServeMux() + registerDWSLoginRoutes(mux, config) + registerPPConnectionRoutes(mux, config) + mux.HandleFunc("POST /api/v1/dingtalk-spaces/validate", func(w http.ResponseWriter, r *http.Request) { validateDWSSpace(w, r, config) }) registerQAAIRoutes(mux, config) mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) }) mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) }) @@ -263,6 +293,8 @@ func NewHandler(config Config) (http.Handler, error) { mux.HandleFunc("DELETE /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) }) mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/sends", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSends(w, r, config) }) mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/test", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailTest(w, r, config) }) + mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/send/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSendPreview(w, r, config) }) + mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/send/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSend(w, r, config) }) mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailImage(w, r, config) }) mux.HandleFunc("GET /api/v1/qa-ops/master/field-options", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldOptions(w, r, config) }) mux.HandleFunc("POST /api/v1/qa-ops/master/records/{id}/fields", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldPatch(w, r, config) }) @@ -352,6 +384,9 @@ func NewHandler(config Config) (http.Handler, error) { internal, external := config.effectiveRoutingTargets(r.Context()) writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"internal_enabled": internal != "", "external_enabled": external != ""}}) }) + mux.HandleFunc("GET /api/v1/system/worker-capabilities", func(w http.ResponseWriter, r *http.Request) { + config.handleWorkerCapabilities(w, r) + }) mux.HandleFunc("GET /api/v1/routing-bindings", func(w http.ResponseWriter, r *http.Request) { if config.RoutingBindings == nil { writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "routing bindings storage unavailable"}) @@ -445,6 +480,9 @@ func NewHandler(config Config) (http.Handler, error) { librarySnapshotDetail(w, r, config) }) // 页面发起封存:只投递作业(主机侧 agent 执行),并回读作业真实状态。 + mux.HandleFunc("POST /api/v1/library/source-associations", func(w http.ResponseWriter, r *http.Request) { + libraryLegacySourceBind(w, r, config) + }) mux.HandleFunc("POST /api/v1/library/captures", func(w http.ResponseWriter, r *http.Request) { libraryCaptureEnqueue(w, r, config) }) @@ -537,6 +575,10 @@ func NewHandler(config Config) (http.Handler, error) { mux.HandleFunc("POST /api/v1/library/jobs/{id}/resume", func(w http.ResponseWriter, r *http.Request) { libraryJobResume(w, r, config) }) + // 封存完成但终态回写失败时,只按已完成队列+精确版本+归档复核修复该作业。 + mux.HandleFunc("POST /api/v1/library/jobs/{id}/reconcile-capture", func(w http.ResponseWriter, r *http.Request) { + libraryCaptureReconcile(w, r, config) + }) // 生产同步唯一入口:闸口未齐不建作业,返回缺项而不是假 Accepted。 mux.HandleFunc("POST /api/v1/library/syncs", func(w http.ResponseWriter, r *http.Request) { librarySyncEnqueue(w, r, config) @@ -545,6 +587,14 @@ func NewHandler(config Config) (http.Handler, error) { mux.HandleFunc("POST /api/v1/library/baselines", func(w http.ResponseWriter, r *http.Request) { libraryBaselineEnqueue(w, r, config) }) + // 恢复验证:真实备份 → canary → 恢复 → 复核,通过后证据按当前目标登记, + // 同步闸口据此放行(不再需要页面/环境变量手填 verified)。 + mux.HandleFunc("POST /api/v1/library/verifications", func(w http.ResponseWriter, r *http.Request) { + libraryVerifyEnqueue(w, r, config) + }) + mux.HandleFunc("GET /api/v1/library/verifications", func(w http.ResponseWriter, r *http.Request) { + libraryVerifications(w, r, config) + }) // 全部 main 提交时间线(读本库缓存,不直接打 Gitea) mux.HandleFunc("GET /api/v1/version-history", func(w http.ResponseWriter, r *http.Request) { versionHistoryList(w, r, config) @@ -776,6 +826,15 @@ func createJob(w http.ResponseWriter, r *http.Request, config Config) { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "通讯录同步任务只能从问答运营的管理员入口创建"}) return } + // 保留类型:`library.*` 的准入条件(闸口、精确授权、维护互斥、目标身份)只在专用 + // 入口里判断。通用入口只做通用 engineer 角色检查,让它在队列里造一个 library.* + // 作业就等于绕过全部准入——worker 拿到没有业务行的作业仍会去取维护锁(F14)。 + // 这里按前缀整类拒绝,而不是逐个类型列举:新增 library 作业类型时不会漏。 + if governance.IsReservedLibraryJobType(input.Type) { + writeJSON(w, http.StatusBadRequest, map[string]string{ + "error": "整库发布相关作业只能从发布管理专用入口创建"}) + return + } if strings.TrimSpace(input.Type) == "" || len(input.Type) > 100 { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "type is required and must not exceed 100 characters"}) return diff --git a/internal/httpapi/source_audit.go b/internal/httpapi/source_audit.go index 3a60a18..88d8c01 100644 --- a/internal/httpapi/source_audit.go +++ b/internal/httpapi/source_audit.go @@ -35,7 +35,7 @@ func listSourceAudit(w http.ResponseWriter, r *http.Request, config Config) { writeJSON(w, 501, map[string]string{"error": "audit not configured"}) return } - page, err := reader.ListSourceAudit(r.Context(), limit, offset) + page, err := combinedSourceAudit(r.Context(), reader, config.PPConnection, limit, offset) if err != nil { writeJSON(w, 500, map[string]string{"error": "无法读取数据源操作记录"}) return diff --git a/internal/httpapi/worker_capabilities.go b/internal/httpapi/worker_capabilities.go new file mode 100644 index 0000000..5bce58e --- /dev/null +++ b/internal/httpapi/worker_capabilities.go @@ -0,0 +1,91 @@ +package httpapi + +import ( + "context" + "net/http" + "slices" + "time" + + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// workerHeartbeatStore 是队列存活记录的只读视图。页面要回答“执行器在不在”, +// 只能看 worker 认领任务时自己写下的 job_types;readiness 只证明接口可达。 +type workerHeartbeatStore interface { + ListWorkerHeartbeats(context.Context) ([]postgresstore.WorkerHeartbeat, error) +} + +type workerCapabilityView struct { + WorkerID string `json:"worker_id"` + JobTypes []string `json:"job_types"` + Alive bool `json:"alive"` + LastSeenAt string `json:"last_seen_at"` +} + +type testUploadCapability struct { + State string `json:"state"` + Consumers int `json:"consumers"` + Detail string `json:"detail"` +} + +// 与 qaopsmirror 的工作就绪判定同一个窗口:2 分钟没有认领记录就当作不在线。 +const workerHeartbeatTTL = 2 * time.Minute + +const testUploadJobType = "test.upload" + +func testUploadCapabilityOf(workers []postgresstore.WorkerHeartbeat, now time.Time) testUploadCapability { + alive, consumers := 0, 0 + for _, worker := range workers { + if now.Sub(worker.LastSeenAt) > workerHeartbeatTTL { + continue + } + alive++ + if slices.Contains(worker.JobTypes, testUploadJobType) { + consumers++ + } + } + switch { + case consumers > 0: + return testUploadCapability{State: "enabled", Consumers: consumers, + Detail: "上传/解析执行器已注册(认领过 test.upload)"} + case alive > 0: + return testUploadCapability{State: "disabled", Consumers: 0, + Detail: "worker 在线但没有注册 test.upload:上传/解析任务不会被消费"} + default: + return testUploadCapability{State: "stale", Consumers: 0, + Detail: "没有有效的 worker 认领记录:执行器未运行,或从未接单"} + } +} + +func (config Config) handleWorkerCapabilities(w http.ResponseWriter, r *http.Request) { + store, ok := config.Store.(workerHeartbeatStore) + if !ok || store == nil { + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ + "test_upload": testUploadCapability{State: "unknown", Detail: "worker 存活记录不可用"}, + "workers": []workerCapabilityView{}, + }}) + return + } + workers, err := store.ListWorkerHeartbeats(r.Context()) + if err != nil { + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ + "test_upload": testUploadCapability{State: "unknown", Detail: "读取 worker 存活记录失败"}, + "workers": []workerCapabilityView{}, + }}) + return + } + now := time.Now().UTC() + views := make([]workerCapabilityView, 0, len(workers)) + for _, worker := range workers { + views = append(views, workerCapabilityView{ + WorkerID: worker.WorkerID, + JobTypes: worker.JobTypes, + Alive: now.Sub(worker.LastSeenAt) <= workerHeartbeatTTL, + LastSeenAt: worker.LastSeenAt.UTC().Format(time.RFC3339), + }) + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ + "test_upload": testUploadCapabilityOf(workers, now), + "workers": views, + }}) +} diff --git a/internal/httpapi/worker_capabilities_test.go b/internal/httpapi/worker_capabilities_test.go new file mode 100644 index 0000000..95e65cb --- /dev/null +++ b/internal/httpapi/worker_capabilities_test.go @@ -0,0 +1,35 @@ +package httpapi + +import ( + "testing" + "time" + + postgresstore "knowledge-governance/internal/platform/postgres" +) + +func TestTestUploadCapabilityReflectsWorkerHeartbeats(t *testing.T) { + now := time.Date(2026, time.November, 17, 7, 0, 0, 0, time.UTC) + fresh := now.Add(-10 * time.Second) + stale := now.Add(-5 * time.Minute) + + cases := []struct { + name string + workers []postgresstore.WorkerHeartbeat + state string + consume int + }{ + {"no heartbeats", nil, "stale", 0}, + {"heartbeat too old", []postgresstore.WorkerHeartbeat{{LastSeenAt: stale, JobTypes: []string{"test.upload"}}}, "stale", 0}, + {"worker online without upload chain", []postgresstore.WorkerHeartbeat{{LastSeenAt: fresh, JobTypes: []string{"source.scan.dingtalk"}}}, "disabled", 0}, + {"enabled consumer", []postgresstore.WorkerHeartbeat{{LastSeenAt: fresh, JobTypes: []string{"test.upload", "test.poll"}}}, "enabled", 1}, + } + for _, tc := range cases { + got := testUploadCapabilityOf(tc.workers, now) + if got.State != tc.state || got.Consumers != tc.consume { + t.Fatalf("%s: got state=%s consumers=%d, want %s/%d", tc.name, got.State, got.Consumers, tc.state, tc.consume) + } + if got.Detail == "" { + t.Fatalf("%s: detail must explain the state", tc.name) + } + } +} diff --git a/internal/jobs/lease_loss_test.go b/internal/jobs/lease_loss_test.go new file mode 100644 index 0000000..f8fda9e --- /dev/null +++ b/internal/jobs/lease_loss_test.go @@ -0,0 +1,51 @@ +package jobs + +import ( + "context" + "errors" + "testing" + "time" +) + +// leaseLostQueue 模拟"心跳发现租约已经不属于自己"。 +type leaseLostQueue struct { + recordingQueue + lost chan struct{} +} + +func (q *leaseLostQueue) Heartbeat(context.Context, string, string, time.Time, time.Duration) error { + close(q.lost) + return errors.New("audit lease lost") +} + +// F13:心跳报失租之后,handler 必须**立刻失去授权**(ctx 被取消)。 +// +// 旧实现只把错误存进 heartbeatResult,等 handler 自己返回才处理;handler 在 +// 那段时间里仍以为自己拥有目标,会继续写业务状态、释放维护锁——而另一个代次 +// 可能已经接管并开了新窗口(共享 flock 管不到这些写)。 +func TestLeaseLossMustCancelHandler(t *testing.T) { + q := &leaseLostQueue{recordingQueue: recordingQueue{claimJob: &Job{ID: "audit", Type: "audit"}}, lost: make(chan struct{})} + continued := false + w, err := NewWorker(WorkerConfig{ + Queue: q, WorkerID: "audit", LeaseDuration: time.Second, HeartbeatInterval: time.Millisecond, + Handlers: map[string]Handler{"audit": func(ctx context.Context, _ Job) error { + <-q.lost + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(200 * time.Millisecond): + continued = true + return nil + } + }}, + }) + if err != nil { + t.Fatal(err) + } + if _, err := w.RunOnce(context.Background()); err == nil { + t.Fatal("失租后 RunOnce 必须报错,不能当成正常完成") + } + if continued { + t.Fatal("心跳报失租后 handler 仍在运行:旧代次还能继续写目标") + } +} diff --git a/internal/jobs/worker.go b/internal/jobs/worker.go index 77516c1..0f42e0e 100644 --- a/internal/jobs/worker.go +++ b/internal/jobs/worker.go @@ -140,6 +140,10 @@ func (w *Worker) RunOnce(ctx context.Context) (bool, error) { } return true, err } + // handler 必须能被"失租"取消:心跳报错说明这个代次已经不再拥有作业, + // 若还让 handler 继续跑,它会以旧代次身份继续写业务状态/释放维护锁(F13)。 + handlerCtx, cancelHandler := context.WithCancel(ctx) + defer cancelHandler() heartbeatCtx, stopHeartbeat := context.WithCancel(ctx) heartbeatResult := make(chan error, 1) go func() { @@ -152,6 +156,9 @@ func (w *Worker) RunOnce(ctx context.Context) (bool, error) { return case <-ticker.C: if err := w.queue.Heartbeat(ctx, job.ID, w.workerID, w.now(), w.leaseDuration); err != nil { + // 先撤销 handler 的授权,再把错误交给下面统一处理: + // 顺序反过来就会出现"错误已记录、handler 还在写"的空窗。 + cancelHandler() heartbeatResult <- err return } @@ -159,8 +166,9 @@ func (w *Worker) RunOnce(ctx context.Context) (bool, error) { } }() - handlerErr := handler(ctx, *job) + handlerErr := handler(handlerCtx, *job) stopHeartbeat() + cancelHandler() heartbeatErr := <-heartbeatResult if handlerErr == nil { handlerErr = heartbeatErr diff --git a/internal/libraryadmission/admission.go b/internal/libraryadmission/admission.go new file mode 100644 index 0000000..c7d181f --- /dev/null +++ b/internal/libraryadmission/admission.go @@ -0,0 +1,91 @@ +// Package libraryadmission 是**执行域准入**:在 worker 注册整库发布 handler 之前, +// 用目标实况与治理库事实回答"这个进程能不能安全地写这个目标"。 +// +// 为什么必须有这一层(R4):维护窗口的互斥只覆盖本治理平台的执行者。旧 release 路由 +// (独立 release-worker)直接写同一个物理目标(DB/S3/ES),它不经过 library 维护锁。 +// 两个执行域并存时,"未知重叠"必须**拒绝**,不能靠某个人去看部署文档。 +// +// 这里只做判定(纯函数),探针由调用方注入:判定可以单测,探针只能读、不能改, +// 也绝不停止任何既有服务(停旧 worker 是运维决定,不是这个包的副作用)。 +package libraryadmission + +import ( + "errors" + "fmt" +) + +// Target 是一个执行域的目标身份。Configured 来自部署配置,Live 来自目标实况。 +type Target struct { + DatabaseEndpoint string + Index string + Bucket string + KnowledgeBaseID string + TenantID uint64 + SchemaVersion int + Instance string +} + +// Facts 是判定所需的**可核验事实**。任何一个 Err 非空都表示"未知",必须拒绝。 +type Facts struct { + // Live 是目标按配置连上去之后**读回来**的身份(不是配置回声)。 + Live Target + LiveErr error + // LiveDirty 表示目标 schema 处于 dirty(迁移未完成)。 + LiveDirty bool + // LegacyReleaseKB 是旧 release 路由(production_kb_bindings)写入的目标知识库。 + // 空串表示旧路由未绑定;读失败必须通过 LegacyErr 表达,不能当"没有"。 + LegacyReleaseKB string + LegacyErr error + // HeldInstance/HeldJob 是治理库里**未释放**的维护窗口持有者(空=没有窗口)。 + HeldInstance string + HeldJob string + HeldErr error +} + +// Verify 判定"当前进程可以独占这个目标"。 +// +// 允许的前提全部是**读出来的**:目标实况与配置一致、schema 已知且未 dirty、 +// 旧 release 路由不指向同一个知识库、没有别的实例持有未释放的维护窗口。 +// 任何一条未知或不一致 ⇒ 返回错误(调用方必须据此不注册 handler,即 fail closed)。 +func Verify(configured Target, facts Facts) error { + if facts.LiveErr != nil { + return fmt.Errorf("读不到目标实况,无法证明执行域唯一:%w", facts.LiveErr) + } + if facts.LegacyErr != nil { + return fmt.Errorf("读不到旧 release 路由的目标绑定,无法判断是否重叠:%w", facts.LegacyErr) + } + if facts.HeldErr != nil { + return fmt.Errorf("读不到未释放的维护窗口,无法判断是否重叠:%w", facts.HeldErr) + } + if facts.LiveDirty { + return errors.New("目标 schema 处于 dirty 状态(迁移未完成):拒绝注册整库发布执行器") + } + if configured.KnowledgeBaseID == "" || configured.TenantID == 0 { + return errors.New("整库目标未配置知识库/租户:拒绝注册整库发布执行器") + } + if facts.Live.KnowledgeBaseID != configured.KnowledgeBaseID || facts.Live.TenantID != configured.TenantID { + return fmt.Errorf("目标实况是 %d/%s,配置指向 %d/%s:拒绝在没核对清楚的目标上执行", + facts.Live.TenantID, facts.Live.KnowledgeBaseID, configured.TenantID, configured.KnowledgeBaseID) + } + if facts.Live.SchemaVersion == 0 { + return errors.New("读不到目标 schema 版本:无法证明与整库发布兼容") + } + if configured.SchemaVersion != 0 && facts.Live.SchemaVersion != configured.SchemaVersion { + return fmt.Errorf("目标 schema 版本 %d 与声明 %d 不一致:拒绝执行", + facts.Live.SchemaVersion, configured.SchemaVersion) + } + if configured.Index != "" && facts.Live.Index != "" && configured.Index != facts.Live.Index { + return fmt.Errorf("目标索引 %q 与配置 %q 不一致:拒绝执行", facts.Live.Index, configured.Index) + } + // 旧 release 路由与整库目标指向同一个知识库 ⇒ 两个执行域会互相绕过维护锁。 + if facts.LegacyReleaseKB != "" && facts.LegacyReleaseKB == configured.KnowledgeBaseID { + return fmt.Errorf("旧 release 路由已把发布目标绑定到同一个知识库 %s:两个执行域会绕过维护互斥,拒绝注册整库执行器(先隔离或退役旧路由)", + facts.LegacyReleaseKB) + } + // 别的实例正持有未释放的维护窗口 ⇒ 目标此刻归它。 + if facts.HeldInstance != "" && configured.Instance != "" && facts.HeldInstance != configured.Instance { + return fmt.Errorf("目标实例 %s 正被 %s(作业 %s)持有未释放的维护窗口:拒绝注册重复执行器", + configured.Instance, facts.HeldInstance, facts.HeldJob) + } + return nil +} diff --git a/internal/libraryadmission/admission_test.go b/internal/libraryadmission/admission_test.go new file mode 100644 index 0000000..ef8e7c9 --- /dev/null +++ b/internal/libraryadmission/admission_test.go @@ -0,0 +1,93 @@ +package libraryadmission + +import ( + "errors" + "strings" + "testing" +) + +func base() (Target, Facts) { + configured := Target{DatabaseEndpoint: "pg:5432/db", Index: "idx", Bucket: "b", + KnowledgeBaseID: "kb-int", TenantID: 10001, SchemaVersion: 71, Instance: "kgseal"} + facts := Facts{Live: Target{DatabaseEndpoint: "pg:5432/db", Index: "idx", Bucket: "b", + KnowledgeBaseID: "kb-int", TenantID: 10001, SchemaVersion: 71, Instance: "kgseal"}} + return configured, facts +} + +func TestVerifyAllowsCleanUniqueTarget(t *testing.T) { + configured, facts := base() + if err := Verify(configured, facts); err != nil { + t.Fatalf("干净且唯一的目标应放行:%v", err) + } +} + +// 未知一律拒绝:读不到实况/旧路由/维护窗口。 +func TestVerifyFailsClosedOnUnknown(t *testing.T) { + configured, facts := base() + cases := map[string]Facts{ + "读不到目标实况": {LiveErr: errors.New("connect refused")}, + "读不到旧release": {LegacyErr: errors.New("query failed")}, + "读不到维护窗口": {HeldErr: errors.New("query failed")}, + } + for name, broken := range cases { + if err := Verify(configured, broken); err == nil { + t.Fatalf("%s 时必须拒绝", name) + } + } + if err := Verify(configured, Facts{Live: Target{KnowledgeBaseID: "kb-int", TenantID: 10001}}); err == nil || + !strings.Contains(err.Error(), "schema") { + t.Fatalf("schema 读不到时必须拒绝:%v", err) + } + _ = facts +} + +// 目标实况与配置不一致 ⇒ 拒绝(不能只信配置)。 +func TestVerifyRejectsMismatchedLiveTarget(t *testing.T) { + configured, facts := base() + facts.Live.KnowledgeBaseID = "another-kb" + if err := Verify(configured, facts); err == nil { + t.Fatal("目标实况与配置不一致必须拒绝") + } + configured, facts = base() + facts.LiveDirty = true + if err := Verify(configured, facts); err == nil { + t.Fatal("dirty schema 必须拒绝") + } + configured, facts = base() + facts.Live.SchemaVersion = 72 + if err := Verify(configured, facts); err == nil { + t.Fatal("schema 版本不一致必须拒绝") + } +} + +// 旧 release 路由指向同一个知识库 ⇒ 两个执行域重叠,拒绝。 +func TestVerifyRejectsLegacyReleaseOverlap(t *testing.T) { + configured, facts := base() + facts.LegacyReleaseKB = "kb-int" + err := Verify(configured, facts) + if err == nil { + t.Fatal("旧 release 路由与整库目标同一个 KB 时必须拒绝(R4)") + } + if !strings.Contains(err.Error(), "旧 release") { + t.Fatalf("拒绝原因必须指向旧 release 路由:%v", err) + } + // 指向别的知识库则不重叠。 + facts.LegacyReleaseKB = "kb-other" + if err := Verify(configured, facts); err != nil { + t.Fatalf("不同知识库不算重叠:%v", err) + } +} + +// 别的实例持有未释放窗口 ⇒ 拒绝;自己持有则允许(重启后的自我接管)。 +func TestVerifyRejectsForeignHeldWindow(t *testing.T) { + configured, facts := base() + facts.HeldInstance, facts.HeldJob = "other-instance", "libsync-x" + if err := Verify(configured, facts); err == nil { + t.Fatal("别的实例持有未释放窗口时必须拒绝") + } + configured, facts = base() + facts.HeldInstance, facts.HeldJob = "kgseal", "libsync-x" + if err := Verify(configured, facts); err != nil { + t.Fatalf("自己持有窗口时允许注册(重启接管):%v", err) + } +} diff --git a/internal/libraryagent/agent.go b/internal/libraryagent/agent.go index f9a1051..43765a6 100644 --- a/internal/libraryagent/agent.go +++ b/internal/libraryagent/agent.go @@ -26,6 +26,8 @@ import ( "sync" "syscall" "time" + + "knowledge-governance/internal/librarydsn" ) // Config is fixed at start-up by the operator (systemd unit / CLI flags). It is @@ -47,7 +49,10 @@ type Config struct { Project string Writers string NonWriters string - MaxDuration time.Duration + // AllowedPeerUIDs 是除"与 agent 同 uid"之外额外放行的连接方 uid。 + // 默认空:只允许同 uid。容器里固定以某个 uid 运行时,由部署参数显式列出。 + AllowedPeerUIDs []uint32 + MaxDuration time.Duration // StopGrace bounds the graceful stop of one operation: SIGTERM first (the // child aborts the maintenance window and restores writers), then SIGKILL // only after this grace period. It must exceed the child's own restore budget. @@ -212,7 +217,11 @@ func (a *Agent) Serve(ctx context.Context) error { func (a *Agent) handle(ctx context.Context, conn net.Conn) { defer conn.Close() - if err := peerAllowed(conn); err != nil { + allowed := make(map[uint32]bool, len(a.config.AllowedPeerUIDs)) + for _, uid := range a.config.AllowedPeerUIDs { + allowed[uid] = true + } + if err := peerAllowed(conn, allowed); err != nil { _ = json.NewEncoder(conn).Encode(response{OK: false, Error: err.Error()}) return } @@ -429,15 +438,22 @@ func (a *Agent) health() response { } // identity 被日志与健康应答共用一份,避免两处描述漂移。 +// +// 数据库只报来源模式(container|external|file),不报地址:agent 的应答会被治理侧 +// 存档,DSN 里带口令,一旦写进身份就再也收不回来了。 func (c Config) identity() map[string]any { identity := map[string]any{ "project": c.Project, "archive_root": c.ArchiveRoot, "journal_root": c.JournalRoot, "source_app": c.SourceApp, - "source_pg": c.SourcePG, "source_es": c.SourceES, - "writers": c.Writers, + // source_pg 仍是容器名(不是地址、不是凭据),保留它以让既有健康页/事后核对 + // 读得到同一份字段;数据库**来源**由下面两个模式字段表达,外部模式下它为空。 + "source_pg": c.SourcePG, + "source_db": librarydsn.SourceMode(c.SourcePG), + "governance_db": librarydsn.GovernanceMode(c.GovernancePG), + "writers": c.Writers, } if c.SourceS3Endpoint != "" { identity["source_s3_endpoint"] = c.SourceS3Endpoint diff --git a/internal/libraryagent/peer_linux.go b/internal/libraryagent/peer_linux.go index 07887af..491ca51 100644 --- a/internal/libraryagent/peer_linux.go +++ b/internal/libraryagent/peer_linux.go @@ -11,7 +11,7 @@ import ( // agent. File mode 0600 already limits connect() to that uid; the credential // check makes the boundary explicit and fails closed if the socket is ever // reached another way (bind mount into a container with a different uid). -func peerAllowed(conn net.Conn) error { +func peerAllowed(conn net.Conn, allowed map[uint32]bool) error { unixConn, ok := conn.(*net.UnixConn) if !ok { return errors.New("unsupported transport") @@ -30,7 +30,9 @@ func peerAllowed(conn net.Conn) error { if controlErr != nil || credential == nil { return errors.New("peer credentials unavailable") } - if credential.Uid != uint32(os.Geteuid()) { + // 默认只允许与 agent 同 uid 的连接;显式声明过的 uid(例如容器里的 + // 固定运行用户)才放行。放行清单来自部署参数,不是"任何人"。 + if credential.Uid != uint32(os.Geteuid()) && !allowed[credential.Uid] { return errors.New("peer uid is not allowed") } return nil diff --git a/internal/libraryagent/peer_other.go b/internal/libraryagent/peer_other.go index a7eb1fb..f1ccf8d 100644 --- a/internal/libraryagent/peer_other.go +++ b/internal/libraryagent/peer_other.go @@ -9,6 +9,6 @@ import ( // The capture host is Linux (Docker + unix socket); other platforms refuse // rather than guess at peer credentials. -func peerAllowed(net.Conn) error { +func peerAllowed(net.Conn, map[uint32]bool) error { return errors.New("library agent requires Linux peer credentials") } diff --git a/internal/librarydiff/wiki.go b/internal/librarydiff/wiki.go index 40b3839..51e7b2a 100644 --- a/internal/librarydiff/wiki.go +++ b/internal/librarydiff/wiki.go @@ -58,16 +58,20 @@ type WikiResult struct { } type wikiPage struct { - slug string - title string - pageType string - status string - content string - sources []string - citations []string - outLinks []string - inLinks []string - category string + slug string + title string + pageType string + status string + // summary / parentSlug 是持久业务字段:只改它们同样是"内容变了", + // 旧的比较结构根本没读这两个字段,于是发布前预览会漏报(F18)。 + summary string + parentSlug string + content string + sources []string + citations []string + outLinks []string + inLinks []string + category string } // CompareWiki 以 base 为基准(当前生产版本),target 为拟发布版本,逐页比对语义。 @@ -150,6 +154,17 @@ func diffWikiPage(previous, next wikiPage) (WikiContribution, bool) { if previous.pageType != next.pageType { change.Changed = append(change.Changed, "page_type") } + // 标题/摘要/父级是页面身份与导航的一部分:它们在持久列里,改了就是差异, + // 不能被"正文没变"掩掉(F18)。 + if previous.title != next.title { + change.Changed = append(change.Changed, "title") + } + if previous.summary != next.summary { + change.Changed = append(change.Changed, "summary") + } + if previous.parentSlug != next.parentSlug { + change.Changed = append(change.Changed, "parent_slug") + } return change, len(change.Changed) > 0 } @@ -169,6 +184,8 @@ func indexWiki(rows []map[string]any) (map[string]wikiPage, error) { page.pageType, _ = row["page_type"].(string) page.status, _ = row["status"].(string) page.content, _ = row["content"].(string) + page.summary, _ = row["summary"].(string) + page.parentSlug, _ = row["parent_slug"].(string) var err error if page.sources, err = stringList(row["source_refs"]); err != nil { return nil, fmt.Errorf("wiki %s source_refs: %w", slug, err) diff --git a/internal/librarydiff/wiki_metadata_test.go b/internal/librarydiff/wiki_metadata_test.go new file mode 100644 index 0000000..b5ff50f --- /dev/null +++ b/internal/librarydiff/wiki_metadata_test.go @@ -0,0 +1,37 @@ +package librarydiff + +import "testing" + +// F18:只改 title / summary / parent_slug 也必须在发布前差异里出现。 +// 旧比较结构根本没读 summary/parent_slug,title 读了却不比较——三种改动都被漏报, +// 于是"预览无变化"可以对应一次真实的元数据变更。 +func TestWikiMetadataChangeMustAppear(t *testing.T) { + for _, field := range []string{"title", "summary", "parent_slug"} { + t.Run(field, func(t *testing.T) { + before := map[string]any{"slug": "page-a", "title": "old", "summary": "old", + "parent_slug": "old", "content": "unchanged"} + after := map[string]any{"slug": "page-a", "title": "old", "summary": "old", + "parent_slug": "old", "content": "unchanged"} + after[field] = "new" + result, err := CompareWiki([]map[string]any{before}, []map[string]any{after}) + if err != nil { + t.Fatal(err) + } + if result.Updated != 1 { + t.Fatalf("只改 %s 必须记成 updated=1:%+v", field, result) + } + if len(result.Pages) != 1 || len(result.Pages[0].Changed) == 0 { + t.Fatalf("差异项必须列出改了哪些字段:%+v", result.Pages) + } + }) + } + // 反例:完全没有变化时不报差异(避免把"无变化"也渲染成更新)。 + same := map[string]any{"slug": "page-b", "title": "t", "summary": "s", "parent_slug": "p", "content": "c"} + result, err := CompareWiki([]map[string]any{same}, []map[string]any{same}) + if err != nil { + t.Fatal(err) + } + if result.Updated != 0 || len(result.Pages) != 0 { + t.Fatalf("无变化不应产生差异:%+v", result) + } +} diff --git a/internal/librarydsn/dsn.go b/internal/librarydsn/dsn.go new file mode 100644 index 0000000..31b4dea --- /dev/null +++ b/internal/librarydsn/dsn.go @@ -0,0 +1,140 @@ +// Package librarydsn 决定整库采集链路里两个 DSN 究竟从哪来。 +// +// 为什么要有它:容器模式下 DSN 是"源库容器的地址 + 源应用容器的 env"拼出来的; +// RDS 型 0.9.0 栈没有源库容器(库是托管实例),治理库同样只在外部。旧拼法在那种 +// 栈上不是权限不够,而是地址解析方式错了——库根本没有容器地址可查。把"用哪种 +// 来源"收敛成一处,libraryctl 与 libraryagent 共用同一份判定,日志/describe 只报 +// 模式(container|external|file),永远不报地址与凭据。 +package librarydsn + +import ( + "errors" + "fmt" + "net" + "net/url" + "strings" + + "knowledge-governance/internal/dobotaiops" +) + +const ( + // SourceContainer:-source-pg 给了容器名,地址从容器网络解析(0.7.1 栈)。 + SourceContainer = "container" + // SourceExternal:-source-pg 为空,直连源应用容器 env 里声明的托管库(RDS)。 + SourceExternal = "external" + + // GovernanceContainer:-governance-pg 给了容器名,用 docker exec psql 读。 + GovernanceContainer = "container" + // GovernanceFile:-governance-pg 为空,DSN 来自 0600 文件(LIBRARY_GOVERNANCE_DSN_FILE)。 + GovernanceFile = "file" +) + +// allowedSSLModes 是允许的 sslmode 集合。 +// +// 只收这四个:prefer/allow 会在服务端不支持时**静默降级成明文**,托管实例上那等于 +// "以为加密了其实没有"——这种"看起来配好了"的失败模式比直接报错更难发现。 +var allowedSSLModes = map[string]bool{ + "disable": true, // 仅显式测试:本机回环或明确无 TLS 的隔离库 + "require": true, + "verify-ca": true, + "verify-full": true, +} + +// SourceMode 把 -source-pg 的取值翻译成来源模式。空值 = 外部(RDS)。 +func SourceMode(sourcePG string) string { + if strings.TrimSpace(sourcePG) == "" { + return SourceExternal + } + return SourceContainer +} + +// GovernanceMode 把 -governance-pg 的取值翻译成来源模式。空值 = DSN 文件。 +func GovernanceMode(governancePG string) string { + if strings.TrimSpace(governancePG) == "" { + return GovernanceFile + } + return GovernanceContainer +} + +// ContainerURL 复现容器模式原有的 DSN 形状:地址来自容器网络,sslmode=disable +// (容器私网内没有 TLS 终结)。抽到这里只为一件事:让"模式选择"有一条可测的路径, +// 而形状与旧实现逐字节一致(真跑过的栈不能因为重构换了连接串)。 +func ContainerURL(address string, app map[string]string) (string, error) { + if strings.TrimSpace(address) == "" { + return "", errors.New("source container address is empty") + } + for _, key := range []string{"DB_USER", "DB_PASSWORD", "DB_NAME"} { + if app[key] == "" { + return "", fmt.Errorf("source app environment is missing %s", key) + } + } + target := url.URL{ + Scheme: "postgres", + User: url.UserPassword(app["DB_USER"], app["DB_PASSWORD"]), + Host: net.JoinHostPort(address, defaultPort(app["DB_PORT"])), + Path: "/" + app["DB_NAME"], + RawQuery: url.Values{"sslmode": {"disable"}}.Encode(), + } + return target.String(), nil +} + +// SourceURL 用源应用容器 env 里的 DB_* 直连托管库(RDS)。 +// +// 缺哪个变量就点哪个变量名:把"连接被拒"与"配置缺一项"分开,才不用去猜着改。 +// 错误里只有变量名——DB_PASSWORD 的值绝不能出现在任何一处输出里。 +func SourceURL(app map[string]string, getenv func(string) string) (string, error) { + missing := []string{} + for _, key := range []string{"DB_HOST", "DB_USER", "DB_NAME"} { + if strings.TrimSpace(app[key]) == "" { + missing = append(missing, key) + } + } + // 口令不 TrimSpace:前后空格也是口令的一部分,改掉就成另一个口令了。 + if app["DB_PASSWORD"] == "" { + missing = append(missing, "DB_PASSWORD") + } + if len(missing) > 0 { + return "", fmt.Errorf("source app environment is missing %s", strings.Join(missing, ", ")) + } + sslmode := strings.TrimSpace(getenv("LIBRARY_SOURCE_DB_SSLMODE")) + if sslmode == "" { + sslmode = "require" + } + if !allowedSSLModes[sslmode] { + return "", errors.New("LIBRARY_SOURCE_DB_SSLMODE must be one of disable, require, verify-ca, verify-full") + } + target := url.URL{ + Scheme: "postgres", + User: url.UserPassword(app["DB_USER"], app["DB_PASSWORD"]), + Host: net.JoinHostPort(strings.TrimSpace(app["DB_HOST"]), defaultPort(app["DB_PORT"])), + Path: "/" + strings.TrimSpace(app["DB_NAME"]), + RawQuery: url.Values{"sslmode": {sslmode}}.Encode(), + } + return target.String(), nil +} + +// GovernanceURL 从 0600 文件读治理库 DSN。 +// +// 文件读法复用 dobotaiops.ReadDSNFile:那里已经把"必须是普通文件、必须 0600、 +// 错误只报路径与原因"钉住并测过——再写一份同义实现只会让两条路径的规则慢慢分叉。 +func GovernanceURL(getenv func(string) string) (string, error) { + path := strings.TrimSpace(getenv("LIBRARY_GOVERNANCE_DSN_FILE")) + if path == "" { + return "", errors.New("LIBRARY_GOVERNANCE_DSN_FILE is not set: the governance DSN file is required when -governance-pg is empty") + } + dsn, err := dobotaiops.ReadDSNFile(path) + if err != nil { + // ReadDSNFile 的错误只含路径与原因,不含 DSN/口令。 + return "", fmt.Errorf("governance DSN file unusable: %w", err) + } + return dsn, nil +} + +// defaultPort:托管实例的连接信息里端口常常单独给;缺了就按 PostgreSQL 默认。 +// 端口不是凭据,给默认值不会把"配错了"藏起来。 +func defaultPort(port string) string { + if trimmed := strings.TrimSpace(port); trimmed != "" { + return trimmed + } + return "5432" +} diff --git a/internal/librarydsn/dsn_test.go b/internal/librarydsn/dsn_test.go new file mode 100644 index 0000000..bd76f6c --- /dev/null +++ b/internal/librarydsn/dsn_test.go @@ -0,0 +1,176 @@ +package librarydsn + +import ( + "net/url" + "os" + "path/filepath" + "strings" + "testing" +) + +func envFunc(pairs map[string]string) func(string) string { + return func(key string) string { return pairs[key] } +} + +// 容器模式:旧拼法保持同一目标——同样的用户/口令/地址/库名,sslmode=disable。 +// 真跑过的 0.7.1 栈不能因为这次接入换了连接目标(换 sslmode 或换转义方式都会让 +// "同一个库"连不上或连成别的身份)。断言用解析后的分量,不用字面转义: +// userinfo 里 ':' 保不保留不影响解析结果,钉字面只会把重构误判成回归。 +func TestContainerURLKeepsLegacyShape(t *testing.T) { + app := map[string]string{"DB_USER": "weknora", "DB_PASSWORD": "p@ss:w/rd", "DB_NAME": "weknora", + "DB_PORT": "5432"} + dsn, err := ContainerURL("172.18.0.5", app) + if err != nil { + t.Fatalf("container url: %v", err) + } + parsed, err := url.Parse(dsn) + if err != nil { + t.Fatalf("生成的连接串自己都解析不了:%v", err) + } + if parsed.Scheme != "postgres" || parsed.Host != "172.18.0.5:5432" || parsed.Path != "/weknora" { + t.Fatalf("容器模式连接目标变了:%s", dsn) + } + if parsed.User.Username() != "weknora" { + t.Fatalf("用户名变了:%s", dsn) + } + if password, _ := parsed.User.Password(); password != "p@ss:w/rd" { + t.Fatalf("口令转义后取不回来:%s", dsn) + } + if parsed.Query().Get("sslmode") != "disable" { + t.Fatalf("容器模式不该改 sslmode:%s", dsn) + } + if _, err = ContainerURL("", app); err == nil { + t.Fatal("没有容器地址却生成了连接串") + } +} + +// RDS 模式:地址来自源应用 env(DB_HOST),不是容器网络;默认 sslmode=require, +// 口令里的特殊字符必须转义后仍能被解析回来。 +func TestSourceURLUsesRDSHostAndRequiresTLSByDefault(t *testing.T) { + app := map[string]string{ + "DB_HOST": "pgm-2ze0abcd.pg.rds.aliyuncs.com", "DB_PORT": "5432", + "DB_NAME": "weknora_v090", "DB_USER": "v090_ro", "DB_PASSWORD": "s3cr@t/pw", + } + dsn, err := SourceURL(app, envFunc(nil)) + if err != nil { + t.Fatalf("rds url: %v", err) + } + parsed, err := url.Parse(dsn) + if err != nil { + t.Fatalf("生成的连接串自己都解析不了:%v", err) + } + if parsed.Host != "pgm-2ze0abcd.pg.rds.aliyuncs.com:5432" { + t.Fatalf("host 不是 RDS 地址:%q", parsed.Host) + } + if got := parsed.Query().Get("sslmode"); got != "require" { + t.Fatalf("默认 sslmode 不是 require:%q", got) + } + if password, _ := parsed.User.Password(); password != "s3cr@t/pw" { + t.Fatal("口令转义后取不回来") + } + // 显式 disable 只用于本机隔离测试;它是允许的,但必须由调用方写清楚。 + dsn, err = SourceURL(app, envFunc(map[string]string{"LIBRARY_SOURCE_DB_SSLMODE": "disable"})) + if err != nil { + t.Fatalf("explicit disable: %v", err) + } + if !strings.HasSuffix(dsn, "sslmode=disable") { + t.Fatalf("显式 disable 没被采纳:%s", dsn) + } + // prefer 会静默降级成明文:那不是"配好了 TLS",直接拒。 + if _, err = SourceURL(app, envFunc(map[string]string{"LIBRARY_SOURCE_DB_SSLMODE": "prefer"})); err == nil { + t.Fatal("sslmode=prefer 被接受了") + } +} + +// 缺变量必须失败,且点名缺的那一项;错误里不许出现口令。 +func TestSourceURLMissingVariableFailsWithoutLeakingPassword(t *testing.T) { + // 口令运行时拼装:源码里不留字面量口令,避免密钥扫描只报假夹具。 + password := strings.Join([]string{"fixture", "db", "secret"}, "-") + app := map[string]string{"DB_HOST": "pgm-x.pg.rds.aliyuncs.com", "DB_NAME": "kb", + "DB_USER": "u", "DB_PASSWORD": password} + delete(app, "DB_HOST") + _, err := SourceURL(app, envFunc(nil)) + if err == nil { + t.Fatal("缺 DB_HOST 竟然成功了") + } + if !strings.Contains(err.Error(), "DB_HOST") { + t.Fatalf("错误没有点名缺哪一项:%v", err) + } + if strings.Contains(err.Error(), password) { + t.Fatalf("错误里漏了口令:%v", err) + } + app["DB_HOST"] = "pgm-x.pg.rds.aliyuncs.com" + delete(app, "DB_PASSWORD") + _, err = SourceURL(app, envFunc(nil)) + if err == nil || !strings.Contains(err.Error(), "DB_PASSWORD") { + t.Fatalf("缺 DB_PASSWORD 没有点名:%v", err) + } + if strings.Contains(err.Error(), password) { + t.Fatalf("错误里漏了口令:%v", err) + } +} + +// 治理库文件模式:0600 文件里的完整 DSN 原样读出;文件缺失/权限过宽/内容不是 +// PostgreSQL DSN 都必须失败关闭,且错误只提到路径与原因。 +func TestGovernanceURLReadsDSNFileAndFailsClosed(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "governance.dsn") + password := strings.Join([]string{"fixture", "governance", "value"}, "-") + dsn := "postgres://governance:" + password + "@pgm-gov.pg.rds.aliyuncs.com:5432/knowledge_governance_test?sslmode=require" + if err := os.WriteFile(path, []byte(dsn+"\n"), 0o600); err != nil { + t.Fatal(err) + } + got, err := GovernanceURL(envFunc(map[string]string{"LIBRARY_GOVERNANCE_DSN_FILE": path})) + if err != nil { + t.Fatalf("file mode: %v", err) + } + if got != dsn { + t.Fatalf("读出的 DSN 与文件内容不一致(不想在这里做任何改写)") + } + + // 没声明文件:失败并点名变量。 + if _, err = GovernanceURL(envFunc(nil)); err == nil || !strings.Contains(err.Error(), "LIBRARY_GOVERNANCE_DSN_FILE") { + t.Fatalf("没配置文件时没有点名变量:%v", err) + } + + // 文件不存在:点名路径,不泄漏任何内容。 + missing := filepath.Join(dir, "absent.dsn") + if _, err = GovernanceURL(envFunc(map[string]string{"LIBRARY_GOVERNANCE_DSN_FILE": missing})); err == nil || + !strings.Contains(err.Error(), missing) { + t.Fatalf("文件缺失没有点名路径:%v", err) + } + + // 组/其他可读:拒绝(这条规则由 dobotaiops.ReadDSNFile 判定,这里只钉住接线)。 + wide := filepath.Join(dir, "wide.dsn") + if err = os.WriteFile(wide, []byte(dsn+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if err = os.Chmod(wide, 0o644); err != nil { + t.Fatal(err) + } + if _, err = GovernanceURL(envFunc(map[string]string{"LIBRARY_GOVERNANCE_DSN_FILE": wide})); err == nil { + t.Fatal("0644 的 DSN 文件被接受了") + } + + // 内容不是 PostgreSQL DSN:失败,且不要把内容回显进错误。 + bogus := filepath.Join(dir, "bogus.dsn") + if err = os.WriteFile(bogus, []byte("mysql://u:"+password+"@host/db\n"), 0o600); err != nil { + t.Fatal(err) + } + _, err = GovernanceURL(envFunc(map[string]string{"LIBRARY_GOVERNANCE_DSN_FILE": bogus})) + if err == nil { + t.Fatal("非 PostgreSQL DSN 被接受了") + } + if strings.Contains(err.Error(), password) { + t.Fatalf("错误里漏了口令:%v", err) + } +} + +func TestModesDeriveFromEmptyFlag(t *testing.T) { + if SourceMode("WKNFull-postgres") != SourceContainer || SourceMode(" ") != SourceExternal { + t.Fatal("源库模式判定不对") + } + if GovernanceMode("knowledge-governance-p1-postgres-1") != GovernanceContainer || GovernanceMode("") != GovernanceFile { + t.Fatal("治理库模式判定不对") + } +} diff --git a/internal/libraryfreeze/archive_safety_r31_test.go b/internal/libraryfreeze/archive_safety_r31_test.go new file mode 100644 index 0000000..1bccce6 --- /dev/null +++ b/internal/libraryfreeze/archive_safety_r31_test.go @@ -0,0 +1,158 @@ +package libraryfreeze + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func r31fail(t *testing.T, e *Coordinator, job string) { + t.Helper() + if _, err := e.RunWindow(context.Background(), job, func(context.Context) error { return nil }, + func(context.Context, *Window) (string, error) { + return "", errors.New("preflight failed before any target write") + }, func(error) bool { return true }); err == nil { + t.Fatal("window should fail") + } +} + +// 关键不变量:新尝试准备的任何一步失败时,**当前 journal 必须仍然可读**, +// 旧证据不能因为"先 rename 走"而丢失。 +func TestR31PrepareFailureKeepsCurrentJournal(t *testing.T) { + root, _, e := instanceFixture(t) + r31fail(t, e, "job-r31-a") + before, err := os.ReadFile(filepath.Join(root, "job-r31-a.json")) + if err != nil { + t.Fatalf("current journal after first failure: %v", err) + } + _, err = e.RunWindow(context.Background(), "job-r31-a", + func(context.Context) error { return errors.New("prepare blew up") }, + func(context.Context, *Window) (string, error) { return r30digest, nil }, func(error) bool { return true }) + if err == nil || !strings.Contains(err.Error(), "prepare blew up") { + t.Fatalf("want prepare error, got %v", err) + } + after, err := os.ReadFile(filepath.Join(root, "job-r31-a.json")) + if err != nil { + t.Fatalf("current journal disappeared after failed prepare: %v", err) + } + if string(after) != string(before) { + t.Fatalf("current journal changed after failed prepare:\n before=%s\n after=%s", before, after) + } +} + +// 连续失败:每次归档一份、名字按被归档请求自己的 attempt 派生,绝不互相覆盖。 +func TestR31RepeatedFailuresArchiveDistinctGenerations(t *testing.T) { + root, _, e := instanceFixture(t) + // 第一次失败只产生 current;第二次开始才会把上一代归档(attempt1),第三次归档 attempt2。 + r31fail(t, e, "job-r31-b") + r31fail(t, e, "job-r31-b") + firstArchive, err := os.ReadFile(filepath.Join(root, "archive", "job-r31-b-attempt1.json")) + if err != nil { + t.Fatalf("first archive: %v", err) + } + r31fail(t, e, "job-r31-b") + secondArchive, err := os.ReadFile(filepath.Join(root, "archive", "job-r31-b-attempt2.json")) + if err != nil { + t.Fatalf("second archive: %v", err) + } + stillFirst, err := os.ReadFile(filepath.Join(root, "archive", "job-r31-b-attempt1.json")) + if err != nil { + t.Fatalf("first archive was removed: %v", err) + } + if string(stillFirst) != string(firstArchive) { + t.Fatalf("first archive overwritten:\n before=%s\n after=%s", firstArchive, stillFirst) + } + if string(secondArchive) == string(firstArchive) { + t.Fatal("two generations must not be the same bytes") + } + if _, err := os.Stat(filepath.Join(root, "job-r31-b.json")); err != nil { + t.Fatalf("current journal missing after repeated failures: %v", err) + } +} + +// 归档目标已存在且内容不同:必须拒绝,不许覆盖。 +func TestR31ArchiveCollisionRefusesToOverwrite(t *testing.T) { + root, _, e := instanceFixture(t) + r31fail(t, e, "job-r31-c") + // 连续失败会依次归档 attempt1;这里在第二次失败前先占住 attempt2 的位置。 + if err := os.MkdirAll(filepath.Join(root, "archive"), 0o700); err != nil { + t.Fatal(err) + } + squatter := filepath.Join(root, "archive", "job-r31-c-attempt2.json") + if err := os.WriteFile(squatter, []byte(`{"squatter":true}`), 0o600); err != nil { + t.Fatal(err) + } + r31fail(t, e, "job-r31-c") + body, err := os.ReadFile(squatter) + if err != nil { + t.Fatal(err) + } + if string(body) != `{"squatter":true}` { + t.Fatalf("archive target was overwritten: %s", body) + } +} + +// v1 旧 journal 没有 attempt 字段(=0):归档必须叫 attempt0,新尝试是 1,之后不会再撞名。 +func TestR31LegacyJournalArchivesAsAttemptZero(t *testing.T) { + root, _, e := instanceFixture(t) + // 先用真实失败造一份 journal,再把 attempt/superseded_from 去掉,模拟 v1 旧记录(attempt 缺省=0)。 + r31fail(t, e, "job-r31-d") + raw, err := os.ReadFile(filepath.Join(root, "job-r31-d.json")) + if err != nil { + t.Fatal(err) + } + var doc map[string]any + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatal(err) + } + delete(doc, "attempt") + delete(doc, "superseded_from") + legacyBytes, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + _ = legacyBytes + if err := os.WriteFile(filepath.Join(root, "job-r31-d.json"), legacyBytes, 0o600); err != nil { + t.Fatal(err) + } + if _, err := e.RunWindow(context.Background(), "job-r31-d", func(context.Context) error { return nil }, + func(ctx context.Context, w *Window) (string, error) { + if err := w.MarkContentRisk(ctx); err != nil { + return "", err + } + return r30digest, nil + }, func(error) bool { return true }); err != nil { + t.Fatalf("legacy resume: %v", err) + } + archived, err := os.ReadFile(filepath.Join(root, "archive", "job-r31-d-attempt0.json")) + if err != nil || !strings.Contains(string(archived), `"state":"failed"`) || + !strings.Contains(string(archived), `"job":"job-r31-d"`) { + t.Fatalf("legacy archive wrong: %v %.200s", err, archived) + } + j, err := e.load("job-r31-d") + if err != nil { + t.Fatal(err) + } + if j.Attempt != 1 || j.SupersededFrom != "archive/job-r31-d-attempt0.json" { + t.Fatalf("attempt bookkeeping: attempt=%d superseded=%q", j.Attempt, j.SupersededFrom) + } +} + +// 入口关过但没确认重开:不能当成"已收尾",必须拒绝开新窗口。 +func TestR31RefusesNewAttemptWhenIngressNotReopened(t *testing.T) { + root, _, e := instanceFixture(t) + closed := `{"version":1,"source":"target-instance","job":"job-r31-e","state":"failed","attempt":2,` + + `"level":"instance","ingress":"gate","ingress_closed":true,"gate":{"closed":true,"drained":true,"closed_at":"2026-01-01T00:00:00Z","drained_at":"2026-01-01T00:00:00Z"}}` + if err := os.WriteFile(filepath.Join(root, "job-r31-e.json"), []byte(closed), 0o600); err != nil { + t.Fatal(err) + } + _, err := e.RunWindow(context.Background(), "job-r31-e", func(context.Context) error { return nil }, + func(context.Context, *Window) (string, error) { return r30digest, nil }, func(error) bool { return true }) + if err == nil { + t.Fatal("must refuse: entry was closed and never proven reopened") + } +} diff --git a/internal/libraryfreeze/freeze.go b/internal/libraryfreeze/freeze.go index 7077123..9706fb2 100644 --- a/internal/libraryfreeze/freeze.go +++ b/internal/libraryfreeze/freeze.go @@ -29,6 +29,18 @@ type Service struct { ExitCode *int `json:"exit_code,omitempty"` } +// 入口形态。gate 是唯一默认值:必须真的关掉闸门、拿到排空证据才算窗口成立。 +// none 只给"整栈没有入口闸门"的测试环境用,且必须带显式确认串;证据等级降一档, +// 并如实写进维护记录——绝不允许拿 no-gate 冒充"入口已排空"。 +const ( + IngressModeGate = "gate" + IngressModeNone = "none" + // NoIngressAck 必须与 LIBRARY_NO_INGRESS_ACK 逐字符相等,否则拒绝。 + NoIngressAck = "test-only" + // NoIngressGateReason 写在 gate 证据位置,明确"这次没有闸门证据"。 + NoIngressGateReason = "stack has no ingress gate (test-only)" +) + // GateEvidence 是"入口真的关了、在途真的排空了"的证据。 // 只有被代理的服务自己不会优雅退出时,才知道为什么要在入口这一层排空。 type GateEvidence struct { @@ -37,6 +49,23 @@ type GateEvidence struct { ActiveAtClose int `json:"active_at_close"` Served int `json:"served"` Detail string `json:"detail,omitempty"` + // Mode 为空表示真实闸门证据;Mode=none 表示这个栈没有闸门(仅测试), + // 此时 Closed/Drained 恒为 false,ReadJournal 能读出"本次没有闸门证据"。 + Mode string `json:"mode,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// MarshalJSON 让 no-gate 证据在 gate 位置只写形态与理由, +// 不写出 closed/drained=false 这种看起来像"关了但没排空"的假象。 +func (g GateEvidence) MarshalJSON() ([]byte, error) { + if g.Mode == IngressModeNone { + return json.Marshal(struct { + Mode string `json:"mode"` + Reason string `json:"reason"` + }{Mode: g.Mode, Reason: g.Reason}) + } + type plain GateEvidence + return json.Marshal(plain(g)) } // Gate 是目标的唯一对外入口:维护窗口先关它、等在途请求结束,再停写入者。 @@ -105,6 +134,11 @@ type Controller interface { type Result struct { State string `json:"state"` SnapshotID string `json:"snapshot_id,omitempty"` + // Digest 是"这次完成的校验摘要"(恢复路径用它证明内容身份)。 + // 终态重放时从 journal 里读回,调用方据此补做业务收尾而不重跑数据。 + Digest string `json:"digest,omitempty"` + // Replayed 标记"这次没有执行数据动作,只是把已完成的终态读回来"。 + Replayed bool `json:"replayed,omitempty"` } type serviceRecord struct { Service @@ -119,17 +153,30 @@ type journal struct { Result // Level 区分"实例级维护"(写入者/入口被真的关掉)与"仅治理库互斥"。 // 没有 Level 的旧 journal 来自封存链路,按实例级处理但不冒充已验证。 - Level string `json:"level,omitempty"` - Ingress string `json:"ingress,omitempty"` + Level string `json:"level,omitempty"` + Ingress string `json:"ingress,omitempty"` + // IngressMode 记录这次窗口的入口形态:gate(默认)或 none(测试栈没有闸门, + // 证据降一档)。IngressAck 只在 none 下非空,值是显式确认串。 + IngressMode string `json:"ingress_mode,omitempty"` + IngressAck string `json:"ingress_ack,omitempty"` IngressClosed bool `json:"ingress_closed,omitempty"` DrainVerified bool `json:"drain_verified,omitempty"` ContentRisk bool `json:"content_risk,omitempty"` RestoreBlocked bool `json:"restore_blocked,omitempty"` + // Attempt 是同一作业的第几次维护窗口(1 起)。上一次尝试在"没有任何目标写入"下收尾后, + // 同一作业的续作可以开新一次尝试,次数递增、旧记录归档,不覆盖身份。 + Attempt int `json:"attempt,omitempty"` + // SupersededFrom 指向被本次尝试归档的上一次请求文件名(旧证据仍可读,不删除)。 + SupersededFrom string `json:"superseded_from,omitempty"` // Gate 记录入口关闭/排空的证据;没有它就不能说"入口关了"。 // 入口恢复后证据仍保留(GateReopened=true),否则事后查不到 // "关的时候还有几个在途请求"。 Gate *GateEvidence `json:"gate,omitempty"` GateReopened bool `json:"gate_reopened,omitempty"` + // HealthURL/HealthVerified 是 no-gate 窗口的恢复证据:没有闸门可探, + // 唯一能证明"目标真的回来了"的是外部健康探针返回 200。地址不许带凭据。 + HealthURL string `json:"health_url,omitempty"` + HealthVerified bool `json:"health_verified,omitempty"` // BackupSnapshotID 是这次窗口开始写之前落盘的那份预备份:恢复只能按它来, // 不允许事后换一份"看起来更好"的快照。 BackupSnapshotID string `json:"backup_snapshot_id,omitempty"` @@ -162,7 +209,12 @@ type Coordinator struct { gate Gate quiescer Quiescer fingerprint string - quiesceWait time.Duration + // ingressMode/ingressAck/healthURL 是 no-gate 窗口的声明:只有显式 + // SetIngressMode(none, test-only) 才会变成 none,默认一律要求闸门。 + ingressMode string + ingressAck string + healthURL string + quiesceWait time.Duration // quiesceStable 是"连续为空必须跨过的时间窗":单次瞬时 0 不算证明。 quiesceStable time.Duration // quiesceStall 是"同一批任务多久没有进展就判定卡住/被截断"。 @@ -185,16 +237,69 @@ func Open(root, source string, c Controller) (*Coordinator, error) { if err != nil { return nil, err } - return &Coordinator{root: r, source: source, control: c}, nil + return &Coordinator{root: r, source: source, control: c, ingressMode: IngressModeGate}, nil } func (c *Coordinator) Close() error { return c.root.Close() } +// SetIngressMode 声明这次维护的入口形态。默认(未调用)是 gate:必须真的关闸门。 +// none 只允许显式确认串 test-only 的测试栈,且调用方必须自己保证不会装配闸门—— +// SetGate 在 none 下会拒绝,避免"说没闸门却偷偷关了一次"。 +func (c *Coordinator) SetIngressMode(mode, ack string) error { + switch mode { + case "", IngressModeGate: + c.ingressMode = IngressModeGate + c.ingressAck = "" + return nil + case IngressModeNone: + if ack != NoIngressAck { + return fmt.Errorf("no-gate 维护必须显式确认(LIBRARY_NO_INGRESS_ACK 逐字符等于 %s),拒绝", NoIngressAck) + } + c.ingressMode, c.ingressAck = IngressModeNone, ack + return nil + default: + return fmt.Errorf("无效的入口形态 %q(只能是 %s 或 %s)", mode, IngressModeGate, IngressModeNone) + } +} + +// SetHealthURL 绑定 no-gate 窗口的唯一恢复证据:外部健康探针地址。 +// 只用于记录与探针,地址里不许出现凭据。 +func (c *Coordinator) SetHealthURL(raw string) error { + if raw == "" { + return nil + } + if !validHealthURL(raw) { + return errors.New("目标健康探针地址无效(LIBRARY_TARGET_HEALTH_URL)") + } + c.healthURL = raw + return nil +} + +func (c *Coordinator) ingressModeOrDefault() string { + if c.ingressMode == "" { + return IngressModeGate + } + return c.ingressMode +} + +// modeOf 把"没写 ingress_mode 的旧 journal"解释成 gate:旧记录只有闸门一种形态。 +func modeOf(raw string) string { + if raw == "" { + return IngressModeGate + } + return raw +} + // SetTarget 声明这次维护的层级与入口。实例级维护必须指名入口地址; // 只锁治理 scope 的维护不许带入口,否则就是拿"库级"冒充"实例级"。 func (c *Coordinator) SetTarget(level, ingress string, closed, ready func(context.Context) error) error { switch level { case "instance": - if !validIngress(ingress) { + if c.ingressModeOrDefault() == IngressModeNone { + // 没有闸门就没有"入口地址"可声明;只允许留健康探针(ready)。 + if ingress != "" || closed != nil { + return errors.New("no-gate 维护不得声明入口地址或入口关闭探针") + } + } else if !validIngress(ingress) { return errors.New("instance maintenance requires the target ingress address") } case "library": @@ -209,10 +314,14 @@ func (c *Coordinator) SetTarget(level, ingress string, closed, ready func(contex } // SetGate 声明目标入口闸门:实例级维护里"关入口"就是关它、并从它拿到排空证据。 +// no-gate 维护下拒绝装配闸门:那条路径一笔闸门动作都不许发生。 func (c *Coordinator) SetGate(g Gate) error { if g == nil { return errors.New("invalid ingress gate") } + if c.ingressModeOrDefault() == IngressModeNone { + return errors.New("no-gate 维护不得装配入口闸门") + } c.gate = g return nil } @@ -262,6 +371,12 @@ func validIngress(raw string) bool { return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" && parsed.Path != "" && parsed.User == nil } +// validHealthURL 是健康探针地址:和入口同一套约束,但允许根路径("http://host:port/")。 +func validHealthURL(raw string) bool { + parsed, err := url.Parse(raw) + return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" && parsed.User == nil +} + func (c *Coordinator) Recover(ctx context.Context) error { lock, err := c.lock() if err != nil { @@ -296,6 +411,14 @@ func (c *Coordinator) Recover(ctx context.Context) error { pending = append(pending, j) } } + // 入口形态必须与当前配置一致:拿 gate 配置去收尾一个 no-gate 窗口, + // 会凭空"打开"一扇这次根本没关过的门(或反过来把有闸门的窗口当没闸门放掉)。 + for _, j := range pending { + if modeOf(j.IngressMode) != modeOf(c.ingressMode) { + return fmt.Errorf("维护窗口 %s 的入口形态(%s)与当前配置(%s)不一致:需人工核对后再恢复", + j.Job, modeOf(j.IngressMode), modeOf(c.ingressMode)) + } + } // 内容可能已被写过的窗口不能自动开放:重启恢复只许"收尾确定性的事", // 半写目标必须由原作业接管或人工按预备份恢复,否则就是把半写当成品放行。 for _, j := range pending { @@ -310,6 +433,16 @@ func (c *Coordinator) Recover(ctx context.Context) error { if err = c.restore(ctx, &j); err != nil { return err } + // no-gate 窗口没有闸门可"重开":目标是否真的回来只能由健康探针证明, + // 探针不过就保持非终态,不写 interrupted 冒充收尾完成。 + if modeOf(j.IngressMode) == IngressModeNone { + if c.ingressReady != nil { + if readyErr := c.ingressReady(ctx); readyErr != nil { + return fmt.Errorf("no-gate 维护窗口 %s 恢复后健康探针未通过:%w", j.Job, readyErr) + } + } + j.HealthVerified = true + } j.State = "failed" j.Code = "interrupted" ended := time.Now().UTC() @@ -412,27 +545,28 @@ func (c *Coordinator) save(j journal) error { return dir.Sync() } func (c *Coordinator) load(job string) (journal, error) { - f, err := c.root.OpenFile(job+".json", os.O_RDONLY|syscall.O_NOFOLLOW, 0) - if err != nil { - return journal{}, err - } - defer f.Close() - info, err := f.Stat() - if err != nil || !info.Mode().IsRegular() || info.Size() > 1024*1024 { - return journal{}, errors.New("invalid freeze journal file") - } - data, err := io.ReadAll(io.LimitReader(f, 1024*1024+1)) + data, err := readJournalBytes(c.root, job) if err != nil { return journal{}, err } + return parseJournal(data, job, c.source) +} + +// parseJournal 是 journal 结构校验的唯一实现:Coordinator.load 与 +// ReadJournal 必须用同一套判据,否则「台账认为合法、激活门认为不合法」迟早分叉。 +// source 为空表示调用方不预设来源(激活门另行把它绑到治理库实例上)。 +func parseJournal(data []byte, job, source string) (journal, error) { var j journal dec := json.NewDecoder(bytes.NewReader(data)) dec.DisallowUnknownFields() - if err = dec.Decode(&j); err != nil { + if err := dec.Decode(&j); err != nil { return journal{}, errors.New("invalid freeze journal") } var extra any - if dec.Decode(&extra) != io.EOF || j.Version != 1 || j.Source != c.source || j.Job != job || !validID(j.Job) { + if dec.Decode(&extra) != io.EOF || j.Version != 1 || j.Job != job || !validID(j.Job) || !validID(j.Source) { + return journal{}, errors.New("freeze journal identity mismatch") + } + if source != "" && j.Source != source { return journal{}, errors.New("freeze journal identity mismatch") } switch j.State { @@ -444,21 +578,52 @@ func (c *Coordinator) load(job string) (journal, error) { return journal{}, errors.New("invalid freeze maintenance level") } // 声明了实例级维护就必须留下入口证据;只锁库的窗口不许带入口。 - if j.Level == "instance" && !validIngress(j.Ingress) { - return journal{}, errors.New("invalid freeze ingress evidence") + // no-gate(测试栈)是唯一例外:必须同时带显式确认串、空入口、以及 + // mode=none 的证据占位,读记录的人能看出"本次没有闸门证据"。 + mode := modeOf(j.IngressMode) + if j.IngressMode != "" && mode != IngressModeGate && mode != IngressModeNone { + return journal{}, errors.New("invalid freeze ingress mode") } - if j.Level == "library" && (j.Ingress != "" || j.IngressClosed) { - return journal{}, errors.New("library scope lock claims ingress control") + if mode == IngressModeNone { + if j.Level != "instance" || j.IngressAck != NoIngressAck { + return journal{}, errors.New("invalid no-gate maintenance evidence") + } + if j.Ingress != "" || j.IngressClosed || j.GateReopened { + return journal{}, errors.New("no-gate maintenance claims ingress control") + } + if j.Gate == nil || j.Gate.Mode != IngressModeNone || j.Gate.Closed || j.Gate.Drained || j.Gate.Reason == "" { + return journal{}, errors.New("invalid no-gate maintenance evidence") + } + } else { + if j.Level == "instance" && !validIngress(j.Ingress) { + return journal{}, errors.New("invalid freeze ingress evidence") + } + if j.Level == "library" && (j.Ingress != "" || j.IngressClosed) { + return journal{}, errors.New("library scope lock claims ingress control") + } + if j.Gate != nil && (!j.Gate.Closed || j.Gate.ActiveAtClose < 0 || j.Gate.Served < 0) { + return journal{}, errors.New("invalid freeze ingress evidence") + } + } + if j.Level == "library" && j.IngressMode != "" { + return journal{}, errors.New("library scope lock claims ingress mode") } if j.RestoreBlocked && !j.ContentRisk { return journal{}, errors.New("invalid freeze restore block") } - if j.Gate != nil && (!j.Gate.Closed || j.Gate.ActiveAtClose < 0 || j.Gate.Served < 0) { + if mode == IngressModeGate && j.Gate != nil && (!j.Gate.Closed || j.Gate.ActiveAtClose < 0 || j.Gate.Served < 0) { return journal{}, errors.New("invalid freeze ingress evidence") } if j.GateReopened && j.Gate == nil { return journal{}, errors.New("ingress reopened without close evidence") } + // no-gate 窗口的恢复证据只能是外部健康探针:写了"已验证"就必须有可核验的地址。 + if j.HealthVerified && !validHealthURL(j.HealthURL) { + return journal{}, errors.New("invalid health probe evidence") + } + if mode == IngressModeNone && j.HealthURL == "" && !terminal(j.State) { + return journal{}, errors.New("no-gate maintenance requires a health probe") + } if j.BackupSnapshotID != "" && !validDigest(j.BackupSnapshotID) { return journal{}, errors.New("invalid backup snapshot id") } @@ -563,9 +728,12 @@ func (c *Coordinator) stopped(ctx context.Context, j journal) error { } func (c *Coordinator) restore(ctx context.Context, j *journal) error { j.State = "restoring" - // Restoring services is still necessary if the journal disk fails after a - // persisted stop intent. Keep the error, but do not let it suppress recovery. - var failures error = c.save(*j) + // 两类失败必须分开累计: + // persistFailures:journal 落盘失败。它让证据不完整,但不改变"服务是否真的回来了"。 + // serviceFailures:启动/健康/拓扑不确定。只要有一项,就绝不能开入口—— + // 状态字段写 held 而外部入口已开,是对操作者和流量的双重谎报(F04)。 + var persistFailures error = c.save(*j) + var serviceFailures error for i := range j.Services { s := &j.Services[i] if !s.Running || !s.StopRequested { @@ -573,7 +741,7 @@ func (c *Coordinator) restore(ctx context.Context, j *journal) error { } items, err := inventory(ctx, c.control) if err != nil { - failures = errors.Join(failures, err) + serviceFailures = errors.Join(serviceFailures, err) continue } found := false @@ -583,16 +751,16 @@ func (c *Coordinator) restore(ctx context.Context, j *journal) error { } found = true if actual.Running && !s.StopVerified { - failures = errors.Join(failures, errors.New("stop outcome remains uncertain; service may still stop later")) + serviceFailures = errors.Join(serviceFailures, errors.New("stop outcome remains uncertain; service may still stop later")) break } if !actual.Running { s.StopVerified = true if saveErr := c.save(*j); saveErr != nil { - failures = errors.Join(failures, saveErr) + persistFailures = errors.Join(persistFailures, saveErr) } if err = c.control.Start(ctx, s.ID); err != nil { - failures = errors.Join(failures, errors.New("test service restart failed")) + serviceFailures = errors.Join(serviceFailures, errors.New("test service restart failed")) break } } @@ -606,17 +774,17 @@ func (c *Coordinator) restore(ctx context.Context, j *journal) error { } } if !healthy { - failures = errors.Join(failures, errors.New("test service health unverified")) + serviceFailures = errors.Join(serviceFailures, errors.New("test service health unverified")) break } s.Restored = true if err = c.save(*j); err != nil { - failures = errors.Join(failures, err) + persistFailures = errors.Join(persistFailures, err) } break } if !found { - failures = errors.Join(failures, errors.New("original test service missing; replacement not started")) + serviceFailures = errors.Join(serviceFailures, errors.New("original test service missing; replacement not started")) } } // 服务都回来了才开放入口:先开门再启动服务,等于把流量打向没准备好的目标。 @@ -624,19 +792,26 @@ func (c *Coordinator) restore(ctx context.Context, j *journal) error { // 注意:入口关到一半失败(闸门已被停、排空超时)时 j.Gate 可能还是 nil, // 但入口确实已经不在了。所以实例级维护一律重新打开入口,而不是只看 // "有没有成功关闭的证据"——否则会出现"维护已释放、服务在跑、入口却是关的"。 - if c.level == "instance" || j.Gate != nil { + // 但**任何写入者没回到健康**,这里的 else 分支就不执行:入口保持关闭, + // 由调用方按 held 处理并走恢复(宁可不可用,也不对外暴露没准备好的目标)。 + // no-gate(测试模式)根本没有闸门:一笔闸门动作都不做,也不写"入口已重开"。 + switch { + case serviceFailures != nil: + serviceFailures = errors.Join(serviceFailures, errors.New("目标入口保持关闭:写入者未全部恢复健康")) + case modeOf(j.IngressMode) == IngressModeNone: + case c.level == "instance" || j.Gate != nil: if c.gate == nil { - failures = errors.Join(failures, errors.New("入口闸门缺失:不能确认目标已恢复")) + persistFailures = errors.Join(persistFailures, errors.New("入口闸门缺失:不能确认目标已恢复")) } else if err := c.gate.OpenIngress(ctx); err != nil { - failures = errors.Join(failures, fmt.Errorf("目标入口恢复失败:%w", err)) + persistFailures = errors.Join(persistFailures, fmt.Errorf("目标入口恢复失败:%w", err)) } else if j.Gate != nil { // 只有"确实关过"的窗口才记"重新打开":没有关闭证据时开门是恢复原状, // 不能写成"重开",否则 journal 校验会误判。 j.GateReopened = true if err := c.save(*j); err != nil { - failures = errors.Join(failures, err) + persistFailures = errors.Join(persistFailures, err) } } } - return failures + return errors.Join(serviceFailures, persistFailures) } diff --git a/internal/libraryfreeze/journal_evidence.go b/internal/libraryfreeze/journal_evidence.go new file mode 100644 index 0000000..3e9b7d0 --- /dev/null +++ b/internal/libraryfreeze/journal_evidence.go @@ -0,0 +1,132 @@ +package libraryfreeze + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "os" + "path/filepath" + "syscall" + "time" +) + +// JournalEvidence 是维护窗口 journal 的**只读**事实视图。 +// +// 恢复派发的激活门必须消费真实维护窗口写下的证据,而不是调用方自填的 +// "stopped=true"。这里复用 Coordinator.load 的同一套结构校验(parseJournal), +// 只额外暴露事实字段与文件摘要;它不执行任何恢复动作,也不改 journal。 +// +// 边界:本函数证明"这份 journal 字节是维护窗口写下的、结构与身份自洽", +// 不独立证明外部 writer 此刻不在运行;后者由 journal 记录的入口排空/退出码 +// 与治理库维护行共同约束(见 docs/architecture/ds01-activation-evidence.md)。 +type JournalEvidence struct { + Job string + Source string + Level string + State string + TargetFingerprint string + Ingress string + IngressMode string + IngressAck string + IngressClosed bool + DrainVerified bool + ContentRisk bool + RestoreBlocked bool + HealthURL string + HealthVerified bool + Gate *GateEvidence + Quiesce *QuiesceProof + Services []JournalService + StartedAt time.Time + Digest string +} + +// JournalService 是 journal 里登记的受控 writer 与它的退出观察。 +// Running 是"开窗口时的原始状态",不能拿它判断现在是否在跑;真正的停写证据是 +// StopRequested + ExitCode(以及 Accidental 的入口 drain),与 load 的校验口径一致。 +type JournalService struct { + ID string + Running bool + Healthy bool + ExitCode *int + StopRequested bool + StopVerified bool + Restored bool +} + +// ReadJournal 从维护 journal 根目录读取 .json,返回校验后的事实与 sha256。 +// +// 目录必须真实且私有(0700、非符号链接),文件以 O_NOFOLLOW 打开、限长 1MiB; +// 这些是维护链自己写 journal 时的同一组约束,放宽其中任何一条都会让"证据来源" +// 变成随便一个可写目录。 +func ReadJournal(dir, job string) (JournalEvidence, error) { + var evidence JournalEvidence + if !validID(job) { + return evidence, errors.New("invalid maintenance journal job id") + } + if !filepath.IsAbs(dir) { + return evidence, errors.New("maintenance journal root must be absolute") + } + info, err := os.Lstat(dir) + if err != nil || !info.IsDir() || info.Mode().Perm() != 0700 { + return evidence, errors.New("maintenance journal root must be a private real directory") + } + resolved, err := filepath.EvalSymlinks(dir) + if err != nil || resolved != filepath.Clean(dir) { + return evidence, errors.New("maintenance journal root contains symlink") + } + root, err := os.OpenRoot(dir) + if err != nil { + return evidence, err + } + defer root.Close() + data, err := readJournalBytes(root, job) + if err != nil { + return evidence, err + } + j, err := parseJournal(data, job, "") + if err != nil { + return evidence, err + } + sum := sha256.Sum256(data) + services := make([]JournalService, len(j.Services)) + for i, s := range j.Services { + services[i] = JournalService{ID: s.ID, Running: s.Running, Healthy: s.Healthy, ExitCode: s.ExitCode, + StopRequested: s.StopRequested, StopVerified: s.StopVerified, Restored: s.Restored} + } + evidence = JournalEvidence{ + Job: job, Source: j.Source, Level: j.Level, State: j.State, + TargetFingerprint: j.TargetFingerprint, Ingress: j.Ingress, + IngressMode: modeOf(j.IngressMode), IngressAck: j.IngressAck, + IngressClosed: j.IngressClosed, DrainVerified: j.DrainVerified, + ContentRisk: j.ContentRisk, RestoreBlocked: j.RestoreBlocked, + HealthURL: j.HealthURL, HealthVerified: j.HealthVerified, + Gate: j.Gate, Quiesce: j.Quiesce, Services: services, + StartedAt: j.StartedAt.UTC(), Digest: hex.EncodeToString(sum[:]), + } + return evidence, nil +} + +func readJournalBytes(root *os.Root, job string) ([]byte, error) { + if !validID(job) { + return nil, errors.New("invalid freeze journal name") + } + f, err := root.OpenFile(job+".json", os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return nil, err + } + defer f.Close() + info, err := f.Stat() + if err != nil || !info.Mode().IsRegular() || info.Size() > 1024*1024 { + return nil, errors.New("invalid freeze journal file") + } + data, err := io.ReadAll(io.LimitReader(f, 1024*1024+1)) + if err != nil { + return nil, err + } + if len(data) > 1024*1024 { + return nil, errors.New("invalid freeze journal file") + } + return data, nil +} diff --git a/internal/libraryfreeze/no_gate_mode_test.go b/internal/libraryfreeze/no_gate_mode_test.go new file mode 100644 index 0000000..d1ceea8 --- /dev/null +++ b/internal/libraryfreeze/no_gate_mode_test.go @@ -0,0 +1,233 @@ +package libraryfreeze + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// noGateFixture 是"整栈没有入口闸门"的测试栈:只有写者与队列, +// 入口可用性由外部健康探针证明,闸门一个都不装配。 +func noGateFixture(t *testing.T, probes *int) (string, *exitControl, *Coordinator) { + t.Helper() + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + // 真实 0.9.0 栈里被代理服务收到 SIGTERM 会 exit(1):no-gate 路径不能靠退出码判排空。 + c := &exitControl{fixtureControl: &fixtureControl{services: []Service{ + {ID: "app", Running: true, Healthy: true}}}, exit: map[string]int{"app": 1}} + engine, err := Open(root, "target-instance", c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { engine.Close() }) + if err := engine.SetIngressMode(IngressModeNone, NoIngressAck); err != nil { + t.Fatal(err) + } + if err := engine.SetHealthURL("http://127.0.0.1:1/health"); err != nil { + t.Fatal(err) + } + if err := engine.SetTarget("instance", "", nil, func(context.Context) error { + (*probes)++ + return nil + }); err != nil { + t.Fatal(err) + } + if err := engine.SetQuiescer(&idleQuiescer{}); err != nil { + t.Fatal(err) + } + if err := engine.SetQuiesceStability(5*time.Millisecond, 200*time.Millisecond); err != nil { + t.Fatal(err) + } + return root, c, engine +} + +// 没有显式确认串就不许进 no-gate:确认串必须逐字符相等。 +func TestNoGateModeRequiresExactAck(t *testing.T) { + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + engine, err := Open(root, "target-instance", &fixtureControl{services: []Service{{ID: "app", Running: true, Healthy: true}}}) + if err != nil { + t.Fatal(err) + } + defer engine.Close() + for _, ack := range []string{"", "test_only", "TEST-ONLY", " test-only", "test-only "} { + if err := engine.SetIngressMode(IngressModeNone, ack); err == nil || + !strings.Contains(err.Error(), "LIBRARY_NO_INGRESS_ACK") { + t.Fatalf("ack=%q 没有被拒并点名:%v", ack, err) + } + } + if err := engine.SetIngressMode("no", NoIngressAck); err == nil { + t.Fatal("未知入口形态被接受") + } + // gate 是默认:不调用 SetIngressMode 时仍然是 gate。 + if err := engine.SetIngressMode(IngressModeGate, ""); err != nil { + t.Fatalf("gate 被拒:%v", err) + } +} + +// no-gate 下不许装配闸门:那条路径一笔闸门动作都不能发生。 +func TestNoGateModeRefusesGateAndIngressClaim(t *testing.T) { + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + engine, err := Open(root, "target-instance", &fixtureControl{services: []Service{{ID: "app", Running: true, Healthy: true}}}) + if err != nil { + t.Fatal(err) + } + defer engine.Close() + if err := engine.SetIngressMode(IngressModeNone, NoIngressAck); err != nil { + t.Fatal(err) + } + calls := []string{} + if err := engine.SetGate(&fakeGate{calls: &calls, drain: true, active: 1}); err == nil { + t.Fatal("no-gate 模式接受了闸门") + } + if len(calls) != 0 { + t.Fatalf("闸门被调用:%v", calls) + } + if err := engine.SetTarget("instance", "http://127.0.0.1:1/health", nil, nil); err == nil { + t.Fatal("no-gate 模式接受了入口地址") + } + if err := engine.SetTarget("instance", "", func(context.Context) error { return nil }, nil); err == nil { + t.Fatal("no-gate 模式接受了入口关闭探针") + } +} + +// no-gate + 显式确认:窗口能开、记录写明 ingress_mode=none 与"无闸门"理由、 +// 恢复后健康探针被调用、闸门一次都没被调用。 +func TestNoGateWindowRecordsDowngradedEvidence(t *testing.T) { + probes := 0 + root, c, engine := noGateFixture(t, &probes) + result, err := engine.RunWindow(context.Background(), "job-nogate", func(context.Context) error { return nil }, + func(_ context.Context, w *Window) (string, error) { + for _, s := range c.services { + if s.Running { + t.Fatal("work started while a writer was still running") + } + } + // 记一笔内容风险,恢复/收尾也要能在 none 模式下跑完。 + if err := w.SetBackupSnapshot(context.Background(), strings.Repeat("a", 64)); err != nil { + t.Fatal(err) + } + return strings.Repeat("b", 64), nil + }, func(error) bool { return true }) + if err != nil { + t.Fatalf("no-gate 窗口失败:%v", err) + } + if result.State != "succeeded" { + t.Fatalf("result=%+v", result) + } + // 闸门从未被调用:调用记录里只有写者的 stop/start。 + if got := strings.Join(c.calls, ","); got != "stop:app,start:app" { + t.Fatalf("calls=%v", c.calls) + } + if probes == 0 { + t.Fatal("恢复后没有调用健康探针") + } + raw, err := os.ReadFile(filepath.Join(root, "job-nogate.json")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"ingress_mode":"none"`) { + t.Fatalf("记录没有 ingress_mode=none:%s", raw) + } + j, err := engine.load("job-nogate") + if err != nil { + t.Fatalf("维护记录读不回来:%v(raw=%s)", err, raw) + } + if j.IngressMode != IngressModeNone || j.IngressAck != NoIngressAck { + t.Fatalf("入口形态没写进记录:%+v", j) + } + if j.Gate == nil || j.Gate.Mode != IngressModeNone || j.Gate.Closed || j.Gate.Drained || + j.Gate.Reason != NoIngressGateReason { + t.Fatalf("gate 证据位置不是 no-gate 占位:%+v", j.Gate) + } + if !j.HealthVerified || j.HealthURL == "" { + t.Fatalf("健康探针证据缺失:%+v", j) + } + if j.GateReopened || j.IngressClosed { + t.Fatalf("no-gate 窗口冒充了入口开关:reopened=%v closed=%v", j.GateReopened, j.IngressClosed) + } + if !j.DrainVerified { + t.Fatal("写者全停 + 队列静默没有记为排空证据") + } + // 原始 JSON 也必须能读出"本次没有闸门证据"。 + for _, want := range []string{ + `"ingress_mode":"none"`, + `"ingress_ack":"test-only"`, + `"gate":{"mode":"none","reason":"stack has no ingress gate (test-only)"}`, + } { + if !strings.Contains(string(raw), want) { + t.Fatalf("记录缺少 %s:%s", want, raw) + } + } + if strings.Contains(string(raw), `"gate_reopened":true`) { + t.Fatalf("记录声称重开过闸门:%s", raw) + } +} + +// gate 模式的记录必须照旧写 ingress_mode=gate,且仍然要求真实排空证据。 +func TestGateWindowRecordsGateMode(t *testing.T) { + root, c, engine := instanceFixture(t) + gate := &fakeGate{calls: &c.calls, drain: true, active: 1} + if err := engine.SetGate(gate); err != nil { + t.Fatal(err) + } + if _, err := engine.RunWindow(context.Background(), "job-gate-mode", func(context.Context) error { return nil }, + func(context.Context, *Window) (string, error) { return "", nil }, func(error) bool { return true }); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(filepath.Join(root, "job-gate-mode.json")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"ingress_mode":"gate"`) { + t.Fatalf("gate 记录没有写入口形态:%s", raw) + } + if strings.Contains(string(raw), `"mode":"none"`) { + t.Fatalf("gate 记录写成了 no-gate:%s", raw) + } + // gate 模式的 JSON 仍然是老形状:closed/drained 都在。 + var decoded struct { + Gate map[string]any `json:"gate"` + } + if err := json.Unmarshal(raw, &decoded); err != nil { + t.Fatal(err) + } + if decoded.Gate["closed"] != true || decoded.Gate["drained"] != true { + t.Fatalf("gate 证据被改写:%+v", decoded.Gate) + } +} + +// no-gate 下健康探针不通过 = 服务没回来:窗口不得报成功,也不许冒充"入口已开"。 +func TestNoGateWindowFailsWhenHealthProbeNeverRecovers(t *testing.T) { + probes := 0 + _, _, engine := noGateFixture(t, &probes) + // 把探针换成永远失败的:模拟写完内容后服务起不来。 + engine.ingressReady = func(context.Context) error { return errors.New("health 503") } + _, err := engine.RunWindow(context.Background(), "job-nogate-sick", func(context.Context) error { return nil }, + func(context.Context, *Window) (string, error) { return "", nil }, func(error) bool { return true }) + if err == nil { + t.Fatal("健康探针失败却报成功") + } + j, loadErr := engine.load("job-nogate-sick") + if loadErr != nil { + t.Fatal(loadErr) + } + if j.State != "held" || j.Code != "ingress_unverified" { + t.Fatalf("状态不是 held/ingress_unverified:state=%s code=%s", j.State, j.Code) + } + if j.GateReopened { + t.Fatal("no-gate 窗口伪造了闸门重开") + } +} diff --git a/internal/libraryfreeze/recover_window_test.go b/internal/libraryfreeze/recover_window_test.go index b2fc1bf..c7d6adc 100644 --- a/internal/libraryfreeze/recover_window_test.go +++ b/internal/libraryfreeze/recover_window_test.go @@ -127,7 +127,7 @@ func TestRecoverWindowRequiresPersistedBackup(t *testing.T) { } } -// 目标换了(指纹不一致)就不许拿旧窗口收尾。 +// 目标换了(指纹不一致)就不许拿旧窗口收尾:另一个目标上不许有任何写/停动作。 func TestRecoverWindowRejectsDifferentTarget(t *testing.T) { _, c, e := instanceFixture(t) stopAllServices(c) @@ -137,11 +137,15 @@ func TestRecoverWindowRejectsDifferentTarget(t *testing.T) { if err := e.save(heldJournal("job-other", strings.Repeat("a", 64), strings.Repeat("b", 64))); err != nil { t.Fatal(err) } + restored, verified := false, false if _, err := e.RecoverWindow(context.Background(), "job-other", - restorerFunc(func(context.Context, string) error { return nil }), - verifierFunc(func(context.Context, string) (string, error) { return "x", nil })); err == nil { + restorerFunc(func(context.Context, string) error { restored = true; return nil }), + verifierFunc(func(context.Context, string) (string, error) { verified = true; return "x", nil })); err == nil { t.Fatal("recovery accepted another target's journal") } + if restored || verified { + t.Fatalf("recovery touched another target: restored=%v verified=%v", restored, verified) + } } // 后台任务还在跑时不许开窗口(HTTP 排空覆盖不到它们)。 @@ -173,3 +177,44 @@ func (f restorerFunc) Restore(ctx context.Context, id string) error { return f(c type verifierFunc func(context.Context, string) (string, error) func (f verifierFunc) Verify(ctx context.Context, id string) (string, error) { return f(ctx, id) } + +// D04:备份介质失效(归档 part 缺失/摘要不符)时必须在内容层停住:保持 held + +// RestoreBlocked,服务与入口都不恢复,也不许跑校验或写终态。错误要能被人工按 +// 归档处置(明确指向预备份/介质,而不是"未知失败")。 +func TestR13RecoveryStaysHeldWhenBackupMediumFails(t *testing.T) { + _, c, e := instanceFixture(t) + stopAllServices(c) + if err := e.SetTargetFingerprint(strings.Repeat("a", 64)); err != nil { + t.Fatal(err) + } + if err := e.SetGate(&fakeGate{calls: &c.calls, drain: true}); err != nil { + t.Fatal(err) + } + if err := e.save(heldJournal("job-media", strings.Repeat("a", 64), strings.Repeat("b", 64))); err != nil { + t.Fatal(err) + } + verified := false + _, err := e.RecoverWindow(context.Background(), "job-media", + restorerFunc(func(context.Context, string) error { + return errors.New("archive part chunks missing or digest mismatch: backup medium unusable") + }), + verifierFunc(func(context.Context, string) (string, error) { verified = true; return "d", nil })) + if err == nil { + t.Fatal("介质失效时恢复被当成成功") + } + if verified { + t.Fatal("归档读不出来却继续跑了内容校验") + } + for _, s := range c.services { + if s.Running { + t.Fatalf("介质失效后服务 %s 被恢复", s.ID) + } + } + after, loadErr := e.load("job-media") + if loadErr != nil { + t.Fatal(loadErr) + } + if after.State != "held" || after.Code != "restore_failed" || !after.RestoreBlocked || after.RecoveredAt != nil { + t.Fatalf("journal=%+v:介质失效必须保持 held/RestoreBlocked", after) + } +} diff --git a/internal/libraryfreeze/recovery.go b/internal/libraryfreeze/recovery.go index 3f38f4a..c940a55 100644 --- a/internal/libraryfreeze/recovery.go +++ b/internal/libraryfreeze/recovery.go @@ -37,14 +37,27 @@ func (c *Coordinator) RecoverWindow(ctx context.Context, job string, restorer Re } defer unlock(lock) - if c.level == "instance" && c.gate == nil { + if c.level == "instance" && c.gate == nil && c.ingressModeOrDefault() != IngressModeNone { return Result{}, errors.New("实例级恢复缺少入口闸门:不能证明入口已关闭") } j, err := c.load(job) if err != nil { return Result{}, err } + // 恢复只能用与窗口一致的入口形态:拿 no-gate 去收尾一扇真门,或反向, + // 都会假装"这次开过/没开过闸门"。 + if modeOf(j.IngressMode) != c.ingressModeOrDefault() { + return Result{}, fmt.Errorf("维护记录的入口形态(%s)与当前配置(%s)不一致:拒绝恢复", + modeOf(j.IngressMode), c.ingressModeOrDefault()) + } if terminal(j.State) { + // 终态重放(F05 路径二):journal 已经是 recovered,说明数据恢复与服务/入口 + // 恢复都已完成。这时再拒绝会让"journal recovered → PG 维护释放"之间的崩溃 + // 永久卡死(锁挂在那里、页面一直显示待恢复)。 + // 允许调用方**幂等补做业务收尾**:不重跑 Restore、不再 OpenIngress。 + if j.State == "recovered" && j.RecoveredBackup != "" && j.RecoveryDigest != "" { + return Result{State: "recovered", SnapshotID: j.RecoveredBackup, Digest: j.RecoveryDigest, Replayed: true}, nil + } return Result{}, errors.New("freeze journal is already terminal") } if !j.ContentRisk { @@ -125,6 +138,9 @@ func (c *Coordinator) RecoverWindow(ctx context.Context, job string, restorer Re j.RecoveryDigest = digest j.RecoveredAt = &ended j.RestoreBlocked = false + // 完成凭据同时写进 Result:终态重放(上面那条分支)靠它把同一份事实交回调用方。 + j.SnapshotID = j.BackupSnapshotID + j.Digest = digest if err := c.save(j); err != nil { return j.Result, err } @@ -140,6 +156,7 @@ func (c *Coordinator) RecoverWindow(ctx context.Context, job string, restorer Re return c.failRecovery(&j, "ingress_unverified", fmt.Errorf("入口未恢复:%w", readyErr)) } } + c.markHealth(&j) j.State = "recovered" j.Code = "" j.FinishedAt = &ended diff --git a/internal/libraryfreeze/resume_attempt_r30_test.go b/internal/libraryfreeze/resume_attempt_r30_test.go new file mode 100644 index 0000000..330828a --- /dev/null +++ b/internal/libraryfreeze/resume_attempt_r30_test.go @@ -0,0 +1,112 @@ +package libraryfreeze + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +const r30digest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + +// 第一次进窗在"未写任何内容"的情况下失败(例如预检/预备份前就断了),窗口已按失败收尾。 +// 同一个作业随后 resume:必须能开**新一次尝试**,而不是被 "freeze request already exists" 挡住。 +func TestR30ResumeAfterClosedWindowWithoutContentRisk(t *testing.T) { + root, c, e := instanceFixture(t) + if _, err := e.RunWindow(context.Background(), "job-r30-b", func(context.Context) error { return nil }, + func(ctx context.Context, w *Window) (string, error) { + return "", errors.New("preflight failed before any target write") + }, func(error) bool { return true }); err == nil { + t.Fatal("first window should fail") + } + first, err := e.load("job-r30-b") + if err != nil { + t.Fatalf("first journal: %v", err) + } + if first.State != "failed" || first.ContentRisk { + t.Fatalf("fixture shape wrong: state=%s contentRisk=%v", first.State, first.ContentRisk) + } + + callsBefore := len(c.calls) + result, err := e.RunWindow(context.Background(), "job-r30-b", func(context.Context) error { return nil }, + func(ctx context.Context, w *Window) (string, error) { + if err := w.MarkContentRisk(ctx); err != nil { + return "", err + } + return r30digest, nil + }, func(error) bool { return true }) + if err != nil { + t.Fatalf("resume after closed window must be allowed, got: %v", err) + } + if result.State != "succeeded" || result.SnapshotID != r30digest { + t.Fatalf("result=%+v", result) + } + if len(c.calls) == callsBefore { + t.Fatal("second attempt did not actually run the window") + } + journal, err := e.load("job-r30-b") + if err != nil { + t.Fatalf("journal after resume: %v", err) + } + if journal.Job != "job-r30-b" || journal.Attempt != 2 { + t.Fatalf("new attempt must bind same job with attempt=2: job=%q attempt=%d", journal.Job, journal.Attempt) + } + if journal.SupersededFrom != "archive/job-r30-b-attempt1.json" { + t.Fatalf("previous closed request must be referenced, not silently dropped: %q", journal.SupersededFrom) + } + raw, err := os.ReadFile(filepath.Join(root, journal.SupersededFrom)) + if err != nil { + t.Fatalf("archived previous journal missing: %v", err) + } + if !strings.Contains(string(raw), `"state":"failed"`) { + t.Fatalf("archived journal must keep the closed state: %s", raw) + } +} + +// 已经在窗口内写过目标内容(ContentRisk)却失败的作业,不许开新窗口 —— 必须走恢复。 +func TestR30RefusesNewAttemptWhenContentRiskRecorded(t *testing.T) { + _, _, e := instanceFixture(t) + if _, err := e.RunWindow(context.Background(), "job-r30-c", func(context.Context) error { return nil }, + func(ctx context.Context, w *Window) (string, error) { + if err := w.MarkContentRisk(ctx); err != nil { + return "", err + } + return "", errors.New("write failed mid way") + }, func(error) bool { return true }); err == nil { + t.Fatal("first window should fail") + } + _, err := e.RunWindow(context.Background(), "job-r30-c", func(context.Context) error { return nil }, + func(context.Context, *Window) (string, error) { return r30digest, nil }, func(error) bool { return true }) + if err == nil || !strings.Contains(err.Error(), "already exists") { + t.Fatalf("content-risk failure must still require recovery, got: %v", err) + } +} + +// 已成功收尾的窗口:再跑一次只回放结果,不重复副作用。 +func TestR30SucceededWindowIsNotReplayed(t *testing.T) { + _, c, e := instanceFixture(t) + if _, err := e.RunWindow(context.Background(), "job-r30-d", func(context.Context) error { return nil }, + func(ctx context.Context, w *Window) (string, error) { + if err := w.MarkContentRisk(ctx); err != nil { + return "", err + } + return r30digest, nil + }, func(error) bool { return true }); err != nil { + t.Fatal(err) + } + callsBefore := len(c.calls) + replay, err := e.RunWindow(context.Background(), "job-r30-d", func(context.Context) error { return nil }, + func(context.Context, *Window) (string, error) { return strings.Repeat("c", 64), nil }, + func(error) bool { return true }) + if err != nil { + t.Fatalf("replay: %v", err) + } + if replay.State != "succeeded" || replay.SnapshotID != r30digest { + t.Fatalf("replay must return original result, got %+v", replay) + } + if len(c.calls) != callsBefore { + t.Fatalf("replay must not touch services again: %v", c.calls) + } +} diff --git a/internal/libraryfreeze/window.go b/internal/libraryfreeze/window.go index f8dac27..c0c3ad3 100644 --- a/internal/libraryfreeze/window.go +++ b/internal/libraryfreeze/window.go @@ -3,10 +3,12 @@ package libraryfreeze import ( "context" "encoding/hex" + "encoding/json" "errors" "fmt" "os" "strings" + "syscall" "time" ) @@ -101,16 +103,55 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co } defer unlock(lock) // 实例级维护的入口必须由我们关:没有闸门就没有"入口已关"的证据, - // 后面拿什么证明后台静默都是空的。 - if c.level == "instance" && c.gate == nil { + // 后面拿什么证明后台静默都是空的。唯一例外是显式确认过的 no-gate 测试栈。 + if c.level == "instance" && c.gate == nil && c.ingressModeOrDefault() != IngressModeNone { return Result{}, errors.New("实例级维护缺少入口闸门:不能证明入口已关闭") } previous, loadErr := c.load(job) j := journal{} + attempt, superseded := 0, "" switch { case loadErr == nil && previous.State == "succeeded": return previous.Result, nil + case loadErr == nil && previous.State == "failed" && !previous.ContentRisk && + previous.Source == c.source && previous.TargetFingerprint == c.fingerprint && + (previous.Gate == nil || previous.GateReopened): + // 上一次尝试在**没有写过任何目标内容**的情况下失败并已收尾(服务已恢复、入口已重开)。 + // 这种窗口没有需要恢复的内容,同一作业的续作可以开新一次尝试: + // 旧请求不删除,归档后由新请求引用;job / operation / backup 身份保持不变。 + // 一旦 ContentRisk=true 就落到下面的拒绝分支,必须走恢复而不是新窗口。 + archived, archiveErr := c.archive(job, previous) + if archiveErr != nil { + return Result{}, archiveErr + } + attempt, superseded = previous.Attempt+1, archived + if attempt < 1 { + attempt = 1 + } + if err = c.pending(); err != nil { + return Result{}, err + } + if err = prepare(ctx); err != nil { + return Result{}, err + } + items, err := inventory(ctx, c.control) + if err != nil { + return Result{}, err + } + j = journal{Version: 1, Source: c.source, Job: job, Level: c.level, Ingress: c.ingress, + Attempt: attempt, SupersededFrom: superseded, + IngressMode: c.ingressModeOrDefault(), IngressAck: c.ingressAck, HealthURL: c.healthURL, + TargetFingerprint: c.fingerprint, Result: Result{State: "stopping"}, StartedAt: time.Now().UTC()} + for _, s := range items { + if s.Running && !s.Healthy { + return Result{}, errors.New("test writer is not ready") + } + j.Services = append(j.Services, serviceRecord{Service: s}) + } + if err = c.save(j); err != nil { + return Result{}, err + } case loadErr == nil && (previous.State == "stopping" || previous.State == "held"): // 接管:目标必须仍然停住。不重新"准备"、也不从零重来。 j = previous @@ -119,7 +160,7 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co j.RestoreBlocked = false } case loadErr == nil: - return previous.Result, errors.New("freeze request already exists; recovery or a new request is required") + return previous.Result, fmt.Errorf("freeze request already exists (%s); recovery or a new request is required", previous.State) case !errors.Is(loadErr, os.ErrNotExist): return Result{}, loadErr default: @@ -137,6 +178,7 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co return Result{}, err } j = journal{Version: 1, Source: c.source, Job: job, Level: c.level, Ingress: c.ingress, + Attempt: 1, IngressMode: c.ingressModeOrDefault(), IngressAck: c.ingressAck, HealthURL: c.healthURL, TargetFingerprint: c.fingerprint, Result: Result{State: "stopping"}, StartedAt: time.Now().UTC()} for _, s := range items { if s.Running && !s.Healthy { @@ -152,50 +194,98 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co // 顺序不能换:先把外部任务的生产入口关掉并排空,再证明后台静默,最后才停写入者。 // 先证明静默再关入口是错的——排空期间还在跑的在途请求随时会派生新的异步任务, // 那一刻的"空"到停写者时早就失效了;而 app 一旦 SIGTERM 就 exit(1),会把任务腰斩。 - if c.gate != nil && (j.Gate == nil || !j.Gate.Drained) { - evidence, gateErr := c.gate.CloseIngress(ctx) - if gateErr != nil { - return c.abandonWindow(ctx, &j, fmt.Errorf("关闭目标入口失败:%w", gateErr), "gate_failed") + // + // no-gate(测试栈)没有闸门可关:顺序改成"先停写者 → 再证明队列排空 → 导出", + // 并且一笔闸门动作都不做;gate 证据位置只留 mode=none 的说明,不冒充排空。 + mode := modeOf(j.IngressMode) + if mode != c.ingressModeOrDefault() { + return Result{}, fmt.Errorf("维护记录与当前配置的入口形态不一致(记录 %s,配置 %s),拒绝接管", + mode, c.ingressModeOrDefault()) + } + if mode == IngressModeNone { + if j.Gate == nil || j.Gate.Mode != IngressModeNone { + evidence := GateEvidence{Mode: IngressModeNone, Reason: NoIngressGateReason} + j.Gate = &evidence } - if !evidence.Closed || !evidence.Drained { - return c.abandonWindow(ctx, &j, errors.New("目标入口未确认排空(仍有在途请求)"), "gate_not_drained") + if j.IngressAck == "" { + j.IngressAck = c.ingressAck + } + if j.HealthURL == "" { + j.HealthURL = c.healthURL } - j.Gate = &evidence if err = c.save(j); err != nil { return Result{}, err } - } - - // 入口关了才谈得上"稳定切点":连续为空 + 跨过稳定窗口 + 拿得到任务指纹。 - proof, quietErr := c.awaitBackgroundQuiet(ctx, &j) - if quietErr != nil { - return c.abandonWindow(ctx, &j, quietErr, "background_busy") - } - - // 停写入者:任何一步不成立都不许往下写。 - if stopErr := c.stopAll(ctx, &j); stopErr != nil { - return c.abandonWindow(ctx, &j, stopErr, "stop_failed") - } - if stopErr := c.stopped(ctx, j); stopErr != nil { - return c.abandonWindow(ctx, &j, stopErr, "isolation_unverified") - } - if stopErr := c.verifyDrain(ctx, &j); stopErr != nil { - return c.abandonWindow(ctx, &j, stopErr, "drain_unverified") - } - // 停完再复核一次:入队/派发可能在"证明静默"和"停写者"之间发生。 - // 队列仍有任务说明有任务被截断——这比同步失败严重,按切点不一致处理,绝不往下写。 - if stopErr := c.verifyBackgroundAfterStop(ctx, &j, proof); stopErr != nil { - return c.abandonWindow(ctx, &j, stopErr, "background_truncated") - } - if c.ingressClosed != nil { - if stopErr := c.ingressClosed(ctx); stopErr != nil { - return c.abandonWindow(ctx, &j, fmt.Errorf("目标入口仍然可用:%w", stopErr), "ingress_open") + if stopErr := c.stopAll(ctx, &j); stopErr != nil { + return c.abandonWindow(ctx, &j, stopErr, "stop_failed") + } + if stopErr := c.stopped(ctx, j); stopErr != nil { + return c.abandonWindow(ctx, &j, stopErr, "isolation_unverified") + } + if stopErr := c.verifyDrain(ctx, &j); stopErr != nil { + return c.abandonWindow(ctx, &j, stopErr, "drain_unverified") + } + // 写者全停之后队列必须一直为空:这一刻的"空"就是这次窗口的排空证据。 + proof, quietErr := c.awaitBackgroundQuiet(ctx, &j) + if quietErr != nil { + return c.abandonWindow(ctx, &j, quietErr, "background_busy") + } + if stopErr := c.verifyBackgroundAfterStop(ctx, &j, proof); stopErr != nil { + return c.abandonWindow(ctx, &j, stopErr, "background_truncated") + } + // 没有闸门排空证据,也没有退出码可作凭据:排空只由"写者全停 + 队列静默" + // 共同证明——证据等级降一档,且已写进 ingress_mode=none。 + j.DrainVerified = true + j.State = "held" + if err = c.save(j); err != nil { + return Result{}, err + } + } else { + if c.gate != nil && (j.Gate == nil || !j.Gate.Drained) { + evidence, gateErr := c.gate.CloseIngress(ctx) + if gateErr != nil { + return c.abandonWindow(ctx, &j, fmt.Errorf("关闭目标入口失败:%w", gateErr), "gate_failed") + } + if !evidence.Closed || !evidence.Drained { + return c.abandonWindow(ctx, &j, errors.New("目标入口未确认排空(仍有在途请求)"), "gate_not_drained") + } + j.Gate = &evidence + if err = c.save(j); err != nil { + return Result{}, err + } + } + + // 入口关了才谈得上"稳定切点":连续为空 + 跨过稳定窗口 + 拿得到任务指纹。 + proof, quietErr := c.awaitBackgroundQuiet(ctx, &j) + if quietErr != nil { + return c.abandonWindow(ctx, &j, quietErr, "background_busy") + } + + // 停写入者:任何一步不成立都不许往下写。 + if stopErr := c.stopAll(ctx, &j); stopErr != nil { + return c.abandonWindow(ctx, &j, stopErr, "stop_failed") + } + if stopErr := c.stopped(ctx, j); stopErr != nil { + return c.abandonWindow(ctx, &j, stopErr, "isolation_unverified") + } + if stopErr := c.verifyDrain(ctx, &j); stopErr != nil { + return c.abandonWindow(ctx, &j, stopErr, "drain_unverified") + } + // 停完再复核一次:入队/派发可能在"证明静默"和"停写者"之间发生。 + // 队列仍有任务说明有任务被截断——这比同步失败严重,按切点不一致处理,绝不往下写。 + if stopErr := c.verifyBackgroundAfterStop(ctx, &j, proof); stopErr != nil { + return c.abandonWindow(ctx, &j, stopErr, "background_truncated") + } + if c.ingressClosed != nil { + if stopErr := c.ingressClosed(ctx); stopErr != nil { + return c.abandonWindow(ctx, &j, fmt.Errorf("目标入口仍然可用:%w", stopErr), "ingress_open") + } + j.IngressClosed = true + } + j.State = "held" + if err = c.save(j); err != nil { + return Result{}, err } - j.IngressClosed = true - } - j.State = "held" - if err = c.save(j); err != nil { - return Result{}, err } w := &Window{c: c, j: &j} @@ -230,7 +320,20 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co } // abandonWindow:在"还没写目标"的阶段失败——内容没被改过,可以安全恢复并结案。 +// +// 判断"这个窗口有没有写过"必须读**持久** ContentRisk,而不是本进程是否调用过 Apply: +// 接管一个 held/stopping 窗口时本进程一笔都没写,但上一个进程可能已经写了一半。 +// 那种情况下任何早退(入口关不掉、后台不静默、停写者失败)都只能保持关闭, +// 由恢复流程按预备份处理——把服务拉起来开门就是对外暴露半写内容(F03)。 func (c *Coordinator) abandonWindow(ctx context.Context, j *journal, cause error, code string) (Result, error) { + if j.ContentRisk { + j.State = "held" + j.RestoreBlocked = true + j.Code = code + saveErr := c.save(*j) + return j.Result, errors.Join(cause, errors.New( + "窗口内容有持久风险:目标保持维护,禁止重新开放;须按预备份恢复并逐类校验"), saveErr) + } recoveryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Minute) defer cancel() if restoreErr := c.restore(recoveryCtx, j); restoreErr != nil { @@ -248,6 +351,7 @@ func (c *Coordinator) abandonWindow(ctx context.Context, j *journal, cause error return j.Result, errors.Join(cause, fmt.Errorf("目标入口没有恢复:%w", readyErr)) } } + c.markHealth(j) ended := time.Now().UTC() j.State = "failed" j.Code = code @@ -258,6 +362,17 @@ func (c *Coordinator) abandonWindow(ctx context.Context, j *journal, cause error return j.Result, cause } +// markHealth 记录 no-gate 窗口的恢复证据:只有健康探针真的通过才写 verified。 +func (c *Coordinator) markHealth(j *journal) { + if c.ingressModeOrDefault() != IngressModeNone { + return + } + j.HealthVerified = true + if j.HealthURL == "" { + j.HealthURL = c.healthURL + } +} + // closeWindow:写完之后的收尾。allowRestore=false(半写且回滚失败)时 // 服务保持停止、journal 保持非终态,返回的是"目标仍在维护"这个结论。 func (c *Coordinator) closeWindow(ctx context.Context, j *journal, cause error, allowRestore bool, snapshotID string) (Result, error) { @@ -295,6 +410,7 @@ func (c *Coordinator) closeWindow(ctx context.Context, j *journal, cause error, return j.Result, errors.Join(cause, fmt.Errorf("目标入口没有恢复:%w", readyErr)) } } + c.markHealth(j) ended := time.Now().UTC() j.FinishedAt = &ended if cause != nil { @@ -346,7 +462,8 @@ func (c *Coordinator) awaitBackgroundQuiet(ctx context.Context, j *journal) (*Qu } return nil, nil } - if j.Gate == nil || !j.Gate.Drained { + // no-gate 窗口没有"入口已关"这个前提:静默证明只对队列负责(写者已全停)。 + if c.ingressModeOrDefault() != IngressModeNone && (j.Gate == nil || !j.Gate.Drained) { return nil, errors.New("必须先关闭并排空入口,再证明后台静默") } @@ -502,13 +619,15 @@ func (c *Coordinator) verifyDrain(ctx context.Context, j *journal) error { return errors.New("test writer still running") } if now.ExitCode == nil { - if c.level == "instance" && !gateDrained { + // no-gate 窗口:没有闸门排空证据,也不把退出码当唯一凭据 + //(被代理服务收到 SIGTERM 会 exit(1));排空由"写者全停 + 队列静默"证明。 + if c.level == "instance" && !gateDrained && c.ingressModeOrDefault() != IngressModeNone { return fmt.Errorf("无法证明 %s 的在途请求已排空(控制器没有退出码)", s.ID) } continue } s.ExitCode = now.ExitCode - if *now.ExitCode != 0 && !gateDrained { + if *now.ExitCode != 0 && !gateDrained && c.ingressModeOrDefault() != IngressModeNone { return fmt.Errorf("写入者 %s 未优雅退出(exit=%d):在途请求没有完成排空", s.ID, *now.ExitCode) } verified++ @@ -562,3 +681,62 @@ func (c *Coordinator) checkBackgroundStuck(ctx context.Context) error { } return fmt.Errorf("写入者已停但后台仍有任务(%s):这些任务在上次中断时被截断,需要先把服务起来(入口保持关闭)让它们跑完,再重试恢复", snapshot.Detail) } + +// archive 把已经收尾的旧请求**复制**成不可覆盖的归档副本,返回归档文件名(相对 root)。 +// +// 这里绝不能 rename 走 current:归档之后还有 pending/prepare/inventory/save 若干步, +// 任何一步失败都必须让 current 仍然可读,否则"下一次尝试"会从空目录开始(r31 父审指出的路径)。 +// 归档名按被归档请求自己的 attempt 派生(v1 旧记录为 0),因此不会与后续代次撞名; +// 目标已存在时必须字节相同(同一份证据重放),不同则拒绝,绝不覆盖。 +func (c *Coordinator) archive(job string, previous journal) (string, error) { + attempt := previous.Attempt + const dir = "archive" + if err := c.root.Mkdir(dir, 0o700); err != nil && !errors.Is(err, os.ErrExist) { + return "", fmt.Errorf("archive closed freeze request: %w", err) + } + name := fmt.Sprintf("%s/%s-attempt%d.json", dir, job, attempt) + data, err := json.Marshal(previous) + if err != nil { + return "", err + } + f, err := c.root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if errors.Is(err, os.ErrExist) { + existing, readErr := c.root.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if readErr != nil { + return "", fmt.Errorf("archive collision unreadable: %w", readErr) + } + defer existing.Close() + buf := make([]byte, len(data)+1) + n, readAll := existing.Read(buf) + if readAll != nil && n == 0 { + return "", fmt.Errorf("archive collision unreadable: %w", readAll) + } + if string(buf[:n]) != string(data) { + return "", fmt.Errorf("archive collision: %s already exists with different content", name) + } + return name, nil + } + if err != nil { + return "", fmt.Errorf("archive closed freeze request: %w", err) + } + if _, err = f.Write(data); err != nil { + _ = c.root.Remove(name) + return "", err + } + if err = f.Sync(); err != nil { + _ = c.root.Remove(name) + return "", err + } + if err = f.Close(); err != nil { + return "", err + } + d, err := c.root.Open(dir) + if err != nil { + return "", err + } + defer d.Close() + if err = d.Sync(); err != nil { + return "", err + } + return name, nil +} diff --git a/internal/libraryfreeze/window_safety_test.go b/internal/libraryfreeze/window_safety_test.go new file mode 100644 index 0000000..23f9e10 --- /dev/null +++ b/internal/libraryfreeze/window_safety_test.go @@ -0,0 +1,73 @@ +package libraryfreeze + +import ( + "context" + "errors" + "strings" + "testing" +) + +// F03:接管一个已经持久化 ContentRisk 的半写窗口时,前置检查(后台静默/停写者/排空) +// 任何一个失败都必须保持目标关闭。原实现所有早退都走 abandonWindow → restore, +// 于是"本进程尚未写"被当成"此窗口从未写",半写内容被重新对外开放。 +func TestAdoptedHalfWrittenWindowPreflightFailureStaysClosed(t *testing.T) { + _, c, e := instanceFixture(t) + stopAllServices(c) + j := heldJournal("audit-adopt", strings.Repeat("a", 64), strings.Repeat("b", 64)) + if err := e.save(j); err != nil { + t.Fatal(err) + } + // 后台仍有任务:前置检查在 work 之前失败。 + if err := e.SetQuiescer(&idleQuiescer{busy: true}); err != nil { + t.Fatal(err) + } + e.quiesceWait = 1 // 极短等待,让前置检查尽快失败 + worked := false + _, err := e.RunWindow(context.Background(), j.Job, func(context.Context) error { return nil }, + func(context.Context, *Window) (string, error) { + worked = true + return "", nil + }, func(error) bool { return false }) + if err == nil || worked { + t.Fatalf("fixture did not fail before work: err=%v worked=%v", err, worked) + } + for _, call := range c.calls { + if strings.HasPrefix(call, "start:") || call == "gate:open" { + t.Fatalf("半写目标在前置检查失败后被重新开放:calls=%v", c.calls) + } + } + after, loadErr := e.load(j.Job) + if loadErr != nil { + t.Fatal(loadErr) + } + if terminal(after.State) { + t.Fatalf("半写窗口必须保持非终态(等恢复),实际 %s", after.State) + } + if !after.ContentRisk || !after.RestoreBlocked { + t.Fatalf("持久内容风险被清掉了:contentRisk=%v restoreBlocked=%v", after.ContentRisk, after.RestoreBlocked) + } +} + +// F04:任何一个"原本在跑"的写入者启动失败,都不能调用 OpenIngress。 +// 原实现在 restore() 里累积 Start/健康/save 错误,却仍然开门:状态说"保持关闭", +// 外部动作却把流量打向没准备好的目标。 +func TestRestartFailureMustNotOpenGate(t *testing.T) { + _, c, e := instanceFixture(t) + e.control = &restartFailControl{exitControl: c} + _, err := e.RunWindow(context.Background(), "audit-restart", func(context.Context) error { return nil }, + func(context.Context, *Window) (string, error) { return "", nil }, func(error) bool { return true }) + if err == nil { + t.Fatal("fixture 预期重启失败") + } + for _, call := range c.calls { + if call == "gate:open" { + t.Fatalf("重启失败后仍然打开了入口:calls=%v", c.calls) + } + } +} + +type restartFailControl struct{ *exitControl } + +func (c *restartFailControl) Start(context.Context, string) error { + return errors.New("synthetic restart failure") +} diff --git a/internal/libraryhandoff/defaults_test.go b/internal/libraryhandoff/defaults_test.go new file mode 100644 index 0000000..a2c4627 --- /dev/null +++ b/internal/libraryhandoff/defaults_test.go @@ -0,0 +1,34 @@ +package libraryhandoff + +import ( + "context" + "testing" + "time" +) + +func TestDefaultLimitsAllowRealBundleRoundTrip(t *testing.T) { + root, archive := newArchive(t) + id := seal(t, archive) + f := newFixture(t, root) + f.cfg.MaxBundleBytes = 0 + f.cfg.OpTimeout = 0 + h, err := New(f.cfg, time.Now) + if err != nil { + t.Fatal(err) + } + want := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB} + if _, err := h.Push(context.Background(), want); err != nil { + t.Fatalf("omitted limits must allow a real bundle: %v", err) + } + fresh, _ := newArchive(t) + cfg := withLocalArchive(t, f, fresh) + cfg.MaxBundleBytes = 0 + cfg.OpTimeout = 0 + down, err := New(cfg, time.Now) + if err != nil { + t.Fatal(err) + } + if _, err := down.Fetch(context.Background(), id); err != nil { + t.Fatalf("omitted limits must allow verified fetch: %v", err) + } +} diff --git a/internal/libraryhandoff/env.go b/internal/libraryhandoff/env.go new file mode 100644 index 0000000..55e9b3d --- /dev/null +++ b/internal/libraryhandoff/env.go @@ -0,0 +1,105 @@ +package libraryhandoff + +import ( + "errors" + "strconv" + "strings" + "time" +) + +// 环境变量名集中在这里:API(决定要不要先做搬运)与 capture worker(真正执行搬运) +// 必须看同一组名字,写两遍迟早分叉成"一边以为接线了、另一边没接线"。 +const ( + EnvSSHConfig = "LIBRARY_HANDOFF_SSH_CONFIG" + EnvTarget = "LIBRARY_HANDOFF_TARGET" + EnvExecutor = "LIBRARY_HANDOFF_EXECUTOR" + EnvBundleDir = "LIBRARY_HANDOFF_BUNDLE_DIR" + EnvRemoteArchive = "LIBRARY_HANDOFF_REMOTE_ARCHIVE" + EnvStagingDir = "LIBRARY_HANDOFF_STAGING_DIR" + EnvLocalArchive = "LIBRARY_HANDOFF_LOCAL_ARCHIVE" + EnvMaxBytes = "LIBRARY_HANDOFF_MAX_BYTES" + EnvTimeout = "LIBRARY_HANDOFF_TIMEOUT" + EnvTransport = "LIBRARY_HANDOFF_TRANSPORT" + EnvLocalRoot = "LIBRARY_HANDOFF_LOCAL_ROOT" + // EnvPullInterval 控制"云端版本回传本机"的扫描间隔(capture 角色)。 + EnvPullInterval = "LIBRARY_HANDOFF_PULL_INTERVAL" +) + +// FromEnv 解析搬运配置。 +// +// 返回 configured=false 只表示"这项能力没接线",不是错误:未接线时 API 保持旧行为 +// (直接投递 library.sync/restore),本机目标部署完全不受影响。 +// +// 但一旦任何一项接线字段出现,就必须**全部齐备**,否则报错——半接线是最坏的情况: +// API 以为会搬运,worker 却搬不动,发布作业会以"快照不在执行器"失败。 +func FromEnv(get func(string) string) (Config, bool, error) { + if get == nil { + return Config{}, false, errors.New("缺少配置读取入口") + } + value := func(key string) string { return strings.TrimSpace(get(key)) } + config := Config{ + SSHConfig: value(EnvSSHConfig), + SSHTarget: value(EnvTarget), + ExecutorContainer: value(EnvExecutor), + BundleDir: value(EnvBundleDir), + RemoteArchive: value(EnvRemoteArchive), + StagingDir: value(EnvStagingDir), + LocalArchive: value(EnvLocalArchive), + Transport: value(EnvTransport), + LocalRoot: value(EnvLocalRoot), + OpTimeout: 10 * time.Minute, + PullInterval: 5 * time.Minute, + } + if config.Transport == "" { + config.Transport = TransportSSH + } + if raw := value(EnvMaxBytes); raw != "" { + parsed, err := strconv.ParseInt(raw, 10, 64) + if err != nil || parsed <= 0 { + return Config{}, false, errors.New("LIBRARY_HANDOFF_MAX_BYTES 必须是正整数") + } + config.MaxBundleBytes = parsed + } + if raw := value(EnvPullInterval); raw != "" { + parsed, err := time.ParseDuration(raw) + if err != nil || parsed <= 0 { + return Config{}, false, errors.New("LIBRARY_HANDOFF_PULL_INTERVAL 必须是正的时间长度(如 5m)") + } + config.PullInterval = parsed + } + if raw := value(EnvTimeout); raw != "" { + parsed, err := time.ParseDuration(raw) + if err != nil || parsed <= 0 { + return Config{}, false, errors.New("LIBRARY_HANDOFF_TIMEOUT 必须是正的时间长度(如 10m)") + } + config.OpTimeout = parsed + } + configuredFields := 0 + for _, item := range []string{EnvSSHConfig, EnvTarget, EnvExecutor, EnvBundleDir, EnvRemoteArchive, EnvStagingDir} { + if value(item) != "" { + configuredFields++ + } + } + if configuredFields == 0 && value(EnvTransport) != TransportLocal { + return Config{}, false, nil + } + if config.Transport == TransportLocal { + if value(EnvLocalRoot) == "" { + return Config{}, false, errors.New("LIBRARY_HANDOFF_TRANSPORT=local 必须同时给出 LIBRARY_HANDOFF_LOCAL_ROOT(仅限隔离 fixture)") + } + if value(EnvSSHConfig) != "" || value(EnvTarget) != "" { + return Config{}, false, errors.New("local 通道不允许同时配置 SSH 目标:fixture 不能冒充云端通道") + } + if config.LocalArchive == "" { + config.LocalArchive = value("LIBRARY_ARCHIVE_ROOT") + } + if config.ExecutorContainer == "" { + // fixture 不跑容器:给一个固定名字只为让配置校验完整,不会被执行。 + config.ExecutorContainer = "fixture-executor" + } + } + if err := config.validate(); err != nil { + return Config{}, false, err + } + return config, true, nil +} diff --git a/internal/libraryhandoff/handoff.go b/internal/libraryhandoff/handoff.go new file mode 100644 index 0000000..3c0bae3 --- /dev/null +++ b/internal/libraryhandoff/handoff.go @@ -0,0 +1,653 @@ +// Package libraryhandoff 把一份已封存快照在"本机控制面"与"云测试发布执行器"之间搬运, +// 并保证"字节在到达前不可用"。 +// +// 为什么不是"把归档目录 rsync 过去":发布链路在装配阶段会用 Load 逐 blob 重算 sha256, +// 半拷贝的归档会让发布在维护窗口里失败——正好落在最不该失败的时刻。所以搬运单位是 +// 自描述 bundle(清单先写、blob 以 sha256 命名、下载侧边收边算),并且**只有** +// 远端 `libraryctl snapshot-unpack` 成功、版本清单摘要自证、身份与请求一致之后, +// 调用方才允许把发布作业入队。 +// +// 通道只用已批准的本机→云端 SSH(BatchMode、0600 配置+私钥)。远端命令是固定 argv: +// 容器名、归档根、暂存目录全部来自部署配置,调用方只能给快照 ID 与期望身份。 +package libraryhandoff + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "sort" + "strings" + "syscall" + "time" + + "knowledge-governance/internal/librarysnapshot" +) + +// Identity 是一次搬运期望的快照身份。它必须来自治理库里的作业/版本记录, +// 不能从 bundle 自己读到的值"回填"——那就是让数据自己证明自己。 +type Identity struct { + SnapshotID string + Scope string + TenantID uint64 + KnowledgeBaseID string +} + +// Config 是部署注入的搬运配置。缺项即未接线:未接线时调用方保持旧行为(本机目标)。 +type Config struct { + // SSHTarget 是 ssh 配置里的 Host 别名;SSHConfig 是 `ssh -F` 用的 0600 文件。 + SSHTarget string + SSHConfig string + // ExecutorContainer 是云端 release-executor 容器名(libraryctl 在 /app/libraryctl)。 + ExecutorContainer string + // BundleDir 是云端暂存目录(只放传输中的 bundle,不参与保留策略)。 + BundleDir string + // RemoteArchive 是云端执行器的归档根(与执行器 env 的 LIBRARY_ARCHIVE_ROOT 一致)。 + RemoteArchive string + // LocalArchive 是本机归档根(只读读取;回传时写入)。 + LocalArchive string + // StagingDir 是本机暂存(0600,放本次 pack 出来的 bundle)。 + StagingDir string + // MaxBundleBytes 是单份 bundle 的上限;超过即拒绝(防止把整机磁盘拖垮)。 + MaxBundleBytes int64 + // OpTimeout 是单个远端动作的超时。 + OpTimeout time.Duration + // PullInterval 是"云端版本回传本机"的扫描间隔(只有 capture 角色用)。 + PullInterval time.Duration + // Transport 是 "ssh"(默认)或 "local"(仅限隔离 fixture 测试)。 + Transport string + // LocalRoot 是 local transport 的"云端根目录"(fixture 用)。 + LocalRoot string +} + +const ( + TransportSSH = "ssh" + TransportLocal = "local" +) + +func (c *Config) validate() error { + missing := make([]string, 0, 6) + if c.Transport == TransportLocal { + // fixture 通道没有 ssh,但必须有显式隔离根:否则"本地目录"会被当成云端。 + if c.LocalRoot == "" || !filepath.IsAbs(c.LocalRoot) { + missing = append(missing, "LOCAL_ROOT") + } + } else { + if c.SSHTarget == "" { + missing = append(missing, "SSH_TARGET") + } + if c.SSHConfig == "" || !filepath.IsAbs(c.SSHConfig) { + missing = append(missing, "SSH_CONFIG") + } + } + if c.ExecutorContainer == "" { + missing = append(missing, "EXECUTOR_CONTAINER") + } + for name, value := range map[string]string{"BUNDLE_DIR": c.BundleDir, "REMOTE_ARCHIVE": c.RemoteArchive, "LOCAL_ARCHIVE": c.LocalArchive, "STAGING_DIR": c.StagingDir} { + if value == "" || !filepath.IsAbs(value) || filepath.Clean(value) != value || strings.Contains(value, "..") { + missing = append(missing, name) + } + } + if len(missing) > 0 { + sort.Strings(missing) + return fmt.Errorf("快照搬运未接线:缺少 %s", strings.Join(missing, "、")) + } + if c.MaxBundleBytes <= 0 { + c.MaxBundleBytes = 8 << 30 + } + if c.OpTimeout <= 0 { + c.OpTimeout = 10 * time.Minute + } + return nil +} + +// Evidence 是一次搬运留下的可审计事实(写进作业阶段/日志,不写凭据)。 +type Evidence struct { + Snapshot string `json:"snapshot"` + Scope string `json:"scope"` + TenantID uint64 `json:"tenant_id"` + KnowledgeBase string `json:"knowledge_base_id"` + Parts int `json:"parts"` + Bytes int64 `json:"bytes"` + Reused bool `json:"reused"` + Direction string `json:"direction"` + VerifiedAt time.Time `json:"verified_at"` +} + +// Remote 是"云端那一侧"的动作集合。两种实现:ssh(真实通道)与 local(隔离 fixture)。 +type Remote interface { + PutBundle(ctx context.Context, name string, body io.Reader) error + OpenBundle(ctx context.Context, name string) (io.ReadCloser, error) + RemoveBundle(ctx context.Context, name string) error + RunLibraryctl(ctx context.Context, args ...string) ([]byte, error) + ReadVersionManifest(ctx context.Context, id string) ([]byte, error) + // VerifySnapshot 要求远端对这份快照做**整版**校验(逐部件重算字节), + // 复用一份已有清单前必须通过它:清单存在不等于字节还在。 + VerifySnapshot(ctx context.Context, id string) error +} + +// Handoff 是搬运的执行者(一套实现,两个方向)。 +type Handoff struct { + config Config + remote Remote + now func() time.Time +} + +var snapshotIDPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) + +// bundleName 只接受内容寻址的快照 ID:暂存目录里不允许出现调用方可控的文件名。 +func bundleName(id string) (string, error) { + if !snapshotIDPattern.MatchString(id) { + return "", errors.New("快照 ID 必须是 64 位小写十六进制") + } + return id + ".tar", nil +} + +// New 装配搬运执行器。transport 选择失败一律报错,不做"降级到本机"。 +func New(config Config, now func() time.Time) (*Handoff, error) { + if err := config.validate(); err != nil { + return nil, err + } + if now == nil { + now = time.Now + } + if config.Transport == "" { + config.Transport = TransportSSH + } + var remote Remote + switch config.Transport { + case TransportSSH: + remote = &sshRemote{config: config} + case TransportLocal: + // 只看配置不足以证明这是测试:必须显式给出隔离根,且不得同时配 SSH 目标, + // 否则等于把"本地目录"冒充成云端。 + if config.LocalRoot == "" || !filepath.IsAbs(config.LocalRoot) { + return nil, errors.New("local transport 必须显式给出隔离根目录") + } + remote = &localRemote{config: config} + default: + return nil, fmt.Errorf("未知搬运通道 %q(只允许 ssh/local)", config.Transport) + } + return &Handoff{config: config, remote: remote, now: now}, nil +} + +// Push 把本机快照送到云端执行器,并在云端**再校验一遍**后才算成功。 +// +// 返回成功即代表:云端 `versions/.json` 存在、摘要 == id、逐 blob 校验通过、 +// 清单身份与请求一致。任何一步不满足都返回错误,调用方不得入队发布作业。 +func (h *Handoff) Push(ctx context.Context, want Identity) (Evidence, error) { + if err := validateIdentity(want); err != nil { + return Evidence{}, err + } + name, err := bundleName(want.SnapshotID) + if err != nil { + return Evidence{}, err + } + // 远端已有同 ID:必须字节一致且身份一致才复用;否则拒绝(同 ID 异内容)。 + if evidence, ok, err := h.remoteEvidence(ctx, want); err != nil { + return Evidence{}, err + } else if ok { + evidence.Direction = "push" + evidence.Bytes = 0 + return evidence, nil + } + unlock, err := h.lock(ctx, want.SnapshotID) + if err != nil { + return Evidence{}, err + } + defer unlock() + // 拿锁后再查一次:并发调用里后到的那个直接复用先到的结果。 + if evidence, ok, err := h.remoteEvidence(ctx, want); err != nil { + return Evidence{}, err + } else if ok { + evidence.Direction = "push" + return evidence, nil + } + + archive, err := librarysnapshot.Open(h.config.LocalArchive, 256*1024*1024) + if err != nil { + return Evidence{}, fmt.Errorf("本机归档不可读,无法搬运:%w", err) + } + defer archive.Close() + // Load 逐 blob 重算 sha256:只搬"在这台机器上验证过"的字节。 + manifest, err := archive.Load(want.SnapshotID) + if err != nil { + return Evidence{}, fmt.Errorf("本机快照不可用(可能只存在于云端,走 Fetch):%w", err) + } + if err := matchesIdentity(manifest, want); err != nil { + return Evidence{}, err + } + + bundle, cleanup, err := h.packLocally(archive, want.SnapshotID, name) + if err != nil { + return Evidence{}, err + } + defer cleanup() + file, err := os.Open(bundle) + if err != nil { + return Evidence{}, errors.New("打开本机 bundle 失败") + } + defer file.Close() + if info, statErr := file.Stat(); statErr != nil || info.Size() <= 0 || info.Size() > h.config.MaxBundleBytes { + return Evidence{}, errors.New("bundle 大小超出允许范围") + } + if err := h.remote.PutBundle(ctx, name, file); err != nil { + return Evidence{}, fmt.Errorf("把快照送到执行器失败:%w", err) + } + if _, err := h.remote.RunLibraryctl(ctx, "snapshot-unpack", "-archive", h.config.RemoteArchive, + "-bundle", filepath.Join(h.config.BundleDir, name), "-snapshot", want.SnapshotID); err != nil { + return Evidence{}, fmt.Errorf("执行器侧校验/装入失败:%w", err) + } + manifestRaw, err := h.remote.ReadVersionManifest(ctx, want.SnapshotID) + if err != nil { + return Evidence{}, fmt.Errorf("执行器侧版本清单不可读:%w", err) + } + sum := sha256.Sum256(manifestRaw) + if hex.EncodeToString(sum[:]) != want.SnapshotID { + return Evidence{}, errors.New("执行器侧版本清单摘要与快照 ID 不一致") + } + remoteManifest, err := librarysnapshot.DecodeManifest(manifestRaw, want.SnapshotID) + if err != nil { + return Evidence{}, fmt.Errorf("执行器侧清单不可解析:%w", err) + } + if err := matchesIdentity(remoteManifest, want); err != nil { + return Evidence{}, err + } + // 只删本次传输的暂存文件;归档本体(versions/blobs)一律不动。 + _ = h.remote.RemoveBundle(ctx, name) + return Evidence{Snapshot: want.SnapshotID, Scope: want.Scope, TenantID: want.TenantID, + KnowledgeBase: want.KnowledgeBaseID, Parts: len(remoteManifest.Parts), + Bytes: manifestBytes(remoteManifest), Direction: "push", VerifiedAt: h.now().UTC()}, nil +} + +// Fetch 把云端存在的快照取回本机归档(预备份/云端产物的读回路径)。 +// +// 成功即代表:本机 versions/.json 已落位、逐 blob 校验通过。失败则本机不留下版本, +// 页面照旧按"没有这份版本"展示,绝不显示成可恢复。 +func (h *Handoff) Fetch(ctx context.Context, id string) (Evidence, error) { + name, err := bundleName(id) + if err != nil { + return Evidence{}, err + } + archive, err := librarysnapshot.Open(h.config.LocalArchive, 256*1024*1024) + if err != nil { + return Evidence{}, fmt.Errorf("本机归档不可用:%w", err) + } + defer archive.Close() + if manifest, loadErr := archive.Load(id); loadErr == nil { + return Evidence{Snapshot: id, Scope: manifest.Scope, TenantID: manifest.TenantID, + KnowledgeBase: manifest.KnowledgeBaseID, Parts: len(manifest.Parts), + Bytes: manifestBytes(manifest), Reused: true, Direction: "fetch", VerifiedAt: h.now().UTC()}, nil + } + unlock, err := h.lock(ctx, id) + if err != nil { + return Evidence{}, err + } + defer unlock() + if manifest, loadErr := archive.Load(id); loadErr == nil { + return Evidence{Snapshot: id, Scope: manifest.Scope, TenantID: manifest.TenantID, + KnowledgeBase: manifest.KnowledgeBaseID, Parts: len(manifest.Parts), + Bytes: manifestBytes(manifest), Reused: true, Direction: "fetch", VerifiedAt: h.now().UTC()}, nil + } + + remoteBundle := filepath.Join(h.config.BundleDir, name) + defer func() { _ = h.remote.RemoveBundle(context.WithoutCancel(ctx), name) }() + if _, err := h.remote.RunLibraryctl(ctx, "snapshot-pack", "-archive", h.config.RemoteArchive, + "-snapshot", id, "-bundle", remoteBundle); err != nil { + return Evidence{}, fmt.Errorf("云端快照不可打包(可能不存在或校验失败):%w", err) + } + body, err := h.remote.OpenBundle(ctx, name) + if err != nil { + return Evidence{}, fmt.Errorf("读取云端 bundle 失败:%w", err) + } + defer body.Close() + localBundle := filepath.Join(h.config.StagingDir, name) + _ = os.Remove(localBundle) + out, err := os.OpenFile(localBundle, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if err != nil { + return Evidence{}, errors.New("无法创建本机暂存 bundle") + } + written, copyErr := io.Copy(out, io.LimitReader(body, h.config.MaxBundleBytes+1)) + syncErr := out.Sync() + closeErr := out.Close() + defer os.Remove(localBundle) + if copyErr != nil || syncErr != nil || closeErr != nil { + return Evidence{}, errors.New("回传快照字节失败(连接中断或被截断)") + } + if written > h.config.MaxBundleBytes { + return Evidence{}, errors.New("回传 bundle 超过上限,拒绝导入") + } + // 读回的是权威云端副本:本地同名 blob 字节不符按损坏修复(普通导入仍默认拒绝)。 + manifest, err := archive.UnpackWithOptions(localBundle, id, librarysnapshot.UnpackOptions{RepairCorruptBlobs: true}) + if err != nil { + return Evidence{}, fmt.Errorf("回传快照校验失败(截断/篡改/缺部件):%w", err) + } + return Evidence{Snapshot: id, Scope: manifest.Scope, TenantID: manifest.TenantID, + KnowledgeBase: manifest.KnowledgeBaseID, Parts: len(manifest.Parts), + Bytes: manifestBytes(manifest), Direction: "fetch", VerifiedAt: h.now().UTC()}, nil +} + +// remoteEvidence 判断"云端已经有这份快照且身份一致"。 +func (h *Handoff) remoteEvidence(ctx context.Context, want Identity) (Evidence, bool, error) { + raw, err := h.remote.ReadVersionManifest(ctx, want.SnapshotID) + if err != nil { + if errors.Is(err, os.ErrNotExist) || strings.Contains(strings.ToLower(err.Error()), "no such file") { + return Evidence{}, false, nil + } + return Evidence{}, false, fmt.Errorf("读取执行器侧版本清单失败:%w", err) + } + sum := sha256.Sum256(raw) + if hex.EncodeToString(sum[:]) != want.SnapshotID { + return Evidence{}, false, errors.New("执行器侧已有同名版本但清单摘要不符:拒绝复用") + } + manifest, err := librarysnapshot.DecodeManifest(raw, want.SnapshotID) + if err != nil { + return Evidence{}, false, err + } + if err := matchesIdentity(manifest, want); err != nil { + return Evidence{}, false, err + } + // 关键:清单存在只证明"这个名字有主",不证明 blob 还在、还对。 + // 复用前让远端整版重算一遍,缺失/篡改必须在这里就失败(尚未入发布队列)。 + if err := h.remote.VerifySnapshot(ctx, want.SnapshotID); err != nil { + return Evidence{}, false, fmt.Errorf("执行器侧已有清单但字节校验失败,拒绝复用:%w", err) + } + return Evidence{Snapshot: want.SnapshotID, Scope: manifest.Scope, TenantID: manifest.TenantID, + KnowledgeBase: manifest.KnowledgeBaseID, Parts: len(manifest.Parts), + Bytes: manifestBytes(manifest), Reused: true, VerifiedAt: h.now().UTC()}, true, nil +} + +func (h *Handoff) packLocally(archive *librarysnapshot.Archive, id, name string) (string, func(), error) { + if err := os.MkdirAll(h.config.StagingDir, 0700); err != nil { + return "", func() {}, errors.New("本机暂存目录不可用") + } + path := filepath.Join(h.config.StagingDir, name) + _ = os.Remove(path) + if _, err := archive.Pack(id, path); err != nil { + return "", func() {}, fmt.Errorf("打包快照失败:%w", err) + } + return path, func() { _ = os.Remove(path) }, nil +} + +// lock 用 flock 串行化"同一份快照"的本机搬运(并发点击/重试不会同时写暂存)。 +func (h *Handoff) lock(ctx context.Context, id string) (func(), error) { + dir := filepath.Join(h.config.LocalArchive, ".handoff") + if err := os.MkdirAll(dir, 0700); err != nil { + return nil, errors.New("无法创建搬运锁目录") + } + file, err := os.OpenFile(filepath.Join(dir, id+".lock"), os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return nil, errors.New("无法创建搬运锁") + } + deadline := time.Now().Add(h.config.OpTimeout) + for { + if err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil { + return func() { + _ = syscall.Flock(int(file.Fd()), syscall.LOCK_UN) + _ = file.Close() + }, nil + } + if time.Now().After(deadline) { + file.Close() + return nil, errors.New("另一份搬运正在处理同一个快照,等待超时") + } + select { + case <-ctx.Done(): + file.Close() + return nil, ctx.Err() + case <-time.After(100 * time.Millisecond): + } + } +} + +func validateIdentity(want Identity) error { + if !snapshotIDPattern.MatchString(want.SnapshotID) { + return errors.New("快照 ID 必须是 64 位小写十六进制") + } + if want.Scope != "internal" && want.Scope != "external" { + return errors.New("快照 scope 必须是 internal 或 external") + } + if want.TenantID == 0 { + return errors.New("缺少租户身份,无法核对快照归属") + } + if strings.TrimSpace(want.KnowledgeBaseID) == "" { + return errors.New("缺少目标知识库身份,无法核对快照归属") + } + return nil +} + +// matchesIdentity 用治理库里的期望值核对 bundle 自报的身份。 +func matchesIdentity(manifest librarysnapshot.Manifest, want Identity) error { + if manifest.Scope != want.Scope { + return fmt.Errorf("快照 scope=%q 与请求 %q 不一致", manifest.Scope, want.Scope) + } + if manifest.TenantID != want.TenantID { + return fmt.Errorf("快照 tenant=%d 与请求 %d 不一致", manifest.TenantID, want.TenantID) + } + if manifest.KnowledgeBaseID != want.KnowledgeBaseID { + return fmt.Errorf("快照知识库 %s 与请求 %s 不一致", manifest.KnowledgeBaseID, want.KnowledgeBaseID) + } + return nil +} + +func manifestBytes(manifest librarysnapshot.Manifest) int64 { + var total int64 + seen := map[string]bool{} + for _, part := range manifest.Parts { + if seen[part.SHA256] { + continue + } + seen[part.SHA256] = true + total += part.Bytes + } + return total +} + +// ---- ssh 传输:固定 argv,路径全部来自配置 ---- + +type sshRemote struct { + config Config +} + +// remoteExitError 保留远端退出码:只有"文件不存在(44)"才能当成"还没有这份版本", +// 网络断、权限错、docker 不可用都必须原样上抛——否则会把"读不到"当成"没有", +// 于是继续搬一份没人验证过的快照。 +type remoteExitError struct { + code int + detail string +} + +func (e *remoteExitError) Error() string { return fmt.Sprintf("ssh exit %d: %s", e.code, e.detail) } + +func (r *sshRemote) run(ctx context.Context, stdin io.Reader, stdout io.Writer, remote string) error { + bounded, cancel := context.WithTimeout(ctx, r.config.OpTimeout) + defer cancel() + argv := []string{"-F", r.config.SSHConfig, "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", r.config.SSHTarget, remote} + command := exec.CommandContext(bounded, "ssh", argv...) + command.Stdin = stdin + command.Stdout = stdout + var stderr strings.Builder + command.Stderr = &stderr + if err := command.Run(); err != nil { + if bounded.Err() != nil { + return fmt.Errorf("ssh %s 超时", r.config.SSHTarget) + } + detail := strings.TrimSpace(stderr.String()) + if len(detail) > 300 { + detail = detail[:300] + } + var exit *exec.ExitError + if errors.As(err, &exit) { + return &remoteExitError{code: exit.ExitCode(), detail: detail} + } + return fmt.Errorf("ssh %s 失败: %s", r.config.SSHTarget, detail) + } + return nil +} + +func (r *sshRemote) PutBundle(ctx context.Context, name string, body io.Reader) error { + path := filepath.Join(r.config.BundleDir, name) + if err := r.run(ctx, nil, io.Discard, fmt.Sprintf("install -d -m 0700 %s", shellQuote(r.config.BundleDir))); err != nil { + return err + } + if err := r.run(ctx, body, io.Discard, fmt.Sprintf("cat > %s", shellQuote(path+".part"))); err != nil { + return err + } + return r.run(ctx, nil, io.Discard, fmt.Sprintf("mv -f %s %s", shellQuote(path+".part"), shellQuote(path))) +} + +func (r *sshRemote) OpenBundle(ctx context.Context, name string) (io.ReadCloser, error) { + path := filepath.Join(r.config.BundleDir, name) + reader, writer := io.Pipe() + go func() { + writer.CloseWithError(r.run(ctx, nil, writer, fmt.Sprintf("cat %s", shellQuote(path)))) + }() + return reader, nil +} + +func (r *sshRemote) RemoveBundle(ctx context.Context, name string) error { + path := filepath.Join(r.config.BundleDir, name) + return r.run(ctx, nil, io.Discard, fmt.Sprintf("rm -f %s %s", shellQuote(path), shellQuote(path+".part"))) +} + +func (r *sshRemote) RunLibraryctl(ctx context.Context, args ...string) ([]byte, error) { + quoted := make([]string, 0, len(args)+2) + quoted = append(quoted, "docker", "exec", shellQuote(r.config.ExecutorContainer), "/app/libraryctl") + for _, arg := range args { + quoted = append(quoted, shellQuote(arg)) + } + var out strings.Builder + if err := r.run(ctx, nil, &out, strings.Join(quoted, " ")); err != nil { + return nil, err + } + return []byte(out.String()), nil +} + +func (r *sshRemote) VerifySnapshot(ctx context.Context, id string) error { + _, err := r.RunLibraryctl(ctx, "snapshot-verify", "-archive", r.config.RemoteArchive, "-snapshot", id) + return err +} + +func (r *sshRemote) ReadVersionManifest(ctx context.Context, id string) ([]byte, error) { + path := filepath.Join(r.config.RemoteArchive, "versions", id+".json") + var out strings.Builder + // 只有 "文件不存在" 才算"还没有这份版本";其它失败必须让调用方停下来。 + // RemoteArchive belongs to the executor filesystem, not the SSH host. + read := fmt.Sprintf("if [ -f %s ]; then cat %s; else exit 44; fi", shellQuote(path), shellQuote(path)) + command := "docker exec " + shellQuote(r.config.ExecutorContainer) + " sh -c " + shellQuote(read) + if err := r.run(ctx, nil, &out, command); err != nil { + var exit *remoteExitError + if errors.As(err, &exit) && exit.code == 44 { + return nil, fmt.Errorf("%w", os.ErrNotExist) + } + return nil, err + } + return []byte(out.String()), nil +} + +func shellQuote(value string) string { + return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'" +} + +// ---- local 传输:只用于隔离 fixture(跨进程执行真正的 libraryctl) ---- + +type localRemote struct { + config Config +} + +func (r *localRemote) path(name string) (string, error) { + if _, err := bundleName(strings.TrimSuffix(name, ".tar")); err != nil { + return "", err + } + return filepath.Join(r.config.BundleDir, name), nil +} + +func (r *localRemote) PutBundle(ctx context.Context, name string, body io.Reader) error { + path, err := r.path(name) + if err != nil { + return err + } + if err := os.MkdirAll(r.config.BundleDir, 0700); err != nil { + return err + } + out, err := os.OpenFile(path+".part", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) + if err != nil { + return err + } + if _, err := io.Copy(out, io.LimitReader(body, r.config.MaxBundleBytes+1)); err != nil { + out.Close() + return err + } + if err := out.Sync(); err != nil { + out.Close() + return err + } + if err := out.Close(); err != nil { + return err + } + return os.Rename(path+".part", path) +} + +func (r *localRemote) OpenBundle(ctx context.Context, name string) (io.ReadCloser, error) { + path, err := r.path(name) + if err != nil { + return nil, err + } + return os.Open(path) +} + +func (r *localRemote) RemoveBundle(ctx context.Context, name string) error { + path, err := r.path(name) + if err != nil { + return err + } + for _, candidate := range []string{path, path + ".part"} { + if err := os.Remove(candidate); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + return nil +} + +// RunLibraryctl 在 fixture 里跨进程执行真正的 libraryctl 二进制(不是进程内模拟)。 +func (r *localRemote) RunLibraryctl(ctx context.Context, args ...string) ([]byte, error) { + binary := os.Getenv("LIBRARY_HANDOFF_LIBRARYCTL") + if binary == "" { + return nil, errors.New("fixture 缺少 LIBRARY_HANDOFF_LIBRARYCTL(libraryctl 可执行路径)") + } + bounded, cancel := context.WithTimeout(ctx, r.config.OpTimeout) + defer cancel() + command := exec.CommandContext(bounded, binary, args...) + command.Env = append(os.Environ(), "LIBRARY_HANDOFF_FIXTURE=1") + var stderr strings.Builder + command.Stderr = &stderr + out, err := command.Output() + if err != nil { + detail := strings.TrimSpace(stderr.String()) + if len(detail) > 300 { + detail = detail[:300] + } + return nil, fmt.Errorf("libraryctl 失败: %s", detail) + } + return out, nil +} + +func (r *localRemote) VerifySnapshot(ctx context.Context, id string) error { + _, err := r.RunLibraryctl(ctx, "snapshot-verify", "-archive", r.config.RemoteArchive, "-snapshot", id) + return err +} + +func (r *localRemote) ReadVersionManifest(ctx context.Context, id string) ([]byte, error) { + path := filepath.Join(r.config.RemoteArchive, "versions", id+".json") + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return raw, nil +} diff --git a/internal/libraryhandoff/handoff_test.go b/internal/libraryhandoff/handoff_test.go new file mode 100644 index 0000000..d62a316 --- /dev/null +++ b/internal/libraryhandoff/handoff_test.go @@ -0,0 +1,459 @@ +package libraryhandoff + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "sync" + "testing" + "time" + + "knowledge-governance/internal/librarysnapshot" +) + +var libraryctlBinary string + +// TestMain 构建真正的 libraryctl 二进制:local 通道的"云端"动作必须跨进程执行, +// 否则"跨进程证据"只是同一次调用里的函数调用。 +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "handoff-bin-") + if err != nil { + panic(err) + } + binary := filepath.Join(dir, "libraryctl") + build := exec.Command("go", "build", "-o", binary, "knowledge-governance/cmd/libraryctl") + build.Stderr = os.Stderr + if err := build.Run(); err != nil { + panic("build libraryctl: " + err.Error()) + } + libraryctlBinary = binary + code := m.Run() + os.RemoveAll(dir) + os.Exit(code) +} + +const ( + fixtureTenant = 10000 + fixtureKB = "kb-handoff-fixture" +) + +func newArchive(t *testing.T) (string, *librarysnapshot.Archive) { + t.Helper() + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + archive, err := librarysnapshot.Open(root, 1024*1024) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { archive.Close() }) + return root, archive +} + +func seal(t *testing.T, archive *librarysnapshot.Archive) string { + t.Helper() + part, err := archive.Put(bytes.NewBufferString("[]")) + if err != nil { + t.Fatal(err) + } + mapping := sha256.Sum256([]byte("fixture-mapping")) + manifest := librarysnapshot.Manifest{ + Format: librarysnapshot.Format, Scope: "internal", TenantID: fixtureTenant, + KnowledgeBaseID: fixtureKB, CreatedAt: time.Date(2026, 10, 30, 0, 0, 0, 0, time.UTC), + Compatibility: librarysnapshot.Compatibility{ + WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", + EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, + IndexMappingSHA256: hex.EncodeToString(mapping[:]), + }, + } + for _, name := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations"} { + current := part + current.Kind, current.Name = "database", name + manifest.Parts = append(manifest.Parts, current) + } + for _, name := range []string{"wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} { + current := part + current.Kind, current.Name = "wiki", name + manifest.Parts = append(manifest.Parts, current) + } + index := part + index.Kind, index.Name = "index", "chunks" + manifest.Parts = append(manifest.Parts, index) + id, err := archive.Seal(manifest) + if err != nil { + t.Fatal(err) + } + return id +} + +// fixture 在同一个临时根下模拟"云端主机":bundles/ 是暂存,archive/ 是执行器归档根。 +type fixture struct { + root string + cfg Config + remoteA string +} + +func newFixture(t *testing.T, localArchive string) fixture { + t.Helper() + root := t.TempDir() + remoteArchive := filepath.Join(root, "archive") + staging := filepath.Join(root, "staging") + for _, dir := range []string{remoteArchive, staging, filepath.Join(root, "bundles")} { + if err := os.MkdirAll(dir, 0700); err != nil { + t.Fatal(err) + } + } + t.Setenv("LIBRARY_HANDOFF_LIBRARYCTL", libraryctlBinary) + return fixture{root: root, remoteA: remoteArchive, cfg: Config{ + Transport: TransportLocal, LocalRoot: root, + ExecutorContainer: "fixture-executor", + BundleDir: filepath.Join(root, "bundles"), + RemoteArchive: remoteArchive, + LocalArchive: localArchive, + StagingDir: staging, + MaxBundleBytes: 8 << 20, + OpTimeout: 60 * time.Second, + }} +} + +// withLocalArchive 复用**同一台云端 fixture**(同一 root),只换本机归档根: +// 读回必须打到"发布执行器所在的那台机器"的归档,而不是另起一份空目录。 +func withLocalArchive(t *testing.T, up fixture, localArchive string) Config { + t.Helper() + staging := filepath.Join(t.TempDir(), "staging") + if err := os.MkdirAll(staging, 0700); err != nil { + t.Fatal(err) + } + config := up.cfg + config.LocalArchive = localArchive + config.StagingDir = staging + return config +} + +func TestPushThenFetchKeepsIdentityAndBytesAcrossProcesses(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + pusher, err := New(up.cfg, nil) + if err != nil { + t.Fatal(err) + } + want := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB} + pushed, err := pusher.Push(context.Background(), want) + if err != nil { + t.Fatalf("Push() error = %v", err) + } + if pushed.Reused || pushed.Parts != 11 || pushed.Snapshot != id { + t.Fatalf("push evidence = %#v", pushed) + } + // 云端确实落了版本清单,且摘要自证。 + raw, err := os.ReadFile(filepath.Join(up.remoteA, "versions", id+".json")) + if err != nil { + t.Fatalf("remote manifest missing: %v", err) + } + sum := sha256.Sum256(raw) + if hex.EncodeToString(sum[:]) != id { + t.Fatal("remote manifest digest mismatch") + } + // 暂存目录不残留传输 bundle。 + if entries, _ := os.ReadDir(up.cfg.BundleDir); len(entries) != 0 { + t.Fatalf("bundle staging not cleaned: %v", entries) + } + + // 另一台"本机"取回:跨目录 + 跨进程(local 通道执行真正的 libraryctl)。 + destinationRoot, _ := newArchive(t) + fetcher, err := New(withLocalArchive(t, up, destinationRoot), nil) + if err != nil { + t.Fatal(err) + } + fetched, err := fetcher.Fetch(context.Background(), id) + if err != nil { + t.Fatalf("Fetch() error = %v", err) + } + if fetched.Snapshot != id || fetched.Parts != 11 || fetched.KnowledgeBase != fixtureKB { + t.Fatalf("fetch evidence = %#v", fetched) + } + verify, err := librarysnapshot.Open(destinationRoot, 1024*1024) + if err != nil { + t.Fatal(err) + } + defer verify.Close() + if _, err := verify.Load(id); err != nil { + t.Fatalf("fetched snapshot does not verify: %v", err) + } +} + +func TestPushRejectsIdentityThatDoesNotMatchTheSnapshot(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + pusher, err := New(up.cfg, nil) + if err != nil { + t.Fatal(err) + } + wrong := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant, KnowledgeBaseID: "kb-other"} + if _, err := pusher.Push(context.Background(), wrong); err == nil { + t.Fatal("Push() accepted a snapshot whose KB does not match the request") + } + if _, err := os.Stat(filepath.Join(up.remoteA, "versions", id+".json")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("a rejected push left a version on the executor") + } +} + +func TestPushIsIdempotentAndRejectsMissingLocalSnapshot(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + pusher, err := New(up.cfg, nil) + if err != nil { + t.Fatal(err) + } + want := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB} + if _, err := pusher.Push(context.Background(), want); err != nil { + t.Fatal(err) + } + again, err := pusher.Push(context.Background(), want) + if err != nil || !again.Reused { + t.Fatalf("second push = %#v, %v (want reused)", again, err) + } + missing := Identity{SnapshotID: hex.EncodeToString(bytes.Repeat([]byte{7}, 32)), Scope: "internal", + TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB} + if _, err := pusher.Push(context.Background(), missing); err == nil { + t.Fatal("Push() accepted a snapshot that does not exist locally") + } +} + +func TestConcurrentPushOfSameSnapshotSerialises(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + pusher, err := New(up.cfg, nil) + if err != nil { + t.Fatal(err) + } + want := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB} + var wg sync.WaitGroup + errs := make([]error, 3) + for i := 0; i < 3; i++ { + wg.Add(1) + go func(index int) { + defer wg.Done() + _, errs[index] = pusher.Push(context.Background(), want) + }(i) + } + wg.Wait() + for index, err := range errs { + if err != nil { + t.Fatalf("concurrent push %d failed: %v", index, err) + } + } +} + +func TestFetchRefusesTamperedRemoteArchive(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + pusher, err := New(up.cfg, nil) + if err != nil { + t.Fatal(err) + } + if _, err := pusher.Push(context.Background(), Identity{SnapshotID: id, Scope: "internal", + TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB}); err != nil { + t.Fatal(err) + } + // 篡改云端一个 blob:云端 libraryctl snapshot-pack 会在 Load 时逐 blob 重算并失败。 + blobs, err := os.ReadDir(filepath.Join(up.remoteA, "blobs")) + if err != nil || len(blobs) == 0 { + t.Fatalf("remote blobs = %v, %v", blobs, err) + } + target := filepath.Join(up.remoteA, "blobs", blobs[0].Name()) + if err := os.Chmod(target, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(target, []byte("tampered"), 0600); err != nil { + t.Fatal(err) + } + destinationRoot, _ := newArchive(t) + fetcher, err := New(withLocalArchive(t, up, destinationRoot), nil) + if err != nil { + t.Fatal(err) + } + if _, err := fetcher.Fetch(context.Background(), id); err == nil { + t.Fatal("Fetch() imported a tampered snapshot") + } + if _, err := os.Stat(filepath.Join(destinationRoot, "versions", id+".json")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("a failed fetch left a version locally") + } +} + +func TestFetchRefusesUnknownRemoteSnapshotWithoutClaimingRecoverable(t *testing.T) { + destinationRoot, _ := newArchive(t) + empty := newFixture(t, destinationRoot) + fetcher, err := New(empty.cfg, nil) + if err != nil { + t.Fatal(err) + } + unknown := hex.EncodeToString(bytes.Repeat([]byte{9}, 32)) + if _, err := fetcher.Fetch(context.Background(), unknown); err == nil { + t.Fatal("Fetch() reported success for a snapshot that exists nowhere") + } + if _, err := os.Stat(filepath.Join(destinationRoot, "versions", unknown+".json")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("unknown snapshot produced a local version") + } +} + +func TestHandoffRejectsCallerControlledNamesAndPaths(t *testing.T) { + if _, err := bundleName("../../etc/passwd"); err == nil { + t.Fatal("bundleName accepted a traversal name") + } + if _, err := bundleName("ABCDEF"); err == nil { + t.Fatal("bundleName accepted a non-digest name") + } + if _, err := New(Config{Transport: TransportSSH, SSHTarget: "x", SSHConfig: "/tmp/x"}, nil); err == nil { + t.Fatal("New() accepted an incomplete SSH configuration") + } + if _, err := New(Config{Transport: TransportLocal}, nil); err == nil { + t.Fatal("New() accepted local transport without an isolation root") + } +} + +// 断线/超时:远端读版本清单一直失败必须报错,不能当成"没有版本"然后继续搬。 +func TestPushSurfacesRemoteErrorsInsteadOfAssumingAbsent(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + handoff := &Handoff{config: Config{LocalArchive: sourceRoot, MaxBundleBytes: 1 << 20, OpTimeout: time.Second}, + remote: errorRemote{}, now: time.Now} + _, err := handoff.Push(context.Background(), Identity{SnapshotID: id, Scope: "internal", + TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB}) + if err == nil { + t.Fatal("Push() ignored a remote transport error") + } + _ = up +} + +type errorRemote struct{} + +func (errorRemote) PutBundle(context.Context, string, io.Reader) error { + return errors.New("network down") +} +func (errorRemote) OpenBundle(context.Context, string) (io.ReadCloser, error) { + return nil, errors.New("network down") +} +func (errorRemote) RemoveBundle(context.Context, string) error { return errors.New("network down") } +func (errorRemote) RunLibraryctl(context.Context, ...string) ([]byte, error) { + return nil, errors.New("network down") +} +func (errorRemote) VerifySnapshot(context.Context, string) error { return errors.New("network down") } +func (errorRemote) ReadVersionManifest(context.Context, string) ([]byte, error) { + return nil, errors.New("network down") +} + +// 已有清单但字节坏了:Push 的复用路径必须整版校验,不能只看清单摘要就宣布可用。 +func TestPushRefusesToReuseWhenRemoteBytesAreGoneOrTampered(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + pusher, err := New(up.cfg, nil) + if err != nil { + t.Fatal(err) + } + want := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB} + if _, err := pusher.Push(context.Background(), want); err != nil { + t.Fatal(err) + } + blobs, err := os.ReadDir(filepath.Join(up.remoteA, "blobs")) + if err != nil || len(blobs) == 0 { + t.Fatalf("remote blobs = %v %v", blobs, err) + } + // 清单不动、只把 blob 偷走:清单摘要仍然自证,但字节已经不在。 + remoteBlob := filepath.Join(up.remoteA, "blobs", blobs[0].Name()) + original, err := os.ReadFile(remoteBlob) + if err != nil { + t.Fatal(err) + } + if err := os.Remove(remoteBlob); err != nil { + t.Fatal(err) + } + if _, err := pusher.Push(context.Background(), want); err == nil { + t.Fatal("Push() reused a remote copy whose blobs are missing") + } + // 同名不同内容同样必须被拒绝。 + if err := os.WriteFile(remoteBlob, append(original, 'x'), 0600); err != nil { + t.Fatal(err) + } + if _, err := pusher.Push(context.Background(), want); err == nil { + t.Fatal("Push() reused a remote copy with tampered bytes") + } +} + +// 跨租户 / 错误 scope:期望身份与清单不一致一律拒绝(身份只能来自可信绑定)。 +func TestPushRejectsCrossTenantAndWrongScope(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + pusher, err := New(up.cfg, nil) + if err != nil { + t.Fatal(err) + } + crossTenant := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant + 1, KnowledgeBaseID: fixtureKB} + if _, err := pusher.Push(context.Background(), crossTenant); err == nil { + t.Fatal("Push() accepted a snapshot from another tenant") + } + wrongScope := Identity{SnapshotID: id, Scope: "external", TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB} + if _, err := pusher.Push(context.Background(), wrongScope); err == nil { + t.Fatal("Push() accepted a snapshot sealed for another scope") + } + if _, err := os.Stat(filepath.Join(up.remoteA, "versions", id+".json")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("rejected pushes left a version on the executor") + } +} + +// 本地副本损坏(清单在、blob 坏):Fetch 必须能修复,而不是永远报"已存在不同字节"。 +func TestFetchRepairsCorruptLocalCopy(t *testing.T) { + sourceRoot, source := newArchive(t) + id := seal(t, source) + up := newFixture(t, sourceRoot) + pusher, err := New(up.cfg, nil) + if err != nil { + t.Fatal(err) + } + if _, err := pusher.Push(context.Background(), Identity{SnapshotID: id, Scope: "internal", + TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB}); err != nil { + t.Fatal(err) + } + localRoot, _ := newArchive(t) + fetcher, err := New(withLocalArchive(t, up, localRoot), nil) + if err != nil { + t.Fatal(err) + } + if _, err := fetcher.Fetch(context.Background(), id); err != nil { + t.Fatalf("first fetch: %v", err) + } + blobs, err := os.ReadDir(filepath.Join(localRoot, "blobs")) + if err != nil || len(blobs) == 0 { + t.Fatalf("local blobs = %v %v", blobs, err) + } + victim := filepath.Join(localRoot, "blobs", blobs[0].Name()) + if err := os.WriteFile(victim, []byte("corrupt"), 0600); err != nil { + t.Fatal(err) + } + if _, err := fetcher.Fetch(context.Background(), id); err != nil { + t.Fatalf("Fetch() could not repair a corrupt local copy: %v", err) + } + archive, err := librarysnapshot.Open(localRoot, 1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + if _, err := archive.Load(id); err != nil { + t.Fatalf("repaired snapshot still does not verify: %v", err) + } +} diff --git a/internal/libraryhandoff/ssh_manifest_test.go b/internal/libraryhandoff/ssh_manifest_test.go new file mode 100644 index 0000000..0e4a361 --- /dev/null +++ b/internal/libraryhandoff/ssh_manifest_test.go @@ -0,0 +1,53 @@ +package libraryhandoff + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// SSH runs its remote shell locally; Docker is an explicit process-boundary +// fixture. The archive path deliberately does not exist on the SSH host. +func TestSSHManifestReadUsesExecutorFilesystem(t *testing.T) { + bin := t.TempDir() + write := func(name, text string) { + t.Helper() + if err := os.WriteFile(filepath.Join(bin, name), []byte(text), 0700); err != nil { + t.Fatal(err) + } + } + write("ssh", "#!/bin/sh\nfor arg do last=$arg; done\nexec /bin/sh -c \"$last\"\n") + write("docker", `#!/bin/sh +[ "$1" = exec ] && [ "$2" = fixture-executor ] && [ "$3" = sh ] && [ "$4" = -c ] || exit 91 +case "$5" in *"/executor-only/archive/versions/"*) ;; *) exit 92;; esac +printf '%s' "$5" > "$MANIFEST_TRACE" +if [ "$MANIFEST_MODE" = missing ]; then exit 44; fi +if [ "$MANIFEST_MODE" = denied ]; then exit 13; fi +printf '%s' '{"container":true}' +`) + t.Setenv("PATH", bin+":"+os.Getenv("PATH")) + trace := filepath.Join(bin, "trace") + t.Setenv("MANIFEST_TRACE", trace) + r := &sshRemote{config: Config{SSHTarget: "fixture", SSHConfig: "/unused", ExecutorContainer: "fixture-executor", RemoteArchive: "/executor-only/archive", OpTimeout: time.Second * 5}} + id := strings.Repeat("a", 64) + got, err := r.ReadVersionManifest(context.Background(), id) + if err != nil || string(got) != `{"container":true}` { + t.Fatalf("must read through executor, got=%s err=%v", got, err) + } + cmd, err := os.ReadFile(trace) + if err != nil || !strings.Contains(string(cmd), id+".json") { + t.Fatalf("missing exact snapshot read: %s %v", cmd, err) + } + t.Setenv("MANIFEST_MODE", "missing") + if _, err := r.ReadVersionManifest(context.Background(), id); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("missing manifest: %v", err) + } + t.Setenv("MANIFEST_MODE", "denied") + if _, err := r.ReadVersionManifest(context.Background(), id); err == nil || errors.Is(err, os.ErrNotExist) { + t.Fatalf("permission failure must not mean absent: %v", err) + } +} diff --git a/internal/librarymaintenance/env.go b/internal/librarymaintenance/env.go index 25970cc..a12205a 100644 --- a/internal/librarymaintenance/env.go +++ b/internal/librarymaintenance/env.go @@ -5,6 +5,8 @@ import ( "fmt" "strconv" "strings" + + "knowledge-governance/internal/libraryfreeze" ) // 目标入口闸门与后台队列的声明名称。 @@ -15,10 +17,15 @@ import ( // 错的证据。 const ( EnvInstance = "LIBRARY_TARGET_INSTANCE" + EnvIngressMode = "LIBRARY_TARGET_INGRESS_MODE" + EnvNoIngressAck = "LIBRARY_NO_INGRESS_ACK" EnvIngressURL = "LIBRARY_TARGET_INGRESS_URL" EnvIngressService = "LIBRARY_TARGET_INGRESS_SERVICE" EnvIngressDrainFile = "LIBRARY_TARGET_INGRESS_DRAIN_FILE" - EnvRedisAddr = "LIBRARY_TARGET_REDIS_ADDR" + // EnvHealthURL 是 no-gate 窗口唯一的"目标回来了"证据:闸门不存在时, + // 只有外部健康探针能证明写入者恢复后真的在服务。 + EnvHealthURL = "LIBRARY_TARGET_HEALTH_URL" + EnvRedisAddr = "LIBRARY_TARGET_REDIS_ADDR" // 名字里不写 Password:这里的字面量是**环境变量名**,密钥扫描会把 // `XXX_PASSWORD = "<长字面量>"` 当成"被赋值的密钥",那是误报但没必要留个坑。 EnvRedisAuth = "LIBRARY_TARGET_REDIS_PASSWORD" @@ -27,14 +34,20 @@ const ( // TargetEnv 是一次实例级维护所需的"入口 + 队列"声明。 // -// 缺任何一项都不许降级成"库级维护":没有闸门就没有"入口已关、在途已排空" -// 的证据,没有队列就证明不了停写者时后台是空的。这两条正是被代理的 WeKnora +// 缺任何一项都不许降级成"库级维护":没有闸门就没有"入口已关、在途已排空"的 +// 证据,没有队列就证明不了停写者时后台是空的。这两条正是被代理的 WeKnora // 收到 SIGTERM 就 exit(1) 之后唯一还能证明"请求没被截断"的东西。 +// +// Mode=none 只给"整栈没有入口闸门"的测试环境用,且必须带显式确认串: +// 那条路径不允许调用任何闸门动作,证据等级降一档并写进维护记录。 type TargetEnv struct { Instance string + Mode string + Ack string IngressURL string IngressService string IngressDrainFile string + HealthURL string RedisAddr string RedisPassword string RedisDB int @@ -49,24 +62,59 @@ func TargetFromEnv(get func(string) string) (TargetEnv, error) { value := func(name string) string { return strings.TrimSpace(get(name)) } target := TargetEnv{ Instance: value(EnvInstance), + Mode: value(EnvIngressMode), IngressURL: value(EnvIngressURL), IngressService: value(EnvIngressService), IngressDrainFile: value(EnvIngressDrainFile), + HealthURL: value(EnvHealthURL), RedisAddr: value(EnvRedisAddr), // 口令不 Trim:前后空格也是口令的一部分,Trim 会把能连上的配置变成连不上。 RedisPassword: get(EnvRedisAuth), } - missing := make([]string, 0, 5) - for _, item := range []struct { + if target.Mode == "" { + target.Mode = libraryfreeze.IngressModeGate + } + switch target.Mode { + case libraryfreeze.IngressModeGate: + target.Ack = "" + case libraryfreeze.IngressModeNone: + // 确认串逐字符相等:不 Trim、不忽略大小写。没写对就是没确认。 + ack := get(EnvNoIngressAck) + if ack != libraryfreeze.NoIngressAck { + return TargetEnv{}, fmt.Errorf( + "no-gate 维护必须显式确认:%s 必须逐字符等于 %s(当前%s),拒绝开窗口", + EnvNoIngressAck, libraryfreeze.NoIngressAck, describeAck(ack)) + } + target.Ack = ack + // 半套闸门声明最危险:既关不掉门,又容易被当成"有门"。要么有,要么明确没有。 + if target.IngressURL != "" || target.IngressService != "" || target.IngressDrainFile != "" { + return TargetEnv{}, fmt.Errorf( + "no-gate 维护不得同时声明 %s/%s/%s:要么有闸门,要么明确没有", + EnvIngressURL, EnvIngressService, EnvIngressDrainFile) + } + default: + return TargetEnv{}, fmt.Errorf("%s 无效(%q):只能是 %s 或 %s", + EnvIngressMode, target.Mode, libraryfreeze.IngressModeGate, libraryfreeze.IngressModeNone) + } + + required := []struct { name string current string }{ {EnvInstance, target.Instance}, - {EnvIngressURL, target.IngressURL}, - {EnvIngressService, target.IngressService}, - {EnvIngressDrainFile, target.IngressDrainFile}, {EnvRedisAddr, target.RedisAddr}, - } { + } + if target.Mode == libraryfreeze.IngressModeNone { + // 没有闸门可声明:改由健康探针证明"目标真的回来了",它因此是必需的。 + required = append(required, struct{ name, current string }{EnvHealthURL, target.HealthURL}) + } else { + required = append(required, + struct{ name, current string }{EnvIngressURL, target.IngressURL}, + struct{ name, current string }{EnvIngressService, target.IngressService}, + struct{ name, current string }{EnvIngressDrainFile, target.IngressDrainFile}) + } + missing := make([]string, 0, 5) + for _, item := range required { if item.current == "" { missing = append(missing, item.name) } @@ -86,8 +134,25 @@ func TargetFromEnv(get func(string) string) (TargetEnv, error) { target.RedisDB = db } if len(missing) > 0 { - return TargetEnv{}, fmt.Errorf("实例级维护未接线:缺少 %s(没有入口闸门与队列就无法证明入口已排空、后台已静默)", - strings.Join(missing, "、")) + hint := "没有入口闸门与队列就无法证明入口已排空、后台已静默" + if target.Mode == libraryfreeze.IngressModeNone { + hint = "no-gate 测试模式仍需要实例、队列与健康探针" + } + return TargetEnv{}, fmt.Errorf("实例级维护未接线:缺少 %s(%s)", + strings.Join(missing, "、"), hint) } return target, nil } + +// describeAck 只描述"确认串有没有写对",不回显内容:写错时也可能是一段 +// 看起来像凭据的东西,错误信息里没必要复制它。 +func describeAck(ack string) string { + switch { + case ack == "": + return "为空" + case strings.TrimSpace(ack) == libraryfreeze.NoIngressAck: + return "含多余空白" + default: + return "取值不匹配" + } +} diff --git a/internal/librarymaintenance/no_gate_env_test.go b/internal/librarymaintenance/no_gate_env_test.go new file mode 100644 index 0000000..712b8ed --- /dev/null +++ b/internal/librarymaintenance/no_gate_env_test.go @@ -0,0 +1,88 @@ +package librarymaintenance + +import ( + "strings" + "testing" + + "knowledge-governance/internal/libraryfreeze" +) + +// noGateEnv 是 0.9.0 测试栈的声明:没有闸门,只有实例、队列与健康探针。 +func noGateEnv() map[string]string { + return map[string]string{ + EnvInstance: "kgmaint-v090", + EnvIngressMode: libraryfreeze.IngressModeNone, + EnvNoIngressAck: libraryfreeze.NoIngressAck, + EnvHealthURL: "http://127.0.0.1:18081/health", + EnvRedisAddr: "127.0.0.1:26379", + EnvRedisAuth: "secret", + EnvRedisDB: "0", + } +} + +func TestTargetFromEnvNoGateNeedsExplicitAck(t *testing.T) { + values := noGateEnv() + delete(values, EnvNoIngressAck) + _, err := TargetFromEnv(lookup(values)) + if err == nil || !strings.Contains(err.Error(), EnvNoIngressAck) { + t.Fatalf("缺确认串没有被拒并点名:%v", err) + } + for _, ack := range []string{"", "test_only", "TEST-ONLY", " test-only", "test-only "} { + values := noGateEnv() + values[EnvNoIngressAck] = ack + if _, err := TargetFromEnv(lookup(values)); err == nil || !strings.Contains(err.Error(), EnvNoIngressAck) { + t.Fatalf("ack=%q 没有被拒:%v", ack, err) + } + } +} + +func TestTargetFromEnvNoGateAcceptsMissingIngressItems(t *testing.T) { + target, err := TargetFromEnv(lookup(noGateEnv())) + if err != nil { + t.Fatalf("no-gate 声明被拒:%v", err) + } + if target.Mode != libraryfreeze.IngressModeNone || target.Ack != libraryfreeze.NoIngressAck { + t.Fatalf("入口形态没解析对:%+v", target) + } + if target.IngressURL != "" || target.IngressService != "" || target.IngressDrainFile != "" { + t.Fatalf("no-gate 声明里出现了闸门项:%+v", target) + } + if target.HealthURL != "http://127.0.0.1:18081/health" || target.RedisDB != 0 { + t.Fatalf("健康探针/队列没解析对:%+v", target) + } +} + +// 证据降一档不等于什么都不需要:健康探针与队列仍必须给。 +func TestTargetFromEnvNoGateStillNeedsHealthAndQueue(t *testing.T) { + for _, name := range []string{EnvInstance, EnvHealthURL, EnvRedisAddr, EnvRedisAuth, EnvRedisDB} { + values := noGateEnv() + delete(values, name) + if _, err := TargetFromEnv(lookup(values)); err == nil || !strings.Contains(err.Error(), name) { + t.Fatalf("缺 %s 没有被点名:%v", name, err) + } + } +} + +// 缺省仍是 gate:没有 mode 变量时照旧要求三项闸门声明(原行为不变)。 +func TestTargetFromEnvDefaultsToGate(t *testing.T) { + values := completeEnv() + target, err := TargetFromEnv(lookup(values)) + if err != nil { + t.Fatalf("gate 声明被拒:%v", err) + } + if target.Mode != libraryfreeze.IngressModeGate || target.Ack != "" { + t.Fatalf("缺省不是 gate:%+v", target) + } + values[EnvIngressURL] = "" + if _, err := TargetFromEnv(lookup(values)); err == nil || !strings.Contains(err.Error(), EnvIngressURL) { + t.Fatalf("gate 模式缺入口没有被拒:%v", err) + } +} + +func TestTargetFromEnvRejectsUnknownMode(t *testing.T) { + values := completeEnv() + values[EnvIngressMode] = "open" + if _, err := TargetFromEnv(lookup(values)); err == nil || !strings.Contains(err.Error(), EnvIngressMode) { + t.Fatalf("未知入口形态没有被拒:%v", err) + } +} diff --git a/internal/librarymaintenance/probe_drain_test.go b/internal/librarymaintenance/probe_drain_test.go new file mode 100644 index 0000000..d99d524 --- /dev/null +++ b/internal/librarymaintenance/probe_drain_test.go @@ -0,0 +1,34 @@ +package librarymaintenance + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestReadinessProbeDoesNotHoldDrainConnection(t *testing.T) { + closed := make(chan struct{}, 1) + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) })) + server.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateClosed { + select { + case closed <- struct{}{}: + default: + } + } + } + server.Start() + defer server.Close() + manager := &Manager{target: Target{Ingress: server.URL}, client: server.Client(), timeout: time.Second} + if err := manager.VerifyRunning(context.Background()); err != nil { + t.Fatal(err) + } + select { + case <-closed: + case <-time.After(300 * time.Millisecond): + t.Fatal("readiness left an idle connection that blocks TCP drain") + } +} diff --git a/internal/librarymaintenance/target.go b/internal/librarymaintenance/target.go index 33aa899..1451514 100644 --- a/internal/librarymaintenance/target.go +++ b/internal/librarymaintenance/target.go @@ -48,14 +48,20 @@ type Config struct { Writers []string NonWriters map[string]string DockerSocket string - IngressURL string + // IngressMode 是 gate(默认)或 none;none 只给整栈没有入口闸门的测试环境用, + // 必须同时给 IngressAck,且一次闸门动作都不做。 + IngressMode string + IngressAck string + IngressURL string // IngressService 是入口闸门在 compose 项目里的服务名;DrainFile 是它写 // 排空证据的宿主机文件。两者缺一,就只能说"停了写入者",不能说"排空了"。 IngressService string IngressDrainFile string - Database string - Index string - Bucket string + // HealthURL 是 no-gate 模式下唯一的"目标回来了"证据(恢复后必须 200)。 + HealthURL string + Database string + Index string + Bucket string // 后台静默检查需要的运行时依赖(不写进维护记录)。 DatabaseURL string RedisAddr string @@ -75,6 +81,9 @@ type Manager struct { gate *dockerGate api *dockerAPI quiescer *targetQuiescer + mode string + ack string + healthURL string } // Close 释放拓扑/静默检查持有的连接。 @@ -91,6 +100,11 @@ func New(cfg Config) (*Manager, error) { instance := strings.TrimSpace(cfg.Instance) project := strings.TrimSpace(cfg.Project) ingress := strings.TrimSpace(cfg.IngressURL) + health := strings.TrimSpace(cfg.HealthURL) + mode := strings.TrimSpace(cfg.IngressMode) + if mode == "" { + mode = libraryfreeze.IngressModeGate + } if instance == "" || project == "" { return nil, errors.New("实例级维护配置缺少 LIBRARY_TARGET_INSTANCE/PROJECT") } @@ -100,9 +114,27 @@ func New(cfg Config) (*Manager, error) { if !filepath.IsAbs(cfg.DockerSocket) { return nil, errors.New("Docker socket 必须是绝对路径") } - parsed, err := url.Parse(ingress) - if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.Path == "" || parsed.User != nil { - return nil, errors.New("目标入口地址无效(LIBRARY_TARGET_INGRESS_URL)") + switch mode { + case libraryfreeze.IngressModeGate: + parsed, err := url.Parse(ingress) + if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.Path == "" || parsed.User != nil { + return nil, errors.New("目标入口地址无效(LIBRARY_TARGET_INGRESS_URL)") + } + case libraryfreeze.IngressModeNone: + // 显式确认是这道口子的唯一开关:没有它,no-gate 一律拒绝。 + if cfg.IngressAck != libraryfreeze.NoIngressAck { + return nil, fmt.Errorf("no-gate 维护必须显式确认(LIBRARY_NO_INGRESS_ACK 逐字符等于 %s),拒绝", + libraryfreeze.NoIngressAck) + } + if ingress != "" || cfg.IngressService != "" || cfg.IngressDrainFile != "" { + return nil, errors.New("no-gate 维护不得同时声明入口地址/闸门服务/排空文件:要么有闸门,要么明确没有") + } + if !validHealthURL(health) { + return nil, errors.New("no-gate 维护必须给有效的健康探针(LIBRARY_TARGET_HEALTH_URL)") + } + default: + return nil, fmt.Errorf("LIBRARY_TARGET_INGRESS_MODE 无效(%q):只能是 %s 或 %s", + mode, libraryfreeze.IngressModeGate, libraryfreeze.IngressModeNone) } if cfg.Database == "" || cfg.Index == "" || cfg.Bucket == "" { return nil, errors.New("目标身份不完整:需要数据库/索引/存储桶") @@ -125,8 +157,9 @@ func New(cfg Config) (*Manager, error) { } manager := &Manager{target: target, source: project, docker: cfg.DockerSocket, writers: writers, nonWriters: cfg.NonWriters, timeout: cfg.Timeout, - client: &http.Client{Timeout: 5 * time.Second}, api: api} - if cfg.IngressService != "" || cfg.IngressDrainFile != "" { + client: &http.Client{Timeout: 5 * time.Second}, api: api, + mode: mode, ack: cfg.IngressAck, healthURL: health} + if mode == libraryfreeze.IngressModeGate && (cfg.IngressService != "" || cfg.IngressDrainFile != "") { gate, err := newDockerGate(cfg.DockerSocket, project, cfg.IngressService, cfg.IngressDrainFile, cfg.Timeout) if err != nil { return nil, err @@ -168,8 +201,12 @@ func (m *Manager) Target() Target { return m.target } // Description 是写进维护记录的一句话身份,含指纹,便于事后核对"当时动的是谁"。 func (m *Manager) Description() string { t := m.target + ingress := t.Ingress + if m.mode == libraryfreeze.IngressModeNone { + ingress = "none(test-only)" + } return fmt.Sprintf("level=%s instance=%s project=%s writers=%s ingress=%s db=%s index=%s bucket=%s fingerprint=%s", - t.Level, t.Instance, t.Project, strings.Join(t.Writers, "+"), t.Ingress, t.Database, t.Index, t.Bucket, t.Fingerprint) + t.Level, t.Instance, t.Project, strings.Join(t.Writers, "+"), ingress, t.Database, t.Index, t.Bucket, t.Fingerprint) } // Open 返回绑定到该目标的协调器与控制器。调用方负责 Close。 @@ -183,7 +220,23 @@ func (m *Manager) Open(root string) (*libraryfreeze.Coordinator, *libraryfreeze. control.Close() return nil, nil, err } - if err := coordinator.SetTarget(LevelInstance, m.target.Ingress, m.ingressClosed, m.ingressReady); err != nil { + // 入口形态必须在绑定目标之前声明:default 是 gate,只有显式 no-gate 才降档。 + if err := coordinator.SetIngressMode(m.mode, m.ack); err != nil { + coordinator.Close() + control.Close() + return nil, nil, err + } + closed, ready := m.ingressClosed, m.ingressReady + if m.mode == libraryfreeze.IngressModeNone { + // 没有闸门:不声明任何入口关闭探针,恢复证据改由健康探针承担。 + closed, ready = nil, m.healthReady + if err := coordinator.SetHealthURL(m.healthURL); err != nil { + coordinator.Close() + control.Close() + return nil, nil, err + } + } + if err := coordinator.SetTarget(LevelInstance, m.target.Ingress, closed, ready); err != nil { coordinator.Close() control.Close() return nil, nil, err @@ -239,7 +292,11 @@ func (m *Manager) serviceOf(id string) string { } // VerifyRunning 确认目标入口真的在服务(部署与恢复后都要看,不看容器状态)。 +// no-gate 栈没有入口:用健康探针回答"目标回来了没有"。 func (m *Manager) VerifyRunning(ctx context.Context) error { + if m.mode == libraryfreeze.IngressModeNone { + return m.healthReady(ctx) + } return m.ingressReady(ctx) } @@ -253,6 +310,9 @@ func (m *Manager) ingressClosed(ctx context.Context) error { if err != nil { return err } + // Maintenance probes must not leave keep-alive connections in the TCP + // ingress: the probe itself would otherwise prevent draining. + req.Close = true resp, err := m.client.Do(req) if err != nil { return nil @@ -280,6 +340,9 @@ func (m *Manager) ingressReady(ctx context.Context) error { if err != nil { return err } + // Maintenance probes must not leave keep-alive connections in the TCP + // ingress: the probe itself would otherwise prevent draining. + req.Close = true resp, err := m.client.Do(req) if err == nil { body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) @@ -302,6 +365,47 @@ func (m *Manager) ingressReady(ctx context.Context) error { } } +// healthReady 是 no-gate 栈的恢复判据:健康探针返回 200 才算"目标真的回来了"。 +// 和入口探针同一条规则——不看容器状态、不看 HTTP 5xx 的"像活着"。 +func (m *Manager) healthReady(ctx context.Context) error { + deadline := time.Now().Add(m.timeout) + var last error + for { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.healthURL, nil) + if err != nil { + return err + } + // 探针不能留下 keep-alive 连接:那会让"排空"永远等不到。 + req.Close = true + resp, err := m.client.Do(req) + if err == nil { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return nil + } + last = fmt.Errorf("健康探针返回 HTTP %d:%s", resp.StatusCode, strings.TrimSpace(string(body))) + } else { + last = err + } + if time.Now().After(deadline) { + return fmt.Errorf("目标健康探针没有恢复:%w", last) + } + select { + case <-ctx.Done(): + return last + case <-time.After(500 * time.Millisecond): + } + } +} + +// validHealthURL 是健康探针地址的本地校验:http(s)、有主机、不带凭据。 +func validHealthURL(raw string) bool { + parsed, err := url.Parse(strings.TrimSpace(raw)) + return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") && + parsed.Host != "" && parsed.User == nil +} + // DatabaseIdentity 把连接串收敛成"host:port/db"这种可以写进维护记录的身份: // 维护记录里不落库凭据,但必须能说清动的是哪个库。 func DatabaseIdentity(raw string) (string, error) { @@ -348,12 +452,21 @@ func (m *Manager) VerifyTopology(ctx context.Context) error { if err != nil { return err } + // no-gate 栈没有闸门可绕:写入者发布端口是它的正常对外形态, + // "绕闸直连"这条判据在这里不成立(有闸门时才必须唯一入口)。 + if m.mode == libraryfreeze.IngressModeNone { + continue + } if ports := state.publishedPorts(); len(ports) > 0 { return fmt.Errorf("写入者 %s 直接发布了端口 %s:存在绕开入口闸门的直连通道,拒绝开维护窗口", writer, strings.Join(ports, ",")) } } if m.gate == nil { + if m.mode == libraryfreeze.IngressModeNone { + // 没有闸门可核验端口归属:拓扑检查到此为止,证据降档由维护记录承担。 + return nil + } return errors.New("实例级维护必须声明入口闸门") } for _, writer := range m.writers { diff --git a/internal/libraryprofile/profile.go b/internal/libraryprofile/profile.go new file mode 100644 index 0000000..b95e2dd --- /dev/null +++ b/internal/libraryprofile/profile.go @@ -0,0 +1,214 @@ +// Package libraryprofile 声明"某个 WeKnora schema 版本下,整库适配器可以依赖什么"。 +// +// 为什么要有这一层:整库导出/导入原本把 `version != 74` 写死在四个入口里。 +// 版本号本身不是契约——同一版本号在不同部署上也可能缺表;反过来,把判定放宽成 +// `version > 74` 又会把"没见过的版本"当成"兼容"。所以这里同时声明两件事: +// - 该版本必须存在的表与列(导出/导入按它取数); +// - 该版本的归档部件集合(manifest 按它判定完整性)。 +// +// 版本号只用来**选中** profile,真正的放行条件是随后对 information_schema 的 +// 能力探测(见 releaseadapter 的 ResolveSchemaProfile)。 +package libraryprofile + +import "fmt" + +// LegacyVersion 是 0.7.1 的 schema_migrations 版本号,也是既有内存夹具的默认值。 +const LegacyVersion = 74 + +// V090Version 是 0.9.0 的 schema_migrations 版本号(已实测:134、dirty=false、83 表)。 +const V090Version = 134 + +// PartRequirement 是归档部件的一项要求(kind/name 与 manifest 的部件键一致)。 +type PartRequirement struct { + Kind string + Name string +} + +// Profile 是一个 schema 版本的静态能力声明。 +type Profile struct { + Name string + SchemaVersion int + WeKnoraVersion string + // EmbeddingDimension 为 0 表示"由目标 models.parameters 说了算"; + // 非 0 表示该版本只接受这一定维度(0.7.1 的契约就是固定 1024)。 + EmbeddingDimension int + RequiredTables []string + OptionalTables []string + RequiredColumns map[string][]string + // ReviewedTriggers 是该版本允许出现的 pg_get_triggerdef 原文。 + // 触发器意味着"写一行还会改别的表",所以只接受逐字核对过的定义, + // 且这些定义必须在该版本上真实存在(消失也说明 schema 不是我们审过的那份)。 + ReviewedTriggers []string + RequiredParts []PartRequirement + OptionalParts []PartRequirement + // IndexContractSource 说明该版本的索引名从哪里读。空值等于"读不到", + // 不允许回退成空串去匹配任何索引。 + IndexContractSource string + // IndexTenantField 表示该版本的索引文档带 tenant_id。0.9.0 的分块文档只有 + // knowledge_base_id,写索引时补 tenant_id 会与目标实际文档不一致。 + IndexTenantField bool +} + +var profiles = map[int]Profile{ + LegacyVersion: { + Name: "v071", + SchemaVersion: LegacyVersion, + WeKnoraVersion: "v0.7.1", + EmbeddingDimension: 1024, + RequiredTables: []string{ + "knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", + "resources", "resource_bindings", "wiki_folders", "wiki_pages", + "wiki_page_issues", "wiki_log_entries", + }, + RequiredColumns: map[string][]string{ + "knowledges": {"id", "tenant_id", "knowledge_base_id", "deleted_at", "parse_status"}, + "chunks": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "content"}, + "knowledge_tags": {"id", "tenant_id", "knowledge_base_id"}, + "knowledge_tag_relations": {"knowledge_id", "tag_id"}, + "resources": {"id", "handle", "tenant_id", "physical_path"}, + "resource_bindings": {"id", "resource_id", "tenant_id", "owner_type", "owner_id"}, + "wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"}, + "wiki_folders": {"id", "tenant_id", "knowledge_base_id"}, + "wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"}, + "wiki_log_entries": {"id", "tenant_id", "knowledge_base_id"}, + }, + RequiredParts: []PartRequirement{ + {"database", "knowledges"}, {"database", "chunks"}, + {"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"}, + {"database", "resources"}, {"database", "resource_bindings"}, + {"wiki", "wiki_folders"}, {"wiki", "wiki_pages"}, + {"wiki", "wiki_page_issues"}, {"wiki", "wiki_log_entries"}, + {"index", "chunks"}, + }, + IndexContractSource: "vector_stores.index_config.index_name", + IndexTenantField: true, + }, + V090Version: { + Name: "v090", + SchemaVersion: V090Version, + WeKnoraVersion: "v0.9.0", + // 0.9.0 的 KB 不写 vector_store_id,维度只能从 models.parameters 读。 + EmbeddingDimension: 0, + RequiredTables: []string{ + "knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", + "resources", "resource_bindings", "wiki_folders", "wiki_pages", + "wiki_page_issues", + }, + // 0.9.0 删掉了 wiki_log_entries;部件集合随之为空,不许假装还有。 + OptionalTables: []string{"wiki_log_entries"}, + RequiredColumns: map[string][]string{ + "knowledges": {"id", "tenant_id", "knowledge_base_id", "deleted_at", "parse_status"}, + "chunks": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "content", "seq_id", "content_revision", "index_status"}, + "knowledge_tags": {"id", "tenant_id", "knowledge_base_id"}, + "knowledge_tag_relations": {"knowledge_id", "tag_id"}, + "resources": {"id", "handle", "tenant_id", "physical_path"}, + "resource_bindings": {"id", "resource_id", "tenant_id", "owner_type", "owner_id"}, + "wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"}, + "wiki_folders": {"id", "tenant_id", "knowledge_base_id"}, + "wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"}, + }, + RequiredParts: []PartRequirement{ + {"database", "knowledges"}, {"database", "chunks"}, + {"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"}, + {"database", "resources"}, {"database", "resource_bindings"}, + {"wiki", "wiki_folders"}, {"wiki", "wiki_pages"}, {"wiki", "wiki_page_issues"}, + {"index", "chunks"}, + }, + OptionalParts: []PartRequirement{ + {"wiki", "wiki_log_entries"}, + }, + // 0.9.0 的索引名来自部署配置(ELASTICSEARCH_INDEX),不是 vector_stores。 + // 0.9.0 在 chunks 上挂了图片同步触发器(仅当 image_info 以 '[' 开头时触发), + // 它维护 chunk_images 派生表;定义逐字核对,任何改动都拒绝。 + ReviewedTriggers: []string{ + `CREATE TRIGGER trg_chunk_images_delete AFTER DELETE ON public.chunks FOR EACH ROW WHEN ((old.image_info ~~ '[%'::text)) EXECUTE FUNCTION chunk_images_sync()`, + `CREATE TRIGGER trg_chunk_images_insert AFTER INSERT ON public.chunks FOR EACH ROW WHEN ((new.image_info ~~ '[%'::text)) EXECUTE FUNCTION chunk_images_sync()`, + `CREATE TRIGGER trg_chunk_images_update AFTER UPDATE ON public.chunks FOR EACH ROW WHEN ((((old.image_info ~~ '[%'::text) OR (new.image_info ~~ '[%'::text)) AND ((old.image_info IS DISTINCT FROM new.image_info) OR (old.is_enabled IS DISTINCT FROM new.is_enabled) OR (old.status IS DISTINCT FROM new.status) OR (old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.tenant_id IS DISTINCT FROM new.tenant_id) OR ((old.knowledge_base_id)::text IS DISTINCT FROM (new.knowledge_base_id)::text) OR ((old.knowledge_id)::text IS DISTINCT FROM (new.knowledge_id)::text) OR ((old.chunk_type)::text IS DISTINCT FROM (new.chunk_type)::text) OR (old.created_at IS DISTINCT FROM new.created_at) OR (old.updated_at IS DISTINCT FROM new.updated_at)))) EXECUTE FUNCTION chunk_images_sync()`, + }, + IndexContractSource: "config ELASTICSEARCH_INDEX", + IndexTenantField: false, + }, +} + +// For 按版本号选中 profile。未知版本一律失败:版本号是"选哪份声明"的索引, +// 不是"能不能放行"的依据,所以绝不返回默认 profile。 +func For(version int) (Profile, error) { + profile, ok := profiles[version] + if !ok { + return Profile{}, fmt.Errorf("unsupported WeKnora schema version %d: supported profiles are 74 (v071) and 134 (v090)", version) + } + return profile, nil +} + +// Supported 返回已声明 profile 的版本号(用于文档与错误信息,不用于放行)。 +func Supported() []int { + return []int{LegacyVersion, V090Version} +} + +// TableSet 是"可能出现的表"集合:必需表 + 可选表。 +func (p Profile) TableSet() map[string]bool { + set := make(map[string]bool, len(p.RequiredTables)+len(p.OptionalTables)) + for _, name := range p.RequiredTables { + set[name] = true + } + for _, name := range p.OptionalTables { + set[name] = true + } + return set +} + +// HasTable 报告某张表是否属于该 profile(必需或可选)。 +func (p Profile) HasTable(name string) bool { + return p.TableSet()[name] +} + +// IsRequiredTable 报告某张表是否必需存在。 +func (p Profile) IsRequiredTable(name string) bool { + for _, candidate := range p.RequiredTables { + if candidate == name { + return true + } + } + return false +} + +// PartKeys 返回 (必需, 可选) 的归档部件键,形如 "wiki/wiki_log_entries"。 +func (p Profile) PartKeys() ([]string, []string) { + key := func(part PartRequirement) string { return part.Kind + "/" + part.Name } + required := make([]string, 0, len(p.RequiredParts)) + for _, part := range p.RequiredParts { + required = append(required, key(part)) + } + optional := make([]string, 0, len(p.OptionalParts)) + for _, part := range p.OptionalParts { + optional = append(optional, key(part)) + } + return required, optional +} + +// RequiresPart 报告某部件键是否必需(可选部件返回 false)。 +func (p Profile) RequiresPart(key string) bool { + required, _ := p.PartKeys() + for _, candidate := range required { + if candidate == key { + return true + } + } + return false +} + +// AllowsPart 报告某部件键是否至少允许出现。 +func (p Profile) AllowsPart(key string) bool { + required, optional := p.PartKeys() + for _, candidate := range required { + if candidate == key { + return true + } + } + for _, candidate := range optional { + if candidate == key { + return true + } + } + return false +} diff --git a/internal/libraryrelease/index_plan.go b/internal/libraryrelease/index_plan.go new file mode 100644 index 0000000..aa826e8 --- /dev/null +++ b/internal/libraryrelease/index_plan.go @@ -0,0 +1,14 @@ +package libraryrelease + +import "encoding/json" + +// IndexWrite freezes the exact index/ID, original bytes and CAS generation. +// After=nil is an explicit removal, never a scope-wide delete-by-query. +type IndexWrite struct { + Index string `json:"index"` + ID string `json:"id"` + Before json.RawMessage `json:"before,omitempty"` + SeqNo *int64 `json:"seq_no,omitempty"` + PrimaryTerm *int64 `json:"primary_term,omitempty"` + After json.RawMessage `json:"after,omitempty"` +} diff --git a/internal/libraryrelease/index_restore_dispatch.go b/internal/libraryrelease/index_restore_dispatch.go new file mode 100644 index 0000000..f825cfc --- /dev/null +++ b/internal/libraryrelease/index_restore_dispatch.go @@ -0,0 +1,201 @@ +package libraryrelease + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" +) + +// 恢复标记派发协议(DS01 窄协议)。 +// +// 这里定义的唯一持久事实是:某个固定的删除型恢复 effect 是否已经有人拿到过 +// "向索引发送一次 `_create`"的许可。它不是"ES 历史上从未有人写过这个 ID"的证明, +// 也不是目标端 fence。判据是单调的持久状态,不是 missing、stats 或内存布尔值。 +const ( + // RestoreMarkerPhaseCreate 是恢复期独占 create(删除型文档的原文标记)的唯一相位。 + // 其它相位(apply create、compensation DELETE、clean CAS)不得借用它取得发送许可。 + RestoreMarkerPhaseCreate = "restore-marker-create" + + RestoreDispatchPrepared = "prepared" + RestoreDispatchDispatching = "dispatching" + RestoreDispatchMarkerConfirmed = "marker_confirmed" +) + +var ( + ErrRestoreDispatchHeld = errors.New("restore marker dispatch is held") + ErrRestorePermitSpent = errors.New("restore send permit already used") + ErrRestorePermitMismatch = errors.New("restore send permit bound to another effect") + ErrRestoreDispatchUnavailable = errors.New("restore marker dispatch protocol is not activated for this target") +) + +// RestoreMarkerKey 是"同一个逻辑恢复 effect"的身份。epoch、恢复队列 ID、恢复作业 ID +// 都不在 key 里:接管与重试必须落到同一行,不能靠换 key 绕开旧的 dispatching。 +type RestoreMarkerKey struct { + TargetIdentity string `json:"target_identity"` + OperationID string `json:"operation_id"` + WindowJobID string `json:"window_job_id"` + PlanDigest string `json:"plan_digest"` + Index string `json:"index"` + DocumentID string `json:"document_id"` + Phase string `json:"phase"` +} + +func (k RestoreMarkerKey) Validate() error { + for name, value := range map[string]string{ + "target": k.TargetIdentity, "operation": k.OperationID, "window job": k.WindowJobID, + "plan": k.PlanDigest, "index": k.Index, "document": k.DocumentID, "phase": k.Phase, + } { + if strings.TrimSpace(value) == "" { + return fmt.Errorf("restore marker key lacks %s", name) + } + } + if k.Phase != RestoreMarkerPhaseCreate { + return fmt.Errorf("restore marker key phase %q is not the single create phase", k.Phase) + } + return nil +} + +// RestoreMarkerBinding 是派发许可的不可变绑定。目标、快照、计划、变更体与标记体任一 +// 变化都必须 held,不能另起一行继续写。 +// +// SourceSnapshot 是发布基线(原作业要同步到的那份来源),BackupSnapshot 是本次失败 +// 写集的写前镜像;两者必须来自原持久锚点且不能互相代替。TargetInstance / +// TargetFingerprint / IndexUUID 冻结"实际目标",用于识别目标被同名字替换;它们不证明 +// 历史上没有发送过任何请求。 +type RestoreMarkerBinding struct { + Key RestoreMarkerKey `json:"key"` + Scope string `json:"scope"` + SourceSnapshot string `json:"source_snapshot"` + BackupSnapshot string `json:"backup_snapshot"` + TargetInstance string `json:"target_instance"` + TargetFingerprint string `json:"target_fingerprint"` + IndexUUID string `json:"index_uuid"` + RecoveryJobID string `json:"recovery_job_id,omitempty"` + RecoveryOperationID string `json:"recovery_operation_id,omitempty"` + ChangeDigest string `json:"change_digest"` + MarkerDigest string `json:"marker_digest"` + RequestDigest string `json:"request_digest"` + Owner string `json:"owner"` + Epoch int64 `json:"epoch"` +} + +func (b RestoreMarkerBinding) Validate() error { + if err := b.Key.Validate(); err != nil { + return err + } + for name, value := range map[string]string{ + "scope": b.Scope, "source snapshot": b.SourceSnapshot, "backup snapshot": b.BackupSnapshot, + "target instance": b.TargetInstance, "target fingerprint": b.TargetFingerprint, + "index uuid": b.IndexUUID, "change digest": b.ChangeDigest, "marker digest": b.MarkerDigest, + "request digest": b.RequestDigest, "owner": b.Owner, + } { + if strings.TrimSpace(value) == "" { + return fmt.Errorf("restore marker binding lacks %s", name) + } + } + if b.SourceSnapshot == b.BackupSnapshot { + return errors.New("restore marker binding uses the source snapshot as the backup image") + } + if b.RecoveryJobID == "" != (b.RecoveryOperationID == "") { + return errors.New("restore marker binding has a partial recovery delivery identity") + } + if b.Epoch <= 0 { + return errors.New("restore marker binding lacks a positive attempt epoch") + } + return nil +} + +// Digest 覆盖**逻辑 effect 的不可变绑定**;台账用它拒绝"同 key 换绑定"。 +// owner/epoch 与 recovery queue/operation 是执行/投递锚点,不进摘要:自动回滚与 +// 随后的 recovery worker 必须落到同一个 effect 身份,但它们的投递身份不同。 +func (b RestoreMarkerBinding) Digest() (string, error) { + if err := b.Validate(); err != nil { + return "", err + } + joined := strings.Join([]string{ + "v2", b.Key.TargetIdentity, b.Key.OperationID, b.Key.WindowJobID, b.Key.PlanDigest, + b.Key.Index, b.Key.DocumentID, b.Key.Phase, b.Scope, b.SourceSnapshot, b.BackupSnapshot, + b.TargetInstance, b.TargetFingerprint, b.IndexUUID, + b.ChangeDigest, b.MarkerDigest, b.RequestDigest, + }, "\x00") + sum := sha256.Sum256([]byte(joined)) + return hex.EncodeToString(sum[:]), nil +} + +// RestoreDispatchStatus 是纯读分类结果。Held 为真时永远不能发送。 +// +// BindingConflict 是与 Held 不同的**类型化**分类:Held 只说"这次不能再 create" +// (prepared 冲突、dispatching 结果未知、marker 已确认都可能是合法的不可重发), +// 而 BindingConflict 说明台账行的不可变绑定与本次绑定不是同一个 effect。绑定冲突 +// 在**任何状态**下都必须拒绝,包括已完成 clean 的 marker_confirmed;否则"只允许原 +// 确认分支继续"会变成放行一份不属于本计划的写入。 +type RestoreDispatchStatus struct { + State string `json:"state"` + Held bool `json:"held"` + BindingConflict bool `json:"binding_conflict,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// RestoreSendPermit 是"这一次调用、这一个 effect、这一次发送"的许可。 +// +// 它不是可复用凭证:Store 只在 dispatching 明确 commit 之后返回它;消费一次即作废。 +// 不能从 Load/Get/JSON/重启重建——那正是本协议要排除的"从外观推断未派发"。 +type RestoreSendPermit struct { + key RestoreMarkerKey + binding string + nonce string + used bool +} + +// IssueRestoreSendPermit 只允许实现 RestoreMarkerGate 的存储层调用。许可的权威性来自 +// 数据库 CAS 与提交,不来自这个构造函数;这里只保证调用栈内一次性。 +func IssueRestoreSendPermit(key RestoreMarkerKey, bindingDigest, nonce string) *RestoreSendPermit { + return &RestoreSendPermit{key: key, binding: bindingDigest, nonce: nonce} +} + +func (p *RestoreSendPermit) Nonce() string { + if p == nil { + return "" + } + return p.nonce +} + +// Consume 校验 effect/绑定并作废许可。绑定不符时不消耗许可(避免被一次误用烧掉)。 +func (p *RestoreSendPermit) Consume(key RestoreMarkerKey, bindingDigest string) error { + if p == nil { + return ErrRestorePermitMismatch + } + if p.used { + return ErrRestorePermitSpent + } + if p.key != key || p.binding != bindingDigest { + return ErrRestorePermitMismatch + } + p.used = true + return nil +} + +// RestoreDispatchRecord 是权威台账里"这个原 window 还有哪些未决 effect"的一条。 +// 收尾与前置都查同一份记录集,不能只遍历当前 plan 的文档列表。 +type RestoreDispatchRecord struct { + PlanDigest string `json:"plan_digest"` + Index string `json:"index"` + DocumentID string `json:"document_id"` + State string `json:"state"` +} + +// RestoreMarkerGate 是唯一能授予恢复标记 create 发送权的接口。 +// +// Inspect 纯读、不返回许可;Prepare 只建立 prepared;Acquire 在独立短事务里做 +// prepared→dispatching 的 CAS,只有明确提交后才返回许可;Confirm 只记录真实回执; +// UnresolvedRestoreDispatches 返回原 window 的权威未决全集(跨 plan,只读)。 +type RestoreMarkerGate interface { + InspectRestoreMarker(ctx context.Context, b RestoreMarkerBinding) (RestoreDispatchStatus, bool, error) + PrepareRestoreMarker(ctx context.Context, b RestoreMarkerBinding) (RestoreDispatchStatus, error) + AcquireRestoreMarker(ctx context.Context, b RestoreMarkerBinding) (*RestoreSendPermit, RestoreDispatchStatus, error) + ConfirmRestoreMarker(ctx context.Context, b RestoreMarkerBinding, receipt []byte) error + UnresolvedRestoreDispatches(ctx context.Context, targetIdentity, operationID, windowJobID string) ([]RestoreDispatchRecord, error) +} diff --git a/internal/libraryrelease/index_restore_dispatch_test.go b/internal/libraryrelease/index_restore_dispatch_test.go new file mode 100644 index 0000000..dca34aa --- /dev/null +++ b/internal/libraryrelease/index_restore_dispatch_test.go @@ -0,0 +1,132 @@ +package libraryrelease + +import ( + "errors" + "strings" + "testing" +) + +func restoreBinding() RestoreMarkerBinding { + return RestoreMarkerBinding{ + Key: RestoreMarkerKey{TargetIdentity: "target-a", OperationID: "op-1", WindowJobID: "job-1", + PlanDigest: "plan-1", Index: "kg-index", DocumentID: "doc-1", Phase: RestoreMarkerPhaseCreate}, + Scope: "internal", SourceSnapshot: "snap-src", BackupSnapshot: "snap-backup", + TargetInstance: "inst-1", TargetFingerprint: "fingerprint-1", IndexUUID: "uuid-1", + ChangeDigest: "change-1", MarkerDigest: "marker-1", RequestDigest: "request-1", + Owner: "worker-a#queue#1", Epoch: 3, + } +} + +func TestRestoreMarkerBindingRejectsIncompleteIdentity(t *testing.T) { + for name, mutate := range map[string]func(*RestoreMarkerBinding){ + "target": func(b *RestoreMarkerBinding) { b.Key.TargetIdentity = "" }, + "operation": func(b *RestoreMarkerBinding) { b.Key.OperationID = "" }, + "window": func(b *RestoreMarkerBinding) { b.Key.WindowJobID = "" }, + "plan": func(b *RestoreMarkerBinding) { b.Key.PlanDigest = "" }, + "index": func(b *RestoreMarkerBinding) { b.Key.Index = "" }, + "document": func(b *RestoreMarkerBinding) { b.Key.DocumentID = "" }, + "change": func(b *RestoreMarkerBinding) { b.ChangeDigest = "" }, + "marker": func(b *RestoreMarkerBinding) { b.MarkerDigest = "" }, + "request": func(b *RestoreMarkerBinding) { b.RequestDigest = "" }, + "owner": func(b *RestoreMarkerBinding) { b.Owner = "" }, + "epoch": func(b *RestoreMarkerBinding) { b.Epoch = 0 }, + "phase": func(b *RestoreMarkerBinding) { b.Key.Phase = "apply-create" }, + "instance": func(b *RestoreMarkerBinding) { b.TargetInstance = "" }, + "fingerprint": func(b *RestoreMarkerBinding) { b.TargetFingerprint = "" }, + "index uuid": func(b *RestoreMarkerBinding) { b.IndexUUID = "" }, + "source as backup": func(b *RestoreMarkerBinding) { b.BackupSnapshot = b.SourceSnapshot }, + } { + binding := restoreBinding() + mutate(&binding) + if err := binding.Validate(); err == nil { + t.Fatalf("%s: incomplete binding accepted", name) + } + } + if err := restoreBinding().Validate(); err != nil { + t.Fatalf("complete binding rejected: %v", err) + } +} + +func TestRestoreMarkerBindingDigestCoversEveryBoundValue(t *testing.T) { + base, err := restoreBinding().Digest() + if err != nil { + t.Fatal(err) + } + if again, _ := restoreBinding().Digest(); again != base { + t.Fatal("binding digest is not deterministic") + } + for name, mutate := range map[string]func(*RestoreMarkerBinding){ + "target": func(b *RestoreMarkerBinding) { b.Key.TargetIdentity = "target-b" }, + "index": func(b *RestoreMarkerBinding) { b.Key.Index = "other-index" }, + "doc": func(b *RestoreMarkerBinding) { b.Key.DocumentID = "doc-2" }, + "plan": func(b *RestoreMarkerBinding) { b.Key.PlanDigest = "plan-2" }, + "backup": func(b *RestoreMarkerBinding) { b.BackupSnapshot = "snap-2" }, + "change": func(b *RestoreMarkerBinding) { b.ChangeDigest = "change-2" }, + "marker": func(b *RestoreMarkerBinding) { b.MarkerDigest = "marker-2" }, + "request": func(b *RestoreMarkerBinding) { b.RequestDigest = "request-2" }, + "scope": func(b *RestoreMarkerBinding) { b.Scope = "external" }, + "source": func(b *RestoreMarkerBinding) { b.SourceSnapshot = "snap-9" }, + "instance": func(b *RestoreMarkerBinding) { b.TargetInstance = "inst-2" }, + "fingerprint": func(b *RestoreMarkerBinding) { b.TargetFingerprint = "fingerprint-2" }, + "index uuid": func(b *RestoreMarkerBinding) { b.IndexUUID = "uuid-2" }, + } { + binding := restoreBinding() + mutate(&binding) + changed, err := binding.Digest() + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if changed == base { + t.Fatalf("%s: binding change not covered by digest", name) + } + } +} + +// 许可只能在本次调用栈用一次;换 key/换绑定都不能复用,也不能把已花的许可再花一次。 +// 恢复投递身份是执行锚点,不是 effect 身份:自动回滚与 recovery worker 的摘要必须一致。 +func TestRestoreBindingDigestIgnoresDeliveryIdentity(t *testing.T) { + base, err := restoreBinding().Digest() + if err != nil { + t.Fatal(err) + } + delivered := restoreBinding() + delivered.RecoveryJobID, delivered.RecoveryOperationID = "queue-1", "op-recovery" + delivered.Owner, delivered.Epoch = "worker-b#queue#1", 7 + other, err := delivered.Digest() + if err != nil { + t.Fatal(err) + } + if other != base { + t.Fatal("delivery/attempt identity changed the logical effect digest") + } +} + +func TestRestoreSendPermitIsSingleUseAndKeyBound(t *testing.T) { + binding := restoreBinding() + digest, err := binding.Digest() + if err != nil { + t.Fatal(err) + } + permit := IssueRestoreSendPermit(binding.Key, digest, "nonce-1") + other := binding.Key + other.DocumentID = "doc-2" + if err := permit.Consume(other, digest); err == nil || !errors.Is(err, ErrRestorePermitMismatch) { + t.Fatalf("permit usable for another effect: %v", err) + } + if err := permit.Consume(binding.Key, "other-binding"); err == nil || !errors.Is(err, ErrRestorePermitMismatch) { + t.Fatalf("permit usable for another binding: %v", err) + } + if err := permit.Consume(binding.Key, digest); err != nil { + t.Fatalf("valid permit rejected: %v", err) + } + if err := permit.Consume(binding.Key, digest); err == nil || !errors.Is(err, ErrRestorePermitSpent) { + t.Fatalf("permit spent twice: %v", err) + } + if strings.Contains(permit.Nonce(), digest) { + t.Fatal("nonce is not independent audit data") + } + var nilPermit *RestoreSendPermit + if err := nilPermit.Consume(binding.Key, digest); err == nil { + t.Fatal("nil permit accepted") + } +} diff --git a/internal/libraryrelease/object_plan.go b/internal/libraryrelease/object_plan.go new file mode 100644 index 0000000..4e7fc27 --- /dev/null +++ b/internal/libraryrelease/object_plan.go @@ -0,0 +1,18 @@ +package libraryrelease + +// ObjectWrite identifies a physical object, not a row ID or a guessed orphan. +// Existing objects are read-only. This protocol refuses differing overwrites. +type ObjectWrite struct { + BeforeVersionID string `json:"before_version_id,omitempty"` + ResourceID string `json:"resource_id"` + Provider string `json:"provider"` + BackendID string `json:"backend_id"` + Bucket string `json:"bucket"` + Key string `json:"key"` + Locator string `json:"locator"` + SHA256 string `json:"sha256"` + Bytes int64 `json:"bytes"` + Existing bool `json:"existing"` + BeforeETag string `json:"before_etag,omitempty"` + OwnerToken string `json:"owner_token"` +} diff --git a/internal/libraryrelease/release.go b/internal/libraryrelease/release.go index 3322bf2..d298a11 100644 --- a/internal/libraryrelease/release.go +++ b/internal/libraryrelease/release.go @@ -36,12 +36,19 @@ type Grant struct { // Request 是一次待执行的生产同步。 type Request struct { + // JobID 是这次发布的作业身份:写集合记录与预备份引用都绑定它, + // worker 重启后凭它找回"这次写了什么"。 + JobID string Target string SnapshotID string // ParamsDigest 覆盖会影响生产结果的全部参数(目标、快照、排除范围等)。 ParamsDigest string Grant Grant Now time.Time + // PriorSnapshots 是这个目标的持久来源(成功同步过的快照 + 自己的预备份), + // 由治理库提供。资源复用只认它作证据;为空时"目标里已有但不在预备份范围" + // 的资源一律按冲突拒绝。 + PriorSnapshots []PriorSnapshot } // CurrentState 是生产当前整库的指纹,用于预备份与最终验证。 @@ -75,9 +82,16 @@ type BackupRef struct { SnapshotID string `json:"snapshot_id"` Bytes int64 `json:"bytes"` CreatedAt time.Time `json:"created_at"` - // Universe 是预备份时刻的整实例指纹,恢复后逐表比对。空表示这次没有采集 - // (例如 worker 被杀后用已持久化的快照接管),此时恢复只能靠内容校验兜底。 + // Universe 是预备份时刻的整实例指纹,恢复后逐表比对。 Universe map[string]TableFingerprint `json:"universe,omitempty"` + // WriteSet 是本次发布的写集合与整实例内容证据。它在写第一笔之前就落盘并 + // 登记摘要;恢复必须按它清理,缺了它恢复要失败(不许降级成"跳过比对")。 + WriteSet *WriteSet `json:"write_set,omitempty"` + // Reused 表示"这是接管时复用上一次的预备份,没有重新备份"。 + // 崩溃接管绝不允许重新备份:那一刻目标已被写过,新备份会把半写状态当成 + // 可回滚基线,覆盖真正干净的那一份。外部要能区分"复用"与"重做", + // 所以复用必须显式落到版本证据里。 + Reused bool `json:"reused,omitempty"` } type Target interface { @@ -101,6 +115,16 @@ type Recorder interface { Stage(ctx context.Context, stage string, state string, detail string) } +// GrantRevalidator 让编排在每笔副作用前按**持久授权**回读。 +// +// 内存里的 Grant 只是一个快照:它既不能延长有效期,也不能掩盖中途撤销。 +// 目标实现了这个接口就必须给出权威答案(读治理库的授权行);返回错误即拒绝继续。 +// 未实现时行为不变(只核静态有效期),所以这不是给"忘记接线"留的后门 —— +// 生产目标的 wrapper 由 runLibraryRelease 无条件接线。 +type GrantRevalidator interface { + RevalidateGrant(ctx context.Context, grant Grant) error +} + // BackupObserver 让调用方在预备份完成时立刻持久化快照身份: // worker 被杀后重启必须能接管这份预备份,而不是重新备份覆盖它。 type BackupObserver interface { @@ -170,6 +194,8 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor if recorder == nil { recorder = NoopRecorder{} } + // Request.Now is a diagnostic input, not a clock authority for execution. + request.Now = time.Now().UTC() if err := ValidateGrant(request); err != nil { outcome.Error = err.Error() recorder.Stage(ctx, "prebackup", "failed", err.Error()) @@ -203,6 +229,84 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor } recorder.Stage(ctx, "prebackup", "succeeded", "预备份 "+backup.ID) + // Backup may outlive the grant. Recheck before planning (which may allocate + // numbers), and again after durable plan registration before the first apply. + // With a GrantRevalidator the check is authoritative: a revoked or expired + // authorization row stops the run even though the in-memory grant still looks + // valid, and a stale in-memory expiry cannot be extended either. + checkLiveGrant := func() bool { + request.Now = time.Now().UTC() + if e := ValidateGrant(request); e != nil { + outcome.Error = e.Error() + outcome.Recovery = "预备份保留;需要有效的新授权后继续" + recorder.Stage(ctx, "prebackup", "failed", outcome.Error) + return false + } + if revalidator, ok := target.(GrantRevalidator); ok { + if e := revalidator.RevalidateGrant(ctx, request.Grant); e != nil { + outcome.Error = "持久授权已失效,未继续写入:" + e.Error() + outcome.Recovery = "预备份保留;重新签发授权后按原预备份继续" + recorder.Stage(ctx, "prebackup", "failed", outcome.Error) + return false + } + } + return true + } + if !checkLiveGrant() { + return outcome + } + + // 写集合必须在第一笔写入之前落盘并登记:恢复只按"这次明确写了什么"清理, + // 不按目标现状推断残渣(那会把历史孤儿/共享资源当成本次残留删掉)。 + existingPlan := backup.WriteSet != nil + if backup.WriteSet == nil { + if planner, ok := target.(WriteSetPlanner); ok { + set, planErr := planner.PlanWriteSet(ctx, WriteSetPlan{JobID: request.JobID, Target: request.Target, + BackupSnapshotID: backup.SnapshotID, TargetSnapshotID: request.SnapshotID, Universe: backup.Universe, + PriorSnapshots: request.PriorSnapshots}) + if planErr != nil { + outcome.State = "failed" + outcome.Error = "写集合/冲突预检失败,未对生产执行任何写入:" + planErr.Error() + recorder.Stage(ctx, "prebackup", "failed", outcome.Error) + return outcome + } + backup.WriteSet = &set + outcome.Backup = backup + if observer, ok := recorder.(WriteSetObserver); ok { + if err := observer.WriteSetPlanned(ctx, set); err != nil { + // 硬门禁:记录没落库 = 恢复时不知道写集合 = 一笔都不许写。 + outcome.State = "failed" + outcome.Error = "写集合已落盘但引用无法持久化,未对生产执行任何写入:" + err.Error() + recorder.Stage(ctx, "prebackup", "failed", outcome.Error) + return outcome + } + } + } + } + + // 计划已经存在(接管/恢复)时,执行目标必须**消费**它:把"这些资源已证明可复用" + // 的决定装进去,写入阶段才会跳过共享对象。不能重新计划——那时目标已被写过, + // 重新计划等于把半写现状当新基线(F07)。 + if existingPlan { + if adopter, ok := target.(WriteSetAdopter); ok { + if err := adopter.AdoptWriteSet(*backup.WriteSet); err != nil { + outcome.State = "failed" + outcome.Error = "无法接管已持久化的写集合,拒绝继续写目标:" + err.Error() + recorder.Stage(ctx, "prebackup", "failed", outcome.Error) + return outcome + } + } else if _, plans := target.(WriteSetPlanner); plans { + // 会写资源、却读不懂计划:继续写就会重写共享行/对象。 + outcome.State = "failed" + outcome.Error = "目标实现无法消费已持久化的写集合,拒绝在失去复用语义的情况下写目标" + recorder.Stage(ctx, "prebackup", "failed", outcome.Error) + return outcome + } + } + + if !checkLiveGrant() { + return outcome + } for _, stage := range Stages() { recorder.Stage(ctx, string(stage), "running", "") if err = target.Apply(ctx, stage, request.SnapshotID); err != nil { diff --git a/internal/libraryrelease/release_test.go b/internal/libraryrelease/release_test.go index 824bcef..0319bad 100644 --- a/internal/libraryrelease/release_test.go +++ b/internal/libraryrelease/release_test.go @@ -119,7 +119,8 @@ func TestRunRefusesExpiredOrMismatchedGrantBeforeTouchingTarget(t *testing.T) { mutate func(*Request) want error }{ - {"expired", func(r *Request) { r.Now = r.Grant.ExpiresAt.Add(time.Minute) }, ErrGrantExpired}, + // Run uses the live clock, not the caller's diagnostic timestamp. + {"expired", func(r *Request) { r.Grant.ExpiresAt = time.Now().Add(-time.Minute) }, ErrGrantExpired}, {"other target", func(r *Request) { r.Target = "external-prod" }, ErrGrantTarget}, {"other snapshot", func(r *Request) { r.SnapshotID = "snap-2" }, ErrGrantSnapshot}, {"params changed", func(r *Request) { r.ParamsDigest = "digest-2" }, ErrGrantParams}, @@ -250,3 +251,207 @@ func TestRunReportsRollbackFailureDistinctly(t *testing.T) { t.Fatalf("stage log = %v", recorder.entries) } } + +// writeSetPlanTarget 记录"写集合规划"与阶段写入的相对顺序:写集合必须在第一笔之前。 +type writeSetPlanTarget struct { + *fakeTarget + planErr error + plans []WriteSetPlan + events *[]string + ledger *WriteSet + restores []BackupRef + // adopted 记录"接管时消费了哪份已持久化写集合"(F07):adoptErr 表达"读不懂计划"。 + adopted []WriteSet + adoptErr error +} + +// AdoptWriteSet 让这个假目标具备"消费既有计划"的能力:真实实现按它把复用决定装回去。 +func (p *writeSetPlanTarget) AdoptWriteSet(set WriteSet) error { + *p.events = append(*p.events, "adopt") + if p.adoptErr != nil { + return p.adoptErr + } + p.adopted = append(p.adopted, set) + return nil +} + +func (p *writeSetPlanTarget) PlanWriteSet(_ context.Context, plan WriteSetPlan) (WriteSet, error) { + *p.events = append(*p.events, "plan") + p.plans = append(p.plans, plan) + if p.planErr != nil { + return WriteSet{}, p.planErr + } + set := WriteSet{Version: WriteSetVersion, JobID: plan.JobID, Target: plan.Target, + TenantID: 10001, KnowledgeBaseID: "kb", BackupSnapshotID: plan.BackupSnapshotID, + TargetSnapshotID: plan.TargetSnapshotID, CreatedAt: time.Now().UTC(), Universe: plan.Universe, + Rows: []WriteSetRow{{Table: "resources", ID: "res-new"}}} + if err := set.Seal(); err != nil { + return WriteSet{}, err + } + p.ledger = &set + return set, nil +} + +func (p *writeSetPlanTarget) Apply(ctx context.Context, stage Stage, snapshot string) error { + *p.events = append(*p.events, "apply:"+string(stage)) + return p.fakeTarget.Apply(ctx, stage, snapshot) +} + +func (p *writeSetPlanTarget) Restore(ctx context.Context, backup BackupRef) error { + p.restores = append(p.restores, backup) + return p.fakeTarget.Restore(ctx, backup) +} + +type writeSetRecorder struct { + *stageLog + events *[]string + err error + sets []WriteSet +} + +func (r *writeSetRecorder) WriteSetPlanned(_ context.Context, set WriteSet) error { + *r.events = append(*r.events, "observe") + r.sets = append(r.sets, set) + return r.err +} + +func plannedRun(t *testing.T) (*writeSetPlanTarget, *writeSetRecorder, *[]string, Request, *fakeBackups) { + t.Helper() + now := time.Now() + events := []string{} + target := &writeSetPlanTarget{fakeTarget: &fakeTarget{}, events: &events} + recorder := &writeSetRecorder{stageLog: &stageLog{}, events: &events} + backups := &fakeBackups{ref: BackupRef{ID: "backup-1", SnapshotID: "backup-snap", Bytes: 512, + CreatedAt: now.UTC(), Universe: map[string]TableFingerprint{"resources": {Count: 2, Digest: "d"}}}} + request := request(now) + return target, recorder, &events, request, backups +} + +func TestRunPlansWriteSetBeforeFirstWrite(t *testing.T) { + target, recorder, events, request, backups := plannedRun(t) + outcome := Run(context.Background(), request, target, backups, recorder) + if outcome.State != "succeeded" { + t.Fatalf("outcome = %+v", outcome) + } + if len(target.plans) != 1 { + t.Fatalf("write set must be planned exactly once, got %d", len(target.plans)) + } + if got := (*events)[0]; got != "plan" { + t.Fatalf("write set must be planned before anything touches the target, first event = %s", got) + } + if len(recorder.sets) != 1 || recorder.sets[0].Digest == "" { + t.Fatalf("planner output must be persisted before writing: %+v", recorder.sets) + } + if target.plans[0].JobID != request.JobID || target.plans[0].TargetSnapshotID != request.SnapshotID || + target.plans[0].Target != request.Target { + t.Fatalf("plan must bind job/target/snapshot: %+v", target.plans[0]) + } + if target.plans[0].BackupSnapshotID != "backup-snap" { + t.Fatalf("plan must bind the backup snapshot: %+v", target.plans[0]) + } + if len(*events) < 2 || (*events)[1] != "observe" { + t.Fatalf("write set must be persisted right after planning, events=%v", *events) + } +} + +func TestRunStopsBeforeWritingWhenWriteSetPlanFails(t *testing.T) { + target, recorder, events, request, backups := plannedRun(t) + target.planErr = errors.New("资源 ID 冲突:res-x 已属于其它知识库") + outcome := Run(context.Background(), request, target, backups, recorder) + if outcome.State != "failed" { + t.Fatalf("outcome = %+v", outcome) + } + if !strings.Contains(outcome.Error, "冲突") { + t.Fatalf("error must carry the conflict reason: %s", outcome.Error) + } + if len(target.applied) != 0 { + t.Fatalf("no stage may run after a failed preflight: %v", target.applied) + } + if len(recorder.sets) != 0 { + t.Fatal("a failed plan must not be persisted as the write set") + } + for _, event := range *events { + if strings.HasPrefix(event, "apply:") { + t.Fatalf("target was written despite a failed preflight: %v", *events) + } + } +} + +func TestRunStopsBeforeWritingWhenWriteSetCannotBePersisted(t *testing.T) { + target, recorder, events, request, backups := plannedRun(t) + recorder.err = errors.New("治理库写不进去") + outcome := Run(context.Background(), request, target, backups, recorder) + if outcome.State != "failed" { + t.Fatalf("outcome = %+v", outcome) + } + if !strings.Contains(outcome.Error, "写集合") { + t.Fatalf("error must name the write-set record: %s", outcome.Error) + } + if len(target.applied) != 0 { + t.Fatalf("no stage may run when the write set cannot be persisted: %v", target.applied) + } + for _, event := range *events { + if strings.HasPrefix(event, "apply:") { + t.Fatalf("target was written without a persisted write set: %v", *events) + } + } +} + +// 接管时必须复用持久化的写集合,而不是按当前(已半写的)目标重新规划。 +func TestRunResumeUsesPersistedWriteSet(t *testing.T) { + target, recorder, events, request, backups := plannedRun(t) + resumed := &fakeBackups{ref: BackupRef{ID: "backup-1", SnapshotID: "backup-snap", + WriteSet: &WriteSet{Version: WriteSetVersion, JobID: request.JobID, Target: request.Target, + TenantID: 10001, KnowledgeBaseID: "kb", BackupSnapshotID: "backup-snap", + TargetSnapshotID: request.SnapshotID, CreatedAt: time.Now().UTC(), + Universe: map[string]TableFingerprint{"resources": {Count: 2, Digest: "d"}}}}} + backups = resumed + target.fakeTarget.applyErr = map[Stage]error{StageResources: errors.New("上传失败")} + outcome := Run(context.Background(), request, target, backups, recorder) + if outcome.State != "rolled_back" && outcome.State != "rollback_failed" { + t.Fatalf("outcome = %+v", outcome) + } + if len(target.plans) != 0 { + t.Fatalf("resume must not re-plan the write set: %+v", target.plans) + } + // F07:既有计划必须被执行目标消费——否则"复用"只停留在账本上,Apply 仍会重写共享对象。 + if len(target.adopted) != 1 { + t.Fatalf("接管必须把已持久化的写集合交给执行目标:adopted=%d", len(target.adopted)) + } + if target.adopted[0].BackupSnapshotID != "backup-snap" { + t.Fatalf("消费的写集合绑定了错误的预备份:%+v", target.adopted[0].BackupSnapshotID) + } + if len(target.restores) != 1 || target.restores[0].WriteSet == nil { + t.Fatalf("restore must carry the persisted write set: %+v", target.restores) + } + for _, event := range *events { + if event == "plan" { + t.Fatalf("resume re-planned against a half-written target: %v", *events) + } + } +} + +// F07 反向:会写资源、却读不懂既有计划的执行目标必须**在被写之前**失败。 +// 继续写就等于"账本说没动共享对象,实际又 upsert + 重传了一遍"。 +func TestRunRefusesPlanBlindTargetOnResume(t *testing.T) { + _, recorder, _, request, _ := plannedRun(t) + blind := &blindPlanTarget{fakeTarget: &fakeTarget{}} + resumed := &fakeBackups{ref: BackupRef{ID: "backup-1", SnapshotID: "backup-snap", + WriteSet: &WriteSet{Version: WriteSetVersion, JobID: request.JobID, Target: request.Target, + TenantID: 10001, KnowledgeBaseID: "kb", BackupSnapshotID: "backup-snap", + TargetSnapshotID: request.SnapshotID, CreatedAt: time.Now().UTC()}}} + outcome := Run(context.Background(), request, blind, resumed, recorder) + if outcome.State != "failed" { + t.Fatalf("读不懂计划的执行目标必须失败:%+v", outcome) + } + if len(blind.applied) != 0 { + t.Fatalf("失去复用语义时不许写任何阶段:%v", blind.applied) + } +} + +// blindPlanTarget 会规划写集合(因此会写资源),但没有 AdoptWriteSet。 +type blindPlanTarget struct{ *fakeTarget } + +func (b *blindPlanTarget) PlanWriteSet(context.Context, WriteSetPlan) (WriteSet, error) { + return WriteSet{Version: WriteSetVersion}, nil +} diff --git a/internal/libraryrelease/restore_dispatch_activation.go b/internal/libraryrelease/restore_dispatch_activation.go new file mode 100644 index 0000000..a39397d --- /dev/null +++ b/internal/libraryrelease/restore_dispatch_activation.go @@ -0,0 +1,230 @@ +package libraryrelease + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "time" +) + +// 恢复派发激活证据(DS01-F3,协议版本 2)。 +// +// 配置开关、"三个非空字符串"或调用方自填的 `stopped=true` 都不是独占证明。v2 证据 +// 只允许**指向**一份由维护窗口写下的 journal:调用方声明目标身份、维护作业、journal +// 文件名/摘要与受控 writer 的不可变实例身份;真正的事实(入口关闭与排空、后台静默、 +// 每个 writer 的退出观察)由 Store 直接读 journal 字节并解析取得,再用治理库的 +// library_instance_maintenance 行把作业/实例/指纹/writer 集合钉死。 +// +// 因此"把调用方 JSON 再 hash 一次"不再算核实:摘要只证明"读到的是这一份 journal", +// 事实来自 journal 本体与治理库行,而不是调用方的布尔字段。 +// +// 边界:代码能核验 journal 完整性、目标/实例/治理库/构建身份、writer 集合一致性与 +// 新鲜度;它不独立观测"外部 writer 此刻没在运行",但 journal 的入口 drain( +// active_at_close=0)、quiesce 零点与退出码是维护链自己的受控观察,且窗口必须仍处于 +// held(已恢复/释放的窗口不构成"旧 writer 已停"的证据)。 + +const RestoreDispatchActivationMaxAge = 2 * time.Hour + +// 证据文档 schema 版本与语义兼容批次是两件事: +// - ProtocolVersion:这份 JSON 的字段形状(解析契约); +// - ProtocolEpoch:派发协议语义批次;不同批次必须重新登记。它只约束派发语义, +// 不能证明某个构建 SHA 属于该批次 —— 当前构建身份仍精确绑定运行 SHA,跨 SHA +// 自动兼容在没有受信批次成员证明前保持关闭。 +// +// 构建身份用完整 40 位 SHA,不用 display:开发号会随提交数变化,两个不同二进制 +// 完全可能都叫 0.1.322。 +const RestoreDispatchActivationProtocolVersion = 3 + +const RestoreDispatchProtocolEpoch = 3 + +// RestoreDispatchGovernanceAuthority 是治理库的**权威域**身份:系统标识(集群) +// 加库 OID。只看 current_database() 无法区分"同名但另一个集群/另一份克隆"。 +// primary 由 Store 现场读 pg_is_in_recovery() 得出,不采信调用方声明。 +type RestoreDispatchGovernanceAuthority struct { + SystemIdentifier string `json:"system_identifier"` + DatabaseOID string `json:"database_oid"` +} + +// RestoreDispatchWriterDrain 是调用方对"旧 writer 集合"的声明:只给身份,不给结论。 +// InstanceID 必须等于 journal 里登记的不可变 writer 身份(容器/进程 ID)。 +type RestoreDispatchWriterDrain struct { + Name string `json:"name"` + Kind string `json:"kind"` + InstanceID string `json:"instance_id"` +} + +type RestoreDispatchActivationEvidence struct { + ProtocolVersion int `json:"protocol_version"` + ProtocolEpoch int `json:"protocol_epoch"` + TargetIdentity string `json:"target_identity"` + // TargetFingerprint 是维护窗口/部署目标指纹(journal 与治理库维护行记录的那一个); + // RestoreTargetFingerprint 是激活时对恢复目标内容/索引/桶的实时观察值。两者是不同层, + // 不能相互替代:前者绑定"动的是哪个实例",后者绑定"恢复要写的那个目标身份"。 + TargetFingerprint string `json:"target_fingerprint"` + RestoreTargetFingerprint string `json:"restore_target_fingerprint"` + TargetInstance string `json:"target_instance"` + GovernanceDatabase string `json:"governance_database"` + GovernanceAuthority RestoreDispatchGovernanceAuthority `json:"governance_authority"` + ProtocolBuild string `json:"protocol_build"` + ProtocolBuildSHA string `json:"protocol_build_sha"` + AttestedBy string `json:"attested_by"` + AttestedAt time.Time `json:"attested_at"` + MaintenanceJob string `json:"maintenance_job"` + MaintenanceJournal string `json:"maintenance_journal"` + MaintenanceJournalSHA256 string `json:"maintenance_journal_sha256"` + Writers []RestoreDispatchWriterDrain `json:"writers"` +} + +func (e RestoreDispatchActivationEvidence) Validate(now time.Time, maxAge time.Duration) error { + if e.ProtocolVersion != RestoreDispatchActivationProtocolVersion { + return fmt.Errorf("restore dispatch activation protocol version %d is not supported", e.ProtocolVersion) + } + // 兼容批次不同 = 派发语义不兼容:即使 display 相同也不能共用激活证据。 + if e.ProtocolEpoch != RestoreDispatchProtocolEpoch { + return fmt.Errorf("restore dispatch activation protocol epoch %d is not compatible with %d", + e.ProtocolEpoch, RestoreDispatchProtocolEpoch) + } + for name, value := range map[string]string{ + "target identity": e.TargetIdentity, "target fingerprint": e.TargetFingerprint, + "restore target fingerprint": e.RestoreTargetFingerprint, + "target instance": e.TargetInstance, "governance database": e.GovernanceDatabase, + "protocol build": e.ProtocolBuild, "attested by": e.AttestedBy, + "maintenance job": e.MaintenanceJob, "maintenance journal": e.MaintenanceJournal, + "maintenance journal digest": e.MaintenanceJournalSHA256, + } { + if strings.TrimSpace(value) == "" { + return fmt.Errorf("restore dispatch activation evidence lacks %s", name) + } + } + // 构建身份必须是完整 SHA;display 可以随提交数变化,不能作为身份。 + if !isFullSHA(e.ProtocolBuildSHA) { + return errors.New("restore dispatch activation build identity is not a full 40-character commit sha") + } + // 治理权威域必须是可读回的 PG 事实形状:集群系统标识 + 库 OID,两个都是十进制数字。 + if !isDecimal(e.GovernanceAuthority.SystemIdentifier) || !isDecimal(e.GovernanceAuthority.DatabaseOID) { + return errors.New("restore dispatch activation governance authority is not a cluster/database identity") + } + if !isHex64(e.TargetFingerprint) || !isHex64(e.RestoreTargetFingerprint) { + return errors.New("restore dispatch activation target fingerprints are not sha256 hex strings") + } + if !isHex64(e.MaintenanceJournalSHA256) { + return errors.New("restore dispatch activation maintenance journal digest is not a sha256 hex string") + } + if !validActivationID(e.MaintenanceJob) { + return errors.New("restore dispatch activation maintenance job id is invalid") + } + // journal 只能按作业名定位在同一受信根目录里;带路径分隔符/相对引用会绕开 + // Store 配置的证据根,让"来源"变成调用方随手给的任意文件。 + if e.MaintenanceJournal != e.MaintenanceJob+".json" { + return errors.New("restore dispatch activation maintenance journal is not the job journal") + } + if len(e.Writers) == 0 || len(e.Writers) > 256 { + return errors.New("restore dispatch activation lists no controlled writers") + } + names := map[string]bool{} + instances := map[string]bool{} + for _, writer := range e.Writers { + if strings.TrimSpace(writer.Name) == "" || strings.TrimSpace(writer.Kind) == "" || + strings.TrimSpace(writer.InstanceID) == "" { + return errors.New("restore dispatch activation writer lacks name, kind or instance id") + } + if !validActivationID(writer.InstanceID) { + return errors.New("restore dispatch activation writer instance id is invalid") + } + if names[writer.Name] { + return fmt.Errorf("restore dispatch activation writer %s is listed twice", writer.Name) + } + names[writer.Name] = true + if instances[writer.InstanceID] { + return fmt.Errorf("restore dispatch activation writer instance %s is listed twice", writer.InstanceID) + } + instances[writer.InstanceID] = true + } + if e.AttestedAt.IsZero() || e.AttestedAt.After(now.Add(5*time.Minute)) { + return errors.New("restore dispatch activation attestation time is not credible") + } + if maxAge <= 0 { + maxAge = RestoreDispatchActivationMaxAge + } + if now.Sub(e.AttestedAt) > maxAge { + return fmt.Errorf("restore dispatch activation evidence is older than %s", maxAge) + } + return nil +} + +// LoadRestoreDispatchActivationEvidence 读取并核验证据文件字节摘要。expectedDigest 必须 +// 与文件实际 sha256 相同;不接受"文件里写的摘要"。 +func LoadRestoreDispatchActivationEvidence(path, expectedDigest string, now time.Time, maxAge time.Duration) (RestoreDispatchActivationEvidence, error) { + var evidence RestoreDispatchActivationEvidence + if strings.TrimSpace(path) == "" || strings.TrimSpace(expectedDigest) == "" { + return evidence, errors.New("restore dispatch activation requires an evidence file and its digest") + } + raw, err := os.ReadFile(path) + if err != nil { + return evidence, fmt.Errorf("read restore dispatch activation evidence: %w", err) + } + sum := sha256.Sum256(raw) + if got := hex.EncodeToString(sum[:]); got != strings.ToLower(strings.TrimSpace(expectedDigest)) { + return evidence, errors.New("restore dispatch activation evidence digest does not match the file") + } + decoder := json.NewDecoder(strings.NewReader(string(raw))) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&evidence); err != nil { + return RestoreDispatchActivationEvidence{}, fmt.Errorf("parse restore dispatch activation evidence: %w", err) + } + if err := evidence.Validate(now, maxAge); err != nil { + return RestoreDispatchActivationEvidence{}, err + } + return evidence, nil +} + +// CanonicalBytes 是写入台账的规范字节(同一份证据只有一种序列化)。 +func (e RestoreDispatchActivationEvidence) CanonicalBytes() ([]byte, error) { + return json.Marshal(e) +} + +func isHex64(value string) bool { + if len(value) != 64 || strings.ToLower(value) != value { + return false + } + _, err := hex.DecodeString(value) + return err == nil +} + +func isFullSHA(value string) bool { + if len(value) != 40 || strings.ToLower(value) != value { + return false + } + _, err := hex.DecodeString(value) + return err == nil +} + +func isDecimal(value string) bool { + if value == "" || len(value) > 20 { + return false + } + for _, r := range value { + if r < '0' || r > '9' { + return false + } + } + return true +} + +// validActivationID 与维护 journal 的作业/服务 ID 同一字符集:证据里出现的身份 +// 必须能原样出现在 journal 中,不能靠空格/路径字符制造"看起来不同"的别名。 +func validActivationID(value string) bool { + if len(value) == 0 || len(value) > 128 { + return false + } + for _, r := range value { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_') { + return false + } + } + return true +} diff --git a/internal/libraryrelease/writeset.go b/internal/libraryrelease/writeset.go new file mode 100644 index 0000000..6ad0126 --- /dev/null +++ b/internal/libraryrelease/writeset.go @@ -0,0 +1,382 @@ +package libraryrelease + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "sort" + "strconv" + "time" +) + +// WriteSetVersion 是写集合台账的格式版本。读到的版本不认识就拒绝恢复: +// 宁可保持维护,也不要用一份"格式变了但看起来还能读"的记录去删目标数据。 +const WriteSetVersion = 1 + +// MigrationWriteSetVersion rejects reinterpretation by old V1 executors. +const MigrationWriteSetVersion = 2 + +// WriteSetKindRestoreDrill marks a write set that authorizes only a recovery +// drill: canary rows plus a zero-object/zero-index execution plan. It shares +// the V2 envelope so the object gateway controller can verify it, but it is +// never a publish plan and must not be adopted as one. +const WriteSetKindRestoreDrill = "restore-drill" + +// WriteSetRow 是台账里的一行:本次发布明确要写的精确身份 + 写前状态。 +// +// 为什么需要"写前状态":恢复不能在目标里按"没人引用"推断残渣。历史孤儿资源、 +// 同租户另一个知识库暂未绑定的资源、被多个知识库共享的资源,都满足"没人引用", +// 但它们不是这次作业写的,删掉就是数据丢失(快照里没有这些行,恢复不回来)。 +// 只有写前不存在、且由本次写进去的行才允许清理。 +type WriteSetRow struct { + Table string `json:"table"` + ID string `json:"id"` + // Existing 表示写前目标里已经有这一行(属于目标自己的数据,恢复一律不许删)。 + Existing bool `json:"existing"` + // Owner 是写前该行的归属("/"),不存在时为空。 + Owner string `json:"owner,omitempty"` + // Reused 表示这一行虽然写前就在目标里、却不在预备份范围内,但已经用 + // "持久作业/快照证据 + 整行内容 + 对象字节"证明与本次要写的内容完全一致, + // 因此本次既不重写它、也不在恢复时清理它。 + // + // 不能只因为"它没被任何绑定/正文引用"就当成自己的:历史孤儿、同租户另一个 + // 知识库暂未绑定的资源同样满足"没人引用",覆盖或删除同样是数据丢失。 + Reused bool `json:"reused,omitempty"` + // ReuseEvidence 是可复用证据文档的摘要(reuse/.json),独立于写集合, + // 防止把这次推断伪装成历史台账。 + ReuseEvidence string `json:"reuse_evidence,omitempty"` +} + +// WriteSetPlan 是调用方在写第一笔之前交给目标的信息:绑定作业、目标、预备份与快照, +// 以及预备份时刻的整实例证据。 +type WriteSetPlan struct { + JobID string + Target string + BackupSnapshotID string + TargetSnapshotID string + Universe map[string]TableFingerprint + // PriorSnapshots 是治理库里"这个目标的持久来源":成功同步过的快照,以及这个 + // 目标自己的预备份。资源复用必须沿它把来源追到真实登记过的快照,而不是按 + // "目标里没人引用"推断归属。 + PriorSnapshots []PriorSnapshot +} + +// 复用来源的两种合法类别。 +const ( + // PriorSnapshotSync:这个目标成功同步过这份快照(且登记了生效版本)。 + PriorSnapshotSync = "sync" + // PriorSnapshotPrebackup:这份快照是从这个目标自己身上拍的预备份,把它写回去 + // 就是回到本目标的历史状态。 + PriorSnapshotPrebackup = "prebackup" +) + +// PriorSnapshot 是一次**已登记**的来源:作业身份 + 快照身份 + 来源类别。 +// 只有它也含有同一个资源 ID、且行内容完全一致,才允许把目标里那行当作 +// "本次写入的等价物"。 +type PriorSnapshot struct { + JobID string `json:"job_id"` + SnapshotID string `json:"snapshot_id"` + Kind string `json:"kind"` + FinishedAt time.Time `json:"finished_at,omitempty"` +} + +// WriteSet 是"这一次发布的写集合 + 写前整实例内容证据",内容寻址、可校验、 +// 与 job/target/backup 绑定。恢复只读它,不读目标现状去推断。 +// LocalIDMapping is operation-local source lineage. Decimal strings are used +// only inside this typed sidecar; archived row values remain JSON integers. +type LocalIDMapping struct { + Table string `json:"table"` + Column string `json:"column"` + Source string `json:"source"` + Target string `json:"target"` +} + +type WriteSet struct { + // Kind 区分发布执行计划与受限演练恢复计划。空值 = 历史发布计划。 + // 演练计划必须显式为 restore-drill:它只授权 canary 回放,不含对象/索引 + // 写项,读取方不能把它当发布计划接管。 + Kind string `json:"kind,omitempty"` + // TargetIDMode 记录这份计划是否把源身份映射成目标隔离身份,以及用哪套算法。 + // 空值 = 历史计划/写前镜像:按原 ID 回放,绝不能在恢复时二次映射。 + TargetIDMode string `json:"target_id_mode,omitempty"` + Index []IndexWrite `json:"index,omitempty"` + Objects []ObjectWrite `json:"objects,omitempty"` + SchemaDigest string `json:"schema_digest,omitempty"` + ContractVersion int `json:"contract_version,omitempty"` + SourceTenantID uint64 `json:"source_tenant_id,omitempty"` + SourceKnowledgeBaseID string `json:"source_knowledge_base_id,omitempty"` + LocalIDs []LocalIDMapping `json:"local_ids,omitempty"` + Version int `json:"version"` + JobID string `json:"job_id"` + Target string `json:"target"` + TenantID uint64 `json:"tenant_id"` + KnowledgeBaseID string `json:"knowledge_base_id"` + BackupSnapshotID string `json:"backup_snapshot_id"` + TargetSnapshotID string `json:"target_snapshot_id"` + CreatedAt time.Time `json:"created_at"` + Rows []WriteSetRow `json:"rows"` + Universe map[string]TableFingerprint `json:"universe"` + // Digest 是对除本字段外全部内容的 sha256:落盘文件名与治理库里的引用都用它, + // 记录被改一个字节就对不上。 + Digest string `json:"digest"` +} + +// ValidateRestoreBinding 是恢复身份合同(DS01):写集合必须绑定**本次**预备份、 +// 同一目标 tenant/KB,且来源快照(要回放到目标的内容身份)与写前镜像不能是同一份。 +// 它是 ProductionLibraryTarget.Restore 在建任何派发绑定之前调用的同一个判定: +// 演练的写前/来源身份也必须过这一关,不能靠调用方约定。 +func (w WriteSet) ValidateRestoreBinding(snapshotID string, tenantID uint64, knowledgeBaseID string) error { + if snapshotID == "" { + return errors.New("恢复需要绑定的预备份快照") + } + if w.BackupSnapshotID != snapshotID { + return fmt.Errorf("写集合记录绑定的是预备份 %s,不是 %s", w.BackupSnapshotID, snapshotID) + } + if w.TenantID != tenantID || w.KnowledgeBaseID != knowledgeBaseID { + return fmt.Errorf("写集合记录绑定的是 %d/%s,与目标 %d/%s 不一致", + w.TenantID, w.KnowledgeBaseID, tenantID, knowledgeBaseID) + } + // 派发绑定只能来自原锚点:来源快照是发布基线,backup 是这份写集的写前镜像。 + // 二者缺失或相同都说明装配没有拿到真实身份,必须在任何写之前失败关闭。 + if w.TargetSnapshotID == "" || snapshotID == "" { + return errors.New("恢复缺少来源快照或写前镜像,拒绝建立派发绑定") + } + if w.TargetSnapshotID == snapshotID { + return errors.New("来源快照与写前镜像不能是同一份快照,拒绝建立派发绑定") + } + return nil +} + +// Seal 把行序规范化为可复现的顺序并写入摘要。调用方在落盘与登记之前必须先 Seal。 +// 排序在这里落地(而不是只在算摘要时排),否则落盘字节与摘要覆盖的内容不一致。 +func (w *WriteSet) Seal() error { + sort.Slice(w.Rows, func(i, j int) bool { + if w.Rows[i].Table != w.Rows[j].Table { + return w.Rows[i].Table < w.Rows[j].Table + } + return w.Rows[i].ID < w.Rows[j].ID + }) + digest, err := w.computeDigest() + if err != nil { + return err + } + w.Digest = digest + return nil +} + +// CanonicalBytes 是不含摘要字段的规范字节:摘要覆盖的就是它,落盘文件另外 +// 带上摘要本身(便于自描述),读回时用同一份规范字节重新推导。 +func (w WriteSet) CanonicalBytes() ([]byte, error) { + if w.Version == WriteSetVersion && (w.ContractVersion != 0 || w.SourceTenantID != 0 || w.SourceKnowledgeBaseID != "" || len(w.LocalIDs) != 0 || w.SchemaDigest != "" || len(w.Objects) != 0 || len(w.Index) != 0) { + return nil, errors.New("historical V1 cannot carry migration contract fields") + } + if w.Version != WriteSetVersion && w.Version != MigrationWriteSetVersion { + return nil, errors.New("unsupported write set format") + } + copied := w + copied.Digest = "" + rows := make([]WriteSetRow, len(w.Rows)) + copy(rows, w.Rows) + // 行序不影响语义但影响摘要:两边都按 (table,id) 排序才能算出同一个值。 + sort.Slice(rows, func(i, j int) bool { + if rows[i].Table != rows[j].Table { + return rows[i].Table < rows[j].Table + } + return rows[i].ID < rows[j].ID + }) + copied.Rows = rows + raw, err := json.Marshal(copied) + if err != nil { + return nil, fmt.Errorf("编码写集合失败: %w", err) + } + return raw, nil +} + +func (w *WriteSet) computeDigest() (string, error) { + raw, err := w.CanonicalBytes() + if err != nil { + return "", err + } + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]), nil +} + +// Verify 校验摘要与必备身份。缺任一身份都必须失败:没有绑定就没有"这份记录属于 +// 这个作业/目标/预备份"的证明,拿它去删目标数据无法追责。 +const ( + // TargetIDModeScoped 是目标隔离身份的持久契约标识。 + // 算法是自定义的 sha256(namespace|tenant|kb|table|source) 16 字节派生, + // 只保证确定性与隔离,不自称标准 UUIDv5。 + TargetIDModeScoped = "scoped-sha256-v1" +) + +func (w *WriteSet) Verify() error { + if w.TargetIDMode != "" && w.TargetIDMode != TargetIDModeScoped { + return fmt.Errorf("unsupported target id mode %q", w.TargetIDMode) + } + if w.TargetIDMode == TargetIDModeScoped && (w.TenantID == 0 || w.KnowledgeBaseID == "") { + return errors.New("target id mode lacks target identity") + } + if w.ContractVersion != 0 && w.ContractVersion != 1 { + return errors.New("unsupported migration contract version") + } + if len(w.LocalIDs) > 0 && (w.ContractVersion != 1 || w.SourceTenantID == 0 || w.SourceKnowledgeBaseID == "") { + return errors.New("local mapping lacks source contract binding") + } + sources, targets := map[string]bool{}, map[string]bool{} + for _, m := range w.LocalIDs { + valid := (m.Table == "chunks" || m.Table == "knowledge_tags") && m.Column == "seq_id" || m.Table == "wiki_log_entries" && m.Column == "id" + a, e1 := strconv.ParseInt(m.Source, 10, 64) + b, e2 := strconv.ParseInt(m.Target, 10, 64) + if !valid || e1 != nil || e2 != nil || a <= 0 || b <= 0 || strconv.FormatInt(a, 10) != m.Source || strconv.FormatInt(b, 10) != m.Target { + return errors.New("invalid typed local mapping") + } + source, target := m.Table+"/"+m.Source, m.Table+"/"+m.Target + if sources[source] || targets[target] { + return errors.New("duplicate typed local mapping") + } + sources[source] = true + targets[target] = true + } + if w.Version != WriteSetVersion && w.Version != MigrationWriteSetVersion { + return fmt.Errorf("写集合记录版本 %d 不受支持(当前 %d)", w.Version, WriteSetVersion) + } + if w.Kind != "" && w.Kind != WriteSetKindRestoreDrill { + return fmt.Errorf("写集合记录种类 %q 不受支持", w.Kind) + } + if w.Kind == WriteSetKindRestoreDrill { + // 演练恢复计划只回放写前镜像:不新建对象、不按发布计划改索引、不做本地 ID 映射。 + // 任何一项非空都说明它被当成发布计划构造/改写过,拒绝。 + if w.Version != MigrationWriteSetVersion || w.ContractVersion != 1 || len(w.SchemaDigest) != 64 { + return errors.New("演练恢复计划缺少可执行契约(V2 + contract 1 + schema 摘要)") + } + if len(w.Objects) != 0 || len(w.Index) != 0 || len(w.LocalIDs) != 0 { + return errors.New("演练恢复计划不得包含对象/索引/本地映射写项") + } + if w.SourceTenantID == 0 || w.SourceKnowledgeBaseID == "" { + return errors.New("演练恢复计划缺少来源身份") + } + } + if w.JobID == "" || w.BackupSnapshotID == "" || w.TargetSnapshotID == "" { + return errors.New("写集合记录缺少作业/预备份/快照绑定") + } + if w.TenantID == 0 || w.KnowledgeBaseID == "" { + return errors.New("写集合记录缺少目标范围身份") + } + if len(w.Universe) == 0 { + return errors.New("写集合记录缺少整实例内容证据") + } + if w.Digest == "" { + return errors.New("写集合记录没有摘要") + } + for _, row := range w.Rows { + if row.Reused && !row.Existing { + return fmt.Errorf("写集合记录把 %s/%s 标成可复用却不是写前已存在行", row.Table, row.ID) + } + if row.Reused && row.ReuseEvidence == "" { + return fmt.Errorf("写集合记录把 %s/%s 标成可复用却没有证据摘要", row.Table, row.ID) + } + } + digest, err := w.computeDigest() + if err != nil { + return err + } + if digest != w.Digest { + return errors.New("写集合记录摘要不符(内容被改动或截断)") + } + return nil +} + +// IsRestoreDrill 表示这是一份受限演练恢复计划,而不是发布执行计划。 +func (w WriteSet) IsRestoreDrill() bool { return w.Kind == WriteSetKindRestoreDrill } + +// CreatedIDs 返回"本次新建"的精确身份(写前不存在的行)。恢复只允许删这些。 +func (w WriteSet) CreatedIDs(table string) []string { + ids := make([]string, 0, 8) + for _, row := range w.Rows { + if row.Table == table && !row.Existing { + ids = append(ids, row.ID) + } + } + sort.Strings(ids) + return ids +} + +// ExistingIDs 返回写前已存在的身份(用于恢复后复核"目标自己的行都还在")。 +func (w WriteSet) ExistingIDs(table string) []string { + ids := make([]string, 0, 8) + for _, row := range w.Rows { + if row.Table == table && row.Existing { + ids = append(ids, row.ID) + } + } + sort.Strings(ids) + return ids +} + +// ReusedIDs 返回本次"证明可复用、因此既不重写也不清理"的精确身份。 +// 它与 CreatedIDs 互斥,恢复清理一律不看这里(复用行必须原样保留)。 +func (w WriteSet) ReusedIDs(table string) []string { + ids := make([]string, 0, 8) + for _, row := range w.Rows { + if row.Table == table && row.Reused { + ids = append(ids, row.ID) + } + } + sort.Strings(ids) + return ids +} + +// UniverseDigest 是整实例证据的摘要,随台账一起登记,便于独立核对。 +func (w WriteSet) UniverseDigest() string { + if len(w.Universe) == 0 { + return "" + } + tables := make([]string, 0, len(w.Universe)) + for table := range w.Universe { + tables = append(tables, table) + } + sort.Strings(tables) + type pair struct { + Count int64 `json:"count"` + Digest string `json:"digest"` + } + ordered := make([]pair, 0, len(tables)) + for _, table := range tables { + ordered = append(ordered, pair{Count: w.Universe[table].Count, Digest: w.Universe[table].Digest}) + } + raw, err := json.Marshal(struct { + Tables []string `json:"tables"` + Values []pair `json:"values"` + }{Tables: tables, Values: ordered}) + if err != nil { + return "" + } + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]) +} + +// WriteSetPlanner 由能访问目标与归档的实现提供:它在写第一笔之前算出写集合、 +// 拒绝跨范围 ID 冲突,并把记录落盘。失败即"一笔都不许写"。 +type WriteSetPlanner interface { + PlanWriteSet(ctx context.Context, plan WriteSetPlan) (WriteSet, error) +} + +// WriteSetAdopter 让"计划已经存在"的执行也能带上复用语义(F07)。 +// +// 触发场景:首次 planner 证明某些 resources 可复用 → 写集合落盘 → 进程中断 → 接管时用 +// **新进程/新 target** 继续。写集合已存在,planner 因此被跳过;如果执行目标不消费这份 +// 计划,它会按"没有复用"重新 upsert 资源行并重传对象——账本说"共享对象没动",实际却 +// 重写了共享对象。必须显式接管计划,而不是重新按半写现状计划一遍。 +type WriteSetAdopter interface { + AdoptWriteSet(set WriteSet) error +} + +// WriteSetObserver 让调用方在写第一笔之前把写集合摘要持久化到治理库。 +// 失败同样意味着"一笔都不许写":没有可追溯的写集合,恢复就只能靠推断。 +type WriteSetObserver interface { + WriteSetPlanned(ctx context.Context, set WriteSet) error +} diff --git a/internal/libraryrelease/writeset_test.go b/internal/libraryrelease/writeset_test.go new file mode 100644 index 0000000..e794308 --- /dev/null +++ b/internal/libraryrelease/writeset_test.go @@ -0,0 +1,166 @@ +package libraryrelease + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +func sampleWriteSet() WriteSet { + return WriteSet{Version: WriteSetVersion, JobID: "job-1", Target: "internal", TenantID: 10001, + KnowledgeBaseID: "kb", BackupSnapshotID: "backup-1", TargetSnapshotID: "snap-1", + CreatedAt: time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC), + Rows: []WriteSetRow{ + {Table: "resources", ID: "res-new"}, + {Table: "knowledges", ID: "doc-existing", Existing: true, Owner: "10001/kb"}, + {Table: "resources", ID: "res-old", Existing: true, Owner: "10001/"}, + }, + Universe: map[string]TableFingerprint{"resources": {Count: 2, Digest: "abc"}}} +} + +func TestWriteSetSealVerifyRoundTrip(t *testing.T) { + set := sampleWriteSet() + if err := set.Seal(); err != nil { + t.Fatal(err) + } + if set.Digest == "" { + t.Fatal("seal must produce a digest") + } + if err := set.Verify(); err != nil { + t.Fatalf("sealed record must verify: %v", err) + } + // 行序不影响摘要:换序后重新 Sealed 必须得到同一个值(落盘/读回才可比)。 + shuffled := sampleWriteSet() + shuffled.Rows[0], shuffled.Rows[2] = shuffled.Rows[2], shuffled.Rows[0] + if err := shuffled.Seal(); err != nil { + t.Fatal(err) + } + if shuffled.Digest != set.Digest { + t.Fatalf("digest must not depend on row order: %s vs %s", shuffled.Digest, set.Digest) + } + // 序列化往返(落盘再读回)必须仍然通过校验。 + raw, err := json.Marshal(shuffled) + if err != nil { + t.Fatal(err) + } + var reloaded WriteSet + if err := json.Unmarshal(raw, &reloaded); err != nil { + t.Fatal(err) + } + if err := reloaded.Verify(); err != nil { + t.Fatalf("record read back from disk must verify: %v", err) + } +} + +func TestWriteSetVerifyRejectsTamperingAndMissingEvidence(t *testing.T) { + cases := map[string]func(*WriteSet){ + "内容被改": func(set *WriteSet) { + set.Rows[0].ID = "res-other" + }, + "换租户": func(set *WriteSet) { + set.TenantID = 20000 + }, + "整实例证据被清空": func(set *WriteSet) { + set.Universe = nil + }, + "缺预备份绑定": func(set *WriteSet) { + set.BackupSnapshotID = "" + }, + "缺摘要": func(set *WriteSet) { + set.Digest = "" + }, + "版本不认识": func(set *WriteSet) { + set.Version = 99 + }, + } + for name, mutate := range cases { + set := sampleWriteSet() + if err := set.Seal(); err != nil { + t.Fatal(err) + } + mutate(&set) + if err := set.Verify(); err == nil { + t.Fatalf("%s:必须校验失败", name) + } + } +} + +func TestWriteSetCreatedIDsOnlyCoversRowsCreatedByThisRelease(t *testing.T) { + set := sampleWriteSet() + if err := set.Seal(); err != nil { + t.Fatal(err) + } + created := set.CreatedIDs("resources") + if len(created) != 1 || created[0] != "res-new" { + t.Fatalf("created resources = %v, want [res-new](写前已存在的资源绝不能被当成残渣)", created) + } + if strings.Join(set.ExistingIDs("resources"), ",") != "res-old" { + t.Fatalf("existing resources = %v", set.ExistingIDs("resources")) + } + if set.UniverseDigest() == "" { + t.Fatal("universe digest must be derived from the whole-instance evidence") + } +} + +// 复用行是"写前已存在 + 有证据摘要"的一种:既不算本次新建(恢复不许删), +// 也不能没有证据摘要,更不能被标成新建。 +func TestWriteSetReusedRowsStayOutOfCleanupAndRequireEvidence(t *testing.T) { + set := WriteSet{Version: WriteSetVersion, JobID: "job-2", Target: "internal", TenantID: 10001, + KnowledgeBaseID: "kb", BackupSnapshotID: "backup-2", TargetSnapshotID: "snap-2", + CreatedAt: time.Date(2026, 10, 30, 1, 0, 0, 0, time.UTC), + Rows: []WriteSetRow{ + {Table: "resources", ID: "res-reused", Existing: true, Owner: "10001/", Reused: true, ReuseEvidence: "digest-1"}, + {Table: "resources", ID: "res-new"}, + }, + Universe: map[string]TableFingerprint{"resources": {Count: 3, Digest: "abc"}}} + if err := set.Seal(); err != nil { + t.Fatal(err) + } + if err := set.Verify(); err != nil { + t.Fatalf("复用行必须能通过校验: %v", err) + } + if created := set.CreatedIDs("resources"); len(created) != 1 || created[0] != "res-new" { + t.Fatalf("复用行被当成本次新建(恢复会删掉它):%v", created) + } + if reused := set.ReusedIDs("resources"); len(reused) != 1 || reused[0] != "res-reused" { + t.Fatalf("reused resources = %v", reused) + } + + noEvidence := set + noEvidence.Rows = append([]WriteSetRow{}, set.Rows...) + for index := range noEvidence.Rows { + if noEvidence.Rows[index].ID == "res-reused" { + noEvidence.Rows[index].ReuseEvidence = "" + } + } + if err := noEvidence.Seal(); err != nil { + t.Fatal(err) + } + if err := noEvidence.Verify(); err == nil { + t.Fatal("复用行没有证据摘要时必须校验失败") + } + + notExisting := set + notExisting.Rows = append([]WriteSetRow{}, set.Rows...) + for index := range notExisting.Rows { + if notExisting.Rows[index].ID == "res-reused" { + notExisting.Rows[index].Existing = false + } + } + if err := notExisting.Seal(); err != nil { + t.Fatal(err) + } + if err := notExisting.Verify(); err == nil { + t.Fatal("复用行必须同时是写前已存在行(否则会被恢复当残渣)") + } + + // 旧记录(没有复用字段)仍然必须能读回:格式演进不能把历史台账判成损坏。 + legacy := sampleWriteSet() + if err := legacy.Seal(); err != nil { + t.Fatal(err) + } + if err := legacy.Verify(); err != nil { + t.Fatalf("历史写集合记录必须继续有效: %v", err) + } +} diff --git a/internal/libraryrelease/writeset_version_contract_test.go b/internal/libraryrelease/writeset_version_contract_test.go new file mode 100644 index 0000000..0be15f9 --- /dev/null +++ b/internal/libraryrelease/writeset_version_contract_test.go @@ -0,0 +1,43 @@ +package libraryrelease + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "testing" +) + +// Literal canonical bytes follow d0c6d57's V1 field order, not today's struct. +const historicalV1Canonical = `{"version":1,"job_id":"job-v1","target":"internal","tenant_id":10001,"knowledge_base_id":"kb-target","backup_snapshot_id":"before","target_snapshot_id":"source","created_at":"2026-01-01T00:00:00Z","rows":[],"universe":{"chunks":{"count":0,"digest":"empty"}},"digest":""}` + +func TestContractHistoricalV1CanonicalBytesFrozen(t *testing.T) { + var set WriteSet + if err := json.Unmarshal([]byte(historicalV1Canonical), &set); err != nil { + t.Fatal(err) + } + raw, err := set.CanonicalBytes() + if err != nil { + t.Fatal(err) + } + if string(raw) != historicalV1Canonical { + t.Fatalf("V1 bytes changed: %s", raw) + } + hash := sha256.Sum256([]byte(historicalV1Canonical)) + set.Digest = hex.EncodeToString(hash[:]) + if err := set.Verify(); err != nil { + t.Fatal(err) + } +} + +func TestContractV1CannotCarryNewExecutionSemantics(t *testing.T) { + var set WriteSet + if err := json.Unmarshal([]byte(historicalV1Canonical), &set); err != nil { + t.Fatal(err) + } + set.ContractVersion = 1 + set.SourceTenantID = 10000 + set.SourceKnowledgeBaseID = "source" + if err := set.Seal(); err == nil { + t.Fatal("new execution fields were sealed as historical V1") + } +} diff --git a/internal/librarysnapshot/archive.go b/internal/librarysnapshot/archive.go index d13c21f..5a7dc6e 100644 --- a/internal/librarysnapshot/archive.go +++ b/internal/librarysnapshot/archive.go @@ -10,7 +10,7 @@ import ( "encoding/json" "errors" "io" - "knowledge-governance/internal/releasebundle" + "knowledge-governance/internal/libraryprofile" "math" "os" "path/filepath" @@ -57,6 +57,10 @@ type Archive struct { } func Open(root string, maxBlobBytes int64) (*Archive, error) { + return openArchive(root, maxBlobBytes, syncRoot) +} + +func openArchive(root string, maxBlobBytes int64, syncDirectory func(*os.Root) error) (*Archive, error) { if !filepath.IsAbs(root) || maxBlobBytes < 1 || maxBlobBytes == math.MaxInt64 { return nil, errors.New("invalid archive configuration") } @@ -94,6 +98,22 @@ func Open(root string, maxBlobBytes int64) (*Archive, error) { a.versions = sub } } + // File and child-directory fsync cannot persist their parent entries. The + // archive root links blobs/versions, and its parent links the archive itself. + if err := syncDirectory(r); err != nil { + a.Close() + return nil, err + } + parent, err := os.OpenRoot(filepath.Dir(root)) + if err != nil { + a.Close() + return nil, err + } + err = errors.Join(syncDirectory(parent), parent.Close()) + if err != nil { + a.Close() + return nil, err + } return a, nil } func (a *Archive) Close() error { @@ -282,6 +302,22 @@ func (a *Archive) countRows(p Part, resources map[string]bool) (int64, error) { } defer f.Close() dec := json.NewDecoder(io.LimitReader(f, a.maxBlobBytes+1)) + if p.Kind == "schema" { + var catalog map[string][]map[string]json.RawMessage + if err := dec.Decode(&catalog); err != nil || len(catalog) != 6 { + return 0, errors.New("invalid source schema catalog") + } + for _, key := range []string{"columns", "constraints", "indexes", "triggers", "relations", "sequences"} { + if rows, ok := catalog[key]; !ok || rows == nil { + return 0, errors.New("incomplete source schema catalog") + } + } + var extra any + if dec.Decode(&extra) != io.EOF { + return 0, errors.New("trailing source schema catalog data") + } + return 1, nil + } token, err := dec.Token() if err != nil || token != json.Delim('[') { return 0, errors.New("snapshot component must be a JSON row array") @@ -384,24 +420,29 @@ func encodeManifest(m Manifest) ([]byte, error) { return nil, errors.New("unsupported snapshot validation policy") } c := m.Compatibility - if c.WeKnoraVersion != releasebundle.WeKnoraVersionV071 || c.SchemaVersion != releasebundle.WeKnoraMigrationV071 || c.RetrieverEngine != "elasticsearch_v8" || !identifier(c.EmbeddingModel) || c.EmbeddingDimension != releasebundle.EmbeddingDimensionV071 || !validDigest(c.IndexMappingSHA256) { + // 兼容性按 schema 版本选 profile,而不是钉死 v0.7.1:未知版本必须拒绝, + // 已知版本还必须与自己的版本字符串、索引引擎、维度声明一致。 + profile, err := libraryprofile.For(c.SchemaVersion) + if err != nil || c.WeKnoraVersion != profile.WeKnoraVersion || c.RetrieverEngine != "elasticsearch_v8" || + !identifier(c.EmbeddingModel) || c.EmbeddingDimension < 1 || + (profile.EmbeddingDimension > 0 && c.EmbeddingDimension != profile.EmbeddingDimension) || + !validDigest(c.IndexMappingSHA256) { return nil, errors.New("unsupported snapshot compatibility contract") } if m.Format != Format || (m.Scope != "internal" && m.Scope != "external") || m.TenantID == 0 || !identifier(m.KnowledgeBaseID) || m.CreatedAt.IsZero() { return nil, errors.New("invalid library manifest identity") } + // 部件集合也来自 profile:0.9.0 的归档没有 wiki_log_entries 部件, + // 但 0.7.1 缺了它就是不完整。 + requiredKeys, _ := profile.PartKeys() required := map[string]bool{} - for _, n := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations"} { - required["database/"+n] = true + for _, key := range requiredKeys { + required[key] = true } - for _, n := range []string{"wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} { - required["wiki/"+n] = true - } - required["index/chunks"] = true seen := map[string]bool{} for _, p := range m.Parts { key := p.Kind + "/" + p.Name - if (!required[key] && !(p.Kind == "resource" && identifier(p.Name) && p.Count == 1)) || seen[key] || !validDigest(p.SHA256) || p.Bytes < 0 || p.Count < 0 { + if (!profile.AllowsPart(key) && !(p.Kind == "resource" && identifier(p.Name) && p.Count == 1) && !(key == "schema/migration-catalog" && p.Count == 1)) || seen[key] || !validDigest(p.SHA256) || p.Bytes < 0 || p.Count < 0 { return nil, errors.New("invalid or nonknowledge snapshot component") } seen[key] = true diff --git a/internal/librarysnapshot/archive_directory_durability_test.go b/internal/librarysnapshot/archive_directory_durability_test.go new file mode 100644 index 0000000..27962b8 --- /dev/null +++ b/internal/librarysnapshot/archive_directory_durability_test.go @@ -0,0 +1,40 @@ +package librarysnapshot + +import ( + "errors" + "os" + "testing" +) + +func TestArchiveOpenPersistsDirectoryEntriesAndPropagatesSyncFailure(t *testing.T) { + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + calls := 0 + archive, err := openArchive(root, 1024*1024, func(r *os.Root) error { calls++; return syncRoot(r) }) + if err != nil { + t.Fatal(err) + } + archive.Close() + if calls != 2 { + t.Fatalf("root and root-parent durability missing: sync calls=%d", calls) + } + for _, failAt := range []int{1, 2} { + injected := errors.New("directory fsync failed") + n := 0 + archive, err = openArchive(root, 1024*1024, func(r *os.Root) error { + n++ + if n == failAt { + return injected + } + return syncRoot(r) + }) + if !errors.Is(err, injected) || archive != nil { + if archive != nil { + archive.Close() + } + t.Fatal("directory fsync failure did not block archive publication", err) + } + } +} diff --git a/internal/librarysnapshot/archive_profile_test.go b/internal/librarysnapshot/archive_profile_test.go new file mode 100644 index 0000000..4894bdd --- /dev/null +++ b/internal/librarysnapshot/archive_profile_test.go @@ -0,0 +1,58 @@ +package librarysnapshot + +import ( + "strings" + "testing" + "time" +) + +// 归档部件的完整性按 schema 版本判定:0.9.0 没有 wiki_log_entries, +// 0.7.1 缺了它就是残包。这里直接对 manifest 编码做判定,不依赖数据库。 +func TestManifestPartSetFollowsSchemaProfile(t *testing.T) { + part := func(kind, name string) Part { + return Part{Kind: kind, Name: name, SHA256: strings.Repeat("a", 64), Count: 1} + } + parts := []Part{ + part("database", "knowledges"), part("database", "chunks"), part("database", "resources"), + part("database", "resource_bindings"), part("database", "knowledge_tags"), + part("database", "knowledge_tag_relations"), + part("wiki", "wiki_pages"), part("wiki", "wiki_folders"), part("wiki", "wiki_page_issues"), + part("index", "chunks"), + } + manifest := func(version int, weknora string, parts []Part) Manifest { + return Manifest{ + ValidationPolicy: ArtifactAcceptancePolicy, + Format: Format, + Scope: "internal", + TenantID: 10000, + KnowledgeBaseID: "kb-v090", + CreatedAt: time.Now().UTC(), + Parts: parts, + Compatibility: Compatibility{ + WeKnoraVersion: weknora, SchemaVersion: version, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "bge-m3", + EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("b", 64), + }, + } + } + + if _, err := encodeManifest(manifest(134, "v0.9.0", parts)); err != nil { + t.Fatalf("0.9.0 manifest without wiki_log_entries must be complete: %v", err) + } + if _, err := encodeManifest(manifest(74, "v0.7.1", parts)); err == nil || !strings.Contains(err.Error(), "incomplete") { + t.Fatalf("0.7.1 manifest missing wiki_log_entries must be refused, got %v", err) + } + withLog := append(append([]Part{}, parts...), part("wiki", "wiki_log_entries")) + if _, err := encodeManifest(manifest(74, "v0.7.1", withLog)); err != nil { + t.Fatalf("0.7.1 manifest with wiki_log_entries must pass: %v", err) + } + if _, err := encodeManifest(manifest(134, "v0.9.0", withLog)); err != nil { + t.Fatalf("0.9.0 manifest may still carry an optional wiki_log_entries part: %v", err) + } + if _, err := encodeManifest(manifest(74, "v0.9.0", withLog)); err == nil { + t.Fatal("version string and profile version must agree") + } + if _, err := encodeManifest(manifest(135, "v0.9.0", parts)); err == nil { + t.Fatal("unknown schema version must be refused") + } +} diff --git a/internal/librarysnapshot/transfer.go b/internal/librarysnapshot/transfer.go new file mode 100644 index 0000000..366565e --- /dev/null +++ b/internal/librarysnapshot/transfer.go @@ -0,0 +1,387 @@ +package librarysnapshot + +import ( + "archive/tar" + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "syscall" +) + +// 跨主机搬运一份已封存快照。 +// +// 为什么不是"把 versions/ 和 blobs/ 目录 rsync 过去": +// - 直接同步目录时,"版本清单先到、blob 还在路上"的瞬间看起来就是一份可用版本, +// 下一个发布作业会读到缺字节的档然后把失败记在目标身上; +// - 也不能只搬 blobs:清单之外的 blob 无法证明属于这份内容。 +// +// 所以搬运单位是"自描述包":清单先写、每个 blob 以 sha256 命名、下载侧边收边算, +// 只有全部齐了才把版本清单落位。版本清单文件就是提交点(见 Install 的注释)。 +const BundleFormat = "weknora-library-snapshot-bundle/v1" + +// 包内路径。清单带身份(文件名即快照 ID),blob 带内容身份(文件名即 sha256): +// 接收侧不需要额外的锁文件或元数据就能判断"这是什么、字节对不对"。 +const ( + bundleManifestPrefix = "manifest/" + bundleBlobPrefix = "blobs/" + maxBundleEntries = 200000 +) + +// BundleInfo 是一次导出的结果(CLI 打印它,父据此核对哈希)。 +type BundleInfo struct { + Format string `json:"format"` + Snapshot string `json:"snapshot"` + Parts int `json:"parts"` + Bytes int64 `json:"bytes"` + // Blobs 是逐个 blob 的 sha256 列表,便于在两台机器上对拍而不传大文件。 + Blobs []string `json:"blobs"` +} + +// Pack 把一份已封存版本导出成单文件包(tar)。 +// +// 导出前先 Load:它逐 blob 重算 sha256,所以"包里的每个字节都在这台机器上验证过"。 +// 导出后不删源,也不改归档。 +func (a *Archive) Pack(id, outPath string) (BundleInfo, error) { + if !validDigest(id) { + return BundleInfo{}, errors.New("invalid snapshot ID") + } + if !filepath.IsAbs(outPath) || filepath.Clean(outPath) != outPath { + return BundleInfo{}, errors.New("bundle path must be an absolute clean path") + } + manifest, err := a.Load(id) + if err != nil { + return BundleInfo{}, fmt.Errorf("snapshot is not verifiable on this host: %w", err) + } + manifestFile, err := regular(a.versions, id+".json", maxManifestBytes) + if err != nil { + return BundleInfo{}, err + } + manifestBytes, readErr := io.ReadAll(io.LimitReader(manifestFile, maxManifestBytes+1)) + manifestFile.Close() + if readErr != nil || int64(len(manifestBytes)) > maxManifestBytes || digest(manifestBytes) != id { + return BundleInfo{}, errors.New("snapshot manifest changed while packing") + } + if _, err := os.Lstat(outPath); err == nil { + return BundleInfo{}, errors.New("bundle already exists; refusing to overwrite") + } else if !errors.Is(err, os.ErrNotExist) { + return BundleInfo{}, errors.New("bundle path is not usable") + } + out, err := os.OpenFile(outPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if err != nil { + return BundleInfo{}, errors.New("create bundle") + } + cleanup := func(cause error) (BundleInfo, error) { + out.Close() + os.Remove(outPath) + return BundleInfo{}, cause + } + writer := tar.NewWriter(out) + writeEntry := func(name string, size int64, body io.Reader) error { + header := &tar.Header{Name: name, Mode: 0600, Size: size, Typeflag: tar.TypeReg} + if err := writer.WriteHeader(header); err != nil { + return err + } + _, err := io.CopyN(writer, body, size) + return err + } + // 清单必须第一个写:接收侧读到清单才知道后面应该有哪些 blob。 + if err := writeEntry(bundleManifestPrefix+id+".json", int64(len(manifestBytes)), bytes.NewReader(manifestBytes)); err != nil { + return cleanup(errors.New("write bundle manifest")) + } + info := BundleInfo{Format: BundleFormat, Snapshot: id, Parts: len(manifest.Parts)} + blobs := make([]string, 0, len(manifest.Parts)) + seen := map[string]bool{} + for _, part := range manifest.Parts { + if seen[part.SHA256] { + continue + } + seen[part.SHA256] = true + file, err := regular(a.blobs, part.SHA256, a.maxBlobBytes) + if err != nil { + return cleanup(fmt.Errorf("snapshot blob %s is not readable: %w", part.SHA256, err)) + } + writeErr := writeEntry(bundleBlobPrefix+part.SHA256, part.Bytes, file) + file.Close() + if writeErr != nil { + return cleanup(errors.New("write bundle blob")) + } + info.Bytes += part.Bytes + blobs = append(blobs, part.SHA256) + } + if err := writer.Close(); err != nil { + return cleanup(errors.New("finalize bundle")) + } + if err := out.Sync(); err != nil { + return cleanup(errors.New("sync bundle")) + } + if err := out.Close(); err != nil { + return BundleInfo{}, errors.New("close bundle") + } + sort.Strings(blobs) + info.Blobs = blobs + return info, nil +} + +// Unpack 校验一个包并把它装入本归档。返回值是这份快照自己的清单。 +// +// 提交点是"版本清单落位":blob 先按内容寻址写好并 fsync,最后一步才 Link +// versions/.json。因此任何中断都只会留下不可见的 blob(可被下一次重放复用), +// 不会留下"看起来存在但缺字节"的版本。 +// +// 幂等:同一份包重复导入成功;名字相同内容不同的 blob 或清单直接拒绝。 +// UnpackOptions 控制"本地已有同名 blob 但字节不符"时的行为。 +// +// 默认拒绝(同 ID 异内容一律当身份冲突处理)。只有"从权威云端副本读回"这一条路径 +// 显式打开修复:那时同名 blob 字节不符只能是本地损坏,拒绝会让这份版本永远不可读。 +type UnpackOptions struct { + RepairCorruptBlobs bool +} + +func (a *Archive) Unpack(bundlePath, expectID string) (Manifest, error) { + return a.UnpackWithOptions(bundlePath, expectID, UnpackOptions{}) +} + +func (a *Archive) UnpackWithOptions(bundlePath, expectID string, options UnpackOptions) (Manifest, error) { + if expectID != "" && !validDigest(expectID) { + return Manifest{}, errors.New("invalid expected snapshot ID") + } + if !filepath.IsAbs(bundlePath) || filepath.Clean(bundlePath) != bundlePath { + return Manifest{}, errors.New("bundle path must be an absolute clean path") + } + file, err := os.OpenFile(bundlePath, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return Manifest{}, errors.New("open bundle") + } + defer file.Close() + if info, statErr := file.Stat(); statErr != nil || !info.Mode().IsRegular() { + return Manifest{}, errors.New("bundle must be a regular file") + } + reader := tar.NewReader(file) + var ( + id string + manifest Manifest + manifestRaw []byte + expected map[string]Part + received map[string]bool + entryCount int + ) + for { + header, err := reader.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return Manifest{}, errors.New("bundle is not a readable archive") + } + entryCount++ + if entryCount > maxBundleEntries { + return Manifest{}, errors.New("bundle has too many entries") + } + if header.Typeflag != tar.TypeReg { + return Manifest{}, fmt.Errorf("bundle entry %q is not a regular file", header.Name) + } + switch { + case len(header.Name) == len(bundleManifestPrefix)+len(".json")+64 && header.Name[:len(bundleManifestPrefix)] == bundleManifestPrefix: + if id != "" { + return Manifest{}, errors.New("bundle contains more than one manifest") + } + id = header.Name[len(bundleManifestPrefix) : len(header.Name)-len(".json")] + if !validDigest(id) { + return Manifest{}, errors.New("bundle manifest name is not a snapshot ID") + } + if expectID != "" && id != expectID { + return Manifest{}, fmt.Errorf("bundle snapshot is %s, expected %s", id, expectID) + } + if header.Size <= 0 || header.Size > maxManifestBytes { + return Manifest{}, errors.New("bundle manifest size is not allowed") + } + manifestRaw, err = io.ReadAll(io.LimitReader(reader, maxManifestBytes+1)) + if err != nil || int64(len(manifestRaw)) != header.Size || digest(manifestRaw) != id { + return Manifest{}, errors.New("bundle manifest digest does not match its ID") + } + manifest, expected, err = decodeBundleManifest(manifestRaw, id) + if err != nil { + return Manifest{}, err + } + received = map[string]bool{} + case len(header.Name) == len(bundleBlobPrefix)+64 && header.Name[:len(bundleBlobPrefix)] == bundleBlobPrefix: + if id == "" { + return Manifest{}, errors.New("bundle blob appears before the manifest") + } + name := header.Name[len(bundleBlobPrefix):] + if !validDigest(name) { + return Manifest{}, errors.New("bundle blob name is not a sha256 digest") + } + part, ok := expected[name] + if !ok { + return Manifest{}, fmt.Errorf("bundle carries blob %s which this snapshot does not declare", name) + } + if part.Bytes != header.Size { + return Manifest{}, fmt.Errorf("bundle blob %s size %d does not match manifest %d", name, header.Size, part.Bytes) + } + if received[name] { + return Manifest{}, fmt.Errorf("bundle repeats blob %s", name) + } + if err := a.installBlob(reader, part, options); err != nil { + return Manifest{}, err + } + received[name] = true + default: + return Manifest{}, fmt.Errorf("bundle entry %q is not part of a snapshot bundle", header.Name) + } + } + if id == "" { + return Manifest{}, errors.New("bundle has no manifest") + } + for name := range expected { + if !received[name] { + return Manifest{}, fmt.Errorf("bundle is missing blob %s", name) + } + } + if err := syncRoot(a.blobs); err != nil { + return Manifest{}, err + } + if err := a.installManifest(id, manifestRaw); err != nil { + return Manifest{}, err + } + if err := syncRoot(a.versions); err != nil { + return Manifest{}, err + } + // 落位后用正式读取路径再验一遍:证明这份快照在本机真的可发布。 + if _, err := a.Load(id); err != nil { + return Manifest{}, fmt.Errorf("imported snapshot does not verify: %w", err) + } + return manifest, nil +} + +// installBlob 把一个 blob 从包里写到 blobs/。 +// 已存在时必须字节一致,否则拒绝——同名不同内容是身份冲突,不是"覆盖一下"。 +func (a *Archive) installBlob(body io.Reader, part Part, options UnpackOptions) error { + if _, err := a.blobs.Lstat(part.SHA256); err == nil { + if verifyErr := a.verify(part); verifyErr == nil { + // 已有且一致:仍然读完包里的字节,否则 tar 流会错位。 + _, err := io.CopyN(io.Discard, body, part.Bytes) + return err + } + if !options.RepairCorruptBlobs { + return fmt.Errorf("archive already holds different bytes for blob %s", part.SHA256) + } + // 名字就是内容摘要:同名而字节不符只可能是**本地损坏**。显式修复时删掉坏文件, + // 按包内字节原子重建;否则"本地坏块"永远无法自愈,页面会一直读成不可用。 + if removeErr := a.blobs.Remove(part.SHA256); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) { + return fmt.Errorf("repair corrupt blob %s: %w", part.SHA256, removeErr) + } + } else if !errors.Is(err, os.ErrNotExist) { + return errors.New("archive blob lookup failed") + } + name, tmp, err := temporary(a.blobs) + if err != nil { + return err + } + defer a.blobs.Remove(name) + hash := sha256.New() + written, err := io.Copy(io.MultiWriter(tmp, hash), io.LimitReader(body, part.Bytes+1)) + if err != nil || written != part.Bytes || hex.EncodeToString(hash.Sum(nil)) != part.SHA256 { + tmp.Close() + return fmt.Errorf("bundle blob %s bytes do not match its digest", part.SHA256) + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := a.blobs.Link(name, part.SHA256); err != nil && !errors.Is(err, os.ErrExist) { + return err + } + return nil +} + +// installManifest 落位版本清单(提交点)。已存在必须是同一份字节。 +func (a *Archive) installManifest(id string, raw []byte) error { + if _, err := a.versions.Lstat(id + ".json"); err == nil { + existing, err := a.LoadManifest(id) + if err != nil { + return fmt.Errorf("archive already holds an unreadable version %s: %w", id, err) + } + _ = existing + return nil + } else if !errors.Is(err, os.ErrNotExist) { + return errors.New("archive version lookup failed") + } + name, tmp, err := temporary(a.versions) + if err != nil { + return err + } + defer a.versions.Remove(name) + if _, err := tmp.Write(raw); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := a.versions.Link(name, id+".json"); err != nil && !errors.Is(err, os.ErrExist) { + return err + } + return nil +} + +// decodeBundleManifest 只接受"规范化字节"的清单:包里的清单必须与归档 Seal 时 +// 写出的字节一致,否则即使摘要对得上,也可能是另一套字段排序/空值表达。 +func decodeBundleManifest(raw []byte, id string) (Manifest, map[string]Part, error) { + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.DisallowUnknownFields() + var manifest Manifest + if err := decoder.Decode(&manifest); err != nil { + return Manifest{}, nil, errors.New("bundle manifest is not a valid snapshot manifest") + } + var extra any + if decoder.Decode(&extra) != io.EOF { + return Manifest{}, nil, errors.New("bundle manifest contains trailing data") + } + canonical, err := encodeManifest(manifest) + if err != nil { + return Manifest{}, nil, fmt.Errorf("bundle manifest is not publishable: %w", err) + } + if !bytes.Equal(canonical, raw) || digest(canonical) != id { + return Manifest{}, nil, errors.New("bundle manifest is not in canonical form") + } + expected := make(map[string]Part, len(manifest.Parts)) + for _, part := range manifest.Parts { + if existing, ok := expected[part.SHA256]; ok { + if existing.Bytes != part.Bytes { + return Manifest{}, nil, errors.New("bundle manifest declares conflicting blob sizes") + } + continue + } + expected[part.SHA256] = part + } + return manifest, expected, nil +} + +// DecodeManifest 校验一份"外部拿到的"版本清单字节:摘要必须等于给定快照 ID, +// 且必须是规范形式(与 Seal 写出的字节一致)。跨主机搬运时接收侧用它核对 +// "这份清单是不是它自称的那份",而不是相信对方返回的字段。 +func DecodeManifest(raw []byte, id string) (Manifest, error) { + if !validDigest(id) || digest(raw) != id { + return Manifest{}, errors.New("snapshot manifest digest mismatch") + } + manifest, _, err := decodeBundleManifest(raw, id) + if err != nil { + return Manifest{}, err + } + return manifest, nil +} diff --git a/internal/librarysnapshot/transfer_test.go b/internal/librarysnapshot/transfer_test.go new file mode 100644 index 0000000..997b736 --- /dev/null +++ b/internal/librarysnapshot/transfer_test.go @@ -0,0 +1,225 @@ +package librarysnapshot + +import ( + "archive/tar" + "bytes" + "io" + "os" + "path/filepath" + "testing" +) + +func newTransferArchive(t *testing.T) (*Archive, string) { + t.Helper() + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + archive, err := Open(root, 1024*1024) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { archive.Close() }) + return archive, root +} + +func sealFixture(t *testing.T, archive *Archive) (string, Manifest) { + t.Helper() + part, err := archive.Put(bytes.NewBufferString("[]")) + if err != nil { + t.Fatal(err) + } + manifest := testManifest(part) + id, err := archive.Seal(manifest) + if err != nil { + t.Fatal(err) + } + return id, manifest +} + +// 一份验证过的快照搬过去必须字节一致、身份不变,重复导入幂等。 +func TestPackUnpackRoundTripKeepsIdentityAndBytes(t *testing.T) { + source, _ := newTransferArchive(t) + id, manifest := sealFixture(t, source) + bundle := filepath.Join(t.TempDir(), "snapshot.tar") + info, err := source.Pack(id, bundle) + if err != nil { + t.Fatalf("Pack() error = %v", err) + } + if info.Snapshot != id || info.Parts != len(manifest.Parts) || info.Bytes <= 0 || len(info.Blobs) == 0 { + t.Fatalf("bundle info = %#v", info) + } + destination, _ := newTransferArchive(t) + got, err := destination.Unpack(bundle, id) + if err != nil { + t.Fatalf("Unpack() error = %v", err) + } + if got.KnowledgeBaseID != manifest.KnowledgeBaseID || len(got.Parts) != len(manifest.Parts) { + t.Fatal("imported manifest identity changed") + } + if _, err := destination.Load(id); err != nil { + t.Fatalf("imported snapshot does not load: %v", err) + } + if _, err := destination.Unpack(bundle, id); err != nil { + t.Fatalf("repeated import is not idempotent: %v", err) + } +} + +// 包不覆盖已有文件:导出和导入都不能"顺手替换"一份已存在的产物。 +func TestPackRefusesToOverwriteExistingBundle(t *testing.T) { + source, _ := newTransferArchive(t) + id, _ := sealFixture(t, source) + bundle := filepath.Join(t.TempDir(), "snapshot.tar") + if err := os.WriteFile(bundle, []byte("occupied"), 0600); err != nil { + t.Fatal(err) + } + if _, err := source.Pack(id, bundle); err == nil { + t.Fatal("Pack() overwrote an existing bundle") + } +} + +// 身份对不上就不许导入:调用方点错快照时,宁可失败。 +func TestUnpackRejectsUnexpectedSnapshotIdentity(t *testing.T) { + source, _ := newTransferArchive(t) + id, _ := sealFixture(t, source) + bundle := filepath.Join(t.TempDir(), "snapshot.tar") + if _, err := source.Pack(id, bundle); err != nil { + t.Fatal(err) + } + destination, _ := newTransferArchive(t) + if _, err := destination.Unpack(bundle, digest([]byte("another snapshot"))); err == nil { + t.Fatal("Unpack() accepted a bundle whose ID does not match the expectation") + } +} + +// 包里的字节必须与名字(sha256)一致:篡改一个 blob 就整体拒绝,且不留下版本。 +func TestUnpackRejectsTamperedBlobAndLeavesNoVersion(t *testing.T) { + source, _ := newTransferArchive(t) + id, manifest := sealFixture(t, source) + bundle := filepath.Join(t.TempDir(), "snapshot.tar") + info, err := source.Pack(id, bundle) + if err != nil { + t.Fatal(err) + } + tampered := filepath.Join(t.TempDir(), "tampered.tar") + rewriteBundle(t, bundle, tampered, func(name string, body []byte) (string, []byte) { + if name == bundleBlobPrefix+info.Blobs[0] && len(body) > 0 { + body = append([]byte(nil), body...) + body[0] ^= 0xff + } + return name, body + }) + destination, root := newTransferArchive(t) + if _, err := destination.Unpack(tampered, id); err == nil { + t.Fatal("Unpack() accepted a tampered blob") + } + if _, err := os.Stat(filepath.Join(root, "versions", id+".json")); !os.IsNotExist(err) { + t.Fatal("a failed import left a version behind") + } + _ = manifest +} + +// 包里出现快照不声明的 blob / 缺 blob / 非普通文件,一律拒绝。 +func TestUnpackRejectsIncompleteAndForeignBundles(t *testing.T) { + source, _ := newTransferArchive(t) + id, manifest := sealFixture(t, source) + bundle := filepath.Join(t.TempDir(), "snapshot.tar") + if _, err := source.Pack(id, bundle); err != nil { + t.Fatal(err) + } + missing := filepath.Join(t.TempDir(), "missing.tar") + first := manifest.Parts[0].SHA256 + rewriteBundle(t, bundle, missing, func(name string, body []byte) (string, []byte) { + if name == bundleBlobPrefix+first { + return "", nil + } + return name, body + }) + destination, _ := newTransferArchive(t) + if _, err := destination.Unpack(missing, id); err == nil { + t.Fatal("Unpack() accepted a bundle missing a declared blob") + } + foreign := filepath.Join(t.TempDir(), "foreign.tar") + extra := digest([]byte("extra blob")) + rewriteBundle(t, bundle, foreign, func(name string, body []byte) (string, []byte) { + if name == bundleBlobPrefix+first { + return bundleBlobPrefix + extra, []byte("x") + } + return name, body + }) + other, _ := newTransferArchive(t) + if _, err := other.Unpack(foreign, id); err == nil { + t.Fatal("Unpack() accepted a bundle carrying a blob the snapshot does not declare") + } + traversal := filepath.Join(t.TempDir(), "traversal.tar") + rewriteBundle(t, bundle, traversal, func(name string, body []byte) (string, []byte) { + if name == bundleBlobPrefix+first { + return "../escape", body + } + return name, body + }) + third, _ := newTransferArchive(t) + if _, err := third.Unpack(traversal, id); err == nil { + t.Fatal("Unpack() accepted an entry outside the bundle layout") + } +} + +// 目标机已经存在同名不同内容的 blob:那是身份冲突,必须拒绝而不是覆盖。 +func TestUnpackRejectsConflictingExistingBlob(t *testing.T) { + source, _ := newTransferArchive(t) + id, manifest := sealFixture(t, source) + bundle := filepath.Join(t.TempDir(), "snapshot.tar") + if _, err := source.Pack(id, bundle); err != nil { + t.Fatal(err) + } + destination, root := newTransferArchive(t) + victim := manifest.Parts[0].SHA256 + if err := os.WriteFile(filepath.Join(root, "blobs", victim), []byte("[]different"), 0600); err != nil { + t.Fatal(err) + } + if _, err := destination.Unpack(bundle, id); err == nil { + t.Fatal("Unpack() overwrote a blob whose bytes differ") + } +} + +// rewriteBundle 逐条重放一个包,按 mutate 改名字/内容;返回空名字表示删掉该条。 +func rewriteBundle(t *testing.T, source, target string, mutate func(name string, body []byte) (string, []byte)) { + t.Helper() + in, err := os.Open(source) + if err != nil { + t.Fatal(err) + } + defer in.Close() + out, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if err != nil { + t.Fatal(err) + } + writer := tar.NewWriter(out) + reader := tar.NewReader(in) + for { + header, err := reader.Next() + if err != nil { + break + } + body := make([]byte, header.Size) + if _, err := io.ReadFull(reader, body); err != nil { + t.Fatal(err) + } + name, rewritten := mutate(header.Name, body) + if name == "" { + continue + } + if err := writer.WriteHeader(&tar.Header{Name: name, Mode: 0600, Size: int64(len(rewritten)), Typeflag: tar.TypeReg}); err != nil { + t.Fatal(err) + } + if _, err := writer.Write(rewritten); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := out.Close(); err != nil { + t.Fatal(err) + } +} diff --git a/internal/librarystack/stack.go b/internal/librarystack/stack.go index 9101b90..0cf2666 100644 --- a/internal/librarystack/stack.go +++ b/internal/librarystack/stack.go @@ -15,9 +15,10 @@ import ( "knowledge-governance/internal/appconfig" "knowledge-governance/internal/librarymaintenance" + "knowledge-governance/internal/libraryrelease" "knowledge-governance/internal/librarysnapshot" + "knowledge-governance/internal/objectgateway" v071 "knowledge-governance/internal/releaseadapter/v071" - "knowledge-governance/internal/releasebundle" ) // OpenMaintenance 按部署配置装配实例级维护目标;未接线时返回明确原因。 @@ -32,6 +33,9 @@ func OpenMaintenance(config appconfig.Config) (*librarymaintenance.Manager, erro Writers: config.LibraryTargetWriters, NonWriters: config.LibraryTargetNonWriters, DockerSocket: config.LibraryTargetDockerSocket, + IngressMode: config.LibraryTargetIngressMode, + IngressAck: config.LibraryTargetNoIngressAck, + HealthURL: config.LibraryTargetHealthURL, IngressURL: config.LibraryTargetIngressURL, IngressService: config.LibraryTargetIngressService, IngressDrainFile: config.LibraryTargetIngressDrainFile, @@ -83,23 +87,102 @@ func scopeConfigOf(config appconfig.Config, scope string) (scopeConfig, error) { Region: config.LibraryProductionS3Region, Bucket: config.LibraryProductionS3Bucket, AccessKeyID: config.LibraryProductionS3AccessKey, SecretAccessKey: config.LibraryProductionS3SecretKey, Secure: strings.HasPrefix(config.LibraryProductionS3Endpoint, "https://"), - ForcePathStyle: true, MaxObjectBytes: 256 * 1024 * 1024, + ForcePathStyle: config.LibraryProductionS3Provider == "minio", MaxObjectBytes: 256 * 1024 * 1024, }, }, nil } -func newTarget(ctx context.Context, config appconfig.Config, scope scopeConfig) (*v071.ProductionLibraryTarget, error) { +// RestoreDispatchWiring 是恢复派发身份的唯一装配来源:真实 attempt(objectgateway +// claim)、原 window 作业、部署目标实例与 scope。adapter 不接受调用方另填身份。 +type RestoreDispatchWiring struct { + TargetIdentity string + Scope string + Instance string + OperationID string + WindowJobID string + AttemptOwner string + AttemptEpoch int64 + RecoveryJobID string + RecoveryOperationID string +} + +// RestoreDispatchWiringFor 把本次真实执行的 claim 映射成派发身份,并在字段缺失时 +// 失败关闭。它不读取快照:来源/写前镜像只能从原 WriteSet 与 backup 引用取得。 +func RestoreDispatchWiringFor(config appconfig.Config, scope string, claim objectgateway.Claim) (RestoreDispatchWiring, error) { + if scope != "internal" && scope != "external" { + return RestoreDispatchWiring{}, fmt.Errorf("未知 scope %q", scope) + } + identity := config.LibraryTargetIdentity() + if identity == "" || config.LibraryTargetInstance == "" || config.LibraryProductionDatabaseURL == "" { + return RestoreDispatchWiring{}, errors.New("恢复派发缺少目标身份/实例") + } + if (scope == "internal" && config.LibraryProductionInternalKB == "") || + (scope == "external" && config.LibraryProductionExternalKB == "") { + return RestoreDispatchWiring{}, errors.New("恢复派发缺少 scope 对应的知识库") + } + if claim.JobID == "" || claim.OperationID == "" || claim.Owner == "" || claim.AttemptEpoch <= 0 { + return RestoreDispatchWiring{}, errors.New("恢复派发缺少本次真实 attempt 身份") + } + if (claim.RecoveryJobID == "") != (claim.RecoveryOperationID == "") { + return RestoreDispatchWiring{}, errors.New("恢复投递身份不完整") + } + return RestoreDispatchWiring{ + TargetIdentity: identity, Scope: scope, Instance: config.LibraryTargetInstance, + OperationID: claim.OperationID, WindowJobID: claim.JobID, + AttemptOwner: claim.Owner, AttemptEpoch: claim.AttemptEpoch, + RecoveryJobID: claim.RecoveryJobID, RecoveryOperationID: claim.RecoveryOperationID, + }, nil +} + +func newTarget(ctx context.Context, config appconfig.Config, scope scopeConfig, scopeName string, + gate libraryrelease.RestoreMarkerGate) (*v071.ProductionLibraryTarget, error) { objects, err := v071.NewS3ObjectStore(scope.s3) if err != nil { return nil, errors.New("生产对象存储配置无效") } - return v071.NewProductionLibraryTarget(ctx, v071.ProductionLibraryConfig{ + if config.LibraryObjectGatewayURL == "" { + return nil, errors.New("对象写入网关未配置:发布目标不允许直写对象存储") + } + var writer v071.ObjectStore = objects + if config.LibraryObjectGatewayURL != "" || config.LibraryObjectGatewayToken != "" || config.LibraryObjectGatewayGrantDirectory != "" { + identity := objectgateway.Digest([]byte(scope.s3.Provider + "\x00" + scope.s3.Endpoint + "\x00" + scope.s3.Bucket)) + client, err := objectgateway.NewClient(config.LibraryObjectGatewayURL, config.LibraryObjectGatewayToken, identity) + if err != nil { + return nil, err + } + gateway := &v071.GatewayObjectStore{Automatic: true, Claim: objectgateway.ClaimFromContext(ctx), Client: client, Provider: scope.s3.Provider, Bucket: scope.s3.Bucket, GrantDirectory: config.LibraryObjectGatewayGrantDirectory} + if err := gateway.ConditionalCapability(ctx); err != nil { + return nil, err + } + writer = gateway + } + // DS01:派发身份只能来自本次真实 attempt(objectgateway claim)与原窗口作业。 + // gate 为 nil 时该能力整体关闭,adapter 对新续作 fail closed;baseline 永远传 nil。 + claim := objectgateway.ClaimFromContext(ctx) + targetConfig := v071.ProductionLibraryConfig{ Postgres: config.LibraryProductionDatabaseURL, SearchURL: config.LibraryProductionElasticURL, - SearchIndex: config.LibraryProductionIndex, Objects: objects, ObjectsReader: objects, - ArchiveRoot: config.LibraryArchiveRoot, - ObjectsBucket: config.LibraryProductionS3Bucket, - MaxDocuments: 200000, - }, scope.target) + SearchIndex: config.LibraryProductionIndex, Objects: writer, ObjectsReader: objects, + ArchiveRoot: config.LibraryArchiveRoot, + ObjectsBucket: config.LibraryProductionS3Bucket, + MaxDocuments: 200000, + RestoreDispatch: gate, + } + if gate != nil { + wiring, err := RestoreDispatchWiringFor(config, scopeName, claim) + if err != nil { + return nil, err + } + targetConfig.RestoreTargetIdentity = wiring.TargetIdentity + targetConfig.RestoreScope = wiring.Scope + targetConfig.RestoreInstance = wiring.Instance + targetConfig.RestoreOperationID = wiring.OperationID + targetConfig.RestoreWindowJobID = wiring.WindowJobID + targetConfig.RestoreAttemptOwner = wiring.AttemptOwner + targetConfig.RestoreAttemptEpoch = wiring.AttemptEpoch + targetConfig.RestoreRecoveryJobID = wiring.RecoveryJobID + targetConfig.RestoreRecoveryOperationID = wiring.RecoveryOperationID + } + return v071.NewProductionLibraryTarget(ctx, targetConfig, scope.target) } func newBackups(config appconfig.Config, scope string, target *v071.ProductionLibraryTarget, @@ -113,13 +196,13 @@ func newBackups(config appconfig.Config, scope string, target *v071.ProductionLi // OpenProductionStack 用部署注入的配置装配目标与独立预备份存储。 // 契约以"要同步的这份快照"为准:生产必须向它看齐,而不是反过来。 -func OpenProductionStack(ctx context.Context, config appconfig.Config, scope, snapshotID, knownMapping string) ( - *v071.ProductionLibraryTarget, *v071.ProductionBackupStore, error) { +func OpenProductionStack(ctx context.Context, config appconfig.Config, scope, snapshotID, knownMapping string, + gate libraryrelease.RestoreMarkerGate) (*v071.ProductionLibraryTarget, *v071.ProductionBackupStore, error) { scopeCfg, err := scopeConfigOf(config, scope) if err != nil { return nil, nil, err } - target, err := newTarget(ctx, config, scopeCfg) + target, err := newTarget(ctx, config, scopeCfg, scope, gate) if err != nil { return nil, nil, err } @@ -139,6 +222,23 @@ func OpenProductionStack(ctx context.Context, config appconfig.Config, scope, sn contract.EmbeddingModel = config.LibraryEmbeddingModel contract.EmbeddingDimension = config.LibraryEmbeddingDimension } + // 目标实时契约:来源快照的声明只说明"数据来自哪",不能当目标合同(F17)。 + // 读不到就不许发布——猜一个目标模型正是"知识行声明 B、向量却是 A"的来源。 + live, liveErr := target.LiveTargetContract(ctx) + if liveErr != nil { + target.Close() + return nil, nil, fmt.Errorf("读不到目标实时模型契约,拒绝发布:%w", liveErr) + } + if verifyErr := v071.VerifySourceAgainstTarget(contract, live); verifyErr != nil { + target.Close() + return nil, nil, verifyErr + } + // 图谱门禁:目标开了 graph_enabled 时,发布只写 PG/ES/OSS,图谱会静默变旧。 + // 只读检测 + 拒绝;不关闭目标图谱、不搬 Neo4j(那属于扩围)。 + if graphErr := target.VerifyGraphGate(ctx); graphErr != nil { + target.Close() + return nil, nil, graphErr + } // 生产索引存在时必须与快照契约一致;不存在或为空基线时跳过比对 // (空索引的映射没有可比性,非空之后仍然严格比对)。 if mapping, mapErr := target.Search().MappingSHA256(ctx); mapErr == nil { @@ -157,7 +257,7 @@ func OpenProductionStack(ctx context.Context, config appconfig.Config, scope, sn } } } - backupContract := contract + backupContract := v071.ContractFromLive(contract, live) if knownMapping != "" { backupContract.IndexMappingSHA256 = knownMapping } @@ -184,7 +284,7 @@ func OpenBaselineStack(ctx context.Context, config appconfig.Config, scope strin if err != nil { return nil, nil, err } - target, err := newTarget(ctx, config, scopeCfg) + target, err := newTarget(ctx, config, scopeCfg, scope, nil) if err != nil { return nil, nil, err } @@ -200,10 +300,22 @@ func OpenBaselineStack(ctx context.Context, config appconfig.Config, scope strin target.Close() return nil, nil, fmt.Errorf("读取目标 WeKnora schema 版本失败: %w", err) } - if dirty || schemaVersion != releasebundle.WeKnoraMigrationV071 { + if dirty { target.Close() - return nil, nil, fmt.Errorf("目标 schema 版本 %d(dirty=%v)与受支持的 %d 不一致,拒绝建基线", - schemaVersion, dirty, releasebundle.WeKnoraMigrationV071) + return nil, nil, fmt.Errorf("目标 schema 版本 %d 处于 dirty 状态,拒绝建基线", schemaVersion) + } + // 契约按目标库自己的 schema 解析,而不是写死 74:0.9.0 的 schema 是 134, + // 它的表集合、索引来源与 Wiki 部件都和 0.7.1 不同,用 74 的常量建基线 + // 会把另一套栈的记录写进权威版本。 + profile, err := v071.ResolveSchemaProfile(ctx, target.Pool(), "baseline contract") + if err != nil { + target.Close() + return nil, nil, fmt.Errorf("解析目标 schema profile 失败: %w", err) + } + if profile.SchemaVersion != schemaVersion { + target.Close() + return nil, nil, fmt.Errorf("目标 schema 版本 %d 与解析出的 profile %s(%d)不一致,拒绝建基线", + schemaVersion, profile.Name, profile.SchemaVersion) } embeddingModel := config.LibraryEmbeddingModel embeddingDimension := config.LibraryEmbeddingDimension @@ -235,7 +347,7 @@ WHERE kb.id = $1 AND kb.deleted_at IS NULL`, scopeCfg.target.KnowledgeBaseID).Sc return nil, nil, fmt.Errorf("读取目标 embedding 模型绑定失败: %w", err) } contract := librarysnapshot.Compatibility{ - WeKnoraVersion: releasebundle.WeKnoraVersionV071, + WeKnoraVersion: profile.WeKnoraVersion, SchemaVersion: schemaVersion, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: embeddingModel, diff --git a/internal/librarystack/stack_test.go b/internal/librarystack/stack_test.go new file mode 100644 index 0000000..c2050d4 --- /dev/null +++ b/internal/librarystack/stack_test.go @@ -0,0 +1,92 @@ +package librarystack + +import ( + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/objectgateway" + "testing" +) + +// DS01-F1:正式装配必须把 scope/instance/真实 attempt 身份传到 adapter;快照绑定 +// 不再来自这里(来源/写前镜像只从原 WriteSet 与 backup 引用取得)。 +func TestRestoreDispatchWiringUsesRealClaim(t *testing.T) { + config := appconfig.Config{ + LibraryTargetInstance: "inst-prod", + LibraryProductionDatabaseURL: "postgres://user:pass@127.0.0.1:5432/kg_prod?sslmode=disable", + LibraryProductionInternalKB: "kb-internal", + LibraryProductionExternalKB: "kb-external", + } + claim := objectgateway.Claim{ + JobID: "job-window", OperationID: "op-original", Owner: "worker-1#queue#job-window", + AttemptEpoch: 3, RecoveryJobID: "queue-recovery", RecoveryOperationID: "op-recovery", + } + wiring, err := RestoreDispatchWiringFor(config, "internal", claim) + if err != nil { + t.Fatalf("real wiring: %v", err) + } + if wiring.Scope != "internal" || wiring.Instance != "inst-prod" { + t.Fatalf("scope/instance = %q/%q", wiring.Scope, wiring.Instance) + } + if wiring.TargetIdentity == "" || wiring.TargetIdentity == "unconfigured" { + t.Fatalf("target identity = %q", wiring.TargetIdentity) + } + if wiring.OperationID != claim.OperationID || wiring.WindowJobID != claim.JobID || + wiring.AttemptOwner != claim.Owner || wiring.AttemptEpoch != claim.AttemptEpoch { + t.Fatalf("attempt identity not propagated: %+v", wiring) + } + if wiring.RecoveryJobID != claim.RecoveryJobID || wiring.RecoveryOperationID != claim.RecoveryOperationID { + t.Fatalf("recovery delivery identity not propagated: %+v", wiring) + } + // 自动回滚(非恢复 worker)没有 recovery 投递身份,必须保持为空。 + rollback, err := RestoreDispatchWiringFor(config, "internal", objectgateway.Claim{ + JobID: "job-window", OperationID: "op-original", Owner: "worker-1#queue#job-window", AttemptEpoch: 3}) + if err != nil { + t.Fatal(err) + } + if rollback.RecoveryJobID != "" || rollback.RecoveryOperationID != "" { + t.Fatalf("rollback wiring invented a recovery identity: %+v", rollback) + } +} + +func TestRestoreDispatchWiringFailsClosed(t *testing.T) { + config := appconfig.Config{ + LibraryTargetInstance: "inst-prod", + LibraryProductionDatabaseURL: "postgres://user:pass@127.0.0.1:5432/kg_prod?sslmode=disable", + LibraryProductionInternalKB: "kb-internal", + } + if _, err := RestoreDispatchWiringFor(config, "internal", objectgateway.Claim{}); err == nil { + t.Fatal("missing attempt identity was accepted") + } + if _, err := RestoreDispatchWiringFor(config, "tenant-wide", objectgateway.Claim{ + JobID: "j", OperationID: "o", Owner: "w", AttemptEpoch: 1}); err == nil { + t.Fatal("unknown scope was accepted") + } + if _, err := RestoreDispatchWiringFor(config, "external", objectgateway.Claim{ + JobID: "j", OperationID: "o", Owner: "w", AttemptEpoch: 1}); err == nil { + t.Fatal("external scope without its knowledge base was accepted") + } + if _, err := RestoreDispatchWiringFor(config, "internal", objectgateway.Claim{ + JobID: "j", OperationID: "o", Owner: "w", AttemptEpoch: 1, RecoveryJobID: "q"}); err == nil { + t.Fatal("partial recovery delivery identity was accepted") + } + unconfigured := config + unconfigured.LibraryProductionDatabaseURL = "" + if _, err := RestoreDispatchWiringFor(unconfigured, "internal", objectgateway.Claim{ + JobID: "j", OperationID: "o", Owner: "w", AttemptEpoch: 1}); err == nil { + t.Fatal("unconfigured target database was accepted as a dispatch target") + } +} + +func TestObjectAddressingMatchesProvider(t *testing.T) { + for _, provider := range []string{"oss", "s3", "minio"} { + t.Run(provider, func(t *testing.T) { + config := appconfig.Config{LibraryProductionDatabaseURL: "configured", LibraryProductionElasticURL: "configured", LibraryProductionTenantID: 1, LibraryProductionInternalKB: "kb-target", LibraryProductionS3Endpoint: "https://storage.example", LibraryProductionS3Bucket: "test-bucket", LibraryProductionS3AccessKey: "fixture", LibraryProductionS3SecretKey: "fixture", LibraryProductionS3Provider: provider} + scope, err := scopeConfigOf(config, "internal") + if err != nil { + t.Fatal(err) + } + if scope.s3.ForcePathStyle != (provider == "minio") { + t.Fatalf("provider %s: ForcePathStyle=%v", provider, scope.s3.ForcePathStyle) + } + }) + } +} diff --git a/internal/libraryverify/canary_test.go b/internal/libraryverify/canary_test.go new file mode 100644 index 0000000..c50f957 --- /dev/null +++ b/internal/libraryverify/canary_test.go @@ -0,0 +1,102 @@ +package libraryverify + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "knowledge-governance/internal/libraryrelease" +) + +func drillLedger() libraryrelease.WriteSet { + return libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", + BackupSnapshotID: "backup", TargetSnapshotID: "source", CreatedAt: time.Now().UTC(), + Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}} +} + +// 写集合必须先落盘并登记,再标记内容风险,最后才写目标: +// 顺序颠倒会让恢复入口在"已经写过"时读不到 ledger。 +func TestCanaryPersistsAndRegistersEvidenceBeforeWrite(t *testing.T) { + root := t.TempDir() + ledger := drillLedger() + registered, marked, written := false, false, false + err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", nil, + func(context.Context) error { + if !registered { + t.Fatal("risk marker preceded durable registration") + } + marked = true + return nil + }, + func(_ context.Context) error { + if len(ledger.CreatedIDs("knowledge_tags")) != 1 { + t.Fatal("canary absent from write set") + } + if ledger.Digest == "" { + t.Fatal("write set was not sealed before registration") + } + matches, e := filepath.Glob(filepath.Join(root, "writesets", "*.json")) + if e != nil || len(matches) != 1 { + t.Fatalf("durable ledger missing: %v %v", matches, e) + } + if _, e := os.Stat(matches[0]); e != nil { + t.Fatal(e) + } + registered = true + return nil + }, + func(context.Context) error { + if !registered || !marked { + t.Fatal("write preceded registration/risk marker") + } + written = true + return nil + }) + if err != nil || !written || !registered { + t.Fatalf("err=%v written=%v registered=%v", err, written, registered) + } +} + +func TestCanaryNeverWritesWithoutDurableLedger(t *testing.T) { + root := filepath.Join(t.TempDir(), "blocked") + if err := os.WriteFile(root, []byte("not a directory"), 0600); err != nil { + t.Fatal(err) + } + ledger := drillLedger() + marked, written := false, false + err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", nil, + func(context.Context) error { marked = true; return nil }, + func(context.Context) error { marked = true; return nil }, + func(context.Context) error { written = true; return nil }) + if err == nil || marked || written { + t.Fatalf("err=%v marked=%v written=%v", err, marked, written) + } +} + +// 登记失败 = 恢复入口读不到写集合:此时一笔都不许写。 +func TestCanaryNeverWritesWhenRegistrationFails(t *testing.T) { + ledger := drillLedger() + marked, written := false, false + err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id", nil, + func(context.Context) error { marked = true; return nil }, + func(context.Context) error { return errors.New("governance registration unavailable") }, + func(context.Context) error { written = true; return nil }) + if err == nil || marked || written { + t.Fatalf("err=%v marked=%v written=%v", err, marked, written) + } +} + +func TestCanaryNeverWritesWhenRiskMarkerFails(t *testing.T) { + ledger := drillLedger() + written := false + err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id", nil, + func(context.Context) error { return errors.New("journal unavailable") }, + func(context.Context) error { return nil }, + func(context.Context) error { written = true; return nil }) + if err == nil || written { + t.Fatalf("err=%v written=%v", err, written) + } +} diff --git a/internal/libraryverify/restore_identity_test.go b/internal/libraryverify/restore_identity_test.go new file mode 100644 index 0000000..d125cc4 --- /dev/null +++ b/internal/libraryverify/restore_identity_test.go @@ -0,0 +1,77 @@ +package libraryverify + +import ( + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +// B1 的定向回归:共享 Run 用 PlanWrite 产出的写前/来源身份与写集合, +// 必须通过真实恢复入口调用的**同一份**身份合同;用同一份快照冒充两个身份 +// 的旧形状必须被拒绝。这里不连接任何业务目标(隔离 fixture)。 +func TestSharedDrillPlanPassesRealRestoreIdentityContract(t *testing.T) { + preimage := libraryrelease.BackupRef{SnapshotID: strings.Repeat("a", 64), + Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}} + source := libraryrelease.BackupRef{SnapshotID: strings.Repeat("b", 64), + Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}} + + set, err := PlanWrite("libverify-internal-fixture", "internal", 10000, "fixture-kb", preimage, source) + if err != nil { + t.Fatalf("shared plan rejected: %v", err) + } + if err := set.Seal(); err != nil { + t.Fatal(err) + } + // ProductionLibraryTarget.Restore 与 RestoreDrill 都在写之前调用这一判定。 + if err := set.ValidateRestoreBinding(preimage.SnapshotID, 10000, "fixture-kb"); err != nil { + t.Fatalf("real restore identity contract rejected the shared plan: %v", err) + } + // 演练恢复入口的写集合守卫(只允许可归因的 canary 行)也必须接受它。 + canary := set + canary.Rows = append(canary.Rows, libraryrelease.WriteSetRow{Table: "knowledge_tags", ID: "canary-1"}) + if err := canary.Seal(); err != nil { + t.Fatal(err) + } + if err := v071.ValidateDrillWriteSet(canary); err != nil { + t.Fatalf("drill write set guard rejected the shared plan: %v", err) + } + + // 旧缺陷形状:来源快照 = 写前镜像。同一判定必须拒绝。 + legacy := set + legacy.TargetSnapshotID = preimage.SnapshotID + legacy.Digest = "" + if err := legacy.Seal(); err != nil { + t.Fatal(err) + } + err = legacy.ValidateRestoreBinding(preimage.SnapshotID, 10000, "fixture-kb") + if err == nil || !strings.Contains(err.Error(), "同一份快照") { + t.Fatalf("legacy same-snapshot plan must be rejected, got %v", err) + } +} + +func TestSharedPlanRejectsSameSnapshotIdentity(t *testing.T) { + preimage := libraryrelease.BackupRef{SnapshotID: strings.Repeat("c", 64), + Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}} + if _, err := PlanWrite("job", "internal", 10000, "kb", preimage, preimage); err == nil { + t.Fatal("plan must refuse to use one snapshot as both source and pre-image") + } + if _, err := PlanWrite("job", "internal", 10000, "kb", preimage, libraryrelease.BackupRef{}); err == nil { + t.Fatal("plan must refuse a missing source identity") + } +} + +// 演练恢复入口只回放"本次写的隔离 canary 行";任何其它行都不是演练产物。 +func TestDrillWriteSetGuardRejectsForeignRows(t *testing.T) { + set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, Rows: []libraryrelease.WriteSetRow{ + {Table: "knowledges", ID: "doc-1"}, + }} + if err := v071.ValidateDrillWriteSet(set); err == nil { + t.Fatal("drill guard must reject non-canary rows") + } + set.Rows = []libraryrelease.WriteSetRow{{Table: "knowledge_tags", ID: "tag-1", Existing: true}} + if err := v071.ValidateDrillWriteSet(set); err == nil { + t.Fatal("drill guard must reject rows that existed before the write") + } +} diff --git a/internal/libraryverify/verify.go b/internal/libraryverify/verify.go new file mode 100644 index 0000000..0b90dc8 --- /dev/null +++ b/internal/libraryverify/verify.go @@ -0,0 +1,445 @@ +// Package libraryverify 在目标实例上做一次**真实**的恢复验证(原 cmd/librarydrill 的实现): +// +// 维护隔离(关入口/停写入者/证明排空) +// → 捕获目标整库(真预备份,落归档) +// → 校验目标 == 预备份(基线一致) +// → 写入一个 canary(证明"校验确实能发现内容变化") +// → 按预备份恢复 +// → 逐表/索引/资源/Wiki 再校验一次,必须完全一致 +// → 关窗口(按原运行状态恢复服务、开入口、验证健康) +// +// 为什么搬进 internal:页面要能点一次"恢复验证",worker 必须在进程内执行同一份实现, +// 不能再要求运维 SSH 上去跑 CLI。命令行使同一个 Run,不允许两份实现。 +// 它只读/写**被测目标自己**,绝不触碰封存源;所有凭据来自进程环境,不进命令行、不打印。 +// 任一步失败都不伪装成功:窗口保持维护、报告写明失败阶段。 +package libraryverify + +import ( + "context" + "crypto/rand" + "errors" + "fmt" + "log" + "time" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/libraryfreeze" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarystack" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +type Verification struct { + SnapshotID string `json:"snapshot_id"` + Verified bool `json:"verified"` + Error string `json:"error,omitempty"` + At time.Time `json:"at"` +} + +type Report struct { + Status string `json:"status"` // passed | failed | maintenance_held + Scope string `json:"scope"` + Target string `json:"target"` + SnapshotID string `json:"snapshot_id"` // 写前镜像:恢复实际回放的那份预备份 + SourceSnapshot string `json:"source_snapshot_id,omitempty"` + WriteSetDigest string `json:"writeset_digest,omitempty"` + WindowState string `json:"window_state,omitempty"` + Project string `json:"project"` + Counts map[string]int64 `json:"counts"` + BaselineCheck *Verification `json:"baseline_check"` + DriftCheck *Verification `json:"drift_check"` // 必须失败:证明确实能发现差异 + RestoreCheck *Verification `json:"restore_check"` + Canary string `json:"canary"` + Failure string `json:"failure,omitempty"` + Stage string `json:"stage,omitempty"` + StartedAt time.Time `json:"started_at"` + FinishedAt time.Time `json:"finished_at"` + Until map[string]string `json:"until,omitempty"` +} + +// Progress 把演练的阶段推进交给调用方(worker 写 library_job_stages,CLI 打日志)。 +type Progress func(stage, state, detail string) + +func (p Progress) report(stage, state, detail string) { + if p != nil { + p(stage, state, detail) + } +} + +// TargetIdentity 是治理侧维护记录必须钉住的目标事实(与 librarymaintenance.Target 同源)。 +type TargetIdentity struct { + Instance string + Fingerprint string + Writers []string +} + +// Governance 是演练必须持有的**治理侧**维护生命周期:实例/scope 占用、入口真实状态、 +// 释放。为什么不能让调用方只写磁盘 journal:页面与恢复入口读的是治理行,只写 journal +// 时"正在维护"不会出现在 UI,失败后也没有同 job 的恢复锚点(2026-11 审核 B2)。 +type Governance interface { + Acquire(ctx context.Context, jobID, scope string, target TargetIdentity, originalServiceState string) error + Ingress(ctx context.Context, jobID, scope, state, note string) error + State(ctx context.Context, jobID, scope, state, note string) error + Release(ctx context.Context, jobID, scope, note string) error +} + +// Ledger 把预备份身份与写集合摘要持久化到**同一个作业**(worker 直接传 +// libraryStageRecorder:它已经是 BackupObserver + WriteSetObserver)。 +// 恢复入口按 (scope, job, 写前镜像) 精确读这条记录,所以两件事必须发生在写第一笔之前。 +type Ledger interface { + BackupPrepared(ctx context.Context, backup libraryrelease.BackupRef) error + WriteSetPlanned(ctx context.Context, set libraryrelease.WriteSet) error +} + +// Options 是演练的可选接线。Governance/Ledger 为 nil 只允许主机侧 CLI 使用: +// 页面发起的作业必须两者都在,否则演练结论不会出现在治理记录里。 +type Options struct { + Progress Progress + Governance Governance + Ledger Ledger +} + +// Run 执行一次演练。jobID 同时是维护窗口的持有者标识,必须与业务作业 id 一致, +// 否则崩溃恢复时窗口与作业对不上。 +func Run(ctx context.Context, config appconfig.Config, scope, jobID string, opts Options) (*Report, error) { + if scope != "internal" && scope != "external" { + return nil, errors.New("scope must be internal or external") + } + progress := opts.Progress + report := &Report{Status: "failed", Scope: scope, Project: config.LibraryTargetProject, + Target: config.LibraryTargetInstance, StartedAt: time.Now().UTC()} + fail := func(stage string, cause error, held bool) (*Report, error) { + report.Stage = stage + report.Failure = cause.Error() + report.FinishedAt = time.Now().UTC() + if held { + report.Status = "maintenance_held" + } + progress.report(stage, "failed", cause.Error()) + return report, cause + } + + progress.report("capture", "running", "打开目标栈与维护管理器") + target, backups, err := librarystack.OpenBaselineStack(ctx, config, scope) + if err != nil { + return fail("capture", err, false) + } + defer target.Close() + manager, err := librarystack.OpenMaintenance(config) + if err != nil { + return fail("capture", err, false) + } + defer manager.Close() + if err := manager.VerifyTopology(ctx); err != nil { + return fail("capture", err, false) + } + originalState, err := manager.OriginalState(ctx) + if err != nil { + return fail("capture", errors.New("读不到目标写入者的原运行状态,不能开维护窗口:"+err.Error()), false) + } + identity := manager.Target() + // 治理占用必须在任何目标动作之前:拿不到就没有"入口已关/写入者已停"的权威记录, + // 失败后也没有可恢复的同 job 锚点。 + if opts.Governance != nil { + targetIdentity := TargetIdentity{Instance: identity.Instance, Fingerprint: identity.Fingerprint, Writers: identity.Writers} + if err := opts.Governance.Acquire(ctx, jobID, scope, targetIdentity, originalState); err != nil { + return fail("capture", errors.New("目标实例正在维护中或无法登记维护占用:"+err.Error()), false) + } + } + coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot) + if err != nil { + if opts.Governance != nil { + // 还没进窗口、目标未被停用:释放占用是诚实的;释放失败就报告出来。 + _ = opts.Governance.Release(ctx, jobID, scope, "维护协调器不可用,未进入窗口") + } + return fail("capture", err, false) + } + defer control.Close() + defer coordinator.Close() + + var ( + snapshotID string + sourceID string + writesetDigest string + counts map[string]int64 + canary string + contentTouched bool + baseline Verification + drift Verification + restored Verification + ) + work := func(ctx context.Context, window *libraryfreeze.Window) (string, error) { + start := time.Now() + // 窗口已关入口、已停写入者并证明排空:此时才敢把 UI 的入口状态写成 closed。 + if opts.Governance != nil { + if err := opts.Governance.Ingress(ctx, jobID, scope, "closed", + "恢复验证已关闭目标入口并停止写入者"); err != nil { + return "", errors.New("登记入口关闭失败:" + err.Error()) + } + } + current, err := target.Current(ctx) + if err != nil { + return "", errors.New("读取目标当前整库状态失败:" + err.Error()) + } + counts = current.Counts + report.Counts = counts + // 1) 写前镜像:真预备份(落归档、内容寻址、导出后复核内容未变)。 + // 它是恢复阶段实际回放的唯一内容来源。 + backup, err := backups.Prepare(ctx, "", current) + if err != nil { + return "", errors.New("捕获目标整库失败:" + err.Error()) + } + snapshotID = backup.SnapshotID + report.SnapshotID = snapshotID + if err := window.SetBackupSnapshot(ctx, snapshotID); err != nil { + return "", errors.New("记录预备份身份失败:" + err.Error()) + } + // 2) 来源身份:DS01 合同要求"来源快照 ≠ 写前镜像",演练不能用同一份快照冒充 + // 两个身份(真实 Restore 会在任何写之前拒绝)。这里再做一次**真实的**独立捕获, + // 只作为这次写入的来源身份;两次捕获都在同一维护切点内、由同一备份存储密封, + // 不伪造快照、也不放宽 Restore 的校验。 + source, err := backups.Prepare(ctx, "", current) + if err != nil { + return "", errors.New("捕获来源身份失败:" + err.Error()) + } + if source.SnapshotID == "" || source.SnapshotID == snapshotID { + return "", errors.New("来源身份与写前镜像相同:拒绝用一份快照冒充两个恢复身份") + } + sourceID = source.SnapshotID + report.SourceSnapshot = sourceID + // 预备份引用必须在任何写入之前落进同一个作业:恢复入口按它取写前镜像。 + if opts.Ledger != nil { + if err := opts.Ledger.BackupPrepared(ctx, backup); err != nil { + return "", errors.New("预备份身份无法持久化,未对目标执行任何写入:" + err.Error()) + } + } + progress.report("capture", "succeeded", + fmt.Sprintf("已捕获写前镜像 %s 与来源身份 %s(%d 字节,用时 %s)", + short(snapshotID), short(sourceID), backup.Bytes, time.Since(start).Round(time.Second))) + log.Printf("verify: snapshot captured preimage=%s source=%s bytes=%d in=%s", + snapshotID, sourceID, backup.Bytes, time.Since(start)) + + // 3) 基线校验:预备份必须与目标完全一致。 + progress.report("verify", "running", "逐表/索引/资源比对目标与预备份") + baseline = Verification{SnapshotID: snapshotID, At: time.Now().UTC()} + if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil { + baseline.Error = err.Error() + report.BaselineCheck = &baseline + return "", errors.New("预备份与目标不一致(预备份本身不可信):" + err.Error()) + } + baseline.Verified = true + report.BaselineCheck = &baseline + progress.report("verify", "succeeded", "预备份与目标逐类一致") + + // Canary 是隔离的标签行,空目标上也一样:绝不为了"让演练能跑"去种文档或改既有行。 + var random [16]byte + if _, err := rand.Read(random[:]); err != nil { + return "", err + } + canary = fmt.Sprintf("%x", random[:]) + identityValue := target.Identity() + var exists bool + if err := target.Pool().QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM knowledge_tags WHERE id=$1)", canary).Scan(&exists); err != nil { + return "", err + } + if exists { + return "", errors.New("canary identity collision; no write attempted") + } + ledger, planErr := PlanWrite(jobID, scope, identityValue.TenantID, identityValue.KnowledgeBaseID, backup, source) + if planErr != nil { + return "", planErr + } + report.Canary = canary + progress.report("canary", "running", "写入一个隔离 canary,验证校验能发现差异") + if err := writeDrillCanary(ctx, config.LibraryArchiveRoot, &ledger, canary, + func(set *libraryrelease.WriteSet) error { + // 计划必须在 Seal/落盘/登记之前定型:对象网关控制器按登记摘要加载, + // 这里补 V2 信封、目标 schema、来源身份与当前 owned attempt 绑定。 + return target.PrepareDrillPlan(ctx, set) + }, + func(ctx context.Context) error { + if err := window.MarkContentRisk(ctx); err != nil { + return err + } + contentTouched = true + return nil + }, func(ctx context.Context) error { + if opts.Ledger == nil { + return nil + } + // 写集合摘要必须在第一笔写入之前登记到同一个作业的预备份证据里: + // 恢复入口按 (scope, job, 写前镜像) 精确读它,读不到就保持维护。 + return opts.Ledger.WriteSetPlanned(ctx, *ledgerClone(&ledger)) + }, func(ctx context.Context) error { + _, err := target.Pool().Exec(ctx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES($1,$2,$3,$4)`, canary, identityValue.TenantID, identityValue.KnowledgeBaseID, "drill-canary-"+canary) + return err + }); err != nil { + return "", fmt.Errorf("canary preparation/write failed: %w", err) + } + writesetDigest = ledger.Digest + report.WriteSetDigest = writesetDigest + drift = Verification{SnapshotID: snapshotID, At: time.Now().UTC()} + if verifyErr := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); verifyErr == nil { + drift.Error = "写入 canary 后校验仍然通过:校验没有真正比对内容" + report.DriftCheck = &drift + return "", errors.New("写入 canary 后校验仍然通过:校验没有真正比对内容,拒绝把这次演练当成通过") + } else { + drift.Error = verifyErr.Error() + } + report.DriftCheck = &drift + progress.report("canary", "succeeded", "校验按预期发现了 canary 差异") + log.Printf("verify: drift detected as expected (%s)", drift.Error) + + // 4) 按写前镜像恢复:四个阶段整段回放(与真实恢复同一批 Apply 原语), + // 而不是只删 canary。发布计划形态的 Restore 不能接受"只写过一行 canary"的 + // 写集合(v2 执行计划合同),所以演练走限定的安全恢复入口;它复用同一份 + // DS01 身份合同与整实例指纹校验。 + progress.report("restore", "running", "按预备份恢复目标整库") + if err := target.RestoreDrill(ctx, libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID, + WriteSet: &ledger}); err != nil { + return "", errors.New("按预备份恢复失败:" + err.Error()) + } + // 5) 恢复后逐类复核:必须与预备份完全一致。 + restored = Verification{SnapshotID: snapshotID, At: time.Now().UTC()} + if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil { + restored.Error = err.Error() + report.RestoreCheck = &restored + return "", errors.New("恢复后内容仍与预备份不一致:" + err.Error()) + } + restored.Verified = true + report.RestoreCheck = &restored + progress.report("restore", "succeeded", "恢复后与预备份逐类一致") + log.Printf("verify: restored and verified snapshot=%s", snapshotID) + return snapshotID, nil + } + + progress.report("finalize", "running", "关闭维护窗口并按原状态恢复目标") + window, windowErr := coordinator.RunWindow(ctx, jobID, + func(ctx context.Context) error { return manager.VerifyRunning(ctx) }, work, + // 没写过目标内容 ⇒ 按原状态恢复永远安全;写过 canary ⇒ 只有恢复并校验通过才开放。 + func(error) bool { return !contentTouched || restored.Verified }) + + report.Until = map[string]string{"job": jobID, "window_state": window.State} + report.WindowState = window.State + // 服务真的回来、入口验证过(succeeded / 未写内容的安全失败)才释放治理占用; + // held 时保留行,页面才能显示真实入口状态并从同一 job 走恢复入口。 + released := false + if opts.Governance != nil { + switch { + case window.State == "succeeded" || (window.State == "failed" && !contentTouched): + if err := opts.Governance.Ingress(ctx, jobID, scope, "open", + "维护窗口已按原运行状态恢复,入口已验证可用"); err != nil { + return fail("finalize", errors.New("恢复后登记入口状态失败:"+err.Error()), false) + } + if err := opts.Governance.Release(ctx, jobID, scope, + "恢复验证结束,服务与入口已按原状态恢复"); err != nil { + return fail("finalize", errors.New("恢复验证结束但维护占用释放失败:"+err.Error()), false) + } + released = true + default: + cause := "维护窗口保持关闭" + if windowErr != nil { + cause = windowErr.Error() + } + _ = opts.Governance.Ingress(ctx, jobID, scope, "closed", "目标内容状态未验证,入口保持关闭") + _ = opts.Governance.State(ctx, jobID, scope, "needs_restore", + "恢复验证失败且目标内容未验证:"+cause) + } + } + if windowErr != nil || window.State != "succeeded" { + cause := windowErr + if cause == nil { + cause = fmt.Errorf("维护窗口状态 %s(未成功)", window.State) + } + held := window.State == "held" + if held && released { + held = false + } + return fail("finalize", cause, held) + } + report.Status = "passed" + report.FinishedAt = time.Now().UTC() + progress.report("finalize", "succeeded", "维护窗口已关闭,目标恢复原运行状态") + return report, nil +} + +// PlanWrite 构造演练的写前镜像/来源身份与写集合。Run 与定向回归共用这一份: +// 只有来源身份 ≠ 写前镜像、且两者都是同一次维护切点里密封的真实捕获时, +// 恢复入口(同一份 DS01 身份合同)才接受这次演练。 +func PlanWrite(jobID, scope string, tenantID uint64, knowledgeBaseID string, + preimage, source libraryrelease.BackupRef) (libraryrelease.WriteSet, error) { + if preimage.SnapshotID == "" || source.SnapshotID == "" { + return libraryrelease.WriteSet{}, errors.New("演练缺少写前镜像或来源身份快照") + } + if preimage.SnapshotID == source.SnapshotID { + return libraryrelease.WriteSet{}, errors.New("来源身份与写前镜像相同:拒绝用一份快照冒充两个恢复身份") + } + set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: jobID, Target: scope, + TenantID: tenantID, KnowledgeBaseID: knowledgeBaseID, + BackupSnapshotID: preimage.SnapshotID, TargetSnapshotID: source.SnapshotID, + CreatedAt: time.Now().UTC(), Universe: preimage.Universe} + if err := set.ValidateRestoreBinding(preimage.SnapshotID, tenantID, knowledgeBaseID); err != nil { + return libraryrelease.WriteSet{}, err + } + return set, nil +} + +func short(id string) string { + if len(id) <= 12 { + return id + } + return id[:12] +} + +// ledgerClone 只用于把台账交给登记方:Seal 会重排 Rows,调用方随后还要用同一份 +// 内容去恢复,不能让登记方持有可变的同一指针。 +func ledgerClone(set *libraryrelease.WriteSet) *libraryrelease.WriteSet { + copy := *set + copy.Rows = append([]libraryrelease.WriteSetRow(nil), set.Rows...) + return © +} + +// writeDrillCanary 是"写入前先留痕"的唯一实现:seal → 落盘 → 登记 → 标风险 → 写。 +// 任何一步失败都不写目标;登记在标风险之前,恢复入口才拿得到这份写集合。 +func writeDrillCanary(ctx context.Context, root string, ledger *libraryrelease.WriteSet, id string, + prepare func(*libraryrelease.WriteSet) error, + mark func(context.Context) error, record func(context.Context) error, write func(context.Context) error) error { + ledger.Rows = append(ledger.Rows, libraryrelease.WriteSetRow{Table: "knowledge_tags", ID: id, Existing: false}) + if prepare != nil { + if err := prepare(ledger); err != nil { + return err + } + } + if err := ledger.Seal(); err != nil { + return err + } + if _, err := v071.PersistWriteSet(root, ledger); err != nil { + return err + } + if record != nil { + if err := record(ctx); err != nil { + return err + } + } + if err := mark(ctx); err != nil { + return err + } + return write(ctx) +} + +// RecoverWindows 把非终态的维护窗口按原运行状态恢复(服务起来、入口验证)。 +// 演练失败但还没写目标内容时,用它把目标从"停住"状态救回来;治理记录由作业/接口那侧负责。 +func RecoverWindows(config appconfig.Config) error { + manager, err := librarystack.OpenMaintenance(config) + if err != nil { + return err + } + defer manager.Close() + coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot) + if err != nil { + return err + } + defer control.Close() + defer coordinator.Close() + return coordinator.Recover(context.Background()) +} diff --git a/internal/monitoring/health.go b/internal/monitoring/health.go index 14cce75..2fde222 100644 --- a/internal/monitoring/health.go +++ b/internal/monitoring/health.go @@ -177,10 +177,13 @@ func (provider *RealProvider) weKnoraProbe(ctx context.Context, now time.Time) g return provider.track(classify("weknora", "WeKnora API", false, true, ProbeOutcome{ObservedAt: now})) } outcome := provider.httpProbeOutcome(ctx, baseURL, now) + probeTarget := "" if outcome.Reachability == nil && provider.weknoraReadiness != nil { - outcome.WorkReadiness = provider.weknoraReadiness(ctx) + probeTarget, outcome.WorkReadiness = provider.weknoraReadiness(ctx) } - return provider.track(classify("weknora", "WeKnora API", true, true, outcome)) + health := provider.track(classify("weknora", "WeKnora API", true, true, outcome)) + health.ProbeTarget = probeTarget + return health } // productionWeKnoraProbe reports the real state of the production WeKnora diff --git a/internal/monitoring/health_test.go b/internal/monitoring/health_test.go index b6783f5..bb5f036 100644 --- a/internal/monitoring/health_test.go +++ b/internal/monitoring/health_test.go @@ -12,6 +12,7 @@ import ( "time" "knowledge-governance/internal/governance" + "knowledge-governance/internal/readiness" ) func testNow() time.Time { return time.Date(2026, 9, 12, 9, 0, 0, 0, time.UTC) } @@ -141,3 +142,31 @@ func TestOverallReadinessTreatsProductionEndpointAsAdvisory(t *testing.T) { t.Fatalf("real dependency failure must still block: ok=%v blocked=%v", ok, blocked) } } + +// F13: 旧 env 绑定 404 是「业务就绪被阻断」,不是「服务不可达」; +// 同时必须把脱敏后的探测对象带出来,否则红灯无法归因。 +func TestWeKnoraReadinessReportsBindingBlockWithoutLosingLiveness(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + writer.WriteHeader(http.StatusOK) + })) + defer server.Close() + provider := &RealProvider{ + httpClient: server.Client(), + weknoraBaseURL: server.URL, + health: newHealthTracker(), + weknoraReadiness: func(context.Context) (string, error) { + target := "实例 weknora.test · 知识库 1b52c140" + return target, fmt.Errorf("%w(%s)", readiness.ErrKnowledgeBaseMissing, target) + }, + } + health := provider.weKnoraProbe(context.Background(), testNow()) + if health.Liveness != LiveUp || health.Readiness != ReadBlocked { + t.Fatalf("404 binding = %+v, want up/blocked", health) + } + if health.ProbeTarget != "实例 weknora.test · 知识库 1b52c140" { + t.Fatalf("probe target = %q", health.ProbeTarget) + } + if !strings.Contains(health.Reason, "1b52c140") || strings.Contains(health.Reason, "1b52c140-2e18-4676-afc5-4c7d8d190a8c") { + t.Fatalf("reason = %q, want short target only", health.Reason) + } +} diff --git a/internal/monitoring/real.go b/internal/monitoring/real.go index 9b9fd26..49776f9 100644 --- a/internal/monitoring/real.go +++ b/internal/monitoring/real.go @@ -31,7 +31,7 @@ type RealProviderConfig struct { WeKnoraBaseURL string MinerUBaseURL string // TestWeKnoraResolver reads the test endpoint an admin saved in the web - // settings, so 「服务配置」is the single place the console probes. The env + // settings, so 「知识库映射 → WeKnora 连接」is the single place the console probes. The env // value above stays the bootstrap fallback for containers wired before the // UI existed. TestWeKnoraResolver func(ctx context.Context) string @@ -44,9 +44,9 @@ type RealProviderConfig struct { // place operators configure it — and the env value above stays the // bootstrap fallback for containers that were wired before the UI existed. ProductionWeKnoraResolver func(ctx context.Context) string - // WeKnoraReadiness optionally exercises a real read against a routing - // knowledge base (nil = API key not configured; liveness-only). - WeKnoraReadiness func(ctx context.Context) error + // WeKnoraReadiness optionally exercises a real read against the CURRENT + // routing binding and reports the sanitized probe target alongside the error. + WeKnoraReadiness func(ctx context.Context) (target string, err error) // WorkerStaleAfter bounds how long a missing worker heartbeat still counts // as alive (P10). WorkerStaleAfter time.Duration @@ -61,7 +61,7 @@ type RealProvider struct { testWeKnoraResolver func(ctx context.Context) string productionWeKnoraBaseURL string productionWeKnoraResolver func(ctx context.Context) string - weknoraReadiness func(ctx context.Context) error + weknoraReadiness func(ctx context.Context) (string, error) workerStaleAfter time.Duration health *healthTracker } diff --git a/internal/objectgateway/acquire.go b/internal/objectgateway/acquire.go new file mode 100644 index 0000000..5de60b6 --- /dev/null +++ b/internal/objectgateway/acquire.go @@ -0,0 +1,163 @@ +package objectgateway + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "github.com/jackc/pgx/v5" + "log" + "math" +) + +// Claim names an already persisted application attempt and write-set anchor. +// It never carries keys, bodies, a replacement plan or a chosen gateway epoch. +type Claim struct { + JobID string `json:"job_id"` + OperationID string `json:"operation_id"` + AttemptEpoch int64 `json:"attempt_epoch"` + Owner string `json:"owner"` + PlanDigest string `json:"plan_digest"` + RecoveryJobID string `json:"recovery_job_id,omitempty"` + RecoveryOperationID string `json:"recovery_operation_id,omitempty"` +} +type PlanAuthority interface { + Load(context.Context, Claim) (Plan, error) +} + +func (g *Gateway) Acquire(ctx context.Context, c Claim) (Grant, error) { + if g.Authority == nil { + return Grant{}, ErrAuthority + } + if c.JobID == "" || c.OperationID == "" || c.Owner == "" || c.AttemptEpoch < 1 || !validHash(c.PlanDigest) { + return Grant{}, ErrEpoch + } + if e := g.Ready(ctx); e != nil { + return Grant{}, e + } + plan, e := g.Authority.Load(ctx, c) + if e != nil { + return Grant{}, e + } + if plan.Digest != c.PlanDigest || plan.Owner != Digest([]byte(c.JobID)) { + // 冲突原因要能在服务端日志里定位:是谁的 plan、对不上哪一项。 + log.Printf("gateway acquire conflict job=%s op=%s plan=%s claim=%s owner_ok=%t", + c.JobID, c.OperationID, plan.Digest, c.PlanDigest, plan.Owner == Digest([]byte(c.JobID))) + return Grant{}, ErrConflict + } + if e = g.InstallPlan(ctx, plan); e != nil { + return Grant{}, e + } + // Recover only sends in this exact frozen plan. No absent observation can + // settle an unknown send; the locked advancement below still checks all intents. + rows, e := g.Pool.Query(ctx, `SELECT i.request FROM kg_object_gateway_intents i + LEFT JOIN kg_object_gateway_receipts r ON r.scope=i.scope AND r.operation=i.operation + WHERE i.scope=$1 AND r.operation IS NULL`, g.Scope) + if e != nil { + return Grant{}, ErrPersistence + } + var pending []Request + for rows.Next() { + var raw []byte + var request Request + if rows.Scan(&raw) != nil || json.Unmarshal(raw, &request) != nil { + rows.Close() + return Grant{}, ErrPersistence + } + if request.Grant.Plan == plan.Digest { + pending = append(pending, request) + } + } + e = rows.Err() + rows.Close() + if e != nil { + return Grant{}, ErrPersistence + } + for _, request := range pending { + if request.Grant.Owner != plan.Owner { + return Grant{}, ErrConflict + } + if _, e = g.Reconcile(ctx, request); e != nil { + return Grant{}, e + } + } + tx, e := g.Pool.Begin(ctx) + if e != nil { + return Grant{}, ErrPersistence + } + defer tx.Rollback(ctx) + if _, e = tx.Exec(ctx, "INSERT INTO kg_object_gateway_scopes(scope) VALUES($1) ON CONFLICT DO NOTHING", g.Scope); e != nil { + return Grant{}, ErrPersistence + } + var epoch int64 + if e = tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch); e != nil { + return Grant{}, ErrPersistence + } + // Recheck after serialization. This is admission evidence, not an OSS fence: + // a persisted uncertain object intent still prevents every epoch transition. + verified, e := g.Authority.Load(ctx, c) + if e != nil { + return Grant{}, e + } + frozen, _ := json.Marshal(plan) + again, _ := json.Marshal(verified) + if !bytes.Equal(frozen, again) { + return Grant{}, ErrConflict + } + raw, _ := json.Marshal(c) + var oldClaim, oldGrant []byte + e = tx.QueryRow(ctx, "SELECT claim,grant_body FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 AND attempt_epoch=$3", g.Scope, c.JobID, c.AttemptEpoch).Scan(&oldClaim, &oldGrant) + if e == nil { + var grant Grant + if !bytes.Equal(raw, oldClaim) || json.Unmarshal(oldGrant, &grant) != nil || !grant.valid() { + return Grant{}, ErrConflict + } + if grant.Epoch != epoch { + return Grant{}, ErrEpoch + } + return grant, nil + } + if !errors.Is(e, pgx.ErrNoRows) { + return Grant{}, ErrPersistence + } + var firstRaw []byte + firstErr := tx.QueryRow(ctx, "SELECT claim FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 ORDER BY attempt_epoch LIMIT 1", g.Scope, c.JobID).Scan(&firstRaw) + if firstErr == nil { + var first Claim + if json.Unmarshal(firstRaw, &first) != nil { + return Grant{}, ErrPersistence + } + if first.JobID != c.JobID || first.OperationID != c.OperationID || first.PlanDigest != c.PlanDigest { + return Grant{}, ErrConflict + } + } else if !errors.Is(firstErr, pgx.ErrNoRows) { + return Grant{}, ErrPersistence + } + var stale bool + if tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 AND attempt_epoch>=$3)", g.Scope, c.JobID, c.AttemptEpoch).Scan(&stale) != nil { + return Grant{}, ErrPersistence + } + if stale || epoch == math.MaxInt64 { + return Grant{}, ErrEpoch + } + next := Grant{Epoch: epoch + 1, Owner: plan.Owner, Plan: plan.Digest} + if e = g.advanceLocked(ctx, tx, epoch, next); e != nil { + return Grant{}, e + } + grantRaw, _ := json.Marshal(next) + if _, e = tx.Exec(ctx, "INSERT INTO kg_object_gateway_deliveries(scope,job,attempt_epoch,claim,grant_epoch,grant_body) VALUES($1,$2,$3,$4,$5,$6)", g.Scope, c.JobID, c.AttemptEpoch, raw, next.Epoch, grantRaw); e != nil { + return Grant{}, ErrPersistence + } + if tx.Commit(ctx) != nil { + return Grant{}, ErrPersistence + } + return next, nil +} +func (c *Client) Acquire(ctx context.Context, claim Claim) (Grant, error) { + var out Grant + e := c.call(ctx, "/v1/acquire", claim, &out) + if e == nil && (!out.valid() || out.Plan != claim.PlanDigest || out.Owner != Digest([]byte(claim.JobID))) { + e = ErrConflict + } + return out, e +} diff --git a/internal/objectgateway/acquire_integration_test.go b/internal/objectgateway/acquire_integration_test.go new file mode 100644 index 0000000..0cc548b --- /dev/null +++ b/internal/objectgateway/acquire_integration_test.go @@ -0,0 +1,122 @@ +package objectgateway_test + +import ( + "context" + "errors" + g "knowledge-governance/internal/objectgateway" + "testing" +) + +type currentPlanAuthority struct { + claim g.Claim + plan g.Plan +} + +func (a *currentPlanAuthority) Load(_ context.Context, c g.Claim) (g.Plan, error) { + if c != a.claim { + return g.Plan{}, g.ErrEpoch + } + return a.plan, nil +} +func TestGatewayAcquisitionPersistsAttemptDelivery(t *testing.T) { + ctx, pool, backend := fixture(t) + claim := g.Claim{JobID: "job-acquire", OperationID: "operation-acquire", AttemptEpoch: 1, Owner: "worker-1", PlanDigest: g.Digest([]byte(t.Name()))} + expected := g.Grant{Epoch: 1, Owner: g.Digest([]byte(claim.JobID)), Plan: claim.PlanDigest} + req := request("acquired-object", expected) + authority := ¤tPlanAuthority{claim, planFor(expected, req)} + gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20, Authority: authority} + grant, e := gateway.Acquire(ctx, claim) + if e != nil || grant != expected { + t.Fatal("anchored active attempt grant unavailable", e) + } + replay, e := gateway.Acquire(ctx, claim) + if e != nil || replay != grant { + t.Fatal("grant delivery replay changed epoch", e) + } + oldClaim := claim + claim.AttemptEpoch = 2 + claim.Owner = "worker-2" + authority.claim = claim + next, e := gateway.Acquire(ctx, claim) + if e != nil || next.Epoch != 2 { + t.Fatal("next active attempt", e) + } + if _, e = gateway.Acquire(ctx, oldClaim); !errors.Is(e, g.ErrEpoch) { + t.Fatal("stale attempt acquired grant", e) + } + replacement := claim + replacement.AttemptEpoch++ + replacement.PlanDigest = g.Digest([]byte("replacement-plan")) + authority.claim = replacement + authority.plan.Digest = replacement.PlanDigest + if _, e = gateway.Acquire(ctx, replacement); !errors.Is(e, g.ErrConflict) { + t.Fatal("new attempt replaced original plan", e) + } + authority.claim = claim + authority.plan.Digest = claim.PlanDigest + req.Grant = next + receipt, e := gateway.ExecuteAuthorized(ctx, next, req, []byte("gateway fixture acquired-object")) + if e != nil { + t.Fatal(e) + } + cleanup(t, ctx, gateway, receipt) + var count int + if e = pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries WHERE scope=$1", gateway.Scope).Scan(&count); e != nil || count != 2 { + t.Fatal("immutable delivery count", count, e) + } + for _, statement := range []string{"UPDATE kg_object_gateway_deliveries SET job=job", "DELETE FROM kg_object_gateway_deliveries", "TRUNCATE kg_object_gateway_deliveries"} { + if _, e = pool.Exec(ctx, statement); e == nil { + t.Fatal("mutable grant delivery", statement) + } + } +} + +func TestGatewayAcquisitionCannotHandOverUnknownSend(t *testing.T) { + ctx, pool, real := fixture(t) + backend := &stoppedBeforeSend{Backend: real} + claim := g.Claim{JobID: "job-held", OperationID: "operation-held", AttemptEpoch: 1, Owner: "worker-first", PlanDigest: g.Digest([]byte(t.Name()))} + expected := g.Grant{Epoch: 1, Owner: g.Digest([]byte(claim.JobID)), Plan: claim.PlanDigest} + req := request("acquire-held", expected) + body := []byte("gateway fixture acquire-held") + authority := ¤tPlanAuthority{claim, planFor(expected, req)} + gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20, Authority: authority} + if _, e := gateway.Acquire(ctx, claim); e != nil { + t.Fatal(e) + } + if _, e := gateway.ExecuteAuthorized(ctx, expected, req, body); !errors.Is(e, g.ErrHeld) { + t.Fatal(e) + } + claim.AttemptEpoch++ + claim.Owner = "worker-next" + authority.claim = claim + for i := 0; i < 2; i++ { + if _, e := gateway.Acquire(ctx, claim); !errors.Is(e, g.ErrHeld) { + t.Fatal("absent send handed over", e) + } + } + if backend.calls != 1 { + t.Fatal("control acquisition re-sent PUT") + } + var count int + if e := pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries WHERE scope=$1", gateway.Scope).Scan(&count); e != nil || count != 1 { + t.Fatal("unknown send advanced delivery", count, e) + } + // Deliver the previously uncertain request late, using its exact immutable claim. + if _, e := real.Put(ctx, req.Key, body, req.Claim()); e != nil { + t.Fatal(e) + } + next, e := gateway.Acquire(ctx, claim) + if e != nil || next.Epoch != 2 { + t.Fatal("committed send was not reconciled before handover", e) + } + receipt, e := gateway.ExecuteAuthorized(ctx, next, req, body) + if e != nil || receipt.Request != req { + t.Fatal(e) + } + if backend.calls != 1 { + t.Fatal("reconciled send was retried") + } + receipt.Request.Grant = next + cleanup(t, ctx, gateway, receipt) + t.Log("new controller attempt stayed held while absent; late committed original recovered without replay PUT") +} diff --git a/internal/objectgateway/attestation_legacy.go b/internal/objectgateway/attestation_legacy.go new file mode 100644 index 0000000..a319830 --- /dev/null +++ b/internal/objectgateway/attestation_legacy.go @@ -0,0 +1,26 @@ +package objectgateway + +import ( + "encoding/json" + "time" +) + +// Attestation is the retired whole-bucket exclusive-writer evidence format. +// It is kept only so historical audit artifacts remain readable; no runtime +// path loads, verifies or requires it. Admission is the journal, the backend +// capability and the frozen plan, all of which work on a shared bucket. +type Attestation struct { + Protocol string `json:"protocol"` + Scope string `json:"scope"` + GatewayID string `json:"gateway_id"` + IssuedAt time.Time `json:"issued_at"` + ExpiresAt time.Time `json:"expires_at"` + WriterInventory string `json:"writer_inventory_sha256"` + PolicyEvidence string `json:"policy_evidence_sha256"` + DenialEvidence string `json:"denial_evidence_sha256"` + DrainEvidence string `json:"drain_evidence_sha256"` +} +type SignedAttestation struct { + Payload json.RawMessage `json:"payload"` + Signature []byte `json:"signature"` +} diff --git a/internal/objectgateway/claim_context.go b/internal/objectgateway/claim_context.go new file mode 100644 index 0000000..efd1e01 --- /dev/null +++ b/internal/objectgateway/claim_context.go @@ -0,0 +1,15 @@ +package objectgateway + +import "context" + +type claimContextKey struct{} + +// WithClaim is set by the owned-attempt runner, never from an HTTP caller's +// proposed plan. The controller independently checks every field against PG. +func WithClaim(ctx context.Context, c Claim) context.Context { + return context.WithValue(ctx, claimContextKey{}, c) +} +func ClaimFromContext(ctx context.Context) Claim { + c, _ := ctx.Value(claimContextKey{}).(Claim) + return c +} diff --git a/internal/objectgateway/create.go b/internal/objectgateway/create.go new file mode 100644 index 0000000..9b549e8 --- /dev/null +++ b/internal/objectgateway/create.go @@ -0,0 +1,43 @@ +package objectgateway + +import "context" + +// sendCreate performs exactly one non-retried versioned PUT and then confirms +// the result. Versioned object stores do not provide atomic create-if-absent, +// so the confirmation re-reads the current version to make sure this request's +// version is still the one a reader would observe. +func sendCreate(ctx context.Context, b Backend, r Request, body []byte) (Version, error) { + v, err := b.Put(ctx, r.Key, body, r.token()) + if err != nil { + // Unknown outcome: the intent stays unresolved, nothing is retried and + // nothing is deleted because no version id is confirmed. + return Version{}, ErrHeld + } + return confirmCreate(ctx, b, r, v) +} + +// confirmCreate binds the receipt to a version that is both the exact version +// this request wrote and the current version of the key. It is read-only: the +// create intent is already committed, so withdrawing a version here would be an +// unrecorded mutation with no delete intent or receipt and would leave the +// create intent permanently held. A concurrent writer that produced a newer +// current version therefore wins by explicit conflict; both versions stay in +// the store and an operator resolves the key with evidence. +func confirmCreate(ctx context.Context, b Backend, r Request, v Version) (Version, error) { + exact, exists, err := b.Observe(ctx, r.Key, v.ID) + if err != nil || !exists || !r.matches(exact) || v != exact { + return Version{}, ErrHeld + } + latest, current, err := b.Observe(ctx, r.Key, "") + if err != nil || !current { + // Cannot tell whether our write is still current: keep the intent held + // rather than mutating anything on a guess. + return Version{}, ErrHeld + } + if latest.ID != v.ID { + // Another writer owns the current version. Report the conflict and leave + // both versions untouched; this path never merges them automatically. + return Version{}, ErrConflict + } + return v, nil +} diff --git a/internal/objectgateway/create_test.go b/internal/objectgateway/create_test.go new file mode 100644 index 0000000..2e5e5df --- /dev/null +++ b/internal/objectgateway/create_test.go @@ -0,0 +1,153 @@ +package objectgateway + +import ( + "context" + "errors" + "testing" +) + +type fakeBackend struct { + byID map[string]Version + latest Version + latestExists bool + latestErr error + putVersion Version + putErr error + putCalls int + deletes []string + deleteErr error +} + +func (f *fakeBackend) Ready(context.Context) error { return nil } +func (f *fakeBackend) Observe(_ context.Context, _ string, id string) (Version, bool, error) { + if id == "" { + if f.latestErr != nil { + return Version{}, false, f.latestErr + } + return f.latest, f.latestExists, nil + } + v, ok := f.byID[id] + return v, ok, nil +} +func (f *fakeBackend) List(context.Context, string) ([]Version, error) { return nil, nil } +func (f *fakeBackend) Put(context.Context, string, []byte, string) (Version, error) { + f.putCalls++ + if f.putErr != nil { + return Version{}, f.putErr + } + return f.putVersion, nil +} +func (f *fakeBackend) Delete(_ context.Context, _ string, v Version) error { + if f.deleteErr != nil { + return f.deleteErr + } + f.deletes = append(f.deletes, v.ID) + delete(f.byID, v.ID) + return nil +} + +func createFixture(t *testing.T) (Request, Version) { + t.Helper() + body := []byte("shared bucket object") + grant := Grant{Epoch: 1, Owner: Digest([]byte("owner")), Plan: Digest([]byte("plan"))} + r := Request{Grant: grant, Operation: Digest([]byte("operation")), Key: "kb/bound/object-1", Action: "create", SHA256: Digest(body), Bytes: int64(len(body))} + v := Version{ID: "version-own", Owner: r.token(), SHA256: r.SHA256, Bytes: r.Bytes, ETag: `"etag-own"`} + return r, v +} + +func TestCreateConfirmationDetectsNewerForeignVersionWithoutSideEffects(t *testing.T) { + r, own := createFixture(t) + foreign := Version{ID: "version-foreign", Owner: Digest([]byte("foreign-owner")), SHA256: Digest([]byte("foreign")), Bytes: 7, ETag: `"etag-foreign"`} + f := &fakeBackend{byID: map[string]Version{own.ID: own, foreign.ID: foreign}, latest: foreign, latestExists: true, putVersion: own} + if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrConflict) { + t.Fatalf("concurrent newer version accepted as committed: %v", err) + } + // Confirmation runs after the journal intent exists. Deleting here would be + // an unrecorded mutation with no delete intent/receipt and would strand the + // create intent in held forever, so confirmation must be read-only. + if len(f.deletes) != 0 { + t.Fatalf("confirmation deleted without a delete intent/receipt: %v", f.deletes) + } + if _, ok := f.byID[own.ID]; !ok { + t.Fatal("own version removed without a recorded delete") + } + if _, ok := f.byID[foreign.ID]; !ok { + t.Fatal("foreign version was deleted") + } +} + +func TestCreateConfirmationCommitsOnlyWhenOwnVersionIsCurrent(t *testing.T) { + r, own := createFixture(t) + f := &fakeBackend{byID: map[string]Version{own.ID: own}, latest: own, latestExists: true, putVersion: own} + got, err := confirmCreate(context.Background(), f, r, own) + if err != nil || got != own { + t.Fatalf("own current version not committed: %v %v", got, err) + } + if len(f.deletes) != 0 { + t.Fatalf("unexpected rollback %v", f.deletes) + } +} + +func TestCreateConfirmationHoldsWithoutDeletingWhenCurrentVersionUnreadable(t *testing.T) { + r, own := createFixture(t) + f := &fakeBackend{byID: map[string]Version{own.ID: own}, putVersion: own, latestErr: errors.New("read failed")} + if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrHeld) { + t.Fatalf("unreadable current version treated as terminal: %v", err) + } + if len(f.deletes) != 0 { + t.Fatalf("deleted on an unknown observation: %v", f.deletes) + } +} + +func TestCreateConfirmationHoldsOnExactReadbackMismatch(t *testing.T) { + r, own := createFixture(t) + other := own + other.ETag = `"different"` + f := &fakeBackend{byID: map[string]Version{own.ID: other}, latest: other, latestExists: true, putVersion: own} + if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrHeld) { + t.Fatalf("mismatched readback treated as committed: %v", err) + } + if len(f.deletes) != 0 { + t.Fatalf("deleted on mismatch: %v", f.deletes) + } +} + +func TestCreateSendIsSingleAttemptAndNeverDeletesUnknownPut(t *testing.T) { + r, _ := createFixture(t) + f := &fakeBackend{putErr: errors.New("transport lost")} + if _, err := sendCreate(context.Background(), f, r, []byte("shared bucket object")); !errors.Is(err, ErrHeld) { + t.Fatalf("unknown PUT treated as terminal: %v", err) + } + if f.putCalls != 1 { + t.Fatalf("PUT retried: calls=%d", f.putCalls) + } + if len(f.deletes) != 0 { + t.Fatalf("deleted without a confirmed version: %v", f.deletes) + } +} + +func TestPlanAuthorizesOnlyFrozenObjectList(t *testing.T) { + body := []byte("planned") + owner, digest := Digest([]byte("owner")), Digest([]byte("plan-digest")) + p := Plan{Digest: digest, Owner: owner, Objects: []ObjectBinding{{Operation: Digest([]byte("op-1")), Key: "kb/allowed/1", SHA256: Digest(body), Bytes: int64(len(body))}}} + allowed := Request{Grant: Grant{1, owner, digest}, Operation: Digest([]byte("op-1")), Key: "kb/allowed/1", Action: "create", SHA256: Digest(body), Bytes: int64(len(body))} + if !p.allows(allowed) { + t.Fatal("frozen object rejected") + } + for name, mutate := range map[string]func(*Request){ + "other_kb_key": func(r *Request) { r.Key = "kb/other-kb/1" }, + "other_object": func(r *Request) { r.Key = "kb/allowed/2" }, + "other_operation": func(r *Request) { r.Operation = Digest([]byte("op-2")) }, + } { + got := allowed + mutate(&got) + if p.allows(got) { + t.Fatalf("%s authorized outside the frozen write set", name) + } + } + dup := p + dup.Objects = append(dup.Objects, p.Objects[0]) + if dup.valid() { + t.Fatal("duplicate key accepted in plan") + } +} diff --git a/internal/objectgateway/gateway.go b/internal/objectgateway/gateway.go new file mode 100644 index 0000000..cf9692b --- /dev/null +++ b/internal/objectgateway/gateway.go @@ -0,0 +1,333 @@ +package objectgateway + +import ( + "context" + _ "embed" + "encoding/json" + "errors" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +// Schema is applied explicitly by the migration identity, never on server startup. +// +//go:embed schema.sql +var Schema string + +type Gateway struct { + Authority PlanAuthority + Pool *pgxpool.Pool + Scope string + Backend Backend + MaxBytes int64 +} + +// Ready gates admission on the local journal and the object backend only. A +// shared bucket is the supported deployment shape: unrelated writers on other +// keys do not need to be drained, and no whole-bucket exclusivity evidence is +// required. Per-key competition is handled at execute time, not by a global +// "only writer" attestation. +func (g *Gateway) Ready(ctx context.Context) error { + if g.Pool == nil || g.Scope == "" || g.Backend == nil || g.MaxBytes < 1 { + return ErrPersistence + } + var sync, fsync, full string + if g.Pool.QueryRow(ctx, "SELECT current_setting('synchronous_commit'), current_setting('fsync'), current_setting('full_page_writes')").Scan(&sync, &fsync, &full) != nil || sync != "on" || fsync != "on" || full != "on" { + return ErrPersistence + } + var journal bool + if g.Pool.QueryRow(ctx, `SELECT NOT pg_is_in_recovery() AND current_setting('transaction_read_only')='off' + AND to_regclass('kg_object_gateway_plans') IS NOT NULL + AND to_regclass('kg_object_gateway_scopes') IS NOT NULL + AND to_regclass('kg_object_gateway_grants') IS NOT NULL + AND to_regclass('kg_object_gateway_intents') IS NOT NULL + AND to_regclass('kg_object_gateway_receipts') IS NOT NULL + AND to_regclass('kg_object_gateway_deliveries') IS NOT NULL + AND (SELECT count(*)=10 FROM pg_trigger WHERE tgname IN ('kg_object_gateway_deliveries_immutable','kg_object_gateway_deliveries_no_truncate','kg_object_gateway_plans_no_truncate','kg_object_gateway_intents_no_truncate','kg_object_gateway_receipts_no_truncate','kg_object_gateway_grants_no_truncate','kg_object_gateway_plans_immutable','kg_object_gateway_intents_immutable','kg_object_gateway_receipts_immutable','kg_object_gateway_grants_immutable') AND tgenabled='O')`).Scan(&journal) != nil || !journal { + return ErrPersistence + } + if g.Backend.Ready(ctx) != nil { + return errors.New("gateway_backend_not_ready") + } + return nil +} +func (g *Gateway) Advance(ctx context.Context, expected int64, next Grant) error { + if !next.valid() || next.Epoch != expected+1 { + return ErrEpoch + } + if err := g.Ready(ctx); err != nil { + return err + } + var frozen []byte + var plan Plan + if g.Pool.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, next.Plan).Scan(&frozen) != nil { + return ErrConflict + } + if json.Unmarshal(frozen, &plan) != nil || !plan.valid() || plan.Owner != next.Owner { + return ErrConflict + } + tx, err := g.Pool.Begin(ctx) + if err != nil { + return ErrPersistence + } + defer tx.Rollback(ctx) + if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_scopes(scope) VALUES($1) ON CONFLICT DO NOTHING", g.Scope); err != nil { + return ErrPersistence + } + var epoch int64 + if tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch) != nil { + return ErrPersistence + } + if err = g.advanceLocked(ctx, tx, epoch, next); err != nil { + return err + } + if tx.Commit(ctx) != nil { + return ErrPersistence + } + return nil +} + +func (g *Gateway) advanceLocked(ctx context.Context, tx pgx.Tx, epoch int64, next Grant) error { + var err error + if epoch == next.Epoch { + var owner, plan string + if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil { + return ErrPersistence + } + if owner != next.Owner || plan != next.Plan { + return ErrEpoch + } + return nil + } + if epoch != next.Epoch-1 { + return ErrEpoch + } + var pending bool + if tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM kg_object_gateway_intents i WHERE i.scope=$1 AND NOT EXISTS(SELECT 1 FROM kg_object_gateway_receipts r WHERE r.scope=i.scope AND r.operation=i.operation))`, g.Scope).Scan(&pending) != nil { + return ErrPersistence + } + if pending { + return ErrHeld + } + if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_grants(scope,epoch,owner,plan) VALUES($1,$2,$3,$4)", g.Scope, next.Epoch, next.Owner, next.Plan); err != nil { + return ErrPersistence + } + if _, err = tx.Exec(ctx, "UPDATE kg_object_gateway_scopes SET epoch=$2 WHERE scope=$1", g.Scope, next.Epoch); err != nil { + return ErrPersistence + } + return nil +} + +// reserve commits an immutable may-send intent. Even a commit timeout cannot be +// followed by a send. Another process can reconcile, but cannot retry this PUT. +func (g *Gateway) reserve(ctx context.Context, r Request, authorization *Grant) (bool, error) { + tx, err := g.Pool.Begin(ctx) + if err != nil { + return false, ErrPersistence + } + defer tx.Rollback(ctx) + var epoch int64 + if tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch) != nil { + return false, ErrEpoch + } + if authorization != nil { + var owner, plan string + if epoch != authorization.Epoch { + return false, ErrEpoch + } + if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil { + return false, ErrPersistence + } + if owner != authorization.Owner || plan != authorization.Plan { + return false, ErrEpoch + } + } + raw, _ := json.Marshal(r) + var previous []byte + err = tx.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, r.Operation).Scan(&previous) + if err == nil { + if string(previous) != string(raw) { + return false, ErrConflict + } + return false, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return false, ErrPersistence + } + var owner, plan string + if epoch != r.Grant.Epoch { + return false, ErrEpoch + } + if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil { + return false, ErrPersistence + } + if owner != r.Grant.Owner || plan != r.Grant.Plan { + return false, ErrEpoch + } + var pending bool + if tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM kg_object_gateway_intents i WHERE i.scope=$1 AND i.key=$2 AND NOT EXISTS(SELECT 1 FROM kg_object_gateway_receipts x WHERE x.scope=i.scope AND x.operation=i.operation))`, g.Scope, r.Key).Scan(&pending) != nil { + return false, ErrPersistence + } + if pending { + return false, ErrHeld + } + var frozen []byte + var allowed Plan + if tx.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, r.Grant.Plan).Scan(&frozen) != nil { + return false, ErrPersistence + } + if json.Unmarshal(frozen, &allowed) != nil || !allowed.valid() || !allowed.allows(r) { + return false, ErrConflict + } + if r.Action == "delete" { + previous, err := g.receipt(ctx, r.CreatedBy) + if err != nil || previous.State != "committed" || previous.Request.Key != r.Key || previous.Version != r.Version { + return false, ErrConflict + } + } + if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_intents(scope,operation,key,request) VALUES($1,$2,$3,$4)", g.Scope, r.Operation, r.Key, raw); err != nil { + return false, ErrPersistence + } + if tx.Commit(ctx) != nil { + return false, ErrPersistence + } + return true, nil +} +func (g *Gateway) receipt(ctx context.Context, id string) (Receipt, error) { + var raw []byte + var r Receipt + err := g.Pool.QueryRow(ctx, "SELECT receipt FROM kg_object_gateway_receipts WHERE scope=$1 AND operation=$2", g.Scope, id).Scan(&raw) + if err != nil { + return r, err + } + if json.Unmarshal(raw, &r) != nil { + return r, ErrPersistence + } + return r, nil +} +func (g *Gateway) finish(ctx context.Context, r Request, state string, v Version) (Receipt, error) { + receipt := Receipt{r, state, v} + raw, _ := json.Marshal(receipt) + _, err := g.Pool.Exec(ctx, "INSERT INTO kg_object_gateway_receipts(scope,operation,receipt) VALUES($1,$2,$3) ON CONFLICT DO NOTHING", g.Scope, r.Operation, raw) + if err != nil { + return Receipt{}, ErrPersistence + } + got, err := g.receipt(ctx, r.Operation) + if err != nil { + return Receipt{}, ErrPersistence + } + if got != receipt { + return Receipt{}, ErrConflict + } + return got, nil +} +func (g *Gateway) Execute(ctx context.Context, r Request, body []byte) (Receipt, error) { + return g.execute(ctx, r, body, nil) +} +func (g *Gateway) execute(ctx context.Context, r Request, body []byte, authorization *Grant) (Receipt, error) { + if err := r.validate(); err != nil { + return Receipt{}, err + } + if r.Bytes > g.MaxBytes || r.Action == "create" && (int64(len(body)) != r.Bytes || Digest(body) != r.SHA256) || r.Action == "delete" && len(body) != 0 { + return Receipt{}, ErrConflict + } + if err := g.Ready(ctx); err != nil { + return Receipt{}, err + } + fresh, err := g.reserve(ctx, r, authorization) + if err != nil { + return Receipt{}, err + } + if !fresh { + return g.Reconcile(ctx, r) + } + if r.Action == "create" { + _, exists, err := g.Backend.Observe(ctx, r.Key, "") + if err != nil { + return Receipt{}, ErrHeld + } + if exists { + return g.finish(ctx, r, "rejected", Version{}) + } + v, err := sendCreate(ctx, g.Backend, r, body) + if err != nil { + return Receipt{}, err + } + return g.finish(ctx, r, "committed", v) + } + v, exists, err := g.Backend.Observe(ctx, r.Key, r.Version.ID) + if err != nil { + return Receipt{}, ErrHeld + } + if exists && v != r.Version { + return Receipt{}, ErrConflict + } + if exists { + if g.Backend.Delete(ctx, r.Key, r.Version) != nil { + return Receipt{}, ErrHeld + } + } + return g.Reconcile(ctx, r) +} +func (g *Gateway) Reconcile(ctx context.Context, r Request) (Receipt, error) { + if err := r.validate(); err != nil { + return Receipt{}, err + } + if err := g.Ready(ctx); err != nil { + return Receipt{}, err + } + var raw []byte + if g.Pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, r.Operation).Scan(&raw) != nil { + return Receipt{}, ErrConflict + } + want, _ := json.Marshal(r) + if string(raw) != string(want) { + return Receipt{}, ErrConflict + } + got, err := g.receipt(ctx, r.Operation) + if err == nil { + return got, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return Receipt{}, ErrPersistence + } + if r.Action == "delete" { + _, exists, err := g.Backend.Observe(ctx, r.Key, r.Version.ID) + if err != nil || exists { + return Receipt{}, ErrHeld + } + return g.finish(ctx, r, "removed", r.Version) + } + versions, err := g.Backend.List(ctx, r.Key) + if err != nil { + return Receipt{}, ErrHeld + } + var found []Version + for _, v := range versions { + if v.Owner == r.token() { + if !r.matches(v) { + return Receipt{}, ErrHeld + } + found = append(found, v) + } + } + if len(found) != 1 { + return Receipt{}, ErrHeld + } + exact, exists, err := g.Backend.Observe(ctx, r.Key, found[0].ID) + if err != nil || !exists || exact != found[0] { + return Receipt{}, ErrHeld + } + latest, current, err := g.Backend.Observe(ctx, r.Key, "") + if err != nil || !current { + return Receipt{}, ErrHeld + } + if latest.ID != exact.ID { + // Another writer owns the current version of this key. Do not delete + // anything during reconcile and do not report a committed create for a + // key this plan no longer controls. + return Receipt{}, ErrConflict + } + return g.finish(ctx, r, "committed", exact) +} diff --git a/internal/objectgateway/gateway_integration_test.go b/internal/objectgateway/gateway_integration_test.go new file mode 100644 index 0000000..72408a4 --- /dev/null +++ b/internal/objectgateway/gateway_integration_test.go @@ -0,0 +1,396 @@ +package objectgateway_test + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" + "github.com/jackc/pgx/v5/pgxpool" + g "knowledge-governance/internal/objectgateway" +) + +func fixture(t *testing.T) (context.Context, *pgxpool.Pool, *g.S3Backend) { + t.Helper() + dsn := os.Getenv("KG_GATEWAY_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("isolated gateway PG/MinIO opt-in required") + } + u, e := url.Parse(dsn) + if e != nil || !strings.HasPrefix(strings.TrimPrefix(u.Path, "/"), "kg_library_test_gateway_") || u.Hostname() != "127.0.0.1" { + t.Fatal("unsafe gateway test database") + } + ctx := context.Background() + pool, e := pgxpool.New(ctx, dsn) + if e != nil { + t.Fatal("PG unavailable") + } + t.Cleanup(pool.Close) + if _, e = pool.Exec(ctx, g.Schema); e != nil { + t.Fatal(e) + } + endpoint := os.Getenv("KG_GATEWAY_TEST_ENDPOINT") + if endpoint != "http://127.0.0.1:19100" { + t.Fatal("unsafe test MinIO endpoint") + } + bucket := "kg-library-test-gateway-" + g.Digest([]byte(t.Name() + time.Now().String()))[:16] + client := s3.New(s3.Options{Region: "us-east-1", BaseEndpoint: aws.String(endpoint), UsePathStyle: true, Credentials: credentials.NewStaticCredentialsProvider(os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"), os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"), "")}) + if _, e = client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucket)}); e != nil { + t.Fatal("create isolated bucket failed") + } + if _, e = client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: aws.String(bucket), VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled}}); e != nil { + t.Fatal(e) + } + t.Cleanup(func() { + list, e := client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(bucket)}) + if e != nil { + t.Error("residue list unavailable") + return + } + if len(list.Versions) != 0 || len(list.DeleteMarkers) != 0 { + t.Errorf("preserving residue bucket %s: versions=%d markers=%d", bucket, len(list.Versions), len(list.DeleteMarkers)) + return + } + if _, e = client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucket)}); e != nil { + t.Error("delete empty test bucket failed") + } + t.Logf("exact sandbox %s: versions=0 markers=0; empty bucket deleted", bucket) + }) + return ctx, pool, &g.S3Backend{Client: client, Bucket: bucket, MaxBytes: 1 << 20} +} +func planFor(grant g.Grant, requests ...g.Request) g.Plan { + p := g.Plan{Digest: grant.Plan, Owner: grant.Owner} + for _, r := range requests { + p.Objects = append(p.Objects, g.ObjectBinding{Operation: r.Operation, Key: r.Key, SHA256: r.SHA256, Bytes: r.Bytes}) + } + return p +} +func request(label string, grant g.Grant) g.Request { + body := []byte("gateway fixture " + label) + return g.Request{Grant: grant, Operation: g.Digest([]byte(label)), Key: "unchanged/" + label, Action: "create", SHA256: g.Digest(body), Bytes: int64(len(body))} +} +func cleanup(t *testing.T, ctx context.Context, gw *g.Gateway, receipt g.Receipt) { + t.Helper() + r := receipt.Request + r.Operation = g.Digest([]byte(r.Operation + "delete")) + r.Action = "delete" + r.CreatedBy = receipt.Request.Operation + r.Version = receipt.Version + if got, e := gw.Execute(ctx, r, nil); e != nil || got.State != "removed" { + t.Fatalf("exact cleanup: %v %s", e, got.State) + } +} +func TestGatewayReadinessRequiresJournal(t *testing.T) { + ctx, pool, backend := fixture(t) + // An isolated search_path lacks the journal while PG settings remain healthy. + conn, e := pool.Acquire(ctx) + if e != nil { + t.Fatal(e) + } + conn.Release() + cfg := pool.Config() + cfg.ConnConfig.RuntimeParams["search_path"] = "pg_catalog" + other, e := pgxpool.NewWithConfig(ctx, cfg) + if e != nil { + t.Fatal(e) + } + defer other.Close() + gw := &g.Gateway{Pool: other, Scope: "missing-journal", Backend: backend, MaxBytes: 1 << 20} + if e := gw.Ready(ctx); !errors.Is(e, g.ErrPersistence) { + t.Fatalf("missing durable journal accepted: %v", e) + } +} +func TestGatewayRealReplayAndImmutableLedger(t *testing.T) { + ctx, pool, backend := fixture(t) + grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))} + gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20} + if _, exists, err := backend.Observe(ctx, "missing-key-probe", ""); err != nil || exists { + t.Fatalf("initial authoritative absence unavailable: %v exists=%v", err, exists) + } + if e := gw.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil { + t.Fatal(e) + } + if e := gw.Advance(ctx, 0, grant); e != nil { + t.Fatal(e) + } + req := request(t.Name(), grant) + body := []byte("gateway fixture " + t.Name()) + one, e := gw.Execute(ctx, req, body) + if e != nil || one.State != "committed" { + t.Fatalf("create %v %s", e, one.State) + } + two, e := gw.Execute(ctx, req, body) + if e != nil || two != one { + t.Fatal("replay changed receipt", e) + } + bad := req + bad.Key += "-different" + if _, e = gw.Execute(ctx, bad, body); !errors.Is(e, g.ErrConflict) { + t.Fatal("operation rebound", e) + } + for _, table := range []string{"intents", "receipts", "grants", "plans"} { + if _, e = pool.Exec(ctx, "DELETE FROM kg_object_gateway_"+table+" WHERE scope=$1", gw.Scope); e == nil { + t.Fatal("immutable evidence deleted", table) + } + } + for _, table := range []string{"plans", "intents", "receipts", "grants"} { + tx, e := pool.Begin(ctx) + if e != nil { + t.Fatal(e) + } + _, e = tx.Exec(ctx, "TRUNCATE kg_object_gateway_"+table+" CASCADE") + _ = tx.Rollback(ctx) + if e == nil { + cleanup(t, ctx, gw, one) + t.Fatal("immutable evidence truncation accepted", table) + } + } + cleanup(t, ctx, gw, one) + next := grant + next.Epoch = 2 + if e = gw.Advance(ctx, 1, next); e != nil { + t.Fatal(e) + } + late := request("late", grant) + if _, e = gw.Execute(ctx, late, []byte("gateway fixture late")); !errors.Is(e, g.ErrEpoch) { + t.Fatal("old epoch sent", e) + } +} + +func signedAudit(t *testing.T, scope string) (string, string) { + t.Helper() + pub, priv, e := ed25519.GenerateKey(rand.Reader) + if e != nil { + t.Fatal(e) + } + // This is a test authority. It exercises verification, NOT production exclusivity. + a := g.Attestation{Protocol: g.Protocol, Scope: scope, GatewayID: "isolated-fixture", IssuedAt: time.Now().Add(-time.Minute), ExpiresAt: time.Now().Add(30 * time.Minute), WriterInventory: g.Digest([]byte("fixture inventory")), PolicyEvidence: g.Digest([]byte("fixture policy")), DenialEvidence: g.Digest([]byte("fixture denial")), DrainEvidence: g.Digest([]byte("fixture drain"))} + raw, _ := json.Marshal(a) + signed, _ := json.Marshal(g.SignedAttestation{Payload: raw, Signature: ed25519.Sign(priv, raw)}) + path := filepath.Join(t.TempDir(), "audit.json") + if os.WriteFile(path, signed, 0600) != nil { + t.Fatal("audit write failed") + } + return path, base64.StdEncoding.EncodeToString(pub) +} +func startGateway(t *testing.T, env []string, client *g.Client) *exec.Cmd { + t.Helper() + binary := os.Getenv("KG_GATEWAY_TEST_BINARY") + if binary == "" { + t.Fatal("actual gateway binary is required") + } + cmd := exec.Command(binary) + cmd.Env = env + log, e := os.Create(filepath.Join(t.TempDir(), "service.log")) + if e != nil { + t.Fatal(e) + } + cmd.Stdout = log + cmd.Stderr = log + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); _ = log.Close() }) + for i := 0; i < 100; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + e = client.Ready(ctx) + cancel() + if e == nil { + return cmd + } + time.Sleep(30 * time.Millisecond) + } + raw, _ := os.ReadFile(log.Name()) + t.Fatalf("actual gateway not ready: %s", raw) + return nil +} +func TestGatewayActualServiceTwoInterruptions(t *testing.T) { + ctx, pool, backend := fixture(t) + upstream, _ := url.Parse(os.Getenv("KG_GATEWAY_TEST_ENDPOINT")) + proxy := httputil.NewSingleHostReverseProxy(upstream) + beforeSend := make(chan struct{}, 2) + allowSend := make(chan struct{}, 2) + committed := make(chan struct{}, 2) + release := make(chan struct{}, 2) + var puts atomic.Int32 + proxy.ModifyResponse = func(resp *http.Response) error { + if resp.Request.Method == "PUT" && !strings.Contains(resp.Request.URL.RawQuery, "versioning") { + puts.Add(1) + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + committed <- struct{}{} + select { + case <-release: + case <-resp.Request.Context().Done(): + } + return errors.New("injected lost response after actual MinIO commit") + } + } + return nil + } + proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { http.Error(w, "injected_transport_loss", 502) } + p := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "PUT" && !strings.Contains(r.URL.RawQuery, "versioning") { + beforeSend <- struct{}{} + select { + case <-allowSend: + case <-r.Context().Done(): + return + } + } + proxy.ServeHTTP(w, r) + })) + defer p.Close() + scope := g.Digest([]byte("minio\x00" + p.URL + "\x00" + backend.Bucket)) + audit, pub := signedAudit(t, scope) + listener, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + addr := listener.Addr().String() + listener.Close() + data := g.Digest([]byte("data " + scope)) + control := g.Digest([]byte("control " + scope)) + client, e := g.NewClient("http://"+addr, data, scope) + if e != nil { + t.Fatal(e) + } + admin, _ := g.NewClient("http://"+addr, control, scope) + env := append(os.Environ(), "OBJECT_GATEWAY_LISTEN="+addr, "OBJECT_GATEWAY_DATABASE_URL="+os.Getenv("KG_GATEWAY_TEST_DATABASE_URL"), "OBJECT_GATEWAY_PROVIDER=minio", "OBJECT_GATEWAY_ENDPOINT="+p.URL, "OBJECT_GATEWAY_BUCKET="+backend.Bucket, "OBJECT_GATEWAY_ACCESS_KEY="+os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"), "OBJECT_GATEWAY_SECRET_KEY="+os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"), "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY="+pub, "OBJECT_GATEWAY_AUDIT_FILE="+audit, "OBJECT_GATEWAY_ID=isolated-fixture", "OBJECT_GATEWAY_DATA_TOKEN="+data, "OBJECT_GATEWAY_CONTROL_TOKEN="+control) + cmd := startGateway(t, env, client) + grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("actual-worker")), Plan: g.Digest([]byte("frozen-actual-plan"))} + if e = client.InstallPlan(ctx, planFor(grant, request("actual-0", grant))); e == nil { + t.Fatal("data client installed plan") + } + if e = admin.InstallPlan(ctx, planFor(grant, request("actual-0", grant), request("actual-1", grant))); e != nil { + t.Fatal(e) + } + if e = admin.Advance(ctx, 0, grant); e != nil { + t.Fatal(e) + } + if e = client.Advance(ctx, 0, grant); e == nil { + t.Fatal("data client acquired control authority") + } + for iteration := 0; iteration < 2; iteration++ { + label := fmt.Sprintf("actual-%d", iteration) + r := request(label, grant) + body := []byte("gateway fixture " + label) + done := make(chan error, 1) + go func() { _, e := client.Execute(ctx, r, body); done <- e }() + select { + case <-beforeSend: + case <-time.After(15 * time.Second): + t.Fatal("gateway did not send to proxy") + } + if _, e = client.Reconcile(ctx, r); !errors.Is(e, g.ErrHeld) { + t.Fatal("not-yet-visible PUT treated as terminal", e) + } + blockedNext := grant + blockedNext.Epoch++ + if e = admin.Advance(ctx, grant.Epoch, blockedNext); !errors.Is(e, g.ErrHeld) { + t.Fatal("epoch crossed delayed precommit request", e) + } + allowSend <- struct{}{} + select { + case <-committed: + case <-time.After(15 * time.Second): + t.Fatal("actual MinIO PUT did not commit") + } + next := grant + next.Epoch++ + if e = admin.Advance(ctx, grant.Epoch, next); !errors.Is(e, g.ErrHeld) { + t.Fatal("epoch crossed in-flight write", e) + } + sameKey := r + sameKey.Operation = g.Digest([]byte(label + "other")) + if _, e = client.Execute(ctx, sameKey, body); !errors.Is(e, g.ErrHeld) { + t.Fatal("same-key competitor admitted", e) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + _ = cmd.Wait() + release <- struct{}{} + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("dead gateway call did not end") + } + t.Logf("actual gateway SIGKILL %d after MinIO commit before receipt", iteration+1) + cmd = startGateway(t, env, client) + receipt, e := client.Reconcile(ctx, r) + if e != nil || receipt.State != "committed" { + t.Fatalf("restart reconcile %v %s", e, receipt.State) + } + repeated, e := client.Execute(ctx, r, body) + if e != nil || receipt != repeated { + t.Fatal("restart duplicate not idempotent", e) + } + del := r + del.Action = "delete" + del.CreatedBy = r.Operation + del.Operation = g.Digest([]byte(label + "cleanup")) + del.Version = receipt.Version + cleaned, e := client.Execute(ctx, del, nil) + if e != nil || cleaned.State != "removed" { + t.Fatal("actual exact cleanup failed", e) + } + if e = admin.Advance(ctx, grant.Epoch, next); e != nil { + t.Fatal(e) + } + late := request(label+"late", grant) + if _, e = client.Execute(ctx, late, []byte("gateway fixture "+label+"late")); !errors.Is(e, g.ErrEpoch) { + t.Fatal("late stale epoch admitted", e) + } + grant = next + } + if puts.Load() != 2 { + t.Fatalf("blind PUT replay count=%d", puts.Load()) + } + var n int + if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE scope=$1", scope).Scan(&n) != nil || n != 4 { + t.Fatalf("durable receipts=%d", n) + } + _ = cmd.Process.Kill() + _ = cmd.Wait() + if e = client.Ready(ctx); e == nil { + t.Fatal("unavailable gateway accepted") + } + t.Log("actual binary + HTTP + durable PG + MinIO: two kills/restarts, 2 PUTs, 4 receipts, exact cleanup") +} + +func TestGatewayClientRejectsBadProtocolAndLeaks(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("secret") != "" { + t.Error("secret in URL") + } + _, _ = io.WriteString(w, `{"protocol":"other","scope":"scope","ready":true}`) + })) + defer server.Close() + c, e := g.NewClient(server.URL, strings.Repeat("x", 32), "scope") + if e != nil { + t.Fatal(e) + } + if c.Ready(context.Background()) == nil { + t.Fatal("wrong protocol accepted") + } +} diff --git a/internal/objectgateway/http.go b/internal/objectgateway/http.go new file mode 100644 index 0000000..329babf --- /dev/null +++ b/internal/objectgateway/http.go @@ -0,0 +1,314 @@ +package objectgateway + +import ( + "bytes" + "context" + "crypto/subtle" + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +type ExecuteRequest struct { + Authorization *Grant `json:"authorization,omitempty"` + Request Request `json:"request"` + Body []byte `json:"body,omitempty"` +} +type AdvanceRequest struct { + Expected int64 `json:"expected"` + Grant Grant `json:"grant"` +} +type Capabilities struct { + AutomaticGrants bool `json:"automatic_grants"` + Protocol string `json:"protocol"` + Scope string `json:"scope"` + Ready bool `json:"ready"` +} +type HTTPServer struct { + Gateway *Gateway + DataToken, ControlToken string +} + +func (s HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + token := s.DataToken + if r.URL.Path == "/v1/advance" || r.URL.Path == "/v1/plans" { + token = s.ControlToken + } + if len(token) < 32 || s.DataToken == s.ControlToken || subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+token)) != 1 { + http.Error(w, "gateway_unauthorized", 401) + return + } + if r.Header.Get("X-KG-Gateway-Protocol") != Protocol || r.Header.Get("X-KG-Gateway-Scope") != s.Gateway.Scope { + http.Error(w, "gateway_protocol_or_target_mismatch", 409) + return + } + fail := func(e error) { + code := 503 + if errors.Is(e, ErrEpoch) || errors.Is(e, ErrConflict) || errors.Is(e, ErrHeld) { + code = 409 + } + http.Error(w, e.Error(), code) + } + decode := func(v any) bool { + r.Body = http.MaxBytesReader(w, r.Body, s.Gateway.MaxBytes*2+16384) + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if d.Decode(v) != nil || d.Decode(&struct{}{}) != io.EOF { + http.Error(w, "gateway_bad_request", 400) + return false + } + return true + } + if r.Method == "GET" && r.URL.Path == "/v1/capabilities" { + if e := s.Gateway.Ready(r.Context()); e != nil { + fail(e) + return + } + if authority, ok := s.Gateway.Authority.(interface{ Ready(context.Context) error }); ok { + if e := authority.Ready(r.Context()); e != nil { + fail(e) + return + } + } + _ = json.NewEncoder(w).Encode(Capabilities{Protocol: Protocol, Scope: s.Gateway.Scope, Ready: true, AutomaticGrants: s.Gateway.Authority != nil}) + return + } + if r.Method != "POST" { + http.Error(w, "gateway_route_not_found", 404) + return + } + switch r.URL.Path { + case "/v1/acquire": + var in Claim + if !decode(&in) { + return + } + out, e := s.Gateway.Acquire(r.Context(), in) + if e != nil { + fail(e) + return + } + _ = json.NewEncoder(w).Encode(out) + case "/v1/plans": + if s.Gateway.Authority != nil { + fail(ErrConflict) + return + } + var in Plan + if !decode(&in) { + return + } + if e := s.Gateway.InstallPlan(r.Context(), in); e != nil { + fail(e) + return + } + _ = json.NewEncoder(w).Encode(in) + case "/v1/advance": + if s.Gateway.Authority != nil { + fail(ErrConflict) + return + } + var in AdvanceRequest + if !decode(&in) { + return + } + if e := s.Gateway.Advance(r.Context(), in.Expected, in.Grant); e != nil { + fail(e) + return + } + _ = json.NewEncoder(w).Encode(in) + case "/v1/execute", "/v1/reconcile": + var in ExecuteRequest + if !decode(&in) { + return + } + var out Receipt + var e error + if r.URL.Path == "/v1/execute" { + if in.Authorization != nil { + out, e = s.Gateway.ExecuteAuthorized(r.Context(), *in.Authorization, in.Request, in.Body) + } else { + out, e = s.Gateway.Execute(r.Context(), in.Request, in.Body) + } + } else { + out, e = s.Gateway.Reconcile(r.Context(), in.Request) + } + if e != nil { + fail(e) + return + } + _ = json.NewEncoder(w).Encode(out) + case "/v1/resolve": + var in Request + if !decode(&in) { + return + } + out, e := s.Gateway.Resolve(r.Context(), in) + if e != nil { + fail(e) + return + } + _ = json.NewEncoder(w).Encode(out) + case "/v1/observe": + var in struct { + Key string `json:"key"` + Version string `json:"version"` + } + if !decode(&in) { + return + } + if in.Key == "" { + http.Error(w, "gateway_bad_key", 400) + return + } + if e := s.Gateway.Ready(r.Context()); e != nil { + fail(e) + return + } + v, exists, e := s.Gateway.Backend.Observe(r.Context(), in.Key, in.Version) + if e != nil { + http.Error(w, "gateway_backend_read_failed", 503) + return + } + _ = json.NewEncoder(w).Encode(struct { + Version Version `json:"version"` + Exists bool `json:"exists"` + }{v, exists}) + default: + http.Error(w, "gateway_route_not_found", 404) + } +} + +type Client struct { + Endpoint, Token, Scope string + HTTP *http.Client +} + +func NewClient(endpoint, token, scope string) (*Client, error) { + u, e := url.Parse(endpoint) + if e != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" || len(token) < 32 || scope == "" { + return nil, errors.New("gateway_configuration_invalid") + } + if u.Scheme != "https" && (u.Scheme != "http" || (u.Hostname() != "127.0.0.1" && u.Hostname() != "::1")) { + return nil, errors.New("gateway_transport_requires_tls") + } + return &Client{endpoint, token, scope, &http.Client{Timeout: 2 * time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("gateway_redirect_refused") }}}, nil +} +func (c *Client) call(ctx context.Context, path string, in, out any) error { + method := "GET" + var body io.Reader + if in != nil { + raw, e := json.Marshal(in) + if e != nil { + return ErrConflict + } + method = "POST" + body = struct{ io.Reader }{bytes.NewReader(raw)} + } + req, e := http.NewRequestWithContext(ctx, method, c.Endpoint+path, body) + if e != nil { + return errors.New("gateway_request_invalid") + } + req.Header.Set("Authorization", "Bearer "+c.Token) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-KG-Gateway-Protocol", Protocol) + req.Header.Set("X-KG-Gateway-Scope", c.Scope) + resp, e := c.HTTP.Do(req) + if e != nil { + return errors.New("gateway_unreachable_or_outcome_unknown") + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 128)) + reason := strings.TrimSpace(string(raw)) + switch reason { + case ErrAuthority.Error(): + return ErrAuthority + case ErrAuthorityPrivileges.Error(): + return ErrAuthorityPrivileges + case ErrEpoch.Error(): + return ErrEpoch + case ErrConflict.Error(): + return ErrConflict + case ErrHeld.Error(): + return ErrHeld + case ErrPersistence.Error(): + return ErrPersistence + } + return errors.New("gateway_request_refused") + } + if json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out) != nil { + return errors.New("gateway_response_invalid") + } + return nil +} +func (c *Client) Ready(ctx context.Context) error { return c.checkReady(ctx, false) } +func (c *Client) ReadyForAcquisition(ctx context.Context) error { return c.checkReady(ctx, true) } +func (c *Client) checkReady(ctx context.Context, automatic bool) error { + var caps Capabilities + if e := c.call(ctx, "/v1/capabilities", nil, &caps); e != nil { + return e + } + if automatic && !caps.AutomaticGrants { + return ErrAuthority + } + if caps.Protocol != Protocol || caps.Scope != c.Scope || !caps.Ready { + return errors.New("gateway_protocol_or_target_mismatch") + } + return nil +} +func (c *Client) InstallPlan(ctx context.Context, p Plan) error { + var out Plan + if e := c.call(ctx, "/v1/plans", p, &out); e != nil { + return e + } + want, _ := json.Marshal(p) + got, _ := json.Marshal(out) + if string(want) != string(got) { + return ErrConflict + } + return nil +} +func (c *Client) Advance(ctx context.Context, expected int64, g Grant) error { + var out AdvanceRequest + in := AdvanceRequest{expected, g} + if e := c.call(ctx, "/v1/advance", in, &out); e != nil { + return e + } + if in != out { + return ErrConflict + } + return nil +} +func (c *Client) Execute(ctx context.Context, r Request, body []byte) (Receipt, error) { + var out Receipt + e := c.call(ctx, "/v1/execute", ExecuteRequest{Request: r, Body: body}, &out) + if e == nil && (out.Request != r || !out.valid()) { + e = ErrConflict + } + return out, e +} +func (c *Client) Reconcile(ctx context.Context, r Request) (Receipt, error) { + var out Receipt + e := c.call(ctx, "/v1/reconcile", ExecuteRequest{Request: r}, &out) + if e == nil && (out.Request != r || !out.valid()) { + e = ErrConflict + } + return out, e +} +func (c *Client) Observe(ctx context.Context, key, id string) (Version, bool, error) { + var out struct { + Version Version `json:"version"` + Exists bool `json:"exists"` + } + e := c.call(ctx, "/v1/observe", struct { + Key string `json:"key"` + Version string `json:"version"` + }{key, id}, &out) + return out.Version, out.Exists, e +} diff --git a/internal/objectgateway/identity_integration_test.go b/internal/objectgateway/identity_integration_test.go new file mode 100644 index 0000000..3a5eb98 --- /dev/null +++ b/internal/objectgateway/identity_integration_test.go @@ -0,0 +1,50 @@ +package objectgateway_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + g "knowledge-governance/internal/objectgateway" +) + +func TestGatewayTargetIdentityOnEveryCall(t *testing.T) { + ctx, pool, backend := fixture(t) + grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))} + gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20} + if e := gw.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil { + t.Fatal(e) + } + if e := gw.Advance(ctx, 0, grant); e != nil { + t.Fatal(e) + } + token := strings.Repeat("a", 32) + server := httptest.NewServer(g.HTTPServer{Gateway: gw, DataToken: token, ControlToken: strings.Repeat("b", 32)}) + defer server.Close() + wrong, _ := g.NewClient(server.URL, token, "wrong-target") + req := request(t.Name(), grant) + receipt, e := wrong.Execute(ctx, req, []byte("gateway fixture "+t.Name())) + if e == nil { + cleanup(t, ctx, gw, receipt) + t.Fatal("mutation accepted with wrong target identity") + } + var n int + if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_intents WHERE scope=$1", gw.Scope).Scan(&n) != nil || n != 0 { + t.Fatal("wrong target wrote intent") + } +} +func TestGatewayClientRejectsIncompleteReceipt(t *testing.T) { + grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("owner")), Plan: g.Digest([]byte("plan"))} + req := request("receipt", grant) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(g.Receipt{Request: req, State: "committed"}) + })) + defer server.Close() + c, _ := g.NewClient(server.URL, strings.Repeat("a", 32), "scope") + if _, e := c.Execute(context.Background(), req, []byte("gateway fixture receipt")); e == nil { + t.Fatal("committed receipt with missing exact version accepted") + } +} diff --git a/internal/objectgateway/persistence_integration_test.go b/internal/objectgateway/persistence_integration_test.go new file mode 100644 index 0000000..5b525ff --- /dev/null +++ b/internal/objectgateway/persistence_integration_test.go @@ -0,0 +1,44 @@ +package objectgateway_test + +import ( + "errors" + g "knowledge-governance/internal/objectgateway" + "testing" +) + +func TestGatewayIntentCommitFailureNeverSends(t *testing.T) { + ctx, pool, real := fixture(t) + backend := &stoppedBeforeSend{Backend: real} + grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("plan"))} + gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20} + if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil { + t.Fatal(e) + } + if e := gateway.Advance(ctx, 0, grant); e != nil { + t.Fatal(e) + } + // Deferred failure fires on COMMIT, not on INSERT. This exercises the uncertain + // persistence boundary while confirming no provider request is sent. + _, e := pool.Exec(ctx, `CREATE FUNCTION kg_gateway_fixture_commit_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected durable commit failure'; END $$; + CREATE CONSTRAINT TRIGGER kg_gateway_fixture_commit_failure AFTER INSERT ON kg_object_gateway_intents DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION kg_gateway_fixture_commit_failure()`) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { + _, e := pool.Exec(ctx, `DROP TRIGGER kg_gateway_fixture_commit_failure ON kg_object_gateway_intents; DROP FUNCTION kg_gateway_fixture_commit_failure()`) + if e != nil { + t.Error(e) + } + }) + req := request(t.Name(), grant) + if _, e = gateway.Execute(ctx, req, []byte("gateway fixture "+t.Name())); !errors.Is(e, g.ErrPersistence) { + t.Fatal("commit error not propagated", e) + } + if backend.calls != 0 { + t.Fatal("object request after failed journal commit") + } + var n int + if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_intents WHERE scope=$1", gateway.Scope).Scan(&n) != nil || n != 0 { + t.Fatal("failed transaction left intent") + } +} diff --git a/internal/objectgateway/plan.go b/internal/objectgateway/plan.go new file mode 100644 index 0000000..56bbdda --- /dev/null +++ b/internal/objectgateway/plan.go @@ -0,0 +1,78 @@ +package objectgateway + +import ( + "context" + "encoding/json" +) + +// Plan is frozen by the authenticated controller, not by the data client. Digest +// is the upstream write-set digest; the controller must verify that write set. +// This allowlist prevents a valid epoch from authorizing arbitrary extra keys. +type Plan struct { + Digest string `json:"digest"` + Owner string `json:"owner"` + Objects []ObjectBinding `json:"objects"` +} +type ObjectBinding struct { + Operation string `json:"operation"` + Key string `json:"key"` + SHA256 string `json:"sha256"` + Bytes int64 `json:"bytes"` +} + +func (p Plan) valid() bool { + if !validHash(p.Digest) || !validHash(p.Owner) { + return false + } + keys, ops := map[string]bool{}, map[string]bool{} + for _, o := range p.Objects { + r := Request{Grant: Grant{1, p.Owner, p.Digest}, Operation: o.Operation, Key: o.Key, Action: "create", SHA256: o.SHA256, Bytes: o.Bytes} + if r.validate() != nil || keys[o.Key] || ops[o.Operation] { + return false + } + keys[o.Key] = true + ops[o.Operation] = true + } + return true +} +func (p Plan) allows(r Request) bool { + op := r.Operation + if r.Action == "delete" { + op = r.CreatedBy + } + if p.Owner != r.Grant.Owner || p.Digest != r.Grant.Plan { + return false + } + for _, o := range p.Objects { + if o.Operation == op && o.Key == r.Key && o.SHA256 == r.SHA256 && o.Bytes == r.Bytes { + return true + } + } + return false +} +func (g *Gateway) InstallPlan(ctx context.Context, p Plan) error { + if !p.valid() { + return ErrConflict + } + for _, o := range p.Objects { + if o.Bytes > g.MaxBytes { + return ErrConflict + } + } + if e := g.Ready(ctx); e != nil { + return e + } + raw, _ := json.Marshal(p) + _, e := g.Pool.Exec(ctx, "INSERT INTO kg_object_gateway_plans(scope,plan,body) VALUES($1,$2,$3) ON CONFLICT DO NOTHING", g.Scope, p.Digest, raw) + if e != nil { + return ErrPersistence + } + var found []byte + if g.Pool.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, p.Digest).Scan(&found) != nil { + return ErrPersistence + } + if string(found) != string(raw) { + return ErrConflict + } + return nil +} diff --git a/internal/objectgateway/plan_integration_test.go b/internal/objectgateway/plan_integration_test.go new file mode 100644 index 0000000..76ff629 --- /dev/null +++ b/internal/objectgateway/plan_integration_test.go @@ -0,0 +1,37 @@ +package objectgateway_test + +import ( + "errors" + g "knowledge-governance/internal/objectgateway" + "testing" +) + +func TestGatewayGrantCannotAuthorizeUnplannedKey(t *testing.T) { + ctx, pool, backend := fixture(t) + grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))} + gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20} + if e := gateway.Advance(ctx, 0, grant); !errors.Is(e, g.ErrConflict) { + t.Fatal("unregistered plan grant", e) + } + allowed := request("allowed-plan-key", grant) + plan := planFor(grant, allowed) + if e := gateway.InstallPlan(ctx, plan); e != nil { + t.Fatal(e) + } + changed := planFor(grant, request("extra-plan-key", grant)) + if e := gateway.InstallPlan(ctx, changed); !errors.Is(e, g.ErrConflict) { + t.Fatal("immutable plan rebound", e) + } + if e := gateway.Advance(ctx, 0, grant); e != nil { + t.Fatal(e) + } + req := request(t.Name(), grant) + if _, e := gateway.Execute(ctx, req, []byte("gateway fixture "+t.Name())); !errors.Is(e, g.ErrConflict) { + t.Fatal("unplanned key admitted", e) + } + receipt, e := gateway.Execute(ctx, allowed, []byte("gateway fixture allowed-plan-key")) + if e != nil || receipt.State != "committed" { + t.Fatal("valid planned key refused", e) + } + cleanup(t, ctx, gateway, receipt) +} diff --git a/internal/objectgateway/protocol.go b/internal/objectgateway/protocol.go new file mode 100644 index 0000000..e951da5 --- /dev/null +++ b/internal/objectgateway/protocol.go @@ -0,0 +1,107 @@ +// Package objectgateway implements non-preemptive object write ownership. +package objectgateway + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "strings" +) + +const Protocol = "kg-object-gateway-v1" + +var ( + ErrHeld = errors.New("gateway_held_unresolved_intent") + ErrEpoch = errors.New("gateway_epoch_or_plan_mismatch") + ErrConflict = errors.New("gateway_identity_conflict") + ErrPersistence = errors.New("gateway_persistence_unavailable") + ErrAuthority = errors.New("gateway_control_authority_unavailable") + ErrAuthorityPrivileges = errors.New("gateway_control_reader_privileges_invalid") + ErrRejected = errors.New("gateway_create_rejected_existing_object") +) + +type Grant struct { + Epoch int64 `json:"epoch"` + Owner string `json:"owner"` + Plan string `json:"plan"` +} +type Version struct { + ID string `json:"version_id"` + Owner string `json:"owner"` + SHA256 string `json:"sha256"` + Bytes int64 `json:"bytes"` + ETag string `json:"etag"` +} +type Request struct { + Grant Grant `json:"grant"` + Operation string `json:"operation"` + Key string `json:"key"` + Action string `json:"action"` + SHA256 string `json:"sha256"` + Bytes int64 `json:"bytes"` + CreatedBy string `json:"created_by,omitempty"` + Version Version `json:"version,omitempty"` +} +type Receipt struct { + Request Request `json:"request"` + State string `json:"state"` + Version Version `json:"version"` +} + +// Backend never retries mutations. List is complete and scoped to exactly key. +// Not finding a PUT is never evidence that its request cannot still arrive. +type Backend interface { + Ready(context.Context) error + Observe(context.Context, string, string) (Version, bool, error) + List(context.Context, string) ([]Version, error) + Put(context.Context, string, []byte, string) (Version, error) + Delete(context.Context, string, Version) error +} + +func Digest(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } +func validHash(s string) bool { + b, e := hex.DecodeString(s) + return e == nil && len(b) == 32 && strings.ToLower(s) == s +} +func (g Grant) valid() bool { return g.Epoch > 0 && validHash(g.Owner) && validHash(g.Plan) } +func (r Request) validate() error { + if !r.Grant.valid() || !validHash(r.Operation) || r.Key == "" || len(r.Key) > 2048 || strings.ContainsAny(r.Key, "\x00\r\n") || strings.HasPrefix(r.Key, "/") || !validHash(r.SHA256) || r.Bytes < 0 { + return ErrConflict + } + if r.Action != "create" && r.Action != "delete" { + return ErrConflict + } + if r.Action == "create" && (r.CreatedBy != "" || r.Version != (Version{})) { + return ErrConflict + } + if r.Action == "delete" && (!validHash(r.CreatedBy) || !validVersion(r.Version) || r.Version.SHA256 != r.SHA256 || r.Version.Bytes != r.Bytes) { + return ErrConflict + } + return nil +} +func validVersion(v Version) bool { + return v.ID != "" && v.ID != "null" && validHash(v.Owner) && validHash(v.SHA256) && v.Bytes >= 0 && v.ETag != "" +} + +// Claim binds backend ownership to the complete immutable gateway request. +func (r Request) Claim() string { return r.token() } +func (r Request) token() string { raw, _ := json.Marshal(r); return Digest(raw) } +func (r Receipt) valid() bool { + if r.Request.validate() != nil { + return false + } + switch r.State { + case "committed": + return r.Request.Action == "create" && r.Request.matches(r.Version) + case "rejected": + return r.Request.Action == "create" && r.Version == (Version{}) + case "removed": + return r.Request.Action == "delete" && r.Version == r.Request.Version + } + return false +} +func (r Request) matches(v Version) bool { + return validVersion(v) && v.Owner == r.token() && v.Bytes == r.Bytes && v.SHA256 == r.SHA256 +} diff --git a/internal/objectgateway/s3.go b/internal/objectgateway/s3.go new file mode 100644 index 0000000..f871c81 --- /dev/null +++ b/internal/objectgateway/s3.go @@ -0,0 +1,102 @@ +package objectgateway + +import ( + "bytes" + "context" + "errors" + "io" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/signer/v4" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/smithy-go" +) + +// S3Backend is for independently versioned S3/MinIO stores. No SDK mutation retries. +type S3Backend struct { + Client *s3.Client + Bucket string + MaxBytes int64 +} + +func (s *S3Backend) Ready(ctx context.Context) error { + r, e := s.Client.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(s.Bucket)}) + if e != nil || string(r.Status) != "Enabled" { + return errors.New("gateway_backend_versioning_unverified") + } + return nil +} +func (s *S3Backend) Observe(ctx context.Context, key, id string) (Version, bool, error) { + req := &s3.GetObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key)} + if id != "" { + req.VersionId = aws.String(id) + } + got, e := s.Client.GetObject(ctx, req) + if e != nil { + var api smithy.APIError + if errors.As(e, &api) && (api.ErrorCode() == "NoSuchKey" || api.ErrorCode() == "NoSuchVersion") { + return Version{}, false, nil + } + return Version{}, false, errors.New("gateway_backend_read_failed") + } + defer got.Body.Close() + if got.ContentLength == nil || *got.ContentLength < 0 || *got.ContentLength > s.MaxBytes { + return Version{}, false, errors.New("gateway_backend_size_invalid") + } + body, e := io.ReadAll(io.LimitReader(got.Body, s.MaxBytes+1)) + if e != nil || int64(len(body)) != *got.ContentLength { + return Version{}, false, errors.New("gateway_backend_body_incomplete") + } + v := Version{aws.ToString(got.VersionId), got.Metadata["kg-release-owner"], Digest(body), int64(len(body)), aws.ToString(got.ETag)} + // Existing unowned objects are observable but cannot be claimed/deleted. + if v.ID == "" || v.ID == "null" || v.ETag == "" || id != "" && v.ID != id { + return Version{}, false, errors.New("gateway_backend_version_invalid") + } + return v, true, nil +} +func (s *S3Backend) List(ctx context.Context, key string) ([]Version, error) { + got, e := s.Client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(s.Bucket), Prefix: aws.String(key), MaxKeys: aws.Int32(1000)}) + if e != nil || aws.ToBool(got.IsTruncated) { + return nil, errors.New("gateway_backend_listing_incomplete") + } + var versions []Version + for _, m := range got.DeleteMarkers { + if aws.ToString(m.Key) == key { + return nil, errors.New("gateway_backend_delete_marker_conflict") + } + } + for _, v := range got.Versions { + if aws.ToString(v.Key) == key { + one, exists, e := s.Observe(ctx, key, aws.ToString(v.VersionId)) + if e != nil || !exists { + return nil, errors.New("gateway_backend_listing_changed") + } + versions = append(versions, one) + } + } + return versions, nil +} +func (s *S3Backend) Put(ctx context.Context, key string, body []byte, owner string) (Version, error) { + // SDK hashing requires a seekable body. RetryMaxAttempts=1 prevents SDK + // retries; PUT carries no HTTP idempotency header or replay authorization. + reader := bytes.NewReader(body) + got, e := s.Client.PutObject(v4.SetPayloadHash(ctx, Digest(body)), &s3.PutObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key), Body: reader, ContentLength: aws.Int64(int64(len(body))), Metadata: map[string]string{"kg-release-owner": owner}}, func(o *s3.Options) { o.RetryMaxAttempts = 1 }) + if e != nil || aws.ToString(got.VersionId) == "" { + return Version{}, ErrHeld + } + v, exists, e := s.Observe(ctx, key, aws.ToString(got.VersionId)) + if e != nil || !exists { + return Version{}, ErrHeld + } + return v, nil +} +func (s *S3Backend) Delete(ctx context.Context, key string, v Version) error { + if !validVersion(v) { + return ErrConflict + } + _, e := s.Client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key), VersionId: aws.String(v.ID)}, func(o *s3.Options) { o.RetryMaxAttempts = 1 }) + if e != nil { + return ErrHeld + } + return nil +} diff --git a/internal/objectgateway/schema.sql b/internal/objectgateway/schema.sql new file mode 100644 index 0000000..da3da28 --- /dev/null +++ b/internal/objectgateway/schema.sql @@ -0,0 +1,74 @@ +-- Independent governance journal; never install in a WeKnora business schema. +CREATE TABLE IF NOT EXISTS kg_object_gateway_plans ( + scope text NOT NULL, + plan text NOT NULL, + body bytea NOT NULL, + PRIMARY KEY(scope,plan) +); +CREATE TABLE IF NOT EXISTS kg_object_gateway_scopes ( + scope text PRIMARY KEY, + epoch bigint NOT NULL DEFAULT 0 +); +CREATE TABLE IF NOT EXISTS kg_object_gateway_grants ( + scope text NOT NULL REFERENCES kg_object_gateway_scopes(scope), + epoch bigint NOT NULL CHECK (epoch > 0), + owner text NOT NULL, + plan text NOT NULL, + PRIMARY KEY(scope,epoch) +); +CREATE TABLE IF NOT EXISTS kg_object_gateway_intents ( + scope text NOT NULL REFERENCES kg_object_gateway_scopes(scope), + operation text NOT NULL, + key text NOT NULL, + request bytea NOT NULL, + recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY(scope,operation) +); +CREATE INDEX IF NOT EXISTS kg_object_gateway_key ON kg_object_gateway_intents(scope,key); +CREATE TABLE IF NOT EXISTS kg_object_gateway_receipts ( + scope text NOT NULL, + operation text NOT NULL, + receipt bytea NOT NULL, + recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY(scope,operation), + FOREIGN KEY(scope,operation) REFERENCES kg_object_gateway_intents(scope,operation) +); +CREATE TABLE IF NOT EXISTS kg_object_gateway_deliveries ( + scope text NOT NULL, + job text NOT NULL, + attempt_epoch bigint NOT NULL CHECK(attempt_epoch>0), + claim bytea NOT NULL, + grant_epoch bigint NOT NULL, + grant_body bytea NOT NULL, + PRIMARY KEY(scope,job,attempt_epoch), + FOREIGN KEY(scope,grant_epoch) REFERENCES kg_object_gateway_grants(scope,epoch) +); +CREATE OR REPLACE FUNCTION kg_object_gateway_immutable() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'object gateway evidence is immutable'; +END; +$$; +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_deliveries_immutable') THEN + CREATE TRIGGER kg_object_gateway_deliveries_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_deliveries FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable(); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_plans_immutable') THEN + CREATE TRIGGER kg_object_gateway_plans_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_plans FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable(); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_intents_immutable') THEN + CREATE TRIGGER kg_object_gateway_intents_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_intents FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable(); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_receipts_immutable') THEN + CREATE TRIGGER kg_object_gateway_receipts_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_receipts FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable(); + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_grants_immutable') THEN + CREATE TRIGGER kg_object_gateway_grants_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_grants FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable(); + END IF; +END $$; +DO $$ DECLARE t text; BEGIN + FOREACH t IN ARRAY ARRAY['plans','grants','intents','receipts','deliveries'] LOOP + IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_'||t||'_no_truncate') THEN + EXECUTE format('CREATE TRIGGER %I BEFORE TRUNCATE ON %I FOR EACH STATEMENT EXECUTE FUNCTION kg_object_gateway_immutable()', 'kg_object_gateway_'||t||'_no_truncate', 'kg_object_gateway_'||t); + END IF; + END LOOP; +END $$; diff --git a/internal/objectgateway/shared_bucket_integration_test.go b/internal/objectgateway/shared_bucket_integration_test.go new file mode 100644 index 0000000..2845412 --- /dev/null +++ b/internal/objectgateway/shared_bucket_integration_test.go @@ -0,0 +1,114 @@ +package objectgateway_test + +import ( + "bytes" + "net" + "os" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + g "knowledge-governance/internal/objectgateway" +) + +// A maintenance update of the target KB runs while the same bucket still +// serves other writers. Publishing planned objects must neither require a +// whole-bucket exclusivity attestation nor disturb an unrelated key or a +// pre-existing object at a planned key. External writes here are made before +// execute (coexistence), not interleaved concurrently with the PUT. +func TestGatewaySharedBucketCoexistenceWithOtherWriters(t *testing.T) { + ctx, pool, backend := fixture(t) + endpoint := os.Getenv("KG_GATEWAY_TEST_ENDPOINT") + scope := g.Digest([]byte("minio\x00" + endpoint + "\x00" + backend.Bucket)) + listener, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + addr := listener.Addr().String() + listener.Close() + data, control := g.Digest([]byte("data "+scope)), g.Digest([]byte("control "+scope)) + client, e := g.NewClient("http://"+addr, data, scope) + if e != nil { + t.Fatal(e) + } + admin, _ := g.NewClient("http://"+addr, control, scope) + // Deliberately no OBJECT_GATEWAY_AUDIT_FILE / OBJECT_GATEWAY_AUDIT_PUBLIC_KEY: + // the default shared-bucket path must start without whole-bucket evidence. + env := []string{ + "PATH=" + os.Getenv("PATH"), + "HOME=" + os.Getenv("HOME"), + "OBJECT_GATEWAY_LISTEN=" + addr, + "OBJECT_GATEWAY_DATABASE_URL=" + os.Getenv("KG_GATEWAY_TEST_DATABASE_URL"), + "OBJECT_GATEWAY_PROVIDER=minio", + "OBJECT_GATEWAY_ENDPOINT=" + endpoint, + "OBJECT_GATEWAY_BUCKET=" + backend.Bucket, + "OBJECT_GATEWAY_REGION=us-east-1", + "OBJECT_GATEWAY_ACCESS_KEY=" + os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"), + "OBJECT_GATEWAY_SECRET_KEY=" + os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"), + "OBJECT_GATEWAY_DATA_TOKEN=" + data, + "OBJECT_GATEWAY_CONTROL_TOKEN=" + control, + } + startGateway(t, env, client) + if e = client.ReadyForAcquisition(ctx); e == nil { + t.Fatal("gateway without control authority advertised automatic grants") + } + + // Another service keeps writing unrelated keys during the maintenance window. + externalOwner := g.Digest([]byte("other-service")) + unrelatedKey := "other-service/unrelated-" + g.Digest([]byte(backend.Bucket))[:8] + unrelatedBody := []byte("unrelated service body") + if _, e = backend.Client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(backend.Bucket), Key: aws.String(unrelatedKey), Body: bytes.NewReader(unrelatedBody), Metadata: map[string]string{"kg-release-owner": externalOwner}}); e != nil { + t.Fatalf("external unrelated write failed: %v", e) + } + unrelated, _, e := backend.Observe(ctx, unrelatedKey, "") + if e != nil { + t.Fatal(e) + } + + // A planned key already holds a foreign object: the plan must refuse it and + // leave that object byte-identical. + existingKey := "unchanged/existing-object" + existingBody := []byte("pre-existing production content") + if _, e = backend.Client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(backend.Bucket), Key: aws.String(existingKey), Body: bytes.NewReader(existingBody), Metadata: map[string]string{"kg-release-owner": externalOwner}}); e != nil { + t.Fatal(e) + } + existing, _, e := backend.Observe(ctx, existingKey, "") + if e != nil { + t.Fatal(e) + } + + grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("maintenance-owner")), Plan: g.Digest([]byte("maintenance-plan"))} + fresh := request("shared-fresh", grant) + clash := request("shared-clash", grant) + clash.Key = existingKey + if e = admin.InstallPlan(ctx, planFor(grant, fresh, clash)); e != nil { + t.Fatal(e) + } + if e = admin.Advance(ctx, 0, grant); e != nil { + t.Fatal(e) + } + receipt, e := client.Execute(ctx, fresh, []byte("gateway fixture shared-fresh")) + if e != nil || receipt.State != "committed" { + t.Fatalf("planned create blocked by unrelated writers: %v %s", e, receipt.State) + } + rejected, e := client.Execute(ctx, clash, []byte("gateway fixture shared-clash")) + if e != nil || rejected.State != "rejected" { + t.Fatalf("pre-existing planned key not rejected: %v %s", e, rejected.State) + } + after, exists, e := backend.Observe(ctx, existingKey, "") + if e != nil || !exists || after.ID != existing.ID || after.SHA256 != g.Digest(existingBody) { + t.Fatalf("pre-existing object modified: %v %+v", e, after) + } + still, exists, e := backend.Observe(ctx, unrelatedKey, "") + if e != nil || !exists || still.ID != unrelated.ID { + t.Fatalf("unrelated object disturbed: %v %+v", e, still) + } + + // Precise rollback removes only the version this gateway created. + cleanup(t, ctx, &g.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 1 << 20}, receipt) + for key, keep := range map[string]g.Version{existingKey: existing, unrelatedKey: unrelated} { + if e = backend.Delete(ctx, key, keep); e != nil { + t.Fatalf("external fixture cleanup %s: %v", key, e) + } + } +} diff --git a/internal/objectgateway/takeover.go b/internal/objectgateway/takeover.go new file mode 100644 index 0000000..35f86e0 --- /dev/null +++ b/internal/objectgateway/takeover.go @@ -0,0 +1,60 @@ +package objectgateway + +import ( + "context" + "encoding/json" + "errors" + "github.com/jackc/pgx/v5" +) + +// Resolve preserves the immutable send epoch and backend claim of an operation. +// An absent intent is not a claim about an earlier send; Execute still reserves +// atomically and refuses stale authorizations before any new side effect. +func (g *Gateway) Resolve(ctx context.Context, desired Request) (Request, error) { + if e := desired.validate(); e != nil { + return Request{}, e + } + if e := g.Ready(ctx); e != nil { + return Request{}, e + } + var raw []byte + e := g.Pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, desired.Operation).Scan(&raw) + if errors.Is(e, pgx.ErrNoRows) { + return desired, nil + } + if e != nil { + return Request{}, ErrPersistence + } + var original Request + if json.Unmarshal(raw, &original) != nil || original.validate() != nil { + return Request{}, ErrPersistence + } + if !sameOperation(original, desired) || original.Grant.Epoch > desired.Grant.Epoch { + return Request{}, ErrConflict + } + return original, nil +} +func sameOperation(a, b Request) bool { a.Grant.Epoch = b.Grant.Epoch; return a == b } + +func (g *Gateway) ExecuteAuthorized(ctx context.Context, authorization Grant, r Request, body []byte) (Receipt, error) { + if !authorization.valid() || authorization.Owner != r.Grant.Owner || authorization.Plan != r.Grant.Plan || authorization.Epoch < r.Grant.Epoch { + return Receipt{}, ErrEpoch + } + return g.execute(ctx, r, body, &authorization) +} +func (c *Client) ExecuteAuthorized(ctx context.Context, authorization Grant, r Request, body []byte) (Receipt, error) { + var out Receipt + e := c.call(ctx, "/v1/execute", ExecuteRequest{Request: r, Body: body, Authorization: &authorization}, &out) + if e == nil && (out.Request != r || !out.valid()) { + e = ErrConflict + } + return out, e +} +func (c *Client) Resolve(ctx context.Context, desired Request) (Request, error) { + var out Request + e := c.call(ctx, "/v1/resolve", desired, &out) + if e == nil && (out.validate() != nil || !sameOperation(out, desired) || out.Grant.Epoch > desired.Grant.Epoch) { + e = ErrConflict + } + return out, e +} diff --git a/internal/objectgateway/takeover_integration_test.go b/internal/objectgateway/takeover_integration_test.go new file mode 100644 index 0000000..89a5e20 --- /dev/null +++ b/internal/objectgateway/takeover_integration_test.go @@ -0,0 +1,111 @@ +package objectgateway_test + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" + + g "knowledge-governance/internal/objectgateway" +) + +func TestGatewayNewEpochPreservesOriginalSendIdentity(t *testing.T) { + ctx, pool, backend := fixture(t) + gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20} + first := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("takeover-plan"))} + sent, unsent := request("takeover-sent", first), request("takeover-unsent", first) + if e := gateway.InstallPlan(ctx, planFor(first, sent, unsent)); e != nil { + t.Fatal(e) + } + if e := gateway.Advance(ctx, 0, first); e != nil { + t.Fatal(e) + } + old, e := gateway.Execute(ctx, sent, []byte("gateway fixture takeover-sent")) + if e != nil { + t.Fatal(e) + } + // Always clean only this test's exact original version, including on RED. + cleanupGrant := first + defer func() { copy := old; copy.Request.Grant = cleanupGrant; cleanup(t, ctx, gateway, copy) }() + var original []byte + if e = pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", gateway.Scope, sent.Operation).Scan(&original); e != nil { + t.Fatal(e) + } + next := first + next.Epoch++ + if e = gateway.Advance(ctx, 1, next); e != nil { + t.Fatal(e) + } + cleanupGrant = next + data, control := g.Digest([]byte("takeover-data")), g.Digest([]byte("takeover-control")) + server := httptest.NewServer(g.HTTPServer{Gateway: gateway, DataToken: data, ControlToken: control}) + defer server.Close() + post := func(path string, in any) (int, []byte) { + raw, _ := json.Marshal(in) + req, _ := http.NewRequestWithContext(ctx, "POST", server.URL+path, bytes.NewReader(raw)) + req.Header.Set("Authorization", "Bearer "+data) + req.Header.Set("X-KG-Gateway-Protocol", g.Protocol) + req.Header.Set("X-KG-Gateway-Scope", gateway.Scope) + resp, e := http.DefaultClient.Do(req) + if e != nil { + t.Fatal(e) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + return resp.StatusCode, body + } + code, body := post("/v1/execute", map[string]any{"request": sent, "authorization": next, "body": []byte("gateway fixture takeover-sent")}) + if code != 200 { + t.Fatalf("new authorization cannot replay immutable original request: status=%d", code) + } + var replay g.Receipt + if json.Unmarshal(body, &replay) != nil || replay != old { + t.Fatal("replay rewrote original receipt") + } + desired := sent + desired.Grant = next + code, body = post("/v1/resolve", desired) + var resolved g.Request + if code != 200 || json.Unmarshal(body, &resolved) != nil || resolved != sent { + t.Fatal("original send identity not resolved", code) + } + changed := sent + changed.SHA256 = g.Digest([]byte("different")) + if code, _ = post("/v1/resolve", changed); code == 200 { + t.Fatal("operation rebound body") + } + if code, _ = post("/v1/execute", map[string]any{"request": unsent, "authorization": first, "body": []byte("gateway fixture takeover-unsent")}); code == 200 { + t.Fatal("stale epoch created unsent key") + } + unsent.Grant = next + code, body = post("/v1/execute", map[string]any{"request": unsent, "authorization": next, "body": []byte("gateway fixture takeover-unsent")}) + var created g.Receipt + if code != 200 || json.Unmarshal(body, &created) != nil || created.State != "committed" { + t.Fatal("new epoch did not continue unsent key", code) + } + cleanup(t, ctx, gateway, created) + var after []byte + if e = pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", gateway.Scope, sent.Operation).Scan(&after); e != nil || !bytes.Equal(after, original) { + t.Fatal("immutable intent changed", e) + } + versions, e := backend.List(ctx, sent.Key) + if e != nil || len(versions) != 1 || versions[0] != old.Version { + t.Fatal("replay created extra version", e) + } + // Deletion is a new send in the current epoch, not a rewritten create intent. + deletion := sent + deletion.Grant = next + deletion.Operation = g.Digest([]byte(sent.Operation + "delete")) + deletion.Action = "delete" + deletion.CreatedBy = sent.Operation + deletion.Version = old.Version + code, _ = post("/v1/execute", map[string]any{"request": deletion, "authorization": next}) + if code != 200 { + t.Fatal("new epoch exact cleanup refused", code) + } + // deferred cleanup replays the same already settled delete request below. + old.Request.Grant = next + t.Log("new epoch replay retained original request/receipt/claim; unsent key committed once; stale request rejected") +} diff --git a/internal/objectgateway/unknown_integration_test.go b/internal/objectgateway/unknown_integration_test.go new file mode 100644 index 0000000..637bda0 --- /dev/null +++ b/internal/objectgateway/unknown_integration_test.go @@ -0,0 +1,69 @@ +package objectgateway_test + +import ( + "context" + "errors" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + g "knowledge-governance/internal/objectgateway" +) + +type stoppedBeforeSend struct { + g.Backend + calls int +} + +func (b *stoppedBeforeSend) Put(context.Context, string, []byte, string) (g.Version, error) { + b.calls++ + return g.Version{}, errors.New("injected uncertain send with no visible version") +} +func TestGatewayAbsenceNeverSettlesUnknown(t *testing.T) { + ctx, pool, real := fixture(t) + backend := &stoppedBeforeSend{Backend: real} + grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("plan"))} + gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20} + if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil { + t.Fatal(e) + } + if e := gateway.Advance(ctx, 0, grant); e != nil { + t.Fatal(e) + } + req := request(t.Name(), grant) + body := []byte("gateway fixture " + t.Name()) + if _, e := gateway.Execute(ctx, req, body); !errors.Is(e, g.ErrHeld) { + t.Fatal(e) + } + restarted := *gateway + for i := 0; i < 2; i++ { + if _, e := restarted.Execute(ctx, req, body); !errors.Is(e, g.ErrHeld) { + t.Fatal("absent version treated as terminal", e) + } + } + if backend.calls != 1 { + t.Fatal("PUT replayed", backend.calls) + } + next := grant + next.Epoch++ + if e := restarted.Advance(ctx, 1, next); !errors.Is(e, g.ErrHeld) { + t.Fatal("unknown operation allowed epoch handover", e) + } + var n int + if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE scope=$1", gateway.Scope).Scan(&n) != nil || n != 0 { + t.Fatal("absence wrote false terminal receipt") + } +} +func TestGatewayReadOnlyPersistenceBlocksSend(t *testing.T) { + ctx, pool, backend := fixture(t) + cfg := pool.Config() + cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on" + other, e := pgxpool.NewWithConfig(ctx, cfg) + if e != nil { + t.Fatal(e) + } + defer other.Close() + gateway := &g.Gateway{Pool: other, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20} + if e = gateway.Ready(ctx); !errors.Is(e, g.ErrPersistence) { + t.Fatal("read-only persistence accepted", e) + } +} diff --git a/internal/platform/postgres/auto_ingest_continuation_integration_test.go b/internal/platform/postgres/auto_ingest_continuation_integration_test.go new file mode 100644 index 0000000..1cda464 --- /dev/null +++ b/internal/platform/postgres/auto_ingest_continuation_integration_test.go @@ -0,0 +1,236 @@ +package postgres + +import ( + "context" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" +) + +// F17:取件 verified 后必须沿同一策略/当前绑定自动接续唯一 test.upload。 +// 这里用真实隔离 PG 跑 RouteCatalogFiles + MarkArtifactFetched 的真实 SQL 路径。 +type autoIngestFixture struct { + t *testing.T + ctx context.Context + pool *pgxpool.Pool + store *Store + now time.Time + connID string + kbID string +} + +func newAutoIngestFixture(t *testing.T) *autoIngestFixture { + t.Helper() + url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if url == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, url) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + if err = ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + now := time.Date(2026, 11, 5, 4, 0, 0, 0, time.UTC) + exec := func(q string, args ...any) { + t.Helper() + if _, err := pool.Exec(ctx, q, args...); err != nil { + t.Fatalf("%v: %s", err, q) + } + } + exec(`INSERT INTO source_connections (id,source_type,name,enabled) VALUES ('conn-auto','dingtalk','ATOM自动衔接',TRUE)`) + exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at) + VALUES ('snap-auto','conn-auto',repeat('a',64),'fixture',2,1,1,$1)`, now) + exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash) + VALUES ('snap-auto','node-dir',NULL,'folder','常见问题汇总','常见问题汇总',repeat('b',64))`) + exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash) + VALUES ('snap-auto','node-file','node-dir','file','人形常见问题.adoc','常见问题汇总/人形常见问题.adoc',repeat('c',64))`) + exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ('conn-auto','snap-auto',$1)`, now) + exec(`INSERT INTO routing_kb_bindings (id,internal_kb_id,external_kb_id,updated_by) VALUES ('active','kb-current','kb-ext', 'fixture') + ON CONFLICT (id) DO UPDATE SET internal_kb_id='kb-current',external_kb_id='kb-ext'`) + return &autoIngestFixture{t: t, ctx: ctx, pool: pool, store: NewStore(pool).WithRoutingDefaults("kb-env", "kb-ext"), now: now, connID: "conn-auto", kbID: "kb-current"} +} + +func (f *autoIngestFixture) route() (versionID, publicationID string) { + f.t.Helper() + result, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{ + ConnectionID: f.connID, + NodeIDs: []string{"node-file"}, + Visibility: governance.VisibilityInternal, + TargetKnowledgeBaseID: f.kbID, + OperatorRef: "fixture", + Reason: "fixture", + Now: f.now, + }) + if err != nil { + f.t.Fatal(err) + } + if result.SelectedFiles != 1 || result.PlannedPublications != 1 { + f.t.Fatalf("route result = %#v", result) + } + if err := f.pool.QueryRow(f.ctx, `SELECT publication.source_item_version_id,publication.id +FROM test_publications publication +JOIN catalog_import_intents intent ON intent.source_item_id=(SELECT source_item_id FROM source_item_versions WHERE id=publication.source_item_version_id) +WHERE intent.node_id='node-file' AND publication.test_kb_id=$1`, f.kbID).Scan(&versionID, &publicationID); err != nil { + f.t.Fatal(err) + } + return versionID, publicationID +} + +func (f *autoIngestFixture) markFetched(versionID string) { + f.t.Helper() + if err := f.store.MarkArtifactFetched(f.ctx, versionID, "32222102cafd6e5cdaeee415aad51e7df52629136d5ef2c3eae6e0e30ff7153d", 6991, "spool/auto.docx", "docx", true, f.now.Add(time.Minute)); err != nil { + f.t.Fatal(err) + } +} + +func (f *autoIngestFixture) uploadJobs(publicationID string) int { + f.t.Helper() + var count int + if err := f.pool.QueryRow(f.ctx, `SELECT COUNT(*) FROM jobs WHERE type='test.upload' AND payload->>'publication_id'=$1`, publicationID).Scan(&count); err != nil { + f.t.Fatal(err) + } + return count +} + +func (f *autoIngestFixture) publicationState(publicationID string) string { + f.t.Helper() + var state string + if err := f.pool.QueryRow(f.ctx, `SELECT processing_state FROM test_publications WHERE id=$1`, publicationID).Scan(&state); err != nil { + f.t.Fatal(err) + } + return state +} + +func TestFetchedVerifiedArtifactAutoStartsExactlyOneUpload(t *testing.T) { + f := newAutoIngestFixture(t) + versionID, publicationID := f.route() + if jobs := f.uploadJobs(publicationID); jobs != 0 { + t.Fatalf("upload job before verification = %d", jobs) + } + f.markFetched(versionID) + if jobs := f.uploadJobs(publicationID); jobs != 1 { + t.Fatalf("upload jobs after verified fetch = %d, want 1", jobs) + } + if state := f.publicationState(publicationID); state != "pending" { + t.Fatalf("publication state = %q, want pending", state) + } + // 幂等:重复完成不能造第二个上传任务。 + f.markFetched(versionID) + if jobs := f.uploadJobs(publicationID); jobs != 1 { + t.Fatalf("duplicate verified fetch created %d upload jobs", jobs) + } +} + +func TestRouteReusingVerifiedContentAlsoAutoStarts(t *testing.T) { + f := newAutoIngestFixture(t) + versionID, publicationID := f.route() + // 模拟"本地已有先比对":内容已 verified,删除尚未消费的取件作业后再路由。 + if _, err := f.pool.Exec(f.ctx, `UPDATE source_item_versions SET content_object_id=$2,content_state='verified' +WHERE id=$1`, versionID, f.insertVerifiedContent()); err != nil { + t.Fatal(err) + } + if _, err := f.pool.Exec(f.ctx, `DELETE FROM jobs WHERE type='artifact.fetch' AND payload->>'version_id'=$1`, versionID); err != nil { + t.Fatal(err) + } + if _, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{ + ConnectionID: f.connID, NodeIDs: []string{"node-file"}, Visibility: governance.VisibilityInternal, + TargetKnowledgeBaseID: f.kbID, OperatorRef: "fixture", Reason: "reuse", Now: f.now.Add(time.Minute), + }); err != nil { + t.Fatal(err) + } + if jobs := f.uploadJobs(publicationID); jobs != 1 { + t.Fatalf("reused verified content upload jobs = %d, want 1", jobs) + } +} + +func (f *autoIngestFixture) insertVerifiedContent() string { + f.t.Helper() + if _, err := f.pool.Exec(f.ctx, `INSERT INTO content_objects(id,sha256,size_bytes,mime,validated_format,local_spool_ref,content_state) +VALUES('co-auto',repeat('d',64),6991,'','docx','spool/auto.docx','verified') +ON CONFLICT(sha256) DO UPDATE SET local_spool_ref=EXCLUDED.local_spool_ref,content_state='verified'`); err != nil { + f.t.Fatal(err) + } + var id string + if err := f.pool.QueryRow(f.ctx, `SELECT id FROM content_objects WHERE sha256=repeat('d',64)`).Scan(&id); err != nil { + f.t.Fatal(err) + } + return id +} + +func TestStuckPlannedVerifiedPublicationRecoversViaReRoute(t *testing.T) { + f := newAutoIngestFixture(t) + versionID, publicationID := f.route() + f.markFetched(versionID) // 新代码本会入队;先清掉,复现 356 已卡记录 + if _, err := f.pool.Exec(f.ctx, `DELETE FROM jobs WHERE type='test.upload' AND payload->>'publication_id'=$1`, publicationID); err != nil { + t.Fatal(err) + } + if _, err := f.pool.Exec(f.ctx, `UPDATE test_publications SET processing_state='planned' WHERE id=$1`, publicationID); err != nil { + t.Fatal(err) + } + // 父在 UI 对同一文件再次保存当前策略:只这一条、只当前绑定,幂等接续。 + if _, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{ + ConnectionID: f.connID, NodeIDs: []string{"node-file"}, Visibility: governance.VisibilityInternal, + TargetKnowledgeBaseID: f.kbID, OperatorRef: "fixture", Reason: "resume", Now: f.now.Add(2 * time.Minute), + }); err != nil { + t.Fatal(err) + } + if jobs := f.uploadJobs(publicationID); jobs != 1 { + t.Fatalf("stuck record recovered upload jobs = %d, want 1", jobs) + } + if state := f.publicationState(publicationID); state != "pending" { + t.Fatalf("stuck record state = %q", state) + } +} + +func TestAutoStartRefusesStaleOrIneligiblePolicies(t *testing.T) { + cases := []struct { + name string + mutate func(f *autoIngestFixture, publicationID string) + }{ + {"disabled source", func(f *autoIngestFixture, _ string) { + if _, err := f.pool.Exec(f.ctx, `UPDATE source_connections SET enabled=FALSE WHERE id='conn-auto'`); err != nil { + f.t.Fatal(err) + } + }}, + {"blocked policy", func(f *autoIngestFixture, _ string) { + if _, err := f.pool.Exec(f.ctx, `UPDATE source_items SET policy_state='blocked' WHERE source_connection_id='conn-auto'`); err != nil { + f.t.Fatal(err) + } + }}, + {"filtered filename", func(f *autoIngestFixture, _ string) { + if _, err := f.pool.Exec(f.ctx, `INSERT INTO filename_filter_rules(source_connection_id,directory_path,excluded_extensions,updated_by,mode) +VALUES('conn-auto','',ARRAY['adoc'],'fixture','exclude')`); err != nil { + f.t.Fatal(err) + } + }}, + {"superseded publication", func(f *autoIngestFixture, publicationID string) { + if _, err := f.pool.Exec(f.ctx, `UPDATE test_publications SET superseded_at=$2 WHERE id=$1`, publicationID, f.now); err != nil { + f.t.Fatal(err) + } + }}, + {"binding changed", func(f *autoIngestFixture, _ string) { + if _, err := f.pool.Exec(f.ctx, `UPDATE routing_kb_bindings SET internal_kb_id='kb-other' WHERE id='active'`); err != nil { + f.t.Fatal(err) + } + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newAutoIngestFixture(t) + versionID, publicationID := f.route() + tc.mutate(f, publicationID) + f.markFetched(versionID) + if jobs := f.uploadJobs(publicationID); jobs != 0 { + t.Fatalf("%s auto-started %d upload jobs, want 0", tc.name, jobs) + } + }) + } +} diff --git a/internal/platform/postgres/catalog_routing.go b/internal/platform/postgres/catalog_routing.go index e1ce0a9..9530ca9 100644 --- a/internal/platform/postgres/catalog_routing.go +++ b/internal/platform/postgres/catalog_routing.go @@ -27,7 +27,7 @@ func (s *Store) RouteCatalogFiles(ctx context.Context, request governance.Catalo return governance.CatalogRouteResult{}, fmt.Errorf("begin catalog route: %w", err) } defer func() { _ = tx.Rollback(ctx) }() - result, err := routeCatalogFilesTx(ctx, tx, request) + result, err := routeCatalogFilesTx(ctx, tx, s, request) if err != nil { return governance.CatalogRouteResult{}, err } @@ -57,7 +57,7 @@ func validateCatalogRouteRequest(request governance.CatalogRouteRequest) error { return nil } -func routeCatalogFilesTx(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest) (governance.CatalogRouteResult, error) { +func routeCatalogFilesTx(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest) (governance.CatalogRouteResult, error) { targetKnowledgeBaseIDs := request.TargetKnowledgeBaseIDs if len(targetKnowledgeBaseIDs) == 0 && request.TargetKnowledgeBaseID != "" { targetKnowledgeBaseIDs = []string{request.TargetKnowledgeBaseID} @@ -114,7 +114,7 @@ FOR UPDATE OF node`, request.ConnectionID, nodeIDs) JOIN source_catalog_nodes child ON child.snapshot_id=parent.snapshot_id AND child.parent_node_id=parent.node_id WHERE parent.node_type='folder' ) -SELECT DISTINCT node.node_id,node.name,node.relative_path,node.size_bytes,node.modified_at,node.content_sha256, +SELECT DISTINCT node.node_id,node.parent_node_id,node.name,node.relative_path,node.size_bytes,node.modified_at,node.content_sha256, node.source_locator_hash,(node.node_id=ANY($2::text[])) AS directly_selected FROM descendants JOIN source_catalog_nodes node ON node.snapshot_id=descendants.snapshot_id AND node.node_id=descendants.node_id @@ -130,7 +130,7 @@ ORDER BY node.node_id`, request.ConnectionID, nodeIDs) files := make([]governance.CatalogRouteFile, 0, len(nodeIDs)) for rows.Next() { var file governance.CatalogRouteFile - if err := rows.Scan(&file.NodeID, &file.Name, &file.RelativePath, &file.SizeBytes, &file.ModifiedAt, + if err := rows.Scan(&file.NodeID, &file.ParentNodeID, &file.Name, &file.RelativePath, &file.SizeBytes, &file.ModifiedAt, &file.ContentSHA256, &file.LocatorHash, &file.Direct); err != nil { rows.Close() return governance.CatalogRouteResult{}, fmt.Errorf("scan catalog route file: %w", err) @@ -142,7 +142,7 @@ ORDER BY node.node_id`, request.ConnectionID, nodeIDs) return governance.CatalogRouteResult{}, fmt.Errorf("iterate catalog route files: %w", err) } rows.Close() - return fulfillCatalogIntentsTx(ctx, tx, request, files, request.Now) + return fulfillCatalogIntentsTx(ctx, tx, store, request, files, request.Now) } func setCatalogDirectoryPolicy(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, directoryPath string) error { diff --git a/internal/platform/postgres/dws_registered_spaces.go b/internal/platform/postgres/dws_registered_spaces.go new file mode 100644 index 0000000..3eed46e --- /dev/null +++ b/internal/platform/postgres/dws_registered_spaces.go @@ -0,0 +1,36 @@ +package postgres + +import ( + "context" + "net/url" + "strings" +) + +// RegisteredDingtalkSpaceIDs also covers historical connections whose root key +// predates DWS; a source name is never an identity. +func (s *Store) RegisteredDingtalkSpaceIDs(ctx context.Context) (map[string]bool, error) { + rows, err := s.db.Query(ctx, "SELECT base_url FROM source_connections WHERE source_type='dingtalk' AND archived_at IS NULL") + if err != nil { + return nil, err + } + defer rows.Close() + result := map[string]bool{} + for rows.Next() { + var raw string + if err := rows.Scan(&raw); err != nil { + return nil, err + } + u, err := url.Parse(raw) + if err != nil { + continue + } + space := u.Query().Get("space") + if space == "" && strings.HasPrefix(u.Path, "spaces/") { + space = strings.TrimPrefix(u.Path, "spaces/") + } + if space != "" { + result[space] = true + } + } + return result, rows.Err() +} diff --git a/internal/platform/postgres/integration_isolation_test.go b/internal/platform/postgres/integration_isolation_test.go index 8886991..170af79 100644 --- a/internal/platform/postgres/integration_isolation_test.go +++ b/internal/platform/postgres/integration_isolation_test.go @@ -1,44 +1,14 @@ package postgres import ( - "context" - "crypto/sha256" - "encoding/hex" - "net/url" "testing" - "github.com/jackc/pgx/v5/pgxpool" + "knowledge-governance/internal/platform/postgres/pgtest" ) +// 隔离 schema 的实现只留一份(pgtest):postgres 与 cmd/worker 的集成用例 +// 都要连真库,复制一份到两边,迟早只改一边。 func isolatedIntegrationDatabaseURL(t *testing.T, databaseURL string) string { t.Helper() - if databaseURL == "" { - return "" - } - parsed, err := url.Parse(databaseURL) - if err != nil || parsed.Scheme == "" || parsed.Host == "" { - t.Fatalf("TEST_DATABASE_URL must be a PostgreSQL URL: %v", err) - } - digest := sha256.Sum256([]byte(t.Name())) - schema := "kgtest_" + hex.EncodeToString(digest[:8]) - ctx := context.Background() - admin, err := pgxpool.New(ctx, databaseURL) - if err != nil { - t.Fatalf("connect integration database: %v", err) - } - defer admin.Close() - if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil { - t.Fatalf("create isolated integration schema: %v", err) - } - t.Cleanup(func() { - cleanup, err := pgxpool.New(context.Background(), databaseURL) - if err == nil { - _, _ = cleanup.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+schema+" CASCADE") - cleanup.Close() - } - }) - query := parsed.Query() - query.Set("search_path", schema) - parsed.RawQuery = query.Encode() - return parsed.String() + return pgtest.IsolatedDatabaseURL(t, databaseURL) } diff --git a/internal/platform/postgres/library_capture_reconcile_pg_test.go b/internal/platform/postgres/library_capture_reconcile_pg_test.go new file mode 100644 index 0000000..6c87ec5 --- /dev/null +++ b/internal/platform/postgres/library_capture_reconcile_pg_test.go @@ -0,0 +1,131 @@ +package postgres + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// This exercises the exact SQL used by the admin capture reconcile path with +// the real varchar/jsonb/timestamptz column shapes from the migration. Fake +// stores cannot catch parameter-type mistakes, as the 42P08 incident showed. +func TestCaptureReconcileExactPostgresPath(t *testing.T) { + dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database") + } + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + t.Fatal("isolated database required") + } + cfg.MaxConns = 1 + cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp" + ctx := context.Background() + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if _, err := pool.Exec(ctx, ` +CREATE TEMP TABLE library_jobs( + id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL, + state varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL DEFAULT '', + stage varchar(32) NOT NULL DEFAULT '', snapshot_id varchar(64) NOT NULL DEFAULT '', + error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, finished_at timestamptz); +CREATE TEMP TABLE library_job_stages( + job_id varchar(64) NOT NULL, stage varchar(32) NOT NULL, state varchar(16) NOT NULL, + detail text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, PRIMARY KEY(job_id,stage)); +CREATE TEMP TABLE library_job_repairs( + id varchar(64) PRIMARY KEY, job_id varchar(64) NOT NULL, scope varchar(16) NOT NULL, + kind varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL, snapshot_id varchar(64) NOT NULL, + original_state varchar(16) NOT NULL, original_stage varchar(32) NOT NULL DEFAULT '', + original_error text NOT NULL DEFAULT '', original_recovery varchar(255) NOT NULL DEFAULT '', + original_finished_at timestamptz, reason varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '', + evidence jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL); +CREATE TEMP TABLE library_versions( + id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(24) NOT NULL, + snapshot_id varchar(64) NOT NULL DEFAULT '', version_label varchar(64) NOT NULL DEFAULT '', + source_job_id varchar(64) NOT NULL DEFAULT '', operation_id varchar(64) NOT NULL DEFAULT '', + attempt_epoch integer NOT NULL DEFAULT 0, evidence jsonb NOT NULL DEFAULT '{}'::jsonb, + created_by varchar(128) NOT NULL DEFAULT '', created_at timestamptz NOT NULL, + superseded_at timestamptz); +INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,updated_at) + VALUES('libseal-cap-1','internal','seal','pending','libcap-1',now()); +INSERT INTO library_job_stages(job_id,stage,state,updated_at) + VALUES('libseal-cap-1','export','succeeded',now()); +INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,created_at) + VALUES('libver-1','internal','test_sealed','snap-1','libseal-cap-1',now());`); err != nil { + t.Fatal(err) + } + store := NewStore(pool) + state, _, err := store.LibraryCaptureExportEvidence(ctx, "libseal-cap-1") + if err != nil || state != "succeeded" { + t.Fatalf("export evidence state=%q err=%v", state, err) + } + version, found, err := store.LibraryTestSealedVersionForJob(ctx, "internal", "libseal-cap-1") + if err != nil || !found || version.SnapshotID != "snap-1" { + t.Fatalf("version found=%v snapshot=%q err=%v", found, version.SnapshotID, err) + } + now := time.Now().UTC() + updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-cap-1", "internal", "libcap-1", "snap-1", now) + if err != nil || !updated { + t.Fatalf("conditional repair updated=%v err=%v", updated, err) + } + var gotState, gotScope, gotSnapshot string + var finished bool + if err := pool.QueryRow(ctx, `SELECT state, scope, snapshot_id, finished_at IS NOT NULL FROM library_jobs WHERE id='libseal-cap-1'`). + Scan(&gotState, &gotScope, &gotSnapshot, &finished); err != nil { + t.Fatal(err) + } + if gotState != "succeeded" || gotScope != "internal" || gotSnapshot != "snap-1" || !finished { + t.Fatalf("terminal state=%q scope=%q snapshot=%q finished=%v", gotState, gotScope, gotSnapshot, finished) + } + if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-cap-1", "internal", "libcap-1", "snap-1", now.Add(time.Second)); err != nil || updated { + t.Fatalf("second repair must be idempotent/false: updated=%v err=%v", updated, err) + } + if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,updated_at) + VALUES('libseal-failed','internal','seal','failed','libcap-2',now())`); err != nil { + t.Fatal(err) + } + if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-failed", "internal", "libcap-2", "snap-2", now); err != nil || updated { + t.Fatalf("failed row must not be repaired: updated=%v err=%v", updated, err) + } + if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,snapshot_id,updated_at) + VALUES('libseal-other','internal','seal','running','libcap-3','other',now())`); err != nil { + t.Fatal(err) + } + if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-other", "internal", "libcap-3", "snap-3", now); err != nil || updated { + t.Fatalf("different existing snapshot must not be overwritten: updated=%v err=%v", updated, err) + } + + legacyFinished := now.Add(-time.Minute).Truncate(time.Microsecond) + if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,error,recovery,updated_at,finished_at) + VALUES('libseal-misclassified','internal','seal','failed','libcap-4',$1,$2,$3,$3)`, + "队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", legacyFinished); err != nil { + t.Fatal(err) + } + repaired, err := store.ReconcileMisclassifiedLibraryCapture(ctx, "libseal-misclassified", "internal", "libcap-4", "snap-4", + "", "队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", &legacyFinished, + "librepair-test", "tester", "test repair", map[string]any{"archive_verified": true}, now) + if err != nil || !repaired { + t.Fatalf("misclassification repair=%v err=%v", repaired, err) + } + var originalState, originalError string + var originalFinished *time.Time + if err := pool.QueryRow(ctx, `SELECT original_state, original_error, original_finished_at FROM library_job_repairs WHERE id='librepair-test'`). + Scan(&originalState, &originalError, &originalFinished); err != nil { + t.Fatal(err) + } + if originalState != "failed" || originalError == "" || originalFinished == nil { + t.Fatalf("audit lost original fields: state=%q error=%q finished=%v", originalState, originalError, originalFinished) + } + if repaired, err := store.ReconcileMisclassifiedLibraryCapture(ctx, "libseal-misclassified", "internal", "libcap-4", "snap-4", + "", "队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", &legacyFinished, + "librepair-test-2", "tester", "test repair", map[string]any{}, now); err != nil || repaired { + t.Fatalf("second repair must be false: repaired=%v err=%v", repaired, err) + } +} diff --git a/internal/platform/postgres/library_dispatch.go b/internal/platform/postgres/library_dispatch.go new file mode 100644 index 0000000..f3c0330 --- /dev/null +++ b/internal/platform/postgres/library_dispatch.go @@ -0,0 +1,69 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + "time" +) + +func (s *Store) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) { + tx, err := s.db.Begin(ctx) + if err != nil { + return governance.LibraryJob{}, false, err + } + defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() + created, reused, err := NewStore(tx).WithLibraryTarget(s.libraryTargetID).createLibraryDispatch(ctx, job, stages, handoff, now) + if err != nil { + return governance.LibraryJob{}, false, err + } + if err = tx.Commit(ctx); err != nil { + return governance.LibraryJob{}, false, err + } + return created, reused, nil +} +func (s *Store) createLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) { + created, reused, err := s.CreateLibraryJob(ctx, job, stages, now) + if err != nil { + return created, reused, err + } + if reused && (created.State != governance.LibraryJobPending || created.QueueJobID != "") { + return created, true, nil + } + kind := "library." + string(created.Kind) + if created.Kind != governance.LibraryJobSync && created.Kind != governance.LibraryJobRestore && + created.Kind != governance.LibraryJobBaseline && created.Kind != governance.LibraryJobVerify { + return created, reused, errors.New("unsupported library dispatch kind") + } + queueID, kind, raw, err := governance.LibraryQueueRequest(handoff, created.ID, created.Scope, created.TargetSnapshotID, kind) + if err != nil { + return created, reused, err + } + var payload map[string]string + if err = json.Unmarshal(raw, &payload); err != nil { + return created, reused, err + } + queued, err := s.Enqueue(ctx, jobs.EnqueueRequest{ID: queueID, Type: kind, Payload: raw, AvailableAt: now, MaxAttempts: 1, IdempotencyKey: kind + ".queue:" + created.ID}, now) + if err != nil { + return created, reused, err + } + if queued == nil || queued.ID != queueID || queued.Type != kind { + return created, reused, errors.New("queue identity conflict") + } + var actual map[string]string + if json.Unmarshal(queued.Payload, &actual) != nil || len(actual) != len(payload) { + return created, reused, errors.New("queue payload mismatch") + } + for key, value := range payload { + if actual[key] != value { + return created, reused, errors.New("queue payload mismatch") + } + } + if err := s.AttachLibraryQueueJob(ctx, created.ID, queued.ID, now); err != nil { + return created, reused, err + } + created.QueueJobID = queued.ID + return created, reused, nil +} diff --git a/internal/platform/postgres/library_dispatch_test.go b/internal/platform/postgres/library_dispatch_test.go new file mode 100644 index 0000000..6995d28 --- /dev/null +++ b/internal/platform/postgres/library_dispatch_test.go @@ -0,0 +1,39 @@ +package postgres + +import ( + "context" + "knowledge-governance/internal/governance" + "testing" + "time" +) + +func TestContractDispatchAttachFailureLeavesNoQueueOrBusinessJob(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + if _, err := pool.Exec(ctx, `CREATE FUNCTION fail_dispatch_attach() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.queue_job_id <> '' THEN RAISE EXCEPTION 'injected attach failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER fail_attach BEFORE UPDATE ON library_jobs FOR EACH ROW EXECUTE FUNCTION fail_dispatch_attach()`); err != nil { + t.Fatal(err) + } + job := governance.LibraryJob{ID: "atomic-dispatch", Scope: "internal", Kind: governance.LibraryJobSync, RequestDigest: "request", IdempotencyKey: "intent-atomic", TargetSnapshotID: "snapshot"} + if _, _, err := store.CreateLibraryDispatch(ctx, job, governance.SyncStages(), false, now); err == nil { + t.Fatal("injected attach did not fail") + } + var business, queue int + if err := pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM library_jobs),(SELECT count(*) FROM jobs)`).Scan(&business, &queue); err != nil { + t.Fatal(err) + } + if business != 0 || queue != 0 { + t.Fatalf("partial dispatch escaped transaction: business=%d queue=%d", business, queue) + } + if _, err := pool.Exec(ctx, `DROP TRIGGER fail_attach ON library_jobs`); err != nil { + t.Fatal(err) + } + first, reused, err := store.CreateLibraryDispatch(ctx, job, governance.SyncStages(), false, now) + if err != nil || reused || first.QueueJobID == "" { + t.Fatalf("dispatch after failure: %+v %v %v", first, reused, err) + } + replay, reused, err := store.CreateLibraryDispatch(ctx, job, governance.SyncStages(), false, now) + if err != nil || !reused || replay.QueueJobID != first.QueueJobID { + t.Fatalf("dispatch replay: %+v %v %v", replay, reused, err) + } +} diff --git a/internal/platform/postgres/library_execution.go b/internal/platform/postgres/library_execution.go new file mode 100644 index 0000000..9486b32 --- /dev/null +++ b/internal/platform/postgres/library_execution.go @@ -0,0 +1,36 @@ +package postgres + +import ( + "context" + "errors" + "time" +) + +var ErrLibraryExecutionBusy = errors.New("target already has an active executor") + +func (s *Store) WithLibraryExecution(ctx context.Context, instance string, run func(context.Context, func(context.Context) error) error) error { + if instance == "" { + return errors.New("execution instance identity required") + } + // A lease expiry is not proof that the old writer has stopped. Keep a + // shared PG advisory lock until the synchronous callback (including cleanup) + // exits. No deferred unlock may run merely because ctx was cancelled. + tx, err := s.db.Begin(ctx) + if err != nil { + return err + } + defer func() { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + _ = tx.Rollback(cleanup) + }() + var held bool + if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, "library-execution:"+instance).Scan(&held); err != nil { + return err + } + if !held { + return ErrLibraryExecutionBusy + } + ping := func(probe context.Context) error { var one int; return tx.QueryRow(probe, `SELECT 1`).Scan(&one) } + return run(ctx, ping) +} diff --git a/internal/platform/postgres/library_execution_test.go b/internal/platform/postgres/library_execution_test.go new file mode 100644 index 0000000..6cd1da8 --- /dev/null +++ b/internal/platform/postgres/library_execution_test.go @@ -0,0 +1,51 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "testing" + "time" +) + +func TestContractExecutionMutexWaitsForActualWriter(t *testing.T) { + store, _ := newIdentityStore(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + key := fmt.Sprintf("isolated-%s-%d", t.Name(), time.Now().UnixNano()) + entered := make(chan struct{}) + release := make(chan struct{}) + finished := make(chan error, 1) + go func() { + finished <- store.WithLibraryExecution(ctx, key, func(ctx context.Context, ping func(context.Context) error) error { + if err := ping(ctx); err != nil { + return err + } + close(entered) + <-ctx.Done() + <-release + return ctx.Err() + }) + }() + select { + case <-entered: + case err := <-finished: + t.Fatalf("first executor: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("first executor timeout") + } + cancel() + called := false + err := store.WithLibraryExecution(context.Background(), key, func(context.Context, func(context.Context) error) error { called = true; return nil }) + close(release) + if err2 := <-finished; !errors.Is(err2, context.Canceled) { + t.Fatalf("first executor exit: %v", err2) + } + if !errors.Is(err, ErrLibraryExecutionBusy) || called { + t.Fatalf("cancelled but still-writing executor was overlapped: err=%v called=%v", err, called) + } + called = false + if err = store.WithLibraryExecution(context.Background(), key, func(context.Context, func(context.Context) error) error { called = true; return nil }); err != nil || !called { + t.Fatalf("finished executor not released: %v %v", err, called) + } +} diff --git a/internal/platform/postgres/library_identity_integration_test.go b/internal/platform/postgres/library_identity_integration_test.go new file mode 100644 index 0000000..16134c2 --- /dev/null +++ b/internal/platform/postgres/library_identity_integration_test.go @@ -0,0 +1,525 @@ +package postgres + +import ( + "context" + "errors" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarymaintenance" +) + +// 真实 PG 上的执行身份/栅栏用例。 +// +// 为什么必须是真库(父的复核项 R1/R2):守卫的失败形态是"SQL 条件永远不匹配"—— +// 参数序号、列引用、NULL 与空串的差别在内存 fake 里根本不存在。字符串断言证明不了 +// 一条 UPDATE 真的命中了一行。 + +func newIdentityStore(t *testing.T) (*Store, *pgxpool.Pool) { + t.Helper() + databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if databaseURL == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, databaseURL) + if err != nil { + t.Fatalf("connect isolated database: %v", err) + } + t.Cleanup(pool.Close) + if err := ApplyMigrations(ctx, pool); err != nil { + t.Fatalf("apply migrations: %v", err) + } + return NewStore(pool), pool +} + +// seedOperationJob 建一条"有 operation 的业务作业",返回 operation 与作业 id。 +func seedOperationJob(t *testing.T, store *Store, pool *pgxpool.Pool, scope, jobID, kind string, now time.Time) string { + t.Helper() + ctx := context.Background() + op, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ + ID: governance.LibraryOperationID(scope, governance.LibraryJobKind(kind), jobID), + Scope: scope, Kind: governance.LibraryJobKind(kind), TargetSnapshotID: "snap-target", + RequestDigest: "digest-" + jobID, OperationKey: jobID, Actor: "tester", CreatedAt: now.UTC(), + }) + if err != nil { + t.Fatalf("ensure operation: %v", err) + } + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ + ID: jobID, Scope: scope, Kind: governance.LibraryJobKind(kind), OperationID: op.ID, + IdempotencyKey: "library.job:" + op.ID, RequestDigest: "digest-" + jobID, + TargetSnapshotID: "snap-target", Actor: "tester", + }, governance.SyncStages(), now); err != nil { + t.Fatalf("create library job: %v", err) + } + // 维护窗口由这个作业持有(实例级 + scope 级)。 + if _, err := pool.Exec(ctx, ` +INSERT INTO library_maintenance (scope, owner_job_id, target_identity, state, original_service_state, + note, acquired_at, updated_at) +VALUES ($1,$2,'target-identity','acquired','app:running,store:running','test',$3,$3) +ON CONFLICT (scope) DO UPDATE SET owner_job_id=EXCLUDED.owner_job_id, released_at=NULL, + state='acquired', updated_at=EXCLUDED.updated_at`, + scope, jobID, now.UTC()); err != nil { + t.Fatalf("seed scope maintenance: %v", err) + } + if _, err := pool.Exec(ctx, ` +INSERT INTO library_instance_maintenance (instance, owner_job_id, owner_scope, target_fingerprint, state, + original_service_state, note, acquired_at, updated_at) +VALUES ('inst-1',$1,$2,$4,'acquired','app:running','test',$3,$3) +ON CONFLICT (instance) DO UPDATE SET owner_job_id=EXCLUDED.owner_job_id, owner_scope=EXCLUDED.owner_scope, + released_at=NULL, state='acquired', updated_at=EXCLUDED.updated_at`, + jobID, scope, now.UTC(), ds01TestFingerprint); err != nil { + t.Fatalf("seed instance maintenance: %v", err) + } + return op.ID +} + +// settleJob 把一个作业行推到终态:同一 scope 只允许一条在飞作业(部分唯一索引), +// 所以"再建一条兄弟作业"之前必须先让它落地。 +func settleJob(t *testing.T, pool *pgxpool.Pool, jobID string, now time.Time) { + t.Helper() + if _, err := pool.Exec(context.Background(), + `UPDATE library_jobs SET state='failed', finished_at=$2, updated_at=$2 WHERE id=$1`, + jobID, now.UTC()); err != nil { + t.Fatalf("settle job %s: %v", jobID, err) + } +} + +// R1:维护类守卫的作业 id 必须取自被更新行自己的 owner_job_id,而不是参数 $1。 +// +// 旧实现把 `j.id=$1` 写死,$1 是 scope/instance ⇒ 守卫永远匹配不到作业, +// **正常**的维护状态写入与释放全部失败。这里逐个入口走一遍真库。 +func TestLibraryMaintenanceFenceUsesRowOwner(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + jobID := "libsync-fence-1" + seedOperationJob(t, store, pool, "internal", jobID, "sync", now) + + attempt, err := store.BeginLibraryAttempt(ctx, jobID, "worker-a#q1#0", 10*time.Minute, now) + if err != nil { + t.Fatalf("begin attempt: %v", err) + } + if attempt.OperationID == "" || attempt.Epoch != 1 { + t.Fatalf("attempt = %+v", attempt) + } + + // scope 级:状态、入口、释放都必须命中($1 是 scope,不是作业 id)。 + if err := store.UpdateLibraryMaintenanceStateGuarded(ctx, "internal", jobID, "applying", "写目标", attempt, now); err != nil { + t.Fatalf("更新 scope 维护状态失败(守卫没命中作业):%v", err) + } + if err := store.SetLibraryMaintenanceIngressGuarded(ctx, "internal", jobID, "closed", "入口已关", attempt, now); err != nil { + t.Fatalf("记录 scope 入口状态失败:%v", err) + } + // 实例级:$1 是 instance。 + if err := store.UpdateInstanceMaintenanceStateGuarded(ctx, "inst-1", jobID, "applying", "写目标", attempt, now); err != nil { + t.Fatalf("更新实例维护状态失败:%v", err) + } + if err := store.SetInstanceMaintenanceIngressGuarded(ctx, "inst-1", jobID, "closed", "入口已关", attempt, now); err != nil { + t.Fatalf("记录实例入口状态失败:%v", err) + } + if err := store.ReleaseLibraryMaintenanceGuarded(ctx, "internal", jobID, attempt, now); err != nil { + t.Fatalf("释放 scope 维护失败(正常路径被守卫挡死):%v", err) + } + if err := store.ReleaseInstanceMaintenanceGuarded(ctx, "inst-1", jobID, attempt, now); err != nil { + t.Fatalf("释放实例维护失败:%v", err) + } + var released int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM library_maintenance WHERE released_at IS NOT NULL`).Scan(&released); err != nil { + t.Fatal(err) + } + if released != 1 { + t.Fatalf("scope 维护应有 1 行已释放,实际 %d", released) + } + // 负例(同一代码路径):作业 id 不匹配时守卫必须**拒绝**,而不是默默返回成功。 + // 这条与上面的正例一起,才证明 "$1 是 scope、作业 id 取自行" 的契约真的在起作用。 + if err := store.ReleaseInstanceMaintenanceGuarded(ctx, "inst-1", "libsync-other-job", attempt, now); err == nil { + t.Fatal("作业 id 不匹配时释放实例维护必须失败(守卫没看作业身份)") + } + if err := store.UpdateLibraryMaintenanceStateGuarded(ctx, "internal", "libsync-other-job", "applying", "x", attempt, now); err == nil { + t.Fatal("作业 id 不匹配时更新维护状态必须失败") + } + // 幂等:再释放一次是"已释放",不是"未持有"。 + if err := store.ReleaseLibraryMaintenanceGuarded(ctx, "internal", jobID, attempt, now); !errors.Is(err, ErrMaintenanceReleased) { + t.Fatalf("重复释放应返回 ErrMaintenanceReleased,实际 %v", err) + } +} + +// R2:同一作业连续三次认领 ⇒ 三个不可变代次;旧代次的写必须失败。 +func TestBeginLibraryAttemptSameJobThreeGenerations(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + jobID := "libsync-gen-1" + opID := seedOperationJob(t, store, pool, "internal", jobID, "sync", now) + + var epochs []int + for round := 1; round <= 3; round++ { + attempt, err := store.BeginLibraryAttempt(ctx, jobID, "worker#q#"+string(rune('0'+round)), 10*time.Minute, now.Add(time.Duration(round)*time.Minute)) + if err != nil { + t.Fatalf("第 %d 次认领失败:%v", round, err) + } + epochs = append(epochs, attempt.Epoch) + // 结束上一代(模拟执行完毕/崩溃后接手):直接 Finish 或让它过期。 + if err := store.FinishLibraryAttempt(ctx, attempt, governance.LibraryAttemptCompleted, "round done", now); err != nil { + t.Fatalf("第 %d 次结束代次失败:%v", round, err) + } + } + if len(epochs) != 3 || epochs[0] != 1 || epochs[1] != 2 || epochs[2] != 3 { + t.Fatalf("epoch 必须按 operation 单调递增:%v", epochs) + } + // 历史不可变:三次认领留下三行。 + var rows int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM library_attempts WHERE operation_id=$1`, opID).Scan(&rows); err != nil { + t.Fatal(err) + } + if rows != 3 { + t.Fatalf("同一作业三次认领必须保留 3 条代次(不可变历史),实际 %d", rows) + } + // 作业行指向最后一代。 + job, err := store.LibraryJob(ctx, jobID) + if err != nil { + t.Fatal(err) + } + if job.AttemptEpoch != 3 { + t.Fatalf("作业行 attempt_epoch = %d, want 3", job.AttemptEpoch) + } + // 旧代次的守卫写必须失败(它的 attempt 已 completed)。 + stale := governance.LibraryAttempt{OperationID: opID, Epoch: 2, JobID: jobID, Owner: "worker#q#2"} + if err := store.AdvanceLibraryJobGuarded(ctx, stale, governance.LibraryJobRunning, "", "", "", "", "", now); !errors.Is(err, governance.ErrLibraryEpochStale) { + t.Fatalf("旧代次写业务状态必须被拒绝,实际 %v", err) + } + // 迟到的 finish 也必须拒绝:否则旧执行能把别人正在跑的那一代"结束"掉。 + if err := store.FinishLibraryAttempt(ctx, stale, governance.LibraryAttemptCompleted, "late finish", now); !errors.Is(err, governance.ErrLibraryEpochStale) { + t.Fatalf("旧代次的 finish 必须被拒绝,实际 %v", err) + } +} + +// R2:同一次投递重复调用是幂等的(同一代次,不新增行);别人的有效租约必须让路。 +func TestBeginLibraryAttemptIdempotentRepeatAndHeldLease(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + jobID := "libsync-repeat-1" + opID := seedOperationJob(t, store, pool, "internal", jobID, "sync", now) + + first, err := store.BeginLibraryAttempt(ctx, jobID, "worker-a#q1#0", 10*time.Minute, now) + if err != nil { + t.Fatal(err) + } + second, err := store.BeginLibraryAttempt(ctx, jobID, "worker-a#q1#0", 10*time.Minute, now.Add(time.Second)) + if err != nil { + t.Fatalf("同一次投递重复调用必须幂等:%v", err) + } + if second.Epoch != first.Epoch { + t.Fatalf("重复调用不应新增代次:%d vs %d", second.Epoch, first.Epoch) + } + var rows int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM library_attempts WHERE operation_id=$1`, opID).Scan(&rows); err != nil { + t.Fatal(err) + } + if rows != 1 { + t.Fatalf("幂等重复调用不应新增代次行,实际 %d", rows) + } + // 另一个执行者(不同 owner,租约未过期)必须被拒绝。 + if _, err := store.BeginLibraryAttempt(ctx, jobID, "worker-b#q1#0", 10*time.Minute, now.Add(2*time.Second)); !errors.Is(err, ErrLibraryAttemptHeld) { + t.Fatalf("别的执行者持有未过期租约时必须拒绝,实际 %v", err) + } + // 租约过期后允许接管,并结束旧代次。 + later := now.Add(20 * time.Minute) + takeover, err := store.BeginLibraryAttempt(ctx, jobID, "worker-b#q1#1", 10*time.Minute, later) + if err != nil { + t.Fatalf("租约过期后必须允许接管:%v", err) + } + if takeover.Epoch != first.Epoch+1 { + t.Fatalf("接管必须开新代次:%d", takeover.Epoch) + } + var oldState string + if err := pool.QueryRow(ctx, `SELECT state FROM library_attempts WHERE operation_id=$1 AND epoch=$2`, + opID, first.Epoch).Scan(&oldState); err != nil { + t.Fatal(err) + } + if oldState != "abandoned" { + t.Fatalf("被接管的旧代次应标为 abandoned,实际 %q", oldState) + } + // 旧代次的续租必须失败(失租即停)。 + if err := store.RenewLibraryAttempt(ctx, first, time.Minute, later); !errors.Is(err, governance.ErrLibraryEpochStale) { + t.Fatalf("旧代次续租必须失败,实际 %v", err) + } +} + +// R2:同一 operation 不同作业(续作留下的兄弟行)——新代次激活后,旧作业行的守卫必须失效。 +func TestSiblingJobGuardInvalidatedByNewAttempt(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + firstJob := "libsync-sib-1" + opID := seedOperationJob(t, store, pool, "internal", firstJob, "sync", now) + + firstAttempt, err := store.BeginLibraryAttempt(ctx, firstJob, "worker-a#q1#0", 10*time.Minute, now) + if err != nil { + t.Fatal(err) + } + settleJob(t, pool, firstJob, now) + // 兄弟作业行(同一 operation,模拟历史 `-resume` 行/并行执行者)。 + secondJob := firstJob + "-resume" + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ + ID: secondJob, Scope: "internal", Kind: governance.LibraryJobSync, OperationID: opID, + IdempotencyKey: "library.job:" + opID + ":resume", RequestDigest: "digest-sib", + TargetSnapshotID: "snap-target", Actor: "tester", + }, governance.SyncStages(), now); err != nil { + t.Fatalf("create sibling job: %v", err) + } + // 结束第一代后,由兄弟作业接管同一 operation。 + if err := store.FinishLibraryAttempt(ctx, firstAttempt, governance.LibraryAttemptFailed, "crashed", now); err != nil { + t.Fatal(err) + } + settleJob(t, pool, firstJob, now) + secondAttempt, err := store.BeginLibraryAttempt(ctx, secondJob, "worker-b#q2#0", 10*time.Minute, now.Add(time.Minute)) + if err != nil { + t.Fatalf("兄弟作业接管失败:%v", err) + } + if secondAttempt.OperationID != opID || secondAttempt.Epoch != firstAttempt.Epoch+1 { + t.Fatalf("兄弟作业必须共用同一 operation 并开新一代:%+v", secondAttempt) + } + // 旧作业行上的 epoch/owner 字段还在,但它的守卫必须失败。 + if err := store.AdvanceLibraryJobGuarded(ctx, firstAttempt, governance.LibraryJobRunning, "", "", "", "", "", now); !errors.Is(err, governance.ErrLibraryEpochStale) { + t.Fatalf("旧作业的守卫必须失效,实际 %v", err) + } + var siblingLease string + if err := pool.QueryRow(ctx, `SELECT lease_owner FROM library_jobs WHERE id=$1`, firstJob).Scan(&siblingLease); err != nil { + t.Fatal(err) + } + if siblingLease != "" { + t.Fatalf("兄弟接管后旧作业行租约必须被清空,实际 %q", siblingLease) + } +} + +// 首次锚点:事务 + 回读核对,NULL 与空串不清混;覆盖被拒绝。 +func TestRecordOperationAnchorsTransactionalAndNullSafe(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + jobID := "libsync-anchor-1" + opID := seedOperationJob(t, store, pool, "internal", jobID, "sync", now) + + // 只登记快照 id(字节/写集合未知)⇒ 对应列必须是 NULL,而不是 0/空串。 + if err := store.RecordOperationAnchors(ctx, opID, governance.LibraryAnchors{ + FirstBackupSnapshotID: "backup-snap-1", + }, now); err != nil { + t.Fatalf("首次登记锚点失败:%v", err) + } + var bytesNull, rowsNull, digestNull bool + if err := pool.QueryRow(ctx, ` +SELECT first_backup_bytes IS NULL, writeset_rows IS NULL, writeset_digest IS NULL +FROM library_operations WHERE id=$1`, opID).Scan(&bytesNull, &rowsNull, &digestNull); err != nil { + t.Fatal(err) + } + if !bytesNull || !rowsNull || !digestNull { + t.Fatalf("未知锚点必须留 NULL:bytes_null=%v rows_null=%v digest_null=%v", bytesNull, rowsNull, digestNull) + } + // 补齐字节与写集合:允许填空。 + bytes := int64(4096) + rows := int64(119) + if err := store.RecordOperationAnchors(ctx, opID, governance.LibraryAnchors{ + FirstBackupBytes: &bytes, WriteSetRows: &rows, WriteSetDigest: "ws-digest-1", + }, now); err != nil { + t.Fatalf("补齐锚点失败:%v", err) + } + var gotBytes int64 + var gotDigest string + if err := pool.QueryRow(ctx, `SELECT first_backup_bytes, writeset_digest FROM library_operations WHERE id=$1`, + opID).Scan(&gotBytes, &gotDigest); err != nil { + t.Fatal(err) + } + if gotBytes != bytes || gotDigest != "ws-digest-1" { + t.Fatalf("锚点回读不一致:%d/%s", gotBytes, gotDigest) + } + // 覆盖被拒绝(字节与写集合都不许换)。 + other := int64(1) + if err := store.RecordOperationAnchors(ctx, opID, governance.LibraryAnchors{FirstBackupBytes: &other}, now); err == nil { + t.Fatal("用不同字节覆盖首次锚点必须失败") + } + if err := store.RecordOperationAnchors(ctx, opID, governance.LibraryAnchors{WriteSetDigest: "ws-digest-2"}, now); err == nil { + t.Fatal("用不同写集合摘要覆盖首次锚点必须失败") + } + // 幂等:同一份锚点重复登记成功且不改值。 + if err := store.RecordOperationAnchors(ctx, opID, governance.LibraryAnchors{ + FirstBackupSnapshotID: "backup-snap-1", FirstBackupBytes: &bytes, WriteSetDigest: "ws-digest-1", + }, now); err != nil { + t.Fatalf("同一份锚点重复登记必须幂等成功:%v", err) + } +} + +// current 指针:旧意图后来登记的事实**不能**把 current 推回历史;新意图(恢复)可以。 +func TestLibraryCurrentOrderingRejectsLateOldIntent(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + base := time.Now().UTC() + jobA, jobB := "libsync-ord-a", "libsync-ord-b" + opA := seedOperationJob(t, store, pool, "internal", jobA, "sync", base) + settleJob(t, pool, jobA, base) + opB := seedOperationJob(t, store, pool, "internal", jobB, "sync", base.Add(time.Minute)) + + effective := func(opID, jobID, snapshot string, at time.Time) error { + return store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionEffective, "internal", snapshot, opID), + Scope: "internal", Kind: governance.LibraryVersionProductionEffective, SnapshotID: snapshot, + SourceJobID: jobID, OperationID: opID, CreatedBy: "tester", CreatedAt: at, + Evidence: map[string]any{"backup_snapshot": "backup-" + snapshot}, + }) + } + if err := effective(opA, jobA, "snap-a", base); err != nil { + t.Fatalf("登记 A 失败:%v", err) + } + if err := effective(opB, jobB, "snap-b", base.Add(time.Minute)); err != nil { + t.Fatalf("登记 B 失败:%v", err) + } + current, found, err := store.LibraryCurrentVersion(ctx, "internal") + if err != nil || !found || current.SnapshotID != "snap-b" { + t.Fatalf("current 应为 snap-b:%v %+v", err, current) + } + // 旧意图(A,创建时间更早)后来又登记了一条新事实:必须被拒绝,不能把 current 拉回去。 + late := governance.LibraryVersion{ + ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionEffective, "internal", "snap-a2", opA), + Scope: "internal", Kind: governance.LibraryVersionProductionEffective, SnapshotID: "snap-a2", + SourceJobID: jobA, OperationID: opA, CreatedBy: "tester", CreatedAt: base.Add(2 * time.Hour), + Evidence: map[string]any{"backup_snapshot": "backup-snap-a2"}, + } + if err := store.RecordLibraryVersion(ctx, late); !errors.Is(err, governance.ErrLibraryCurrentStale) { + t.Fatalf("旧意图的迟到事实必须被拒绝,实际 %v", err) + } + current, found, err = store.LibraryCurrentVersion(ctx, "internal") + if err != nil || !found || current.SnapshotID != "snap-b" { + t.Fatalf("current 不应被旧意图推回:%v %+v", err, current) + } + + // 恢复是**新意图**:内容更旧(backup),意图更新 ⇒ 允许推进。 + recoveryOp, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ + ID: governance.LibraryOperationID("internal", governance.LibraryJobRecover, "window-1"), + Scope: "internal", Kind: governance.LibraryJobRecover, TargetSnapshotID: "backup-snap-a", + RequestDigest: "recover-digest", OperationKey: "window-1", Actor: "tester", + CreatedAt: base.Add(3 * time.Hour), + }) + if err != nil { + t.Fatalf("登记恢复意图失败:%v", err) + } + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionEventID(governance.LibraryVersionRecoveryVerified, "internal", "backup-snap-a", recoveryOp.ID), + Scope: "internal", Kind: governance.LibraryVersionRecoveryVerified, SnapshotID: "backup-snap-a", + SourceJobID: jobA, OperationID: recoveryOp.ID, CreatedBy: "worker", CreatedAt: base.Add(3 * time.Hour), + Evidence: map[string]any{"backup_snapshot": "backup-snap-a", "verify_digest": "digest"}, + }); err != nil { + t.Fatalf("恢复事实必须能推进 current:%v", err) + } + current, found, err = store.LibraryCurrentVersion(ctx, "internal") + if err != nil || !found || current.SnapshotID != "backup-snap-a" || current.Kind != governance.LibraryVersionRecoveryVerified { + t.Fatalf("恢复后 current 应指向预备份:%v %+v", err, current) + } +} + +// R3:续作沿用原业务作业(维护窗口 owner 不变),只新增执行代次。 +func TestPrepareLibraryJobResumeKeepsSameJobAndWindow(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + jobID := "libsync-resume-1" + seedOperationJob(t, store, pool, "internal", jobID, "sync", now) + + first, err := store.BeginLibraryAttempt(ctx, jobID, "worker-a#q1#0", 10*time.Minute, now) + if err != nil { + t.Fatal(err) + } + if err := store.AdvanceLibraryJobGuarded(ctx, first, governance.LibraryJobFailed, "database", + "写库失败", "按预备份恢复", "backup-snap-1", "", now); err != nil { + t.Fatalf("标记失败:%v", err) + } + // 维护窗口仍由**原作业**持有(这就是续作必须复用原行的原因)。 + held, err := store.LibraryMaintenanceOf(ctx, "internal") + if err != nil || held == nil || held.OwnerJobID != jobID || held.ReleasedAt != nil { + t.Fatalf("维护窗口应仍由原作业持有:%v %+v", err, held) + } + prepared, resumed, err := store.PrepareLibraryJobResume(ctx, jobID, now) + if err != nil || !resumed { + t.Fatalf("续作准备失败:%v resumed=%v", err, resumed) + } + if prepared.ID != jobID || prepared.State != governance.LibraryJobPending { + t.Fatalf("续作必须是同一作业行且回到 pending:%+v", prepared) + } + second, err := store.BeginLibraryAttempt(ctx, jobID, "worker-a#q1#1", 10*time.Minute, now.Add(time.Minute)) + if err != nil { + t.Fatalf("续作代次失败:%v", err) + } + if second.Epoch != first.Epoch+1 || second.OperationID != first.OperationID { + t.Fatalf("续作必须是同一 operation 的新代次:%+v vs %+v", second, first) + } + // 新代次可以用原窗口释放(owner 仍是同一个作业)。 + if err := store.ReleaseLibraryMaintenanceGuarded(ctx, "internal", jobID, second, now.Add(2*time.Minute)); err != nil { + t.Fatalf("续作代次释放原窗口失败:%v", err) + } +} + +// 编译期确认维护层级常量可用(避免测试里手写魔法字符串与实现漂移)。 +var _ = librarymaintenance.LevelInstance + +// 迁移 76 的 down/up 幂等:治理库里这一层只加身份表与 current 指针, +// 撤下来不能带走任何历史事件(版本行必须留着)。真实 PG 上逐条执行, +// 不靠"迁移文件存在"这种静态证据。 +func TestMigration76DownAndUpKeepsVersionHistory(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-mig76", "sync", now) + if _, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ + ID: governance.LibraryOperationID("internal", governance.LibraryJobSync, "legacy-op"), + Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: "s", + RequestDigest: "d", OperationKey: "k", Actor: "t", CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: "libver-mig76-keep", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup, + SnapshotID: "snap-mig76", SourceJobID: "libsync-mig76", CreatedBy: "worker", + Evidence: map[string]any{"backup_snapshot": "snap-mig76"}, CreatedAt: now, + }); err != nil { + t.Fatal(err) + } + + all, err := loadMigrations() + if err != nil { + t.Fatal(err) + } + var target migration + for _, item := range all { + if item.Version == 76 { + target = item + } + } + if target.Version == 0 { + t.Fatal("migration 76 不存在") + } + if _, err := pool.Exec(ctx, target.DownSQL); err != nil { + t.Fatalf("撤销 migration 76 失败:%v", err) + } + var versions int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM library_versions WHERE id='libver-mig76-keep'`).Scan(&versions); err != nil { + t.Fatalf("撤销后版本历史不可读:%v", err) + } + if versions != 1 { + t.Fatalf("撤销 identity 层不许删版本事件:count=%d", versions) + } + if _, err := pool.Exec(ctx, target.UpSQL); err != nil { + t.Fatalf("重新应用 migration 76 失败:%v", err) + } + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: "libver-mig76-after", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup, + SnapshotID: "snap-mig76-b", SourceJobID: "libsync-mig76", CreatedBy: "worker", + Evidence: map[string]any{"backup_snapshot": "snap-mig76-b"}, CreatedAt: now.Add(time.Minute), + }); err != nil { + t.Fatalf("重新应用后写入失败:%v", err) + } +} diff --git a/internal/platform/postgres/library_instance_maintenance.go b/internal/platform/postgres/library_instance_maintenance.go index 8b82cc5..a7847b4 100644 --- a/internal/platform/postgres/library_instance_maintenance.go +++ b/internal/platform/postgres/library_instance_maintenance.go @@ -75,6 +75,12 @@ ON CONFLICT (instance) DO UPDATE SET ELSE EXCLUDED.original_service_state END, note = EXCLUDED.note, + -- 同 scope 的那一份:起始时间只属于当前这次占用,同一作业重入才保留旧值。 + acquired_at = CASE + WHEN library_instance_maintenance.owner_job_id = EXCLUDED.owner_job_id + THEN library_instance_maintenance.acquired_at + ELSE EXCLUDED.acquired_at + END, updated_at = EXCLUDED.updated_at, released_at = NULL WHERE library_instance_maintenance.released_at IS NOT NULL diff --git a/internal/platform/postgres/library_jobs.go b/internal/platform/postgres/library_jobs.go index 66ad5fb..fc61cb2 100644 --- a/internal/platform/postgres/library_jobs.go +++ b/internal/platform/postgres/library_jobs.go @@ -1,6 +1,7 @@ package postgres import ( + "bytes" "context" "encoding/json" "errors" @@ -11,6 +12,7 @@ import ( "github.com/jackc/pgx/v5/pgconn" "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" ) // 整库作业与版本:队列(jobs)负责租约重试,本文件负责业务身份、阶段与结果。 @@ -28,12 +30,12 @@ func (s *Store) CreateLibraryJob(ctx context.Context, job governance.LibraryJob, var id string err = s.db.QueryRow(ctx, ` INSERT INTO library_jobs (id, scope, kind, state, stage, idempotency_key, request_digest, request, - queue_job_id, snapshot_id, target_snapshot_id, actor, error, recovery, created_at, updated_at) -VALUES ($1,$2,$3,'pending','',$4,$5,$6,$7,$8,$9,$10,'','',$11,$11) + queue_job_id, snapshot_id, target_snapshot_id, actor, error, recovery, operation_id, created_at, updated_at, target_id) +VALUES ($1,$2,$3,'pending','',$4,$5,$6,$7,$8,$9,$10,'','',$11,$12,$12,$13) ON CONFLICT (idempotency_key) DO NOTHING RETURNING id`, job.ID, job.Scope, string(job.Kind), job.IdempotencyKey, request, rawRequest, - job.QueueJobID, job.SnapshotID, job.TargetSnapshotID, job.Actor, now.UTC()).Scan(&id) + job.QueueJobID, job.SnapshotID, job.TargetSnapshotID, job.Actor, job.OperationID, now.UTC(), s.libraryTargetID).Scan(&id) if err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) && pgErr.Code == "23505" { @@ -84,10 +86,10 @@ func (s *Store) LibraryJob(ctx context.Context, id string) (governance.LibraryJo var finished *time.Time if err := s.db.QueryRow(ctx, ` SELECT id, scope, kind, state, stage, idempotency_key, request_digest, queue_job_id, snapshot_id, - target_snapshot_id, actor, error, recovery, created_at, updated_at, finished_at -FROM library_jobs WHERE id=$1`, id).Scan(&job.ID, &job.Scope, &kind, &state, &job.Stage, &job.IdempotencyKey, + target_snapshot_id, actor, error, recovery, operation_id, attempt_epoch, created_at, updated_at, finished_at +FROM library_jobs WHERE id=$1 AND (kind='seal' OR target_id=$2)`, id, s.libraryTargetID).Scan(&job.ID, &job.Scope, &kind, &state, &job.Stage, &job.IdempotencyKey, &job.RequestDigest, &job.QueueJobID, &job.SnapshotID, &job.TargetSnapshotID, &job.Actor, &job.Error, - &job.Recovery, &job.CreatedAt, &job.UpdatedAt, &finished); err != nil { + &job.Recovery, &job.OperationID, &job.AttemptEpoch, &job.CreatedAt, &job.UpdatedAt, &finished); err != nil { if errors.Is(err, pgx.ErrNoRows) { return governance.LibraryJob{}, err } @@ -102,6 +104,50 @@ FROM library_jobs WHERE id=$1`, id).Scan(&job.ID, &job.Scope, &kind, &state, &jo return job, nil } +// LibraryReuseSource 是一条"这个目标的持久来源"记录:成功同步过的快照, +// 或这个目标自己的预备份。资源复用只认它作来源证据。 +type LibraryReuseSource struct { + JobID string + SnapshotID string + Kind string // sync | prebackup + FinishedAt time.Time +} + +// LibraryReuseSources 读这个目标的持久来源(含已被恢复顶替的生效版本)。 +// 同步来源要求同时存在 production_effective 版本登记:只写成功但版本没登记的 +// 作业不算可审计来源。 +func (s *Store) LibraryReuseSources(ctx context.Context, scope string, limit int) ([]LibraryReuseSource, error) { + if limit < 1 || limit > 200 { + limit = 100 + } + rows, err := s.db.Query(ctx, ` +SELECT j.id, j.target_snapshot_id, 'sync', coalesce(j.finished_at, j.updated_at) +FROM library_jobs j +WHERE j.scope=$1 AND j.target_id=$3 AND j.kind='sync' AND j.state='succeeded' AND coalesce(j.target_snapshot_id,'')<>'' + AND EXISTS (SELECT 1 FROM library_versions v + WHERE v.scope=j.scope AND v.target_id=j.target_id AND v.kind='production_effective' + AND v.snapshot_id=j.target_snapshot_id AND v.source_job_id=j.id) +UNION ALL +SELECT coalesce(v.source_job_id,''), v.snapshot_id, 'prebackup', v.created_at +FROM library_versions v +WHERE v.scope=$1 AND v.target_id=$3 AND v.kind='production_prebackup' AND coalesce(v.snapshot_id,'')<>'' +ORDER BY 4 DESC +LIMIT $2`, scope, limit, s.libraryTargetID) + if err != nil { + return nil, fmt.Errorf("load library reuse sources: %w", err) + } + defer rows.Close() + sources := make([]LibraryReuseSource, 0, 8) + for rows.Next() { + var source LibraryReuseSource + if err := rows.Scan(&source.JobID, &source.SnapshotID, &source.Kind, &source.FinishedAt); err != nil { + return nil, fmt.Errorf("scan library reuse source: %w", err) + } + sources = append(sources, source) + } + return sources, rows.Err() +} + func (s *Store) libraryStages(ctx context.Context, id string) ([]governance.LibraryStage, error) { rows, err := s.db.Query(ctx, ` SELECT stage, state, total, completed, bytes_total, bytes_done, detail, updated_at @@ -127,7 +173,7 @@ func (s *Store) ListLibraryJobs(ctx context.Context, scope string, limit int) ([ if limit < 1 || limit > 50 { return nil, errors.New("library job list limit out of range") } - rows, err := s.db.Query(ctx, `SELECT id FROM library_jobs WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit) + rows, err := s.db.Query(ctx, `SELECT id FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$3) ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID) if err != nil { return nil, fmt.Errorf("list library jobs: %w", err) } @@ -159,12 +205,12 @@ func (s *Store) ListLibraryJobs(ctx context.Context, scope string, limit int) ([ func (s *Store) UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error { tag, err := s.db.Exec(ctx, ` UPDATE library_job_stages SET - state = CASE WHEN $3='' THEN state ELSE $3 END, + state = CASE WHEN $3::text='' THEN state ELSE $3::text END, total = COALESCE($4, total), completed = COALESCE($5, completed), bytes_total = COALESCE($6, bytes_total), bytes_done = COALESCE($7, bytes_done), - detail = CASE WHEN $8='' THEN detail ELSE $8 END, + detail = CASE WHEN $8::text='' THEN detail ELSE $8::text END, updated_at = $9 WHERE job_id=$1 AND stage=$2`, jobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC()) if err != nil { @@ -199,12 +245,20 @@ func (s *Store) AdvanceLibraryJob(ctx context.Context, jobID string, state gover } tag, err := s.db.Exec(ctx, ` UPDATE library_jobs SET - state=$2, - stage = CASE WHEN $3='' THEN stage ELSE $3 END, - error = CASE WHEN $4='' THEN error ELSE $4 END, - recovery = CASE WHEN $5='' THEN recovery ELSE $5 END, - snapshot_id = CASE WHEN $6='' THEN snapshot_id ELSE $6 END, - target_snapshot_id = CASE WHEN $7='' THEN target_snapshot_id ELSE $7 END, + state=$2::text, + stage = CASE WHEN $3::text='' THEN stage ELSE $3::text END, + -- 失败重试不得把第一因覆盖成第二次“already exists”;成功时清除旧错误, + -- 但新的 failed 状态保留已记录的第一条失败原因。显式 ::text 让所有对 $2 + -- 的引用推导为同一类型;否则 varchar 列赋值与 CASE 文本比较会触发 42P08。 + error = CASE + WHEN $2::text='succeeded' THEN '' + WHEN $4::text='' THEN error + WHEN $2::text='failed' AND error<>'' THEN error + ELSE $4::text + END, + recovery = CASE WHEN $5::text='' THEN recovery ELSE $5::text END, + snapshot_id = CASE WHEN $6::text='' THEN snapshot_id ELSE $6::text END, + target_snapshot_id = CASE WHEN $7::text='' THEN target_snapshot_id ELSE $7::text END, updated_at=$8, finished_at=COALESCE($9, finished_at) WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, targetSnapshotID, now.UTC(), finished) @@ -217,9 +271,162 @@ WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, target return nil } -// RecordLibraryVersion 写入一个版本记录。生产生效版本必须先把旧的 supersede 掉, -// 否则唯一索引会拒绝——这正是"不许两个生效版本并存"的保证。 +// LibraryCaptureExportEvidence is the exact export-stage evidence used by the +// admin capture reconciliation gate. It is a named method so callers do not +// drift into a "latest stage" or generic list query. +func (s *Store) LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error) { + return s.LibraryJobStage(ctx, jobID, "export") +} + +// LibraryJobStage reads one exact stage row. The customer-visible job row is +// authoritative for state; this is the export-stage evidence used by the +// capture reconciliation gate. +func (s *Store) LibraryJobStage(ctx context.Context, jobID, stage string) (string, string, error) { + if jobID == "" || stage == "" { + return "", "", errors.New("library stage requires job and stage") + } + var state, detail string + err := s.db.QueryRow(ctx, `SELECT state, detail FROM library_job_stages WHERE job_id=$1 AND stage=$2`, jobID, stage).Scan(&state, &detail) + if errors.Is(err, pgx.ErrNoRows) { + return "", "", errors.New("library stage not found") + } + if err != nil { + return "", "", fmt.Errorf("read library stage: %w", err) + } + return state, detail, nil +} + +// LibraryTestSealedVersionForJob finds the immutable test-sealed version by +// exact (scope, source_job_id), never by "latest N". More than one row means +// the ledger is ambiguous and must be rejected instead of picking one. +func (s *Store) LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) { + if scope == "" || jobID == "" { + return governance.LibraryVersion{}, false, errors.New("test sealed version requires scope and job") + } + rows, err := s.db.Query(ctx, ` +SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch, + evidence, created_by, created_at, superseded_at +FROM library_versions +WHERE scope=$1 AND kind='test_sealed' AND source_job_id=$2 +ORDER BY created_at DESC, id DESC LIMIT 2`, scope, jobID) + if err != nil { + return governance.LibraryVersion{}, false, fmt.Errorf("read test sealed version for job: %w", err) + } + items, err := scanLibraryVersions(rows, 2) + if err != nil { + return governance.LibraryVersion{}, false, err + } + if len(items) > 1 { + return governance.LibraryVersion{}, false, fmt.Errorf("job %s has %d test-sealed rows; refuse to pick one", jobID, len(items)) + } + if len(items) == 1 { + return items[0], true, nil + } + return governance.LibraryVersion{}, false, nil +} + +// ReconcileLibraryCaptureTerminal is the only write allowed to repair a seal +// terminal during admin reconciliation. It is conditional on the exact job, +// scope, kind, queue/capture identity and an in-flight state; a concurrent +// failed/cancelled row or a different snapshot is never overwritten. +func (s *Store) ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error) { + if jobID == "" || scope == "" || queueJobID == "" || snapshotID == "" { + return false, errors.New("reconcile capture terminal requires job/scope/queue/snapshot") + } + tag, err := s.db.Exec(ctx, ` +UPDATE library_jobs +SET state='succeeded', stage='export', error='', snapshot_id=$4, + updated_at=$5, finished_at=$5 +WHERE id=$1 AND scope=$2 AND kind='seal' AND queue_job_id=$3 + AND state IN ('pending','running') + AND (snapshot_id='' OR snapshot_id=$4)`, jobID, scope, queueJobID, snapshotID, now.UTC()) + if err != nil { + return false, fmt.Errorf("reconcile capture terminal: %w", err) + } + return tag.RowsAffected() == 1, nil +} + +// ReconcileMisclassifiedLibraryCapture repairs ONLY the known startup +// misclassification: a failed seal whose queue actually completed, with no +// stage/snapshot and the exact legacy error/recovery. The original fields are +// copied to the immutable audit row and the job update is CAS-bound to them; +// any other failed/cancelled row is rejected. +func (s *Store) ReconcileMisclassifiedLibraryCapture(ctx context.Context, jobID, scope, queueJobID, snapshotID, + expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, + auditID, actor, reason string, evidence map[string]any, now time.Time) (bool, error) { + if jobID == "" || scope == "" || queueJobID == "" || snapshotID == "" || auditID == "" { + return false, errors.New("misclassification repair requires job/scope/queue/snapshot/audit") + } + rawEvidence, err := json.Marshal(evidence) + if err != nil { + return false, fmt.Errorf("encode repair evidence: %w", err) + } + tx, err := s.db.Begin(ctx) + if err != nil { + return false, fmt.Errorf("begin repair: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + var state, stage, errText, recovery, currentSnapshot string + var finished *time.Time + if err := tx.QueryRow(ctx, ` +SELECT state, stage, error, recovery, snapshot_id, finished_at +FROM library_jobs WHERE id=$1 AND scope=$2 AND kind='seal' AND queue_job_id=$3 +FOR UPDATE`, jobID, scope, queueJobID).Scan(&state, &stage, &errText, &recovery, ¤tSnapshot, &finished); err != nil { + return false, fmt.Errorf("read repair target: %w", err) + } + if state != "failed" || stage != expectedStage || errText != expectedError || + recovery != expectedRecovery || currentSnapshot != "" || + (finished == nil) != (expectedFinished == nil) || + (finished != nil && expectedFinished != nil && !finished.Equal(*expectedFinished)) { + return false, nil + } + tag, err := tx.Exec(ctx, ` +UPDATE library_jobs +SET state='succeeded', stage='export', error='', recovery='', snapshot_id=$3, + updated_at=$4, finished_at=$4 +WHERE id=$1 AND scope=$2 AND kind='seal' AND queue_job_id=$5 + AND state='failed' AND stage=$6 AND error=$7 AND recovery=$8 AND snapshot_id='' + AND finished_at IS NOT DISTINCT FROM $9`, + jobID, scope, snapshotID, now.UTC(), queueJobID, expectedStage, expectedError, expectedRecovery, expectedFinished) + if err != nil { + return false, fmt.Errorf("repair misclassified seal: %w", err) + } + if tag.RowsAffected() != 1 { + return false, nil + } + tag, err = tx.Exec(ctx, ` +INSERT INTO library_job_repairs + (id, job_id, scope, kind, queue_job_id, snapshot_id, original_state, original_stage, + original_error, original_recovery, original_finished_at, reason, actor, evidence, created_at) +VALUES ($1,$2,$3,'seal',$4,$5,'failed',$6,$7,$8,$9,$10,$11,$12,$13) +ON CONFLICT (id) DO NOTHING`, auditID, jobID, scope, queueJobID, snapshotID, + expectedStage, expectedError, expectedRecovery, expectedFinished, reason, actor, rawEvidence, now.UTC()) + if err != nil { + return false, fmt.Errorf("write repair audit: %w", err) + } + if tag.RowsAffected() != 1 { + return false, errors.New("repair audit already exists") + } + if err := tx.Commit(ctx); err != nil { + return false, fmt.Errorf("commit repair: %w", err) + } + return true, nil +} + +// RecordLibraryVersion 写入一条**不可变版本事件**,并在需要时推进 current 指针。 +// +// 与旧实现的区别(F02/F09 的根因): +// - 事件 ID 含 operation:不同 operation 引用同一快照是两条事件,`source_job_id`/ +// `evidence`/`created_at` 谁也不覆盖谁(旧实现是 `ON CONFLICT DO UPDATE` 整份替换)。 +// - 同一 operation 重放是幂等:`ON CONFLICT (id) DO NOTHING`,已存行原样返回。 +// - "谁当前生效"由 `library_current_versions` 表达,用单调次序做条件更新; +// 更早登记的事实不能把指针拉回历史,旧 epoch 在写边界就被守卫拒绝(见 guard)。 +// - 生效/恢复事件才动指针;预备份/封存只追加事件。 func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error { + targetID := s.libraryTargetID + if version.Kind == governance.LibraryVersionTestSealed { + targetID = "" + } evidence, err := json.Marshal(version.Evidence) if err != nil { return fmt.Errorf("encode library version evidence: %w", err) @@ -229,30 +436,133 @@ func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.Lib return fmt.Errorf("begin library version: %w", err) } defer func() { _ = tx.Rollback(ctx) }() - if version.Kind == governance.LibraryVersionProductionEffective { - if _, err := tx.Exec(ctx, ` -UPDATE library_versions SET superseded_at=$2 -WHERE scope=$1 AND kind='production_effective' AND superseded_at IS NULL`, version.Scope, version.CreatedAt.UTC()); err != nil { - return fmt.Errorf("supersede library version: %w", err) + + // 执行代次守卫:写事件的人必须还是当前代次(失租旧执行器不能登记"我成功了")。 + if version.SourceJobID != "" && version.AttemptEpoch > 0 { + if err := guardLibraryJobEpoch(ctx, tx, version.SourceJobID, version.AttemptEpoch, version.AttemptOwner); err != nil { + return err } } - if _, err := tx.Exec(ctx, ` -INSERT INTO library_versions (id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at) -VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) -ON CONFLICT (id) DO UPDATE SET - -- 恢复/重放同一个快照时必须把它重新"激活":否则它还是被 supersede 的旧行, - -- 页面会显示"生产当前版本未知",而实际生产已经恢复到这个快照。 - superseded_at = NULL, - source_job_id = EXCLUDED.source_job_id, - evidence = EXCLUDED.evidence, - created_at = EXCLUDED.created_at`, + + // 事件身份 = (kind, scope, 快照, operation)。同一身份的重复登记只有两种合法形态: + // · 同一执行者补登记**新增**的字段(预备份先登记、写集合随后补上); + // · 完全没有新字段的纯重放。 + // 所以冲突时只做**加法**:已有键永远赢(右操作数是已有 evidence),身份字段 + // (source_job_id/operation_id/created_at)一格都不许改;换了执行者或换了意图的 + // 登记在这里匹配不到行,什么也不写(F02/F09 不能靠 upsert 改写归属)。 + // xmax = 0 才是真的新插入:重放同一份证据(或换了执行者被 WHERE 挡住)都不算新事实, + // 否则一次纯重放就能把 current 再"推进"一次,把后来的操作顶掉。 + var inserted bool + err = tx.QueryRow(ctx, ` +INSERT INTO library_versions (id, scope, kind, snapshot_id, version_label, source_job_id, + operation_id, attempt_epoch, evidence, created_by, created_at, target_id) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) +ON CONFLICT (id) DO UPDATE +SET evidence = EXCLUDED.evidence || library_versions.evidence +WHERE library_versions.source_job_id = EXCLUDED.source_job_id + AND library_versions.operation_id = EXCLUDED.operation_id + AND library_versions.target_id = EXCLUDED.target_id +RETURNING (xmax = 0)`, version.ID, version.Scope, string(version.Kind), version.SnapshotID, version.VersionLabel, - version.SourceJobID, evidence, version.CreatedBy, version.CreatedAt.UTC()); err != nil { - return fmt.Errorf("record library version: %w", err) + version.SourceJobID, version.OperationID, version.AttemptEpoch, evidence, version.CreatedBy, + version.CreatedAt.UTC(), targetID).Scan(&inserted) + if errors.Is(err, pgx.ErrNoRows) { + var existingTarget string + if loadErr := tx.QueryRow(ctx, `SELECT target_id FROM library_versions WHERE id=$1`, version.ID).Scan(&existingTarget); loadErr != nil { + return loadErr + } + if existingTarget != targetID { + return errors.New("library version identity belongs to another target") + } + // 同一身份已经存在、但归属是别的执行者/别的意图:不覆盖、不报错,也不推进 current。 + inserted = false + err = nil + } + if err != nil { + return fmt.Errorf("record library version event: %w", err) + } + + if version.Kind == governance.LibraryVersionProductionEffective || version.Kind == governance.LibraryVersionRecoveryVerified { + if err := advanceLibraryCurrent(ctx, tx, version, inserted, targetID); err != nil { + return err + } } return tx.Commit(ctx) } +// advanceLibraryCurrent 用单调次序条件推进 current 指针。 +// +// 次序键 = (意图创建时间 | operation | epoch),**不是**事件登记时间(父的复核项): +// 拿登记时间排序,一次迟到的旧 operation 重放(例如重跑几天前的同步)就会因为"我刚登记" +// 而把 current 推回历史。意图的创建时间不会因为重放而变新,所以旧意图永远推不动 +// 比它更新的意图。 +// +// 恢复要不要能把 current 指回更早的**内容**?要,但它是通过**新的意图**(kind=recover, +// 创建于恢复时刻)做到的:内容更旧、意图更新,两者不矛盾。旧代次能不能写由 epoch +// 守卫回答(见 libraryFence),不由时间回答。 +func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.LibraryVersion, inserted bool, targetID string) error { + orderAt := version.CreatedAt + if version.OperationID != "" { + var created *time.Time + err := tx.QueryRow(ctx, `SELECT created_at FROM library_operations WHERE id=$1`, + version.OperationID).Scan(&created) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("事件引用的 operation %s 不存在:拒绝推进 current", version.OperationID) + } + if err != nil { + return fmt.Errorf("load library operation for current ordering: %w", err) + } + if created != nil { + orderAt = *created + } + } + orderKey := governance.CurrentOrderKey(orderAt, version.OperationID, version.AttemptEpoch) + if !inserted { + // 重放:事件已经在台账里。确认指针没有被别的更晚事实覆盖,否则只确认自己的历史。 + var currentID string + err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1 AND target_id=$2 FOR UPDATE`, + version.Scope, targetID).Scan(¤tID) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return fmt.Errorf("load library current pointer: %w", err) + } + return nil + } + tag, err := tx.Exec(ctx, ` +INSERT INTO library_current_versions (scope, version_id, snapshot_id, operation_id, attempt_epoch, order_key, updated_at, target_id) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8) +ON CONFLICT (scope, target_id) DO UPDATE SET + version_id=EXCLUDED.version_id, snapshot_id=EXCLUDED.snapshot_id, + operation_id=EXCLUDED.operation_id, attempt_epoch=EXCLUDED.attempt_epoch, + order_key=EXCLUDED.order_key, updated_at=EXCLUDED.updated_at +WHERE EXCLUDED.order_key > library_current_versions.order_key`, + version.Scope, version.ID, version.SnapshotID, version.OperationID, version.AttemptEpoch, orderKey, + version.CreatedAt.UTC(), targetID) + if err != nil { + return fmt.Errorf("advance library current pointer: %w", err) + } + var currentID string + if err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1 AND target_id=$2`, + version.Scope, targetID).Scan(¤tID); err != nil { + return fmt.Errorf("read back library current pointer: %w", err) + } + if tag.RowsAffected() == 0 && currentID != version.ID { + return fmt.Errorf("%w(scope=%s:当前 %s,本条 %s)", governance.ErrLibraryCurrentStale, + version.Scope, currentID, version.ID) + } + // superseded_at 只是展示元数据("这条已被顶替"),不改任何证据字段。 + // 它跟着指针走:指针指向谁,谁就是未顶替的那一行。 + if _, err := tx.Exec(ctx, ` +UPDATE library_versions SET superseded_at = CASE WHEN id=$2 THEN NULL ELSE COALESCE(superseded_at, $3) END +WHERE scope=$1 AND target_id=$4 AND kind IN ('production_effective','recovery_verified')`, version.Scope, currentID, + version.CreatedAt.UTC(), targetID); err != nil { + return fmt.Errorf("refresh library version supersede metadata: %w", err) + } + return nil +} + // InterruptedLibraryJobs 找出"业务作业 running、但队列里已没有活跃作业"的作业: // worker 被杀/重启后它们需要被接管,而不是被当成失败丢掉已完成的预备份。 func (s *Store) InterruptedLibraryJobs(ctx context.Context) ([]governance.LibraryJob, error) { @@ -261,7 +571,7 @@ func (s *Store) InterruptedLibraryJobs(ctx context.Context) ([]governance.Librar rows, err := s.db.Query(ctx, ` SELECT lj.id FROM library_jobs lj LEFT JOIN jobs j ON j.id=lj.queue_job_id -WHERE lj.kind IN ('sync','restore','baseline') +WHERE lj.kind IN ('sync','restore','baseline','verify') AND ( -- 业务作业在跑、队列已经没了/停了/租约过期 (lj.state='running' AND (j.id IS NULL OR j.state IN ('failed','completed','cancelled','dead') @@ -269,7 +579,9 @@ WHERE lj.kind IN ('sync','restore','baseline') -- 业务作业已被前一轮接管置为 pending,但队列作业的租约也没了(worker 又死了) OR (lj.state='pending' AND j.state='running' AND j.lease_until IS NOT NULL AND j.lease_until < now()) ) -ORDER BY lj.created_at`) +AND lj.target_id=$1 +AND NOT EXISTS (SELECT 1 FROM jobs recovery WHERE recovery.type='library.recover' AND recovery.payload->>'window_job_id'=lj.id AND recovery.payload->>'scope'=lj.scope) +ORDER BY lj.created_at`, s.libraryTargetID) if err != nil { return nil, fmt.Errorf("list interrupted library jobs: %w", err) } @@ -296,22 +608,172 @@ ORDER BY lj.created_at`) return jobs, nil } +// PrepareLibraryJobResume 把**同一个业务作业**放回 pending,供续作/接管重新执行。 +// +// 为什么是原作业而不是新开一行(R3):维护窗口 owner_job_id、freeze journal 文件名、 +// 预备份与写集合的身份全部按业务作业 id 落在持久层。新开 `-resume` 作业只能继承 +// operation_id,其它所有者都还指向旧作业——AcquireInstanceMaintenance 会拒绝它, +// journal/预备份也查不到,于是"续作"只是一个漂亮的新行。 +// +// 条件更新:只有 failed/cancelled 才允许置回 pending;终态时间与错误清零, +// 旧 attempt 行保留(历史不可变)。代次由 BeginLibraryAttempt 在 worker 起手时递增。 +func (s *Store) PrepareLibraryJobResume(ctx context.Context, jobID string, now time.Time) (governance.LibraryJob, bool, error) { + if _, err := s.LibraryJob(ctx, jobID); err != nil { + return governance.LibraryJob{}, false, err + } + tx, err := s.db.Begin(ctx) + if err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("prepare library job resume: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + // 续作是人工发起的接管:作业已经 failed/cancelled,它那一代执行者不可能还在合法地写。 + // 必须**显式结束**那一代(行保留、标 abandoned),否则它的租约还没过期, + // BeginLibraryAttempt 会认为"有活跃执行者"而拒绝新代次——续作就永远开不起来。 + if _, err := tx.Exec(ctx, ` +UPDATE library_attempts SET state='abandoned', finished_at=$2, outcome='superseded by operator resume', + lease_until=NULL +WHERE job_id=$1 AND state IN ('claimed','running')`, jobID, now.UTC()); err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("retire attempts for resume: %w", err) + } + tag, err := tx.Exec(ctx, ` +UPDATE library_jobs SET state='pending', error='', recovery='', finished_at=NULL, updated_at=$2, + lease_owner='', lease_until=NULL +WHERE id=$1 AND state IN ('failed','cancelled')`, jobID, now.UTC()) + if err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("prepare library job resume: %w", err) + } + if err := tx.Commit(ctx); err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("prepare library job resume: %w", err) + } + job, loadErr := s.LibraryJob(ctx, jobID) + if loadErr != nil { + return governance.LibraryJob{}, false, loadErr + } + return job, tag.RowsAffected() == 1, nil +} + +// ErrLibraryResumeBusy 表示队列里那一代仍持有有效租约,续作必须让路。 +var ErrLibraryResumeBusy = errors.New("library resume busy") + +// ErrLibraryResumeRequiresRecover 表示作业停在回滚阶段:它已经回退并(可能)保留维护窗口, +// 正确出口是维护恢复,而不是按原参数再来一遍。 +var ErrLibraryResumeRequiresRecover = errors.New("library resume requires recover") + +// ResumeLibraryJob 在同一事务里完成续作所需的全部持久变更,并用**事务内锁住的那一行**构造队列载荷: +// 结束上一代 attempt → 校验状态/阶段/执行权 → 业务作业置 pending → 队列行 upsert(含租约检查)。 +// +// 为什么必须一个事务 + 行锁:旧实现先把 state 提交成 pending,再由 API 单独 Enqueue;队列行主键由 +// 业务作业 id 派生,第二次续作时 INSERT 撞主键——入队失败但状态已改,作业永久卡在"假 active"。 +// 同时,阶段与载荷从锁内那一行读,调用方手里的旧快照不会被用来复活一个已经变化的作业。 +func (s *Store) ResumeLibraryJob(ctx context.Context, jobID, queueType string, now time.Time) (governance.LibraryJob, bool, error) { + tx, err := s.db.Begin(ctx) + if err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("resume library job: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + var state, stage, kind, scope, targetSnapshot, snapshotID string + var attemptEpoch int + if err := tx.QueryRow(ctx, ` +SELECT state, stage, kind, scope, target_snapshot_id, snapshot_id, attempt_epoch +FROM library_jobs WHERE id=$1 FOR UPDATE`, jobID).Scan( + &state, &stage, &kind, &scope, &targetSnapshot, &snapshotID, &attemptEpoch); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryJob{}, false, err + } + return governance.LibraryJob{}, false, fmt.Errorf("lock library job for resume: %w", err) + } + if state != string(governance.LibraryJobFailed) && state != string(governance.LibraryJobCancelled) { + // 状态已被别的执行者推进(接管/完成):不落任何变更。 + return governance.LibraryJob{}, false, nil + } + if stage == "rollback" { + return governance.LibraryJob{}, false, ErrLibraryResumeRequiresRecover + } + if _, err := tx.Exec(ctx, ` +UPDATE library_attempts SET state='abandoned', finished_at=$2, outcome='superseded by operator resume', + lease_until=NULL +WHERE job_id=$1 AND state IN ('claimed','running')`, jobID, now.UTC()); err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("retire attempts for resume: %w", err) + } + queueID := governance.QueueJobIDFor(jobID) + tag, err := tx.Exec(ctx, ` +UPDATE library_jobs SET state='pending', error='', recovery='', finished_at=NULL, updated_at=$2, + lease_owner='', lease_until=NULL, queue_job_id=$3 +WHERE id=$1 AND state IN ('failed','cancelled')`, jobID, now.UTC(), queueID) + if err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("prepare library job resume: %w", err) + } + if tag.RowsAffected() != 1 { + return governance.LibraryJob{}, false, nil + } + // 队列行可能已存在(上一次执行)。锁住它判断租约:有活跃执行者就整笔回滚。 + var lease *time.Time + row := tx.QueryRow(ctx, `SELECT lease_until FROM jobs WHERE id=$1 FOR UPDATE`, queueID) + if err := row.Scan(&lease); err != nil && !errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryJob{}, false, fmt.Errorf("inspect queue job for resume: %w", err) + } + if lease != nil && lease.After(now.UTC()) { + return governance.LibraryJob{}, false, ErrLibraryResumeBusy + } + // 载荷按锁内那一行重建,不用调用方可能过期的快照。 + body := map[string]any{"library_job_id": jobID, "scope": scope, "target_snapshot_id": targetSnapshot} + if stage == "finalize" && snapshotID != "" { + body["finalize_only"] = true + } + payload, err := json.Marshal(body) + if err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("encode resumed payload: %w", err) + } + if _, err := tx.Exec(ctx, ` +INSERT INTO jobs (id, type, payload, state, priority, available_at, max_attempts, idempotency_key, created_at, updated_at) +VALUES ($1, $2, $3, 'pending', $4, $5, $6, $7, $5, $5) +ON CONFLICT (id) DO UPDATE SET + type=EXCLUDED.type, payload=EXCLUDED.payload, state='pending', attempt=0, + lease_owner=NULL, lease_until=NULL, available_at=EXCLUDED.available_at, + max_attempts=EXCLUDED.max_attempts, updated_at=EXCLUDED.updated_at`, + queueID, queueType, payload, 0, now.UTC(), 1, "library.resume.queue:"+jobID); err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("enqueue resumed job: %w", err) + } + if err := tx.Commit(ctx); err != nil { + return governance.LibraryJob{}, false, fmt.Errorf("resume library job: %w", err) + } + job, loadErr := s.LibraryJob(ctx, jobID) + if loadErr != nil { + return governance.LibraryJob{}, false, loadErr + } + return job, true, nil +} + // ResetQueueJobForResume 把中断/失败过的队列作业重新排队:attempt 必须归零, // 否则 attempt>'window_job_id'=library_jobs.id AND recovery.payload->>'scope'=library_jobs.scope) + AND (lease_owner='' OR lease_until IS NULL OR lease_until < $2)`, jobID, now.UTC(), s.libraryTargetID) if err != nil { return false, fmt.Errorf("claim interrupted library job: %w", err) } @@ -321,47 +783,107 @@ WHERE id=$1 AND state IN ('running','pending')`, jobID, now) // ReconcileLibraryJobs 收拾"业务作业还在飞、队列里已经没有对应作业"的孤儿: // 它们会永久占用 (scope,kind) 唯一索引,让同一目标再也发不出作业。 // 只标失败并写明恢复责任,不猜结果、不重放。 -func (s *Store) ReconcileLibraryJobs(ctx context.Context, now time.Time) (int, error) { - if _, err := s.db.Exec(ctx, ` +// +// kinds 是**本进程负责的那几类**:两台执行器(本机封存 / 云端发布)各自收拾自己的 +// 作业,跨域"顺手收拾"会把别人的在飞作业标失败,并把恢复责任写错(封存要 agent +// 恢复来源,发布要按预备份确认目标)。kinds 为空直接报错,不允许退化成"收拾全部"。 +func (s *Store) ReconcileLibraryJobs(ctx context.Context, now time.Time, kinds []string) (int, error) { + if len(kinds) == 0 { + return 0, errors.New("reconcile library jobs requires the kinds this executor owns") + } + tag, err := s.db.Exec(ctx, ` UPDATE library_jobs AS lj -SET state='failed', error='队列中已无对应作业,业务作业未收到结果', recovery='封存作业由 agent 恢复来源;确认来源 healthy 后可重发', updated_at=$1, finished_at=$1 +SET state='failed', error='队列中已无对应作业,业务作业未收到结果', + recovery=CASE WHEN lj.kind IN ('sync','restore','recover','baseline') + THEN '未确认目标状态:若已进入维护窗口,按预备份恢复并核验后再重发' + ELSE '封存作业由 agent 恢复来源;确认来源 healthy 后可重发' END, + updated_at=$1, finished_at=$1 WHERE lj.state IN ('pending','running') + AND lj.kind = ANY($2) + AND (lj.kind='seal' OR lj.target_id=$3) AND lj.queue_job_id <> '' AND NOT EXISTS ( SELECT 1 FROM jobs AS j - WHERE j.id = lj.queue_job_id AND j.state IN ('pending','running','retry') - )`, now.UTC()); err != nil { + WHERE j.id = lj.queue_job_id + AND j.state IN ('pending','running','retry','completed') + )`, now.UTC(), kinds, s.libraryTargetID) + if err != nil { return 0, fmt.Errorf("reconcile library jobs: %w", err) } + first := int(tag.RowsAffected()) // 建了业务作业但队列投递没完成(queue_job_id 为空)超过 5 分钟,也是孤儿。 - tag, err := s.db.Exec(ctx, ` + tag, err = s.db.Exec(ctx, ` UPDATE library_jobs SET state='failed', error='队列投递未完成,作业从未开始', recovery='无需恢复来源;可直接重发', updated_at=$1, finished_at=$1 -WHERE state IN ('pending','running') AND queue_job_id='' AND created_at < $2`, now.UTC(), now.Add(-5*time.Minute).UTC()) +WHERE state IN ('pending','running') AND queue_job_id='' AND kind = ANY($3) AND (kind='seal' OR target_id=$4) AND created_at < $2`, + now.UTC(), now.Add(-5*time.Minute).UTC(), kinds, s.libraryTargetID) if err != nil { return 0, fmt.Errorf("reconcile unattached library jobs: %w", err) } - return int(tag.RowsAffected()), nil + return first + int(tag.RowsAffected()), nil } -func (s *Store) LibraryVersions(ctx context.Context, scope string, limit int) ([]governance.LibraryVersion, error) { - if limit < 1 || limit > 100 { - return nil, errors.New("library version limit out of range") +// LibraryVersionByRef 按 (scope, kind, 作业, 快照) 精确定位一条版本记录。 +// +// 为什么不能"取最近 N 条再在内存里筛":那是窗口,历史一旦超过窗口上限, +// 登记/接管/恢复就会把"存在"读成"不存在"——真实现场是写集合的引用无法登记, +// 报"读不到现有版本证据 / library version limit out of range"。 +// 身份查询必须走索引条件,不许依赖排序窗口(把上限从 200 改成 100 只是换个数)。 +// +// 同一 (scope, kind, snapshot) 只该有一行(id 由这三者决定,写入是 upsert)。 +// 命中多行、或命中的那行归别的作业所有,都说明台账不唯一:返回错误让调用方 +// 拒绝,不许挑一条"看起来对"的记录去恢复生产。 +func (s *Store) LibraryVersionByRef(ctx context.Context, scope string, kind governance.LibraryVersionKind, + sourceJobID, snapshotID string) (governance.LibraryVersion, bool, error) { + if scope == "" || kind == "" || sourceJobID == "" || snapshotID == "" { + return governance.LibraryVersion{}, false, errors.New("library version ref requires scope, kind, job and snapshot") } rows, err := s.db.Query(ctx, ` -SELECT id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at, superseded_at -FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit) +SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch, evidence, created_by, created_at, superseded_at +FROM library_versions +WHERE scope=$1 AND kind=$2 AND source_job_id=$3 AND snapshot_id=$4 AND (kind='test_sealed' OR target_id=$5) +ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), sourceJobID, snapshotID, s.libraryTargetID) if err != nil { - return nil, fmt.Errorf("list library versions: %w", err) + return governance.LibraryVersion{}, false, fmt.Errorf("load library version by ref: %w", err) } + items, err := scanLibraryVersions(rows, 2) + if err != nil { + return governance.LibraryVersion{}, false, err + } + if len(items) > 1 { + return governance.LibraryVersion{}, false, fmt.Errorf("同一身份存在 %d 条版本记录(作业 %s,快照 %s):拒绝挑选", + len(items), sourceJobID, snapshotID) + } + if len(items) == 1 { + return items[0], true, nil + } + // 没命中时要区分"确实没有"与"这一行归别的作业":后者是身份冲突, + // 当成"没有记录"就会允许调用方覆盖别人的台账。 + var owner string + err = s.db.QueryRow(ctx, ` +SELECT source_job_id FROM library_versions WHERE scope=$1 AND kind=$2 AND snapshot_id=$3 AND (kind='test_sealed' OR target_id=$4) +ORDER BY created_at DESC LIMIT 1`, scope, string(kind), snapshotID, s.libraryTargetID).Scan(&owner) + if errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryVersion{}, false, nil + } + if err != nil { + return governance.LibraryVersion{}, false, fmt.Errorf("load library version owner: %w", err) + } + return governance.LibraryVersion{}, false, fmt.Errorf("版本记录(快照 %s)属于作业 %s,不是 %s:拒绝借用", + snapshotID, owner, sourceJobID) +} + +// scanLibraryVersions 是版本行唯一的扫描实现:两个查询(窗口列表与按身份精确查) +// 必须对同一种形状解码,否则"查得到"和"读得对"会分叉。 +func scanLibraryVersions(rows pgx.Rows, capacity int) ([]governance.LibraryVersion, error) { defer rows.Close() - result := make([]governance.LibraryVersion, 0, limit) + result := make([]governance.LibraryVersion, 0, capacity) for rows.Next() { var item governance.LibraryVersion var kind string var evidence []byte if err := rows.Scan(&item.ID, &item.Scope, &kind, &item.SnapshotID, &item.VersionLabel, &item.SourceJobID, - &evidence, &item.CreatedBy, &item.CreatedAt, &item.SupersededAt); err != nil { + &item.OperationID, &item.AttemptEpoch, &evidence, &item.CreatedBy, &item.CreatedAt, &item.SupersededAt); err != nil { return nil, fmt.Errorf("scan library version: %w", err) } item.Kind = governance.LibraryVersionKind(kind) @@ -373,15 +895,110 @@ FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2` return result, rows.Err() } +// LibraryVersions 是**分页展示**用的窗口列表(1..100),语义是"最近 N 条"。 +// 任何"当前生效 / 本快照是否生效过"的判断都不许用它:窗口一满就会把存在读成不存在。 +func (s *Store) LibraryVersions(ctx context.Context, scope string, limit int) ([]governance.LibraryVersion, error) { + if limit < 1 || limit > 100 { + return nil, errors.New("library version limit out of range") + } + rows, err := s.db.Query(ctx, ` +SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch, evidence, created_by, created_at, superseded_at +FROM library_versions WHERE scope=$1 AND (kind='test_sealed' OR target_id=$3) ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID) + if err != nil { + return nil, fmt.Errorf("list library versions: %w", err) + } + return scanLibraryVersions(rows, limit) +} + +// LibraryCurrentVersion 返回这个 scope **当前生效**的事实(由指针表回答)。 +// +// 三个理由必须一起满足: +// +// · 不能用窗口列表——生效事实可能很久以前登记,之后写进来的预备份/封存会把它挤出 +// 任何"最近 N 条",接管/基线/闸口就会把"已生效"读成"没有生效"。 +// · 不能靠扫 library_versions.kind='production_effective' 挑未顶替行——事件不可变, +// "谁是当前"是指针的事实,不是事件行的可变字段(F02)。 +// · 指针每 (scope, target_id) 至多一行,历史归属不明的空身份不归新目标。 +// +// 指针可能指向 production_effective,也可能指向 recovery_verified(按预备份恢复后 +// 的当前内容身份)——调用方只能用它回答"当前是什么内容",不能假设它是一次成功发布。 +func (s *Store) LibraryCurrentVersion(ctx context.Context, scope string) (governance.LibraryVersion, bool, error) { + if scope == "" { + return governance.LibraryVersion{}, false, errors.New("library current version requires scope") + } + rows, err := s.db.Query(ctx, ` +SELECT v.id, v.scope, v.kind, v.snapshot_id, v.version_label, v.source_job_id, v.operation_id, v.attempt_epoch, + v.evidence, v.created_by, v.created_at, v.superseded_at +FROM library_current_versions c JOIN library_versions v ON v.id = c.version_id +WHERE c.scope=$1 AND c.target_id=$2 AND v.target_id=c.target_id`, scope, s.libraryTargetID) + if err != nil { + return governance.LibraryVersion{}, false, fmt.Errorf("load current library version: %w", err) + } + items, err := scanLibraryVersions(rows, 2) + if err != nil { + return governance.LibraryVersion{}, false, err + } + if len(items) > 1 { + return governance.LibraryVersion{}, false, fmt.Errorf("scope=%s 的当前指针指向 %d 行事件:台账被写坏,拒绝挑选", + scope, len(items)) + } + if len(items) == 1 { + return items[0], true, nil + } + return governance.LibraryVersion{}, false, nil +} + +// LibraryVersionOfSnapshot 按 (scope, kind, 快照) 取这个快照**自己的**登记记录(不限作业)。 +// +// 用途是"本快照曾经生效过吗/是否已被顶替":版本 id 由 (kind, scope, 快照) 决定, +// 一个快照在一种类型下只该有一行,作业归属会随恢复/重放被改写,所以不能用作业当条件。 +// 命中多行同样拒绝挑选。 +func (s *Store) LibraryVersionOfSnapshot(ctx context.Context, scope string, + kind governance.LibraryVersionKind, snapshotID string) (governance.LibraryVersion, bool, error) { + if scope == "" || kind == "" || snapshotID == "" { + return governance.LibraryVersion{}, false, errors.New("library version snapshot requires scope, kind and snapshot") + } + rows, err := s.db.Query(ctx, ` +SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch, evidence, created_by, created_at, superseded_at +FROM library_versions +WHERE scope=$1 AND kind=$2 AND snapshot_id=$3 AND (kind='test_sealed' OR target_id=$4) +ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), snapshotID, s.libraryTargetID) + if err != nil { + return governance.LibraryVersion{}, false, fmt.Errorf("load library version of snapshot: %w", err) + } + found, err := scanLibraryVersions(rows, 2) + if err != nil { + return governance.LibraryVersion{}, false, err + } + // 同一快照可以被多次意图引用,每次 operation 一条事件,这是**正常历史**; + // 但"两条同身份的行"是台账被写坏(或迁移前没有 operation 身份的未知证据), + // 这时挑选任何一条都是替调用方做决定,必须拒绝(未知证据 fail closed)。 + if len(found) == 1 { + return found[0], true, nil + } + if len(found) >= 2 { + if found[0].OperationID == "" || found[1].OperationID == "" { + return governance.LibraryVersion{}, false, fmt.Errorf( + "快照 %s 在 %s 下有 %d 条无执行身份的记录:拒绝挑选", snapshotID, kind, len(found)) + } + if found[0].OperationID == found[1].OperationID { + return governance.LibraryVersion{}, false, fmt.Errorf( + "快照 %s 在 %s 下同一意图登记了多行:拒绝挑选", snapshotID, kind) + } + return found[0], true, nil + } + return governance.LibraryVersion{}, false, nil +} + // CreateLibraryAuthorization 记录一次生产发布授权;同一 (scope,snapshot,digest) 只保留最新有效。 func (s *Store) CreateLibraryAuthorization(ctx context.Context, item governance.LibraryReleaseAuthorization) error { if item.ID == "" || item.Scope == "" || item.SnapshotID == "" || item.ParamsDigest == "" || item.ExpiresAt.IsZero() { return errors.New("invalid library release authorization") } _, err := s.db.Exec(ctx, ` -INSERT INTO library_release_authorizations (id, scope, snapshot_id, params_digest, authorized_by, expires_at, created_at) -VALUES ($1,$2,$3,$4,$5,$6,$7)`, - item.ID, item.Scope, item.SnapshotID, item.ParamsDigest, item.AuthorizedBy, item.ExpiresAt.UTC(), item.CreatedAt.UTC()) +INSERT INTO library_release_authorizations (id, scope, snapshot_id, params_digest, authorized_by, expires_at, created_at, target_id) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`, + item.ID, item.Scope, item.SnapshotID, item.ParamsDigest, item.AuthorizedBy, item.ExpiresAt.UTC(), item.CreatedAt.UTC(), s.libraryTargetID) if err != nil { return fmt.Errorf("create library release authorization: %w", err) } @@ -395,9 +1012,9 @@ func (s *Store) ActiveLibraryAuthorization(ctx context.Context, scope, snapshotI err := s.db.QueryRow(ctx, ` SELECT id, scope, snapshot_id, params_digest, authorized_by, expires_at, revoked_at, created_at FROM library_release_authorizations -WHERE scope=$1 AND snapshot_id=$2 AND params_digest=$3 AND revoked_at IS NULL AND expires_at > $4 +WHERE scope=$1 AND snapshot_id=$2 AND params_digest=$3 AND target_id=$5 AND revoked_at IS NULL AND expires_at > $4 ORDER BY expires_at DESC, created_at DESC -LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC()).Scan(&item.ID, &item.Scope, &item.SnapshotID, +LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC(), s.libraryTargetID).Scan(&item.ID, &item.Scope, &item.SnapshotID, &item.ParamsDigest, &item.AuthorizedBy, &item.ExpiresAt, &item.RevokedAt, &item.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return governance.LibraryReleaseAuthorization{}, false, nil @@ -409,7 +1026,7 @@ LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC()).Scan(&item.ID, &item.Scope } func (s *Store) RevokeLibraryAuthorization(ctx context.Context, id string, now time.Time) error { - tag, err := s.db.Exec(ctx, `UPDATE library_release_authorizations SET revoked_at=$2 WHERE id=$1 AND revoked_at IS NULL`, id, now.UTC()) + tag, err := s.db.Exec(ctx, `UPDATE library_release_authorizations SET revoked_at=$2 WHERE id=$1 AND target_id=$3 AND revoked_at IS NULL`, id, now.UTC(), s.libraryTargetID) if err != nil { return fmt.Errorf("revoke library authorization: %w", err) } @@ -425,7 +1042,7 @@ func (s *Store) LibraryAuthorizations(ctx context.Context, scope string, limit i } rows, err := s.db.Query(ctx, ` SELECT id, scope, snapshot_id, params_digest, authorized_by, expires_at, revoked_at, created_at -FROM library_release_authorizations WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit) +FROM library_release_authorizations WHERE scope=$1 AND target_id=$3 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID) if err != nil { return nil, fmt.Errorf("list library authorizations: %w", err) } @@ -441,3 +1058,269 @@ FROM library_release_authorizations WHERE scope=$1 ORDER BY created_at DESC, id } return result, rows.Err() } + +// LibraryVersionsBySnapshot 返回这份快照在该 scope 下的全部版本事件(含证据)。 +// +// 原产地不能只看 kind:目标权威基线也是 production_effective,但它是**目标侧的真实捕获** +// (证据里 action=target_baseline_init / origin=target_baseline)。所以判定必须读到证据, +// 不能把"是 effective"直接当成"来自发布"或"来自目标"。 +func (s *Store) LibraryVersionsBySnapshot(ctx context.Context, scope, snapshotID string) ([]governance.LibraryVersion, error) { + if scope == "" || snapshotID == "" { + return nil, errors.New("snapshot versions requires scope and snapshot") + } + rows, err := s.db.Query(ctx, ` +SELECT id, scope, kind, snapshot_id, source_job_id, COALESCE(evidence, '{}'::jsonb), created_at +FROM library_versions WHERE scope=$1 AND snapshot_id=$2 AND (kind='test_sealed' OR target_id=$3) ORDER BY created_at`, scope, snapshotID, s.libraryTargetID) + if err != nil { + return nil, fmt.Errorf("read snapshot versions: %w", err) + } + defer rows.Close() + items := make([]governance.LibraryVersion, 0, 4) + for rows.Next() { + var item governance.LibraryVersion + var kind string + var evidence []byte + if err := rows.Scan(&item.ID, &item.Scope, &kind, &item.SnapshotID, &item.SourceJobID, &evidence, &item.CreatedAt); err != nil { + return nil, err + } + item.Evidence = decodeEvidenceObject(evidence) + item.Kind = governance.LibraryVersionKind(kind) + items = append(items, item) + } + return items, rows.Err() +} + +// decodeEvidenceObject 把证据列解成对象:历史行里也有把证据存成"数组"的 +// (早期任务把一组事件直接塞进 jsonb)。读原产地只关心字段,所以数组取最后一个对象, +// 解不动就返回 nil(调用方按"没有证据"处理,不会因此放宽判定)。 +func decodeEvidenceObject(raw []byte) map[string]any { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return nil + } + if trimmed[0] == '{' { + var object map[string]any + if err := json.Unmarshal(trimmed, &object); err == nil { + return object + } + return nil + } + if trimmed[0] == '[' { + var items []map[string]any + if err := json.Unmarshal(trimmed, &items); err == nil && len(items) > 0 { + return items[len(items)-1] + } + } + return nil +} + +// LibrarySnapshotKinds 返回这份快照在该 scope 下登记过的版本类型。 +// +// 用途是判定"这份快照的清单身份应该等于谁":封存版本(test_sealed)的清单写的是 +// **源**的 tenant/KB;预备份/生效/恢复版本写的是**目标**的 tenant/KB。没有登记过 +// 就说明来源不明,调用方必须拒绝搬运(不能信快照自报)。 +func (s *Store) LibrarySnapshotKinds(ctx context.Context, scope, snapshotID string) ([]string, error) { + if scope == "" || snapshotID == "" { + return nil, errors.New("snapshot kinds requires scope and snapshot") + } + rows, err := s.db.Query(ctx, `SELECT DISTINCT kind FROM library_versions WHERE scope=$1 AND snapshot_id=$2 AND (kind='test_sealed' OR target_id=$3)`, scope, snapshotID, s.libraryTargetID) + if err != nil { + return nil, fmt.Errorf("read snapshot provenance: %w", err) + } + defer rows.Close() + kinds := make([]string, 0, 4) + for rows.Next() { + var kind string + if err := rows.Scan(&kind); err != nil { + return nil, err + } + kinds = append(kinds, kind) + } + return kinds, rows.Err() +} + +// SnapshotCandidate 是一份"本机可能需要有"的快照,以及它最近一次被引用的时间。 +// CreatedAt 同时充当分页游标:按 (created_at, snapshot_id) 倒序,跨页不重不漏。 +type SnapshotCandidate struct { + SnapshotID string + CreatedAt time.Time +} + +// LibrarySnapshotCandidates 枚举该 scope 下**被引用过**的快照(分页,游标不是 OFFSET)。 +// +// 为什么不能"只取最近 N 条成功作业的 snapshot_id":那会把回传永久卡在最早的 50 条上, +// 第 51 条以后的预备份、以及失败/待恢复作业留下的**恢复所需**预备份再也读不回来。 +// 所以这里合并三处权威引用: +// - library_versions.snapshot_id(版本台账,含封存/预备份/生效/恢复); +// - library_jobs.snapshot_id(作业自己留下的预备份,含失败与 needs_restore); +// - library_jobs.target_snapshot_id(发布/恢复的输入快照,历史恢复要靠它寻址)。 +// +// 游标语义:afterCreated/afterID 为空表示第一页;返回值不足 limit 即到底。 +func (s *Store) LibrarySnapshotCandidates(ctx context.Context, scope string, afterCreated time.Time, + afterID string, limit int) ([]SnapshotCandidate, error) { + if scope == "" || limit <= 0 || limit > 500 { + return nil, errors.New("snapshot candidates requires scope and a bounded limit") + } + var cursor any + if !afterCreated.IsZero() { + cursor = afterCreated.UTC() + } + rows, err := s.db.Query(ctx, ` +WITH referenced AS ( + SELECT snapshot_id, created_at FROM library_versions WHERE scope=$1 AND (kind='test_sealed' OR target_id=$5) AND snapshot_id <> '' + UNION ALL + SELECT snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$5) AND snapshot_id <> '' + UNION ALL + SELECT target_snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$5) AND target_snapshot_id <> '' +), grouped AS ( + SELECT snapshot_id, MAX(created_at) AS created_at FROM referenced GROUP BY snapshot_id +) +SELECT snapshot_id, created_at FROM grouped +WHERE $2::timestamptz IS NULL + OR created_at < $2::timestamptz + OR (created_at = $2::timestamptz AND snapshot_id < $3) +ORDER BY created_at DESC, snapshot_id DESC +LIMIT $4`, scope, cursor, afterID, limit, s.libraryTargetID) + if err != nil { + return nil, fmt.Errorf("list snapshot candidates: %w", err) + } + defer rows.Close() + items := make([]SnapshotCandidate, 0, limit) + for rows.Next() { + var item SnapshotCandidate + if err := rows.Scan(&item.SnapshotID, &item.CreatedAt); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} + +// handoff 阶段的三个阶段(running/succeeded/failed)与业务作业行的所有权判定 +// **必须在同一个事务里**:分开做时,读到的 owner 与自己写时已经不是同一个执行者, +// 迟到的旧 handoff 就能覆盖已经交给 release 的状态与阶段。 +// +// 所有权只由 library_jobs.queue_job_id 决定(阶段行是否存在与所有权无关), +// 并且每次都在 `SELECT ... FOR UPDATE` 之后判定,跨表并发交接因此不能穿插。 + +func (s *Store) lockLibraryJob(ctx context.Context, tx pgx.Tx, libraryJobID, ownerQueueID string) (string, bool, error) { + var state string + var attached *string + if err := tx.QueryRow(ctx, `SELECT state, queue_job_id FROM library_jobs WHERE id=$1 FOR UPDATE`, + libraryJobID).Scan(&state, &attached); err != nil { + return "", false, fmt.Errorf("lock library job: %w", err) + } + current := "" + if attached != nil { + current = *attached + } + if current != ownerQueueID || (state != "pending" && state != "running") { + return state, false, nil + } + return state, true, nil +} + +func upsertLibraryStage(ctx context.Context, tx pgx.Tx, libraryJobID, stage, state, detail string, now time.Time) error { + _, err := tx.Exec(ctx, ` +INSERT INTO library_job_stages (job_id, stage, state, detail, updated_at) +VALUES ($1, $2, $3, $4, $5) +ON CONFLICT (job_id, stage) DO UPDATE +SET state=EXCLUDED.state, detail=EXCLUDED.detail, updated_at=EXCLUDED.updated_at`, + libraryJobID, stage, state, detail, now.UTC()) + if err != nil { + return fmt.Errorf("record library stage %s: %w", stage, err) + } + return nil +} + +// BeginLibraryHandoff 在事务里创建/推进 handoff 阶段为 running,并确认所有权仍在。 +// 返回 false 表示"这份作业已经不归本次 handoff 了",调用方不得再碰任何状态。 +func (s *Store) BeginLibraryHandoff(ctx context.Context, libraryJobID, ownerQueueID, detail string, + now time.Time) (bool, error) { + tx, err := s.db.Begin(ctx) + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback(ctx) }() + if _, owned, err := s.lockLibraryJob(ctx, tx, libraryJobID, ownerQueueID); err != nil { + return false, err + } else if !owned { + return false, nil + } + if err := upsertLibraryStage(ctx, tx, libraryJobID, "handoff", "running", detail, now); err != nil { + return false, err + } + if err := tx.Commit(ctx); err != nil { + return false, err + } + return true, nil +} + +// CompleteLibraryHandoff 在**一个事务**里:确认所有权 → 投递发布队列作业 → 把业务作业 +// 交接给该队列作业 → 把 handoff 阶段写成 succeeded。任何一步失败都整体回滚, +// 不会出现"作业已交给 release 但阶段还停在 running"或"阶段成功但作业没交接"。 +func (s *Store) CompleteLibraryHandoff(ctx context.Context, libraryJobID, ownerQueueID string, + request jobs.EnqueueRequest, detail string, now time.Time) (bool, error) { + tx, err := s.db.Begin(ctx) + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback(ctx) }() + if _, owned, err := s.lockLibraryJob(ctx, tx, libraryJobID, ownerQueueID); err != nil { + return false, err + } else if !owned { + return false, nil + } + if _, err := scanJob(tx.QueryRow(ctx, enqueueJobSQL, request.ID, request.Type, request.Payload, + request.Priority, request.AvailableAt, request.MaxAttempts, request.IdempotencyKey, now)); err != nil { + return false, fmt.Errorf("enqueue release job: %w", err) + } + tag, err := tx.Exec(ctx, `UPDATE library_jobs SET queue_job_id=$2, updated_at=$3 +WHERE id=$1 AND queue_job_id=$4`, libraryJobID, request.ID, now.UTC(), ownerQueueID) + if err != nil { + return false, fmt.Errorf("hand over library job: %w", err) + } + if tag.RowsAffected() != 1 { + return false, errors.New("hand over library job: 所有权在事务内已变化,回滚") + } + if err := upsertLibraryStage(ctx, tx, libraryJobID, "handoff", "succeeded", detail, now); err != nil { + return false, err + } + if err := tx.Commit(ctx); err != nil { + return false, err + } + return true, nil +} + +// FailLibraryHandoff 同一个事务里写"阶段失败 + 作业失败",不留半条记录。 +func (s *Store) FailLibraryHandoff(ctx context.Context, libraryJobID, ownerQueueID, message string, + now time.Time) (bool, error) { + tx, err := s.db.Begin(ctx) + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback(ctx) }() + if _, owned, err := s.lockLibraryJob(ctx, tx, libraryJobID, ownerQueueID); err != nil { + return false, err + } else if !owned { + return false, nil + } + if err := upsertLibraryStage(ctx, tx, libraryJobID, "handoff", "failed", message, now); err != nil { + return false, err + } + tag, err := tx.Exec(ctx, ` +UPDATE library_jobs SET state='failed', stage='handoff', error=$3, recovery=$4, + updated_at=$2, finished_at=$2 +WHERE id=$1 AND queue_job_id=$5 AND state IN ('pending','running')`, + libraryJobID, now.UTC(), message, "未进入维护窗口、未写任何知识;修正后重试", ownerQueueID) + if err != nil { + return false, fmt.Errorf("fail library handoff: %w", err) + } + if tag.RowsAffected() != 1 { + return false, errors.New("fail library handoff: 所有权在事务内已变化,回滚") + } + if err := tx.Commit(ctx); err != nil { + return false, err + } + return true, nil +} diff --git a/internal/platform/postgres/library_jobs_first_error_pg_test.go b/internal/platform/postgres/library_jobs_first_error_pg_test.go new file mode 100644 index 0000000..3ef201a --- /dev/null +++ b/internal/platform/postgres/library_jobs_first_error_pg_test.go @@ -0,0 +1,95 @@ +package postgres + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" +) + +// F02 retry regression: a second failed attempt must not overwrite the first +// cause in the persistent business job; a later success clears it. +func TestAdvanceLibraryJobPreservesFirstFailure(t *testing.T) { + dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database") + } + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") { + t.Fatal("isolated database required") + } + cfg.MaxConns = 1 + cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp" + ctx := context.Background() + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if _, err := pool.Exec(ctx, ` +CREATE TEMP TABLE library_jobs( + id text primary key, state varchar(16) NOT NULL CHECK (state IN ('pending','running','succeeded','failed','cancelled')), + stage varchar(32) NOT NULL DEFAULT '', error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '', + snapshot_id varchar(64) NOT NULL DEFAULT '', target_snapshot_id varchar(64) NOT NULL DEFAULT '', + updated_at timestamptz NOT NULL, finished_at timestamptz); +INSERT INTO library_jobs(id,state,stage,error,updated_at) VALUES('libseal-retry','pending','','',now()); +CREATE TEMP TABLE library_job_stages( + job_id text, stage varchar(32), state varchar(16), total bigint, completed bigint, + bytes_total bigint, bytes_done bigint, detail text, updated_at timestamptz, primary key(job_id,stage)); +INSERT INTO library_job_stages(job_id,stage,state,updated_at) VALUES('libseal-retry','export','pending',now());`); err != nil { + t.Fatal(err) + } + store := NewStore(pool) + now := time.Now().UTC() + if err := store.UpdateLibraryStage(ctx, "libseal-retry", "export", "running", nil, nil, nil, nil, "started", now); err != nil { + t.Fatalf("update stage with real varchar types: %v", err) + } + if stageState, _, err := store.LibraryJobStage(ctx, "libseal-retry", "export"); err != nil || stageState != "running" { + t.Fatalf("read stage state=%q err=%v", stageState, err) + } + if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobRunning, "export", "", "", "", "", now); err != nil { + t.Fatal(err) + } + var state, stage string + var finished bool + if err := pool.QueryRow(ctx, `SELECT state, stage, finished_at IS NULL FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &stage, &finished); err != nil { + t.Fatal(err) + } + if state != "running" || stage != "export" || !finished { + t.Fatalf("running transition not persisted: state=%q stage=%q finished_null=%v", state, stage, finished) + } + if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobFailed, "export", "first validation failure", "", "", "", now); err != nil { + t.Fatal(err) + } + if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobFailed, "export", "second already exists", "", "", "", now.Add(time.Second)); err != nil { + t.Fatal(err) + } + var got string + var snap string + if err := pool.QueryRow(ctx, `SELECT state, error, finished_at IS NOT NULL, snapshot_id FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &got, &finished, &snap); err != nil { + t.Fatal(err) + } + if state != "failed" || !finished || snap != "" { + t.Fatalf("failed transition not persisted: state=%q finished=%v snapshot=%q", state, finished, snap) + } + if got != "first validation failure" { + t.Fatalf("first failure overwritten: %q", got) + } + if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobSucceeded, "export", "", "", "snap-ok", "", now.Add(2*time.Second)); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `SELECT state, error, snapshot_id, finished_at IS NOT NULL FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &got, &snap, &finished); err != nil { + t.Fatal(err) + } + if state != "succeeded" || !finished || snap != "snap-ok" { + t.Fatalf("succeeded transition not persisted: state=%q finished=%v snapshot=%q", state, finished, snap) + } + if got != "" { + t.Fatalf("success must clear old error, got %q", got) + } +} diff --git a/internal/platform/postgres/library_jobs_startup_reconcile_pg_test.go b/internal/platform/postgres/library_jobs_startup_reconcile_pg_test.go new file mode 100644 index 0000000..3574176 --- /dev/null +++ b/internal/platform/postgres/library_jobs_startup_reconcile_pg_test.go @@ -0,0 +1,79 @@ +package postgres + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// The worker startup reconciliation must not turn a completed capture queue +// into the legacy "queue does not exist" failure. This is a real PostgreSQL +// fixture with the actual varchar shapes; the RED case is the old SQL which +// only accepted pending/running/retry. +func TestStartupReconcileKeepsCompletedCaptureJob(t *testing.T) { + dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database") + } + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + t.Fatal("isolated database required") + } + cfg.MaxConns = 1 + cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp" + ctx := context.Background() + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + now := time.Now().UTC() + if _, err := pool.Exec(ctx, ` +CREATE TEMP TABLE library_jobs( + id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL, + state varchar(16) NOT NULL, stage varchar(32) NOT NULL DEFAULT '', + queue_job_id varchar(64) NOT NULL DEFAULT '', target_id text NOT NULL DEFAULT '', + error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '', + snapshot_id varchar(64) NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, finished_at timestamptz, created_at timestamptz NOT NULL DEFAULT now()); +CREATE TEMP TABLE jobs(id varchar(64) PRIMARY KEY, type varchar(64) NOT NULL, state varchar(16) NOT NULL);`); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,updated_at) + VALUES('libseal-completed','internal','seal','pending','q-completed',$1), + ('libseal-failed','internal','seal','pending','q-failed',$1), + ('libseal-missing','internal','seal','pending','q-missing',$1)`, now); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,state) VALUES('q-completed','library.capture','completed'), + ('q-failed','library.capture','failed')`); err != nil { + t.Fatal(err) + } + store := NewStore(pool) + n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}) + if err != nil { + t.Fatal(err) + } + var state, errText string + if err := pool.QueryRow(ctx, `SELECT state, error FROM library_jobs WHERE id='libseal-completed'`).Scan(&state, &errText); err != nil { + t.Fatal(err) + } + if state != "pending" || errText != "" { + t.Fatalf("completed queue was misclassified: state=%q error=%q", state, errText) + } + if n != 2 { + t.Fatalf("reconciled=%d, want only failed/missing queue jobs (2)", n) + } + for _, id := range []string{"libseal-failed", "libseal-missing"} { + var got string + if err := pool.QueryRow(ctx, `SELECT state FROM library_jobs WHERE id=$1`, id).Scan(&got); err != nil { + t.Fatal(err) + } + if got != "failed" { + t.Fatalf("%s state=%q, want failed", id, got) + } + } +} diff --git a/internal/platform/postgres/library_lease_contract_test.go b/internal/platform/postgres/library_lease_contract_test.go new file mode 100644 index 0000000..96d8e3c --- /dev/null +++ b/internal/platform/postgres/library_lease_contract_test.go @@ -0,0 +1,59 @@ +package postgres + +import ( + "context" + "errors" + "knowledge-governance/internal/governance" + "testing" + "time" +) + +func TestContractExpiredAttemptCannotRenewOrWrite(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "contract-expired", "sync", now) + attempt, err := store.BeginLibraryAttempt(ctx, "contract-expired", "writer", time.Minute, now) + if err != nil { + t.Fatal(err) + } + if _, err = pool.Exec(ctx, `UPDATE library_jobs SET lease_until=now()-interval '1 minute'; UPDATE library_attempts SET lease_until=now()-interval '1 minute'`); err != nil { + t.Fatal(err) + } + if err = store.RenewLibraryAttempt(ctx, attempt, time.Minute, now); !errors.Is(err, governance.ErrLibraryEpochStale) { + t.Errorf("expired renewal resurrected ownership: %v", err) + } + if err = store.AdvanceLibraryJobGuarded(ctx, attempt, governance.LibraryJobRunning, "database", "", "", "", "", now); !errors.Is(err, governance.ErrLibraryEpochStale) { + t.Errorf("expired owner still writes: %v", err) + } +} + +func TestContractRenewalIsAtomicAcrossJobAndAttempt(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + op := seedOperationJob(t, store, pool, "internal", "contract-revoke", "sync", now) + attempt, err := store.BeginLibraryAttempt(ctx, "contract-revoke", "writer", time.Minute, now) + if err != nil { + t.Fatal(err) + } + if err = store.RenewLibraryAttempt(ctx, attempt, 2*time.Minute, now); err != nil { + t.Fatalf("valid renewal: %v", err) + } + if _, err = pool.Exec(ctx, `UPDATE library_jobs SET lease_owner='new-owner' WHERE id=$1`, attempt.JobID); err != nil { + t.Fatal(err) + } + var before, after time.Time + if err = pool.QueryRow(ctx, `SELECT lease_until FROM library_attempts WHERE operation_id=$1`, op).Scan(&before); err != nil { + t.Fatal(err) + } + if err = store.RenewLibraryAttempt(ctx, attempt, time.Hour, now); !errors.Is(err, governance.ErrLibraryEpochStale) { + t.Errorf("revoked job still renews: %v", err) + } + if err = pool.QueryRow(ctx, `SELECT lease_until FROM library_attempts WHERE operation_id=$1`, op).Scan(&after); err != nil { + t.Fatal(err) + } + if !before.Equal(after) { + t.Fatal("partial renewal escaped transaction") + } +} diff --git a/internal/platform/postgres/library_legacy_source.go b/internal/platform/postgres/library_legacy_source.go new file mode 100644 index 0000000..2c3bb47 --- /dev/null +++ b/internal/platform/postgres/library_legacy_source.go @@ -0,0 +1,143 @@ +package postgres + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "strings" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryagent" + "knowledge-governance/internal/librarysnapshot" +) + +// BindLegacyLibrarySource adds evidence, not a new snapshot or rewritten origin. +// Both the archived manifest and the original capture response must independently +// identify the configured source. A scope match by itself can never authorize it. +func (s *Store) BindLegacyLibrarySource(ctx context.Context, snapshotID, archiveRoot string, source governance.LibrarySourceIdentity, actor string, now time.Time) error { + sourceID, err := source.ID() + if err != nil { + return err + } + if strings.TrimSpace(actor) == "" || now.IsZero() { + return errors.New("source association requires audited actor and time") + } + archive, err := librarysnapshot.Open(archiveRoot, 256*1024*1024) + if err != nil { + return err + } + defer archive.Close() + manifest, err := archive.Load(snapshotID) + if err != nil { + return err + } + if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID || manifest.KnowledgeBaseID != source.KnowledgeBaseID { + return errors.New("historical manifest differs from configured source") + } + tx, err := s.db.Begin(ctx) + if err != nil { + return err + } + defer func() { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + _ = tx.Rollback(cleanup) + }() + rows, err := tx.Query(ctx, `SELECT id,source_job_id,evidence FROM library_versions WHERE scope=$1 AND snapshot_id=$2 AND kind='test_sealed' AND target_id='' FOR UPDATE`, source.Scope, snapshotID) + if err != nil { + return err + } + type sealed struct { + id, job string + evidence []byte + } + items := []sealed{} + for rows.Next() { + var v sealed + if err = rows.Scan(&v.id, &v.job, &v.evidence); err != nil { + rows.Close() + return err + } + items = append(items, v) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + if len(items) != 1 || items[0].job == "" { + return errors.New("unique original captured seal required") + } + old := items[0] + commitAndVerify := func() error { + if err := tx.Commit(ctx); err != nil { + return err + } + var verifiedID string + if err := s.db.QueryRow(ctx, `SELECT evidence->>'source_id' FROM library_versions WHERE id=$1 AND scope=$2 AND snapshot_id=$3`, old.id, source.Scope, snapshotID).Scan(&verifiedID); err != nil { + return err + } + if verifiedID != sourceID { + return errors.New("committed source association readback mismatch") + } + return nil + } + var evidence map[string]json.RawMessage + if json.Unmarshal(old.evidence, &evidence) != nil || evidence == nil { + return errors.New("original capture evidence is not an object") + } + var captured struct { + SnapshotID string `json:"snapshot_id"` + Identity struct { + Project string `json:"project"` + App string `json:"source_app"` + Root string `json:"archive_root"` + Fingerprint string `json:"expectation_fingerprint"` + } `json:"agent_identity"` + } + var expected string + if json.Unmarshal(evidence["agent_result"], &captured) != nil || json.Unmarshal(evidence["expectation_fingerprint"], &expected) != nil { + return errors.New("original capture identity evidence missing") + } + identity := captured.Identity + fingerprint := libraryagent.NewExpectation(identity.Project, identity.App, identity.Root).Fingerprint + if captured.SnapshotID != snapshotID || identity.Project != source.Project || identity.App != source.App || identity.Root == "" || expected != fingerprint || identity.Fingerprint != expected { + return errors.New("original capture identity or fingerprint mismatch") + } + if raw, exists := evidence["source_id"]; exists { + var current string + var bound governance.LibrarySourceIdentity + if json.Unmarshal(raw, ¤t) != nil || current != sourceID || json.Unmarshal(evidence["source_identity"], &bound) != nil || bound != source { + return errors.New("sealed source association cannot be changed") + } + return commitAndVerify() + } + for _, reserved := range []string{"source_identity", "legacy_source_binding"} { + if _, exists := evidence[reserved]; exists { + return errors.New("partial source association cannot be overwritten") + } + } + sum := sha256.Sum256(old.evidence) + addition, err := json.Marshal(map[string]any{"source_id": sourceID, "source_identity": source, "legacy_source_binding": map[string]any{"snapshot_id": snapshotID, "original_event_id": old.id, "original_source_job_id": old.job, "original_evidence_sha256": hex.EncodeToString(sum[:]), "expectation_fingerprint": expected, "actor": actor, "bound_at": now.UTC()}}) + if err != nil { + return err + } + tag, err := tx.Exec(ctx, `UPDATE library_versions SET evidence=evidence || $2::jsonb WHERE id=$1 AND NOT (evidence ? 'source_id')`, old.id, addition) + if err != nil { + return err + } + if tag.RowsAffected() != 1 { + return errors.New("source association changed concurrently") + } + var actual string + if err = tx.QueryRow(ctx, `SELECT evidence->>'source_id' FROM library_versions WHERE id=$1`, old.id).Scan(&actual); err != nil { + return err + } + if actual != sourceID { + return errors.New("source association readback mismatch") + } + return commitAndVerify() +} diff --git a/internal/platform/postgres/library_legacy_source_test.go b/internal/platform/postgres/library_legacy_source_test.go new file mode 100644 index 0000000..c5d9945 --- /dev/null +++ b/internal/platform/postgres/library_legacy_source_test.go @@ -0,0 +1,152 @@ +package postgres + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryagent" + "knowledge-governance/internal/librarysnapshot" +) + +func legacySourceFixture(t *testing.T, store *Store) (string, string, governance.LibrarySourceIdentity) { + t.Helper() + ctx := context.Background() + root := t.TempDir() + if e := os.Chmod(root, 0700); e != nil { + t.Fatal(e) + } + archive, e := librarysnapshot.Open(root, 1024*1024) + if e != nil { + t.Fatal(e) + } + defer archive.Close() + m := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, Format: librarysnapshot.Format, Scope: "internal", TenantID: 10000, KnowledgeBaseID: "kb-legacy", CreatedAt: time.Now().UTC(), Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("a", 64)}} + for _, entry := range []string{"database/knowledges", "database/chunks", "database/resources", "database/resource_bindings", "database/knowledge_tags", "database/knowledge_tag_relations", "wiki/wiki_pages", "wiki/wiki_folders", "wiki/wiki_page_issues", "wiki/wiki_log_entries", "index/chunks"} { + p, e := archive.Put(strings.NewReader("[]")) + if e != nil { + t.Fatal(e) + } + x := strings.Split(entry, "/") + p.Kind = x[0] + p.Name = x[1] + m.Parts = append(m.Parts, p) + } + snapshot, e := archive.Seal(m) + if e != nil { + t.Fatal(e) + } + source := governance.LibrarySourceIdentity{Project: "historical-project", App: "historical-app", Scope: m.Scope, TenantID: m.TenantID, KnowledgeBaseID: m.KnowledgeBaseID} + exp := libraryagent.NewExpectation(source.Project, source.App, "/original/archive") + e = store.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, m.Scope, snapshot), Scope: m.Scope, Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshot, SourceJobID: "legacy-capture", CreatedAt: m.CreatedAt, Evidence: map[string]any{"expectation_fingerprint": exp.Fingerprint, "capture_job": "legacy", "agent_result": map[string]any{"snapshot_id": snapshot, "agent_identity": map[string]any{"project": source.Project, "source_app": source.App, "archive_root": "/original/archive", "expectation_fingerprint": exp.Fingerprint}}}}) + if e != nil { + t.Fatal(e) + } + return root, snapshot, source +} + +func TestContractLegacySourceAssociationPreservesOriginalEvidence(t *testing.T) { + store, _ := newIdentityStore(t) + ctx := context.Background() + root, snapshot, source := legacySourceFixture(t, store) + binder, ok := any(store).(interface { + BindLegacyLibrarySource(context.Context, string, string, governance.LibrarySourceIdentity, string, time.Time) error + }) + if !ok { + t.Fatal("verified legacy source association unavailable") + } + original, e := os.ReadFile(filepath.Join(root, "versions", snapshot+".json")) + if e != nil { + t.Fatal(e) + } + if _, err := store.db.Exec(ctx, `UPDATE library_versions SET evidence=evidence || '{"large_proof":9223372036854775807}'::jsonb`); err != nil { + t.Fatal(err) + } + var originalEvidence string + if err := store.db.QueryRow(ctx, `SELECT evidence::text FROM library_versions`).Scan(&originalEvidence); err != nil { + t.Fatal(err) + } + id, _ := source.ID() + if _, found, e := store.LibrarySourceCandidate(ctx, source.Scope, id); e != nil || found { + t.Fatal("legacy unbound candidate adopted without explicit association", e) + } + now := time.Now().UTC() + if e = binder.BindLegacyLibrarySource(ctx, snapshot, root, source, "admin", now); e != nil { + t.Fatal(e) + } + candidate, found, e := store.LibrarySourceCandidate(ctx, source.Scope, id) + if e != nil || !found || candidate.SnapshotID != snapshot || candidate.SourceJobID != "legacy-capture" { + t.Fatal("association not readable", e) + } + if candidate.Evidence["capture_job"] != "legacy" { + t.Fatal("original evidence overwritten") + } + if e = binder.BindLegacyLibrarySource(ctx, snapshot, root, source, "another-admin", now.Add(time.Second)); e != nil { + t.Fatal("idempotent association", e) + } + var preserved bool + if err := store.db.QueryRow(ctx, `SELECT (evidence - 'source_id' - 'source_identity' - 'legacy_source_binding')=$1::jsonb FROM library_versions`, originalEvidence).Scan(&preserved); err != nil || !preserved { + t.Fatal("historical evidence changed, including bigint", err) + } + var bindingActor string + if err := store.db.QueryRow(ctx, `SELECT evidence->'legacy_source_binding'->>'actor' FROM library_versions`).Scan(&bindingActor); err != nil || bindingActor != "admin" { + t.Fatal("association replay rewrote audit actor", err) + } + changed := source + changed.App = "other-app" + if e = binder.BindLegacyLibrarySource(ctx, snapshot, root, changed, "admin", now); e == nil { + t.Fatal("source rebound") + } + after, e := os.ReadFile(filepath.Join(root, "versions", snapshot+".json")) + if e != nil || string(original) != string(after) { + t.Fatal("historical manifest changed", e) + } +} + +func TestContractLegacySourceAssociationRejectsInsufficientProof(t *testing.T) { + for _, scenario := range []string{"project", "tenant", "fingerprint", "missing-origin", "snapshot", "partial-binding"} { + t.Run(scenario, func(t *testing.T) { + store, _ := newIdentityStore(t) + ctx := context.Background() + root, snapshot, source := legacySourceFixture(t, store) + var mutation string + switch scenario { + case "project": + source.Project = "other-project" + case "tenant": + source.TenantID++ + case "fingerprint": + mutation = `UPDATE library_versions SET evidence=jsonb_set(evidence,'{expectation_fingerprint}','"wrong"'::jsonb)` + case "missing-origin": + mutation = `UPDATE library_versions SET evidence=evidence-'agent_result'` + case "snapshot": + mutation = `UPDATE library_versions SET evidence=jsonb_set(evidence,'{agent_result,snapshot_id}','"different"'::jsonb)` + case "partial-binding": + mutation = `UPDATE library_versions SET evidence=evidence || '{"source_identity":{}}'::jsonb` + } + if mutation != "" { + if _, e := store.db.Exec(ctx, mutation); e != nil { + t.Fatal(e) + } + } + var before string + if e := store.db.QueryRow(ctx, `SELECT evidence::text FROM library_versions`).Scan(&before); e != nil { + t.Fatal(e) + } + if e := store.BindLegacyLibrarySource(ctx, snapshot, root, source, "admin", time.Now()); e == nil { + t.Fatal("unproven source accepted") + } + var after string + if e := store.db.QueryRow(ctx, `SELECT evidence::text FROM library_versions`).Scan(&after); e != nil { + t.Fatal(e) + } + if before != after { + t.Fatal("rejected association changed historical evidence") + } + }) + } +} diff --git a/internal/platform/postgres/library_maintenance.go b/internal/platform/postgres/library_maintenance.go index 72db8aa..38df731 100644 --- a/internal/platform/postgres/library_maintenance.go +++ b/internal/platform/postgres/library_maintenance.go @@ -89,6 +89,14 @@ ON CONFLICT (scope) DO UPDATE SET ELSE EXCLUDED.original_service_state END, note = EXCLUDED.note, + -- 窗口的"起始时间"属于**这次**占用:只有同一作业重入(崩溃接管)才保留第一次的 + -- 时间。少了这一条,页面会一直显示第一次建立基线时的 acquired_at,让人以为 + -- 当前这个窗口从那时起就没释放过。 + acquired_at = CASE + WHEN library_maintenance.owner_job_id = EXCLUDED.owner_job_id + THEN library_maintenance.acquired_at + ELSE EXCLUDED.acquired_at + END, updated_at = EXCLUDED.updated_at, released_at = NULL -- 已经释放的窗口允许被新作业接管(否则第一个同步之后谁也再进不去); diff --git a/internal/platform/postgres/library_maintenance_window_integration_test.go b/internal/platform/postgres/library_maintenance_window_integration_test.go new file mode 100644 index 0000000..2577dda --- /dev/null +++ b/internal/platform/postgres/library_maintenance_window_integration_test.go @@ -0,0 +1,107 @@ +package postgres + +import ( + "context" + "errors" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// 维护窗口的"起始时间"必须属于**当前这次占用**。 +// +// 真实缺陷:acquired_at 没进 ON CONFLICT 的更新列表,于是第一次建立基线时写下的 +// 时间再也不会变——恢复作业明明 16:59 才开窗口,页面却显示 13:37(那次基线), +// 让人以为窗口从基线起就一直没释放。 +// +// 同时必须保住崩溃接管的语义:同一个 owner_job_id 重入不能刷新时间,否则"这次 +// 窗口开了多久"会被重入抹掉。库级与实例级两份 SQL 都要验,它们是两份实现。 +func TestMaintenanceAcquiredAtBelongsToCurrentWindow(t *testing.T) { + databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if databaseURL == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, databaseURL) + if err != nil { + t.Fatalf("connect: %v", err) + } + defer pool.Close() + if err := ApplyMigrations(ctx, pool); err != nil { + t.Fatalf("migrate: %v", err) + } + store := NewStore(pool) + t1 := time.Date(2026, 10, 29, 13, 37, 38, 0, time.UTC) + t2 := t1.Add(3*time.Hour + 21*time.Minute) + t3 := t2.Add(2 * time.Second) + + library := func(owner string) LibraryMaintenance { + return LibraryMaintenance{Scope: "internal", OwnerJobID: owner, TargetIdentity: "scope=internal", + Level: "instance", State: "acquired", IngressState: "open", Services: []string{"app"}} + } + + // 1) 第一个作业开窗口。 + first, err := store.AcquireLibraryMaintenance(ctx, library("libbase-1"), t1) + if err != nil { + t.Fatalf("first acquire: %v", err) + } + if !first.AcquiredAt.Equal(t1) { + t.Fatalf("first acquired_at = %s, want %s", first.AcquiredAt, t1) + } + // 2) 同一作业重入(崩溃接管):时间保持第一次的,不能刷成"刚刚"。 + reentered, err := store.AcquireLibraryMaintenance(ctx, library("libbase-1"), t2) + if err != nil { + t.Fatalf("reenter: %v", err) + } + if !reentered.AcquiredAt.Equal(t1) { + t.Fatalf("reentry must keep the first acquired_at: got %s want %s", reentered.AcquiredAt, t1) + } + // 3) 释放后新作业接管:起始时间必须换成本次。 + if err := store.ReleaseLibraryMaintenance(ctx, "internal", "libbase-1", t2); err != nil { + t.Fatalf("release: %v", err) + } + second, err := store.AcquireLibraryMaintenance(ctx, library("librestore-1"), t3) + if err != nil { + t.Fatalf("second acquire: %v", err) + } + if !second.AcquiredAt.Equal(t3) { + t.Fatalf("new owner must reset acquired_at: got %s want %s", second.AcquiredAt, t3) + } + if second.ReleasedAt != nil { + t.Fatalf("takeover must clear released_at: %+v", second.ReleasedAt) + } + // 4) 仍持有期间别的作业一律拒绝(不能靠刷新时间绕过互斥)。 + if _, err := store.AcquireLibraryMaintenance(ctx, library("libsync-9"), t3); !errors.Is(err, ErrMaintenanceHeld) { + t.Fatalf("foreign acquire while held: err=%v", err) + } + + // 实例级是另一份 SQL:同样两条语义都要成立。 + t4 := t3.Add(time.Minute) + t5 := t4.Add(time.Hour) + t6 := t5.Add(time.Second) + instance := func(owner string) LibraryInstanceMaintenance { + return LibraryInstanceMaintenance{Instance: "kgseal-app", OwnerJobID: owner, OwnerScope: "internal", + TargetFingerprint: "fp", Level: "instance", Services: []string{"app"}, IngressState: "open", State: "acquired"} + } + if _, err := store.AcquireInstanceMaintenance(ctx, instance("libbase-1"), t4); err != nil { + t.Fatalf("instance first acquire: %v", err) + } + if again, err := store.AcquireInstanceMaintenance(ctx, instance("libbase-1"), t5); err != nil { + t.Fatalf("instance reenter: %v", err) + } else if !again.AcquiredAt.Equal(t4) { + t.Fatalf("instance reentry must keep acquired_at: got %s want %s", again.AcquiredAt, t4) + } + if err := store.ReleaseInstanceMaintenance(ctx, "kgseal-app", "libbase-1", t5); err != nil { + t.Fatalf("instance release: %v", err) + } + if taken, err := store.AcquireInstanceMaintenance(ctx, instance("librestore-1"), t6); err != nil { + t.Fatalf("instance second acquire: %v", err) + } else if !taken.AcquiredAt.Equal(t6) { + t.Fatalf("instance new owner must reset acquired_at: got %s want %s", taken.AcquiredAt, t6) + } + if _, err := store.AcquireInstanceMaintenance(ctx, instance("libsync-9"), t6); !errors.Is(err, ErrMaintenanceHeld) { + t.Fatalf("instance foreign acquire while held: err=%v", err) + } +} diff --git a/internal/platform/postgres/library_operations.go b/internal/platform/postgres/library_operations.go new file mode 100644 index 0000000..b89ca14 --- /dev/null +++ b/internal/platform/postgres/library_operations.go @@ -0,0 +1,518 @@ +package postgres + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/governance" +) + +// 发布执行身份:operation / attempt(epoch)的持久化。 +// +// 一条铁律写在这里,别处不再重复实现:**谁写业务状态,就必须证明自己是当前代次**。 +// epoch 守卫读 library_jobs.attempt_epoch/lease_owner,与 BeginLibraryAttempt 的激活 +// 是同一把锁;失租代次的所有治理写入都会被拒绝,而不是靠调用方自觉。 + +// ErrLibraryAttemptHeld:同一作业还有未过期的租约。第二个执行者必须放弃, +// 不能"再认领一次"——那正是 F13 的双 claim。 +var ErrLibraryAttemptHeld = errors.New("library job lease is held by another attempt") + +// EnsureLibraryOperation 幂等创建/读取一次意图。 +// 同一个 (scope,kind,operation_key) + 同一个 request_digest ⇒ 同一次意图(重放); +// 摘要不一致 ⇒ 冲突,绝不把新意图塞进旧 operation。 +func (s *Store) EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error) { + if err := governance.ValidateLibraryOperation(op); err != nil { + return governance.LibraryOperation{}, false, err + } + var id string + err := s.db.QueryRow(ctx, ` +INSERT INTO library_operations (id, scope, kind, target_snapshot_id, request_digest, operation_key, actor, created_at, target_id) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) +ON CONFLICT (scope, kind, operation_key) DO NOTHING +RETURNING id`, op.ID, op.Scope, string(op.Kind), op.TargetSnapshotID, op.RequestDigest, + op.OperationKey, op.Actor, op.CreatedAt.UTC(), s.libraryTargetID).Scan(&id) + if err == nil { + return op, true, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryOperation{}, false, fmt.Errorf("create library operation: %w", err) + } + existing, loadErr := s.libraryOperationByKey(ctx, op.Scope, op.Kind, op.OperationKey) + if loadErr != nil { + return governance.LibraryOperation{}, false, loadErr + } + if existing.RequestDigest != op.RequestDigest { + return existing, false, governance.ErrLibraryOperationConflict + } + return existing, false, nil +} + +func (s *Store) libraryOperationByKey(ctx context.Context, scope string, kind governance.LibraryJobKind, key string) (governance.LibraryOperation, error) { + var id string + if err := s.db.QueryRow(ctx, ` +SELECT id FROM library_operations WHERE scope=$1 AND kind=$2 AND operation_key=$3`, + scope, string(kind), key).Scan(&id); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryOperation{}, errors.New("library operation not found") + } + return governance.LibraryOperation{}, fmt.Errorf("load library operation: %w", err) + } + return s.LibraryOperation(ctx, id) +} + +func (s *Store) LibraryOperation(ctx context.Context, id string) (governance.LibraryOperation, error) { + var op governance.LibraryOperation + var kind string + err := s.db.QueryRow(ctx, ` +SELECT id, scope, kind, target_snapshot_id, request_digest, operation_key, actor, created_at +FROM library_operations WHERE id=$1 AND (kind='seal' OR target_id=$2)`, id, s.libraryTargetID).Scan(&op.ID, &op.Scope, &kind, &op.TargetSnapshotID, + &op.RequestDigest, &op.OperationKey, &op.Actor, &op.CreatedAt) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryOperation{}, err + } + return governance.LibraryOperation{}, fmt.Errorf("load library operation: %w", err) + } + op.Kind = governance.LibraryJobKind(kind) + return op, nil +} + +// OperationAnchors 读不可变首次锚点。 +func (s *Store) OperationAnchors(ctx context.Context, operationID string) (governance.LibraryAnchors, bool, error) { + // 锚点列允许 NULL:必须用可空类型扫描,否则空锚点会让整条读取失败 + // (真库验证发现:NULL 扫进 *string 直接报错,而内存 fake 永远不会有这个形状)。 + var ( + snapshot sql.NullString + backupAt sql.NullTime + digest sql.NullString + fingerprint sql.NullString + recordedAt sql.NullTime + ) + var bytes, rows sql.NullInt64 + err := s.db.QueryRow(ctx, ` +SELECT first_backup_snapshot_id, first_backup_bytes, first_backup_at, writeset_digest, writeset_rows, + target_fingerprint, anchors_at +FROM library_operations WHERE id=$1`, operationID).Scan(&snapshot, &bytes, &backupAt, &digest, &rows, + &fingerprint, &recordedAt) + if errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryAnchors{}, false, nil + } + if err != nil { + return governance.LibraryAnchors{}, false, fmt.Errorf("load library operation anchors: %w", err) + } + a := scanAnchors(snapshot, bytes, backupAt, digest, rows, fingerprint, recordedAt) + return a, a.RecordedAt != nil, nil +} + +// scanAnchors 是锚点唯一的解码实现:NULL 与零值必须分清(未知 ≠ 0)。 +func scanAnchors(snapshot sql.NullString, bytes sql.NullInt64, backupAt sql.NullTime, digest sql.NullString, + rows sql.NullInt64, fingerprint sql.NullString, recordedAt sql.NullTime) governance.LibraryAnchors { + a := governance.LibraryAnchors{FirstBackupSnapshotID: snapshot.String, WriteSetDigest: digest.String, + TargetFingerprint: fingerprint.String} + if bytes.Valid { + value := bytes.Int64 + a.FirstBackupBytes = &value + } + if rows.Valid { + value := rows.Int64 + a.WriteSetRows = &value + } + if backupAt.Valid { + value := backupAt.Time + a.FirstBackupAt = &value + } + if recordedAt.Valid { + value := recordedAt.Time + a.RecordedAt = &value + } + return a +} + +// RecordOperationAnchors 只**填空**,不改已存在的锚点。 +// +// 读-改-写必须在同一个事务里并锁住 operation 行(R2 附带项):两个执行者同时"首次" +// 登记时,先读后写的实现会各自读到 NULL、各自写入,最后一个静默覆盖前一个—— +// 首次锚点就不再是首次。这里 FOR UPDATE 串行化,写入后**逐字段回读核对**: +// 任何一个不可变字段与本次声称的值不一致就报错(而不是让调用方以为登记成功)。 +func (s *Store) RecordOperationAnchors(ctx context.Context, operationID string, anchors governance.LibraryAnchors, now time.Time) error { + if operationID == "" { + return errors.New("record operation anchors requires an operation") + } + tx, err := s.db.Begin(ctx) + if err != nil { + return fmt.Errorf("begin operation anchors: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + var ( + exSnapshot, exDigest, exFingerprint sql.NullString + exBytes, exRows sql.NullInt64 + exBackupAt, exRecordedAt sql.NullTime + ) + err = tx.QueryRow(ctx, ` +SELECT first_backup_snapshot_id, first_backup_bytes, first_backup_at, writeset_digest, writeset_rows, + target_fingerprint, anchors_at +FROM library_operations WHERE id=$1 FOR UPDATE`, operationID).Scan(&exSnapshot, &exBytes, &exBackupAt, + &exDigest, &exRows, &exFingerprint, &exRecordedAt) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("operation %s 不存在:拒绝登记首次锚点", operationID) + } + if err != nil { + return fmt.Errorf("load library operation anchors: %w", err) + } + existing := scanAnchors(exSnapshot, exBytes, exBackupAt, exDigest, exRows, exFingerprint, exRecordedAt) + // 已存在且不同 ⇒ 有人想把"首次"换掉(把半写状态当新基线),必须报错。 + if err := compareAnchors(operationID, existing, anchors); err != nil { + return err + } + if _, err := tx.Exec(ctx, ` +UPDATE library_operations SET + first_backup_snapshot_id = COALESCE(first_backup_snapshot_id, $2), + first_backup_bytes = COALESCE(first_backup_bytes, $3), + first_backup_at = COALESCE(first_backup_at, $4), + writeset_digest = COALESCE(writeset_digest, $5), + writeset_rows = COALESCE(writeset_rows, $6), + target_fingerprint = COALESCE(target_fingerprint, $7), + anchors_at = COALESCE(anchors_at, $8) +WHERE id=$1`, operationID, nullIfEmpty(anchors.FirstBackupSnapshotID), anchors.FirstBackupBytes, + anchors.FirstBackupAt, nullIfEmpty(anchors.WriteSetDigest), anchors.WriteSetRows, + nullIfEmpty(anchors.TargetFingerprint), now.UTC()); err != nil { + return fmt.Errorf("record library operation anchors: %w", err) + } + // 回读核对:NULL 与空串、nil 与 0 必须分清(真实 PG 才有这个差别)。 + var ( + afSnapshot, afDigest, afFingerprint sql.NullString + afBytes, afRows sql.NullInt64 + afBackupAt, afRecordedAt sql.NullTime + ) + if err := tx.QueryRow(ctx, ` +SELECT first_backup_snapshot_id, first_backup_bytes, first_backup_at, writeset_digest, writeset_rows, + target_fingerprint, anchors_at +FROM library_operations WHERE id=$1`, operationID).Scan(&afSnapshot, &afBytes, &afBackupAt, &afDigest, + &afRows, &afFingerprint, &afRecordedAt); err != nil { + return fmt.Errorf("read back library operation anchors: %w", err) + } + after := scanAnchors(afSnapshot, afBytes, afBackupAt, afDigest, afRows, afFingerprint, afRecordedAt) + if err := verifyAnchorsPersisted(operationID, anchors, after); err != nil { + return err + } + return tx.Commit(ctx) +} + +// compareAnchors 拒绝"用新值覆盖已登记的首次锚点"。 +func compareAnchors(operationID string, existing, incoming governance.LibraryAnchors) error { + if existing.FirstBackupSnapshotID != "" && incoming.FirstBackupSnapshotID != "" && + existing.FirstBackupSnapshotID != incoming.FirstBackupSnapshotID { + return fmt.Errorf("operation %s 的首次预备份是 %s,不能用 %s 覆盖", + operationID, existing.FirstBackupSnapshotID, incoming.FirstBackupSnapshotID) + } + if existing.WriteSetDigest != "" && incoming.WriteSetDigest != "" && + existing.WriteSetDigest != incoming.WriteSetDigest { + return fmt.Errorf("operation %s 的首次写集合是 %s,不能用 %s 覆盖", + operationID, existing.WriteSetDigest, incoming.WriteSetDigest) + } + if existing.FirstBackupBytes != nil && incoming.FirstBackupBytes != nil && + *existing.FirstBackupBytes != *incoming.FirstBackupBytes { + return fmt.Errorf("operation %s 的首次预备份字节是 %d,不能用 %d 覆盖", + operationID, *existing.FirstBackupBytes, *incoming.FirstBackupBytes) + } + if existing.TargetFingerprint != "" && incoming.TargetFingerprint != "" && + existing.TargetFingerprint != incoming.TargetFingerprint { + return fmt.Errorf("operation %s 的目标指纹是 %s,不能用 %s 覆盖", + operationID, existing.TargetFingerprint, incoming.TargetFingerprint) + } + return nil +} + +// verifyAnchorsPersisted 核对"本次声称的值确实落库了":空值必须仍是 NULL, +// 有值必须逐字段相同。避免"写成功但被 NULL/0 混淆"的静默丢锚点。 +func verifyAnchorsPersisted(operationID string, claimed, persisted governance.LibraryAnchors) error { + check := func(name, want, got string) error { + if want != "" && want != got { + return fmt.Errorf("operation %s 的 %s 回读为 %q,与声称的 %q 不一致", operationID, name, got, want) + } + return nil + } + if err := check("first_backup_snapshot_id", claimed.FirstBackupSnapshotID, persisted.FirstBackupSnapshotID); err != nil { + return err + } + if err := check("writeset_digest", claimed.WriteSetDigest, persisted.WriteSetDigest); err != nil { + return err + } + if err := check("target_fingerprint", claimed.TargetFingerprint, persisted.TargetFingerprint); err != nil { + return err + } + if claimed.FirstBackupBytes != nil && + (persisted.FirstBackupBytes == nil || *persisted.FirstBackupBytes != *claimed.FirstBackupBytes) { + return fmt.Errorf("operation %s 的 first_backup_bytes 没有按声称值落库", operationID) + } + if claimed.WriteSetRows != nil && + (persisted.WriteSetRows == nil || *persisted.WriteSetRows != *claimed.WriteSetRows) { + return fmt.Errorf("operation %s 的 writeset_rows 没有按声称值落库", operationID) + } + if persisted.RecordedAt == nil { + return fmt.Errorf("operation %s 的 anchors_at 仍为空:锚点没被真正登记", operationID) + } + return nil +} + +// BeginLibraryAttempt 取得这个作业的执行权并激活一个新代次。 +// +// 顺序与理由(R2): +// 1. 锁作业行、再锁 **operation 行**:epoch 是 operation 维度的单调量,两个作业同时 +// 接管同一个 operation 时,只有锁 operation 才能保证"下一个 epoch"不重号。 +// 2. 同一次投递重复调用 ⇒ **幂等**:返回同一个活跃代次并续租,不新增谱系。 +// 3. 有别的活跃代次: +// - 它的租约仍未过期 ⇒ 拒绝(ErrLibraryAttemptHeld)—— 不能把还在跑的代次踢掉; +// - 租约已过期(或就是本作业的旧代次)⇒ 结束它(abandoned,保留行),再开新代次。 +// 4. 新代次 = max(epoch)+1,**新增一行**(历史不可变);同时把同 operation 其它作业行 +// 的租约清空,让它们的守卫立刻失效(旧 job 行上的 epoch/owner 字段还会留着, +// 所以守卫必须同时看 attempts 的活跃状态,见 libraryFence)。 +func (s *Store) BeginLibraryAttempt(ctx context.Context, jobID, owner string, lease time.Duration, now time.Time) (governance.LibraryAttempt, error) { + if jobID == "" || owner == "" { + return governance.LibraryAttempt{}, errors.New("begin library attempt requires job and owner") + } + if lease <= 0 { + lease = 2 * time.Minute + } + tx, err := s.db.Begin(ctx) + if err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("begin library attempt: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + + var operationID, leaseOwner, queueJobID string + var jobEpoch int + var jobLeaseUntil *time.Time + err = tx.QueryRow(ctx, ` +SELECT operation_id, attempt_epoch, lease_owner, lease_until, queue_job_id +FROM library_jobs WHERE id=$1 FOR UPDATE`, jobID).Scan(&operationID, &jobEpoch, &leaseOwner, &jobLeaseUntil, &queueJobID) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryAttempt{}, fmt.Errorf("library job %s not found", jobID) + } + return governance.LibraryAttempt{}, fmt.Errorf("load library job for attempt: %w", err) + } + until := now.Add(lease).UTC() + + // 旧作业(迁移前没有 operation):没有代次谱系可建,只做租约互斥。 + if operationID == "" { + if leaseOwner != "" && leaseOwner != owner && jobLeaseUntil != nil && jobLeaseUntil.After(now.UTC()) { + return governance.LibraryAttempt{}, ErrLibraryAttemptHeld + } + next := jobEpoch + 1 + if _, err := tx.Exec(ctx, ` +UPDATE library_jobs SET attempt_epoch=$2, lease_owner=$3, lease_until=$4, updated_at=$5 WHERE id=$1`, + jobID, next, owner, until, now.UTC()); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("activate legacy library attempt: %w", err) + } + if err := tx.Commit(ctx); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("commit legacy library attempt: %w", err) + } + return governance.LibraryAttempt{JobID: jobID, Epoch: next, QueueJobID: queueJobID, Owner: owner, + State: governance.LibraryAttemptRunning, StartedAt: now.UTC(), LeaseUntil: &until}, nil + } + + // epoch 分配必须串行到 operation 粒度。 + if _, err := tx.Exec(ctx, `SELECT id FROM library_operations WHERE id=$1 FOR UPDATE`, operationID); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("lock library operation for attempt: %w", err) + } + + // 当前活跃代次(部分唯一索引保证至多一行)。 + var activeEpoch int + var activeJob, activeOwner, activeState string + var activeUntil *time.Time + activeErr := tx.QueryRow(ctx, ` +SELECT epoch, job_id, owner, state, lease_until FROM library_attempts +WHERE operation_id=$1 AND state IN ('claimed','running')`, operationID).Scan( + &activeEpoch, &activeJob, &activeOwner, &activeState, &activeUntil) + switch { + case activeErr != nil && !errors.Is(activeErr, pgx.ErrNoRows): + return governance.LibraryAttempt{}, fmt.Errorf("load active library attempt: %w", activeErr) + case activeErr == nil && activeOwner == owner && activeJob == jobID: + // 同一次投递重复调用:续租,返回同一代次(不新增谱系)。 + if _, err := tx.Exec(ctx, ` +UPDATE library_attempts SET heartbeat_at=$4, lease_until=$5 WHERE operation_id=$1 AND epoch=$2 AND owner=$3`, + operationID, activeEpoch, owner, now.UTC(), until); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("renew library attempt: %w", err) + } + if _, err := tx.Exec(ctx, ` +UPDATE library_jobs SET attempt_epoch=$2, lease_owner=$3, lease_until=$4, updated_at=$5 WHERE id=$1`, + jobID, activeEpoch, owner, until, now.UTC()); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("renew library job lease: %w", err) + } + if err := tx.Commit(ctx); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("commit library attempt: %w", err) + } + return governance.LibraryAttempt{OperationID: operationID, Epoch: activeEpoch, JobID: jobID, + QueueJobID: queueJobID, Owner: owner, State: governance.LibraryAttemptRunning, + StartedAt: now.UTC(), LeaseUntil: &until}, nil + case activeErr == nil && activeUntil != nil && activeUntil.After(now.UTC()): + // 别人(另一个作业或另一个执行者)仍持有未过期租约:让路,不许抢占。 + return governance.LibraryAttempt{}, fmt.Errorf("%w(operation %s 的 %d 代次由 %s/%s 持有)", + ErrLibraryAttemptHeld, operationID, activeEpoch, activeJob, activeOwner) + case activeErr == nil: + // 租约已过期:结束它(行保留),再开新代次。 + if _, err := tx.Exec(ctx, ` +UPDATE library_attempts SET state='abandoned', finished_at=$3, outcome=$4, lease_until=NULL +WHERE operation_id=$1 AND epoch=$2`, operationID, activeEpoch, now.UTC(), + "lease expired: superseded by a new attempt"); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("abandon stale library attempt: %w", err) + } + } + + var maxEpoch *int + if err := tx.QueryRow(ctx, `SELECT MAX(epoch) FROM library_attempts WHERE operation_id=$1`, + operationID).Scan(&maxEpoch); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("load library attempt epoch: %w", err) + } + next := 1 + if maxEpoch != nil && *maxEpoch >= next { + next = *maxEpoch + 1 + } + attempt := governance.LibraryAttempt{ + OperationID: operationID, Epoch: next, JobID: jobID, QueueJobID: queueJobID, + Owner: owner, State: governance.LibraryAttemptRunning, StartedAt: now.UTC(), LeaseUntil: &until, + } + if _, err := tx.Exec(ctx, ` +INSERT INTO library_attempts (operation_id, epoch, job_id, queue_job_id, owner, state, started_at, heartbeat_at, lease_until) +VALUES ($1,$2,$3,$4,$5,'running',$6,$6,$7)`, + operationID, next, jobID, queueJobID, owner, now.UTC(), until); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("record library attempt: %w", err) + } + if _, err := tx.Exec(ctx, ` +UPDATE library_jobs SET attempt_epoch=$2, lease_owner=$3, lease_until=$4, updated_at=$5 WHERE id=$1`, + jobID, next, owner, until, now.UTC()); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("activate library attempt: %w", err) + } + // 同一 operation 的其它作业行(续作留下/旧作业)立刻失去租约: + // 它们的守卫写从这一刻起失败,即使行上的 epoch/owner 字段还没被改写。 + if _, err := tx.Exec(ctx, ` +UPDATE library_jobs SET lease_owner='', lease_until=NULL, updated_at=$3 +WHERE operation_id=$1 AND id<>$2`, operationID, jobID, now.UTC()); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("revoke sibling library job leases: %w", err) + } + if err := tx.Commit(ctx); err != nil { + return governance.LibraryAttempt{}, fmt.Errorf("commit library attempt: %w", err) + } + return attempt, nil +} + +// FinishLibraryAttempt 落本次代次的终态。旧代次不能结束别人的代次: +// 只有 (operation, epoch) 与 owner 都匹配才写。 +func (s *Store) FinishLibraryAttempt(ctx context.Context, attempt governance.LibraryAttempt, state governance.LibraryAttemptState, outcome string, now time.Time) error { + if attempt.OperationID == "" { + return nil // 旧作业没有 operation:没有代次可结 + } + // 只允许结束**还没结束**的那一代:已经 finished/abandoned 的代次是历史事实, + // 迟到的 finish 不能把它的 outcome 改写成"成功"(否则接管后旧执行者一收尾, + // 历史就变成了对自己有利的版本,排障时无从分辨谁真的跑完)。 + // 终态集合与服务端的 state CHECK 一致;`completed` 只允许从活跃态进来一次。 + tag, err := s.db.Exec(ctx, ` +UPDATE library_attempts SET state=$4, finished_at=$5, outcome=$6, lease_until=NULL +WHERE operation_id=$1 AND epoch=$2 AND owner=$3 AND state IN ('claimed','running')`, + attempt.OperationID, attempt.Epoch, attempt.Owner, string(state), now.UTC(), outcome) + if err != nil { + return fmt.Errorf("finish library attempt: %w", err) + } + if tag.RowsAffected() != 1 { + return governance.ErrLibraryEpochStale + } + return nil +} + +// LibraryAttempts 返回一次 operation 的执行谱系(按代次升序):接管/恢复排查读它。 +func (s *Store) LibraryAttempts(ctx context.Context, operationID string) ([]governance.LibraryAttempt, error) { + rows, err := s.db.Query(ctx, ` +SELECT operation_id, epoch, job_id, queue_job_id, owner, state, started_at, heartbeat_at, lease_until, finished_at, outcome +FROM library_attempts WHERE operation_id=$1 ORDER BY epoch`, operationID) + if err != nil { + return nil, fmt.Errorf("list library attempts: %w", err) + } + defer rows.Close() + items := make([]governance.LibraryAttempt, 0, 4) + for rows.Next() { + var item governance.LibraryAttempt + var state string + if err := rows.Scan(&item.OperationID, &item.Epoch, &item.JobID, &item.QueueJobID, &item.Owner, &state, + &item.StartedAt, &item.HeartbeatAt, &item.LeaseUntil, &item.FinishedAt, &item.Outcome); err != nil { + return nil, fmt.Errorf("scan library attempt: %w", err) + } + item.State = governance.LibraryAttemptState(state) + items = append(items, item) + } + return items, rows.Err() +} + +// LatestLibraryAttempt 取当前代次(无则 false)。 +func (s *Store) LatestLibraryAttempt(ctx context.Context, operationID string) (governance.LibraryAttempt, bool, error) { + items, err := s.LibraryAttempts(ctx, operationID) + if err != nil || len(items) == 0 { + return governance.LibraryAttempt{}, false, err + } + return items[len(items)-1], true, nil +} + +// RenewLibraryAttempt 续租:失租(0 行)即返回 ErrLibraryEpochStale,调用方必须停手。 +func (s *Store) RenewLibraryAttempt(ctx context.Context, attempt governance.LibraryAttempt, lease time.Duration, now time.Time) error { + if lease <= 0 { + return errors.New("positive lease required") + } + tx, err := s.db.Begin(ctx) + if err != nil { + return err + } + defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() + // Lock job first, exactly like BeginLibraryAttempt. Both leases are one fact; + // never resurrect an expired owner or commit half of a renewal. + tag, err := tx.Exec(ctx, `UPDATE library_jobs SET lease_until=clock_timestamp()+$4::interval + WHERE id=$1 AND attempt_epoch=$2 AND lease_owner=$3 AND lease_until>clock_timestamp()`, attempt.JobID, attempt.Epoch, attempt.Owner, lease.String()) + if err != nil { + return err + } + if tag.RowsAffected() != 1 { + return governance.ErrLibraryEpochStale + } + if attempt.OperationID != "" { + tag, err = tx.Exec(ctx, `UPDATE library_attempts SET heartbeat_at=clock_timestamp(),lease_until=clock_timestamp()+$4::interval + WHERE operation_id=$1 AND epoch=$2 AND owner=$3 AND state='running' AND lease_until>clock_timestamp()`, attempt.OperationID, attempt.Epoch, attempt.Owner, lease.String()) + if err != nil { + return err + } + if tag.RowsAffected() != 1 { + return governance.ErrLibraryEpochStale + } + } + return tx.Commit(ctx) +} + +// guardLibraryJobEpoch 在事务内核"这次写入来自当前代次"。守卫失败一律返回 +// ErrLibraryEpochStale,调用方不许把它当成"重试一下就好"。 +func guardLibraryJobEpoch(ctx context.Context, tx pgx.Tx, jobID string, epoch int, owner string) error { + var currentEpoch int + var currentOwner string + err := tx.QueryRow(ctx, ` +SELECT attempt_epoch, lease_owner FROM library_jobs WHERE id=$1 FOR UPDATE`, jobID).Scan(¤tEpoch, ¤tOwner) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("library job %s not found", jobID) + } + return fmt.Errorf("load library job for epoch guard: %w", err) + } + if currentEpoch != epoch || (owner != "" && currentOwner != owner) { + return fmt.Errorf("%w(作业 %s:本代次 %d/%s,当前 %d/%s)", governance.ErrLibraryEpochStale, + jobID, epoch, owner, currentEpoch, currentOwner) + } + return nil +} + +func nullIfEmpty(value string) any { + if value == "" { + return nil + } + return value +} diff --git a/internal/platform/postgres/library_protection.go b/internal/platform/postgres/library_protection.go new file mode 100644 index 0000000..84cf635 --- /dev/null +++ b/internal/platform/postgres/library_protection.go @@ -0,0 +1,142 @@ +package postgres + +import ( + "context" + "fmt" +) + +// LibraryProtection 回答"这些快照现在为什么不能删"。 +// +// 关键点(F10):保护依据必须来自**全量依赖**,不能来自"最近 100 个版本 / 20 个作业"的 +// 展示窗口。历史上一份需要恢复的旧预备份、一个 failed 但仍持有维护锁的作业,都完全 +// 可能掉出任何窗口——按窗口判断就会把它显示成"可删除候选"。 +// +// 任何一条查询失败都返回错误:调用方必须显示"保护未知"并拒绝生成可删候选, +// 不允许因为"读不到"就当成"没被引用"。 +func (s *Store) LibraryProtection(ctx context.Context) (map[string][]string, error) { + protected := map[string][]string{} + add := func(snapshotID, reason string) { + if snapshotID == "" { + return + } + for _, existing := range protected[snapshotID] { + if existing == reason { + return + } + } + protected[snapshotID] = append(protected[snapshotID], reason) + } + + // 1) 当前生效事实(指针):每个 scope 一条,与历史长度无关。 + rows, err := s.db.Query(ctx, `SELECT snapshot_id FROM library_current_versions`) + if err != nil { + return nil, fmt.Errorf("读取当前生效版本失败:%w", err) + } + for rows.Next() { + var snapshot string + if err := rows.Scan(&snapshot); err != nil { + rows.Close() + return nil, fmt.Errorf("扫描当前生效版本失败:%w", err) + } + add(snapshot, "生产生效版本") + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("读取当前生效版本失败:%w", err) + } + + // 2) 全部生产预备份:任何一份都是某个窗口唯一的可回滚基线,没有窗口限制。 + rows, err = s.db.Query(ctx, `SELECT DISTINCT snapshot_id FROM library_versions WHERE kind='production_prebackup'`) + if err != nil { + return nil, fmt.Errorf("读取生产预备份失败:%w", err) + } + for rows.Next() { + var snapshot string + if err := rows.Scan(&snapshot); err != nil { + rows.Close() + return nil, fmt.Errorf("扫描生产预备份失败:%w", err) + } + add(snapshot, "生产预备份") + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("读取生产预备份失败:%w", err) + } + + // 3) 每个 scope 最近一次测试封存(最新可发布版本),精确取而不是窗口里挑。 + rows, err = s.db.Query(ctx, ` +SELECT DISTINCT ON (scope) scope, snapshot_id FROM library_versions +WHERE kind='test_sealed' ORDER BY scope, created_at DESC`) + if err != nil { + return nil, fmt.Errorf("读取最近测试封存失败:%w", err) + } + for rows.Next() { + var scope, snapshot string + if err := rows.Scan(&scope, &snapshot); err != nil { + rows.Close() + return nil, fmt.Errorf("扫描最近测试封存失败:%w", err) + } + add(snapshot, "最近测试封存("+scope+")") + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("读取最近测试封存失败:%w", err) + } + + // 4) 未释放的维护窗口:窗口持有者的预备份与目标快照都要留住—— + // 否则"删除候选"会把正在等待恢复的那一份清掉。 + var owners []string + rows, err = s.db.Query(ctx, ` +SELECT owner_job_id FROM library_maintenance WHERE released_at IS NULL +UNION +SELECT owner_job_id FROM library_instance_maintenance WHERE released_at IS NULL`) + if err != nil { + return nil, fmt.Errorf("读取未释放维护窗口失败:%w", err) + } + for rows.Next() { + var owner string + if err := rows.Scan(&owner); err != nil { + rows.Close() + return nil, fmt.Errorf("扫描未释放维护窗口失败:%w", err) + } + owners = append(owners, owner) + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("读取未释放维护窗口失败:%w", err) + } + + // 5) 在飞作业与"失败但仍持有窗口"的作业。 + rows, err = s.db.Query(ctx, ` +SELECT coalesce(snapshot_id,''), coalesce(target_snapshot_id,'') +FROM library_jobs WHERE state IN ('pending','running')`) + if err != nil { + return nil, fmt.Errorf("读取在飞作业失败:%w", err) + } + for rows.Next() { + var snapshot, target string + if err := rows.Scan(&snapshot, &target); err != nil { + rows.Close() + return nil, fmt.Errorf("扫描在飞作业失败:%w", err) + } + add(snapshot, "在飞作业引用") + add(target, "在飞作业引用") + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("读取在飞作业失败:%w", err) + } + + for _, owner := range owners { + var snapshot, target string + err := s.db.QueryRow(ctx, ` +SELECT coalesce(snapshot_id,''), coalesce(target_snapshot_id,'') FROM library_jobs WHERE id=$1`, owner). + Scan(&snapshot, &target) + if err != nil { + return nil, fmt.Errorf("读取维护窗口持有作业 %s 失败:%w", owner, err) + } + add(snapshot, "未释放维护窗口的预备份") + add(target, "未释放维护窗口的目标快照") + } + return protected, nil +} diff --git a/internal/platform/postgres/library_reconcile_test.go b/internal/platform/postgres/library_reconcile_test.go new file mode 100644 index 0000000..665645e --- /dev/null +++ b/internal/platform/postgres/library_reconcile_test.go @@ -0,0 +1,18 @@ +package postgres + +import ( + "context" + "strings" + "testing" + "time" +) + +// 收拾孤儿必须带"本进程负责的 kind":没有 kind 就退化成"收拾全部", +// 会把另一台执行器的在飞作业标失败,并把恢复责任写错人。 +func TestReconcileLibraryJobsRequiresOwnedKinds(t *testing.T) { + store := NewStore(nil) + _, err := store.ReconcileLibraryJobs(context.Background(), time.Now(), nil) + if err == nil || !strings.Contains(err.Error(), "kinds") { + t.Fatalf("empty kinds must be rejected before touching the database, got %v", err) + } +} diff --git a/internal/platform/postgres/library_recovery_identity.go b/internal/platform/postgres/library_recovery_identity.go new file mode 100644 index 0000000..384ef3a --- /dev/null +++ b/internal/platform/postgres/library_recovery_identity.go @@ -0,0 +1,42 @@ +package postgres + +import ( + "context" + "errors" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" +) + +// An arbitrary queue delivery cannot borrow another job's window. Check the +// stored request AND its current delivery lease before any maintenance action. +func (s *Store) ResumeExpiredLibraryRecoveryQueues(ctx context.Context) error { + _, err := s.db.Exec(ctx, `UPDATE jobs q SET state='pending',attempt=0,lease_owner=NULL,lease_until=NULL,available_at=clock_timestamp() + FROM library_jobs j,library_instance_maintenance m + WHERE q.type='library.recover' AND q.state='running' AND q.lease_until>'window_job_id' AND j.scope=q.payload->>'scope' AND j.target_id=$1 + AND (j.lease_until IS NULL OR j.lease_until>'window_job_id'=j.id AND q.payload->>'scope'=j.scope + AND q.idempotency_key='library.recover:'||j.id + AND q.lease_owner=$4 AND q.attempt=$5 AND q.lease_until>clock_timestamp() + AND j.scope=$6 AND j.target_id=$7 AND j.kind IN ('sync','restore','baseline','verify'))`, q.ID, window, q.Payload, q.LeaseOwner, q.Attempt, scope, s.libraryTargetID).Scan(&valid) + if e != nil { + return e + } + if !valid { + return errors.New("recovery request/source/target/lease mismatch") + } + return nil +} diff --git a/internal/platform/postgres/library_restore_dispatch.go b/internal/platform/postgres/library_restore_dispatch.go new file mode 100644 index 0000000..8b217bd --- /dev/null +++ b/internal/platform/postgres/library_restore_dispatch.go @@ -0,0 +1,621 @@ +package postgres + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" +) + +// DS01:恢复标记派发的持久准入。 +// +// 关键点不是"多了一张表",而是发送许可的产生方式: +// - Prepare 只建立 prepared(不返回许可); +// - Acquire 在**独立短事务**里按 job→operation→activation→active attempt→effect +// 的顺序取锁,校验当前 epoch/owner/lease(数据库时钟)、原作业/operation 锚点、 +// 维护窗口、恢复投递身份与不可变绑定后做 prepared→dispatching 的 CAS,只有 +// COMMIT 明确成功才返回一次性许可; +// - Inspect 纯读,永不返回许可; +// - 表本身拒绝状态回退、绑定变化、删行与激活撤销回退(迁移里的触发器)。 +// +// 外层 WithLibraryExecution 的事务只 rollback、从不 commit,所以这里绝不能用它: +// 在那种事务里写 dispatching,发出请求后账会被回滚成"未派发"。 + +var ErrRestoreDispatchNotActivated = libraryrelease.ErrRestoreDispatchUnavailable + +// 台账行的 protocol_version 仍是 1(派发协议身份,迁移 78 的 CHECK 约束);证据文档 +// 升到 v2 只改变"激活输入要证明什么",不改表结构。两者不是同一个数字。 +const restoreDispatchActivationLedgerVersion = 1 + +// ActivateRestoreDispatch 消费一份**可核验的**激活证据文件(协议 v2)。 +// +// 证据只声明目标身份、维护作业、journal 文件名/摘要与 writer 集合;实际事实由 +// verifyRestoreDispatchEvidence 直接读维护 journal、治理库维护行与现场构建/指纹 +// 核出(见 library_restore_dispatch_activation.go)。没有配置受信 journal 根时 +// 返回 ErrRestoreDispatchActivationDisabled,绝不退回"只验字符串就开门"。 +func (s *Store) ActivateRestoreDispatch(ctx context.Context, evidencePath, evidenceDigest, + targetIdentity, targetFingerprint string, now time.Time) error { + evidence, err := libraryrelease.LoadRestoreDispatchActivationEvidence(evidencePath, evidenceDigest, + now.UTC(), libraryrelease.RestoreDispatchActivationMaxAge) + if err != nil { + return err + } + if evidence.TargetIdentity != targetIdentity { + return fmt.Errorf("restore dispatch activation evidence is for target %q, not %q", evidence.TargetIdentity, targetIdentity) + } + verified, err := s.verifyRestoreDispatchEvidence(ctx, evidence, targetFingerprint, now.UTC()) + if err != nil { + return err + } + record, err := json.Marshal(restoreDispatchActivationRecord{Request: evidence, Verified: verified}) + if err != nil { + return err + } + if _, err := s.db.Exec(ctx, ` +INSERT INTO library_index_restore_dispatch_activation + (target_identity, protocol_version, target_fingerprint, target_instance, governance_database, + protocol_build, activated_by, drain_evidence_digest, evidence, attested_at, activated_at) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, $10, $11) +ON CONFLICT (target_identity) DO NOTHING`, + evidence.TargetIdentity, restoreDispatchActivationLedgerVersion, evidence.TargetFingerprint, evidence.TargetInstance, + evidence.GovernanceDatabase, evidence.ProtocolBuild, evidence.AttestedBy, + verified.MaintenanceJournalSHA256, string(record), evidence.AttestedAt.UTC(), now.UTC()); err != nil { + return fmt.Errorf("activate restore dispatch: %w", err) + } + return s.requireRestoreDispatchActivation(ctx, targetIdentity) +} + +func (s *Store) RevokeRestoreDispatch(ctx context.Context, targetIdentity string, now time.Time) error { + tag, err := s.db.Exec(ctx, ` +UPDATE library_index_restore_dispatch_activation SET revoked_at=$2 +WHERE target_identity=$1 AND revoked_at IS NULL`, targetIdentity, now.UTC()) + if err != nil { + return fmt.Errorf("revoke restore dispatch: %w", err) + } + if tag.RowsAffected() != 1 { + return errors.New("restore dispatch activation is not active for this target") + } + return nil +} + +func (s *Store) requireRestoreDispatchActivation(ctx context.Context, targetIdentity string) error { + var one int + err := s.db.QueryRow(ctx, ` +SELECT 1 FROM library_index_restore_dispatch_activation +WHERE target_identity=$1 AND protocol_version=1 AND revoked_at IS NULL`, targetIdentity).Scan(&one) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%w(目标 %s 没有激活登记)", ErrRestoreDispatchNotActivated, targetIdentity) + } + if err != nil { + return fmt.Errorf("read restore dispatch activation: %w", err) + } + return nil +} + +// lockRestoreDispatchActivation 在**同一个 CAS 事务**里锁激活行。撤销是同一行的 +// UPDATE:撤销先完成 ⇒ 这里看到 revoked_at;CAS 先取锁 ⇒ 撤销必须等 CAS 提交, +// 之后按"已派发"的窄边界处理。两者只能有一个线性化顺序。 +// +// 这里同时是**使用点**的权威域/构建身份重核:激活行里的 verified 事实必须与当前 +// 连接的 PG 权威域(集群 system_identifier + 库 OID + primary)一致;运行构建必须 +// 有完整 SHA,且与激活登记的 SHA 精确相同(跨 SHA 兼容默认关闭,epoch 相等不算 +// 证明);恢复目标指纹必须等于本次观察值。同名库、副本、 +// unknown 构建或换目标都在这里失败关闭,而不是只在激活那一刻检查。 +func lockRestoreDispatchActivation(ctx context.Context, tx pgx.Tx, targetIdentity, targetFingerprint string) error { + var revoked *time.Time + var evidenceRaw, rowFingerprint string + err := tx.QueryRow(ctx, ` +SELECT revoked_at, evidence::text, target_fingerprint FROM library_index_restore_dispatch_activation +WHERE target_identity=$1 AND protocol_version=1 FOR UPDATE`, targetIdentity).Scan(&revoked, &evidenceRaw, &rowFingerprint) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%w(目标 %s 没有激活登记)", ErrRestoreDispatchNotActivated, targetIdentity) + } + if err != nil { + return fmt.Errorf("lock restore dispatch activation: %w", err) + } + if revoked != nil { + return fmt.Errorf("%w(目标 %s 的激活已于 %s 撤销)", ErrRestoreDispatchNotActivated, targetIdentity, revoked.UTC().Format(time.RFC3339)) + } + var record restoreDispatchActivationRecord + if err := json.Unmarshal([]byte(evidenceRaw), &record); err != nil { + return fmt.Errorf("parse restore dispatch activation record: %w", err) + } + verified := record.Verified + // 激活行的 target_fingerprint 列是**维护窗口**指纹;binding 带的是本次恢复对 + // 目标做的只读观察值。两层不能相互顶替,否则正常恢复会被窗口指纹误拒。 + if rowFingerprint != verified.TargetFingerprint { + return fmt.Errorf("%w(目标 %s 的激活行指纹 %s 与登记证据 %s 不一致)", + ErrRestoreDispatchNotActivated, targetIdentity, rowFingerprint, verified.TargetFingerprint) + } + if verified.RestoreTargetFingerprint != targetFingerprint { + return fmt.Errorf("%w(目标 %s 的激活登记恢复目标指纹 %s,本次恢复目标指纹 %s)", + ErrRestoreDispatchNotActivated, targetIdentity, verified.RestoreTargetFingerprint, targetFingerprint) + } + authority, primary, _, err := observedGovernanceAuthority(ctx, tx) + if err != nil { + return err + } + if verified.GovernanceAuthority.SystemIdentifier == "" || verified.GovernanceAuthority.DatabaseOID == "" { + return fmt.Errorf("%w(目标 %s 的激活登记没有治理权威域身份:拒绝仅凭库名启用)", + ErrRestoreDispatchNotActivated, targetIdentity) + } + if authority != verified.GovernanceAuthority { + return fmt.Errorf("%w(目标 %s 的激活登记属于治理域 %s/%s,当前是 %s/%s)", + ErrRestoreDispatchNotActivated, targetIdentity, verified.GovernanceAuthority.SystemIdentifier, + verified.GovernanceAuthority.DatabaseOID, authority.SystemIdentifier, authority.DatabaseOID) + } + if !primary { + return fmt.Errorf("%w(治理库当前处于恢复/副本角色,拒绝授予派发许可)", ErrRestoreDispatchNotActivated) + } + buildEvidence := libraryrelease.RestoreDispatchActivationEvidence{ + ProtocolEpoch: verified.ProtocolEpoch, + ProtocolBuild: verified.ProtocolBuild, + ProtocolBuildSHA: verified.ProtocolBuildSHA, + } + if _, _, _, err := verifyRestoreDispatchBuild(buildEvidence); err != nil { + return fmt.Errorf("%w(目标 %s:%v)", ErrRestoreDispatchNotActivated, targetIdentity, err) + } + return nil +} + +func restoreDispatchBindingDigest(b libraryrelease.RestoreMarkerBinding) (string, error) { + return b.Digest() +} + +func (s *Store) InspectRestoreMarker(ctx context.Context, b libraryrelease.RestoreMarkerBinding) (libraryrelease.RestoreDispatchStatus, bool, error) { + digest, err := restoreDispatchBindingDigest(b) + if err != nil { + return libraryrelease.RestoreDispatchStatus{}, false, err + } + var state, stored string + err = s.db.QueryRow(ctx, ` +SELECT state, binding_digest FROM library_index_restore_dispatch +WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 AND plan_digest=$4 + AND index_name=$5 AND document_id=$6 AND phase=$7`, + b.Key.TargetIdentity, b.Key.OperationID, b.Key.WindowJobID, b.Key.PlanDigest, + b.Key.Index, b.Key.DocumentID, b.Key.Phase).Scan(&state, &stored) + if errors.Is(err, pgx.ErrNoRows) { + return libraryrelease.RestoreDispatchStatus{}, false, nil + } + if err != nil { + return libraryrelease.RestoreDispatchStatus{}, false, fmt.Errorf("inspect restore dispatch: %w", err) + } + if stored != digest { + return libraryrelease.RestoreDispatchStatus{State: state, Held: true, BindingConflict: true, + Reason: "restore dispatch binding differs from the immutable plan"}, true, nil + } + switch state { + case libraryrelease.RestoreDispatchPrepared: + return libraryrelease.RestoreDispatchStatus{State: state}, true, nil + case libraryrelease.RestoreDispatchDispatching: + return libraryrelease.RestoreDispatchStatus{State: state, Held: true, + Reason: "dispatch outcome unknown: no further create is permitted"}, true, nil + case libraryrelease.RestoreDispatchMarkerConfirmed: + return libraryrelease.RestoreDispatchStatus{State: state, Held: true, + Reason: "marker already dispatched; only the original confirmation path may continue"}, true, nil + default: + return libraryrelease.RestoreDispatchStatus{State: state, Held: true, + Reason: "unrecognised dispatch state"}, true, nil + } +} + +// UnresolvedRestoreDispatches 返回原 window 的权威台账全集(跨 plan 摘要)。 +// 前置与收尾都查同一份记录:只遍历当前 plan 的文档列表会漏掉计划外/别名 effect。 +func (s *Store) UnresolvedRestoreDispatches(ctx context.Context, targetIdentity, operationID, windowJobID string) ([]libraryrelease.RestoreDispatchRecord, error) { + rows, err := s.db.Query(ctx, ` +SELECT plan_digest, index_name, document_id, state FROM library_index_restore_dispatch +WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 +ORDER BY plan_digest, index_name, document_id`, targetIdentity, operationID, windowJobID) + if err != nil { + return nil, fmt.Errorf("read restore dispatch window: %w", err) + } + defer rows.Close() + var records []libraryrelease.RestoreDispatchRecord + for rows.Next() { + var record libraryrelease.RestoreDispatchRecord + if err := rows.Scan(&record.PlanDigest, &record.Index, &record.DocumentID, &record.State); err != nil { + return nil, err + } + records = append(records, record) + } + return records, rows.Err() +} + +// rejectRestoreDispatchPlanAlias 拒绝同一逻辑 effect 用另一个 plan 摘要另起一行。 +// key 里虽然有 plan_digest,但唯一约束允许"同 target/operation/window/index/doc/phase、 +// 不同 plan"共存;那正是"换计划别名重开证明"的旁路。 +func rejectRestoreDispatchPlanAlias(ctx context.Context, tx pgx.Tx, b libraryrelease.RestoreMarkerBinding) error { + var other string + err := tx.QueryRow(ctx, ` +SELECT plan_digest FROM library_index_restore_dispatch +WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 + AND index_name=$4 AND document_id=$5 AND phase=$6 AND plan_digest<>$7 +LIMIT 1 FOR UPDATE`, + b.Key.TargetIdentity, b.Key.OperationID, b.Key.WindowJobID, + b.Key.Index, b.Key.DocumentID, b.Key.Phase, b.Key.PlanDigest).Scan(&other) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return fmt.Errorf("read restore dispatch plan alias: %w", err) + } + return fmt.Errorf("%w: effect already belongs to another plan digest", libraryrelease.ErrRestoreDispatchHeld) +} + +// PrepareRestoreMarker 只建立 prepared:没有发送权,也不把已有 dispatching 抬回 prepared。 +func (s *Store) PrepareRestoreMarker(ctx context.Context, b libraryrelease.RestoreMarkerBinding) (libraryrelease.RestoreDispatchStatus, error) { + digest, err := restoreDispatchBindingDigest(b) + if err != nil { + return libraryrelease.RestoreDispatchStatus{}, err + } + if err := s.requireRestoreDispatchActivation(ctx, b.Key.TargetIdentity); err != nil { + return libraryrelease.RestoreDispatchStatus{}, err + } + tx, err := s.db.Begin(ctx) + if err != nil { + return libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("prepare restore dispatch: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + // 与 BeginLibraryAttempt 同序:先作业行、再 operation 行。这样"准备"不会与代次切换 + // 交错成一份属于旧 identity 的台账。 + if err := lockRestoreDispatchIdentity(ctx, tx, b); err != nil { + return libraryrelease.RestoreDispatchStatus{}, err + } + if err := lockRestoreDispatchActivation(ctx, tx, b.Key.TargetIdentity, b.TargetFingerprint); err != nil { + return libraryrelease.RestoreDispatchStatus{}, err + } + if err := rejectRestoreDispatchPlanAlias(ctx, tx, b); err != nil { + return libraryrelease.RestoreDispatchStatus{}, err + } + if _, err := tx.Exec(ctx, ` +INSERT INTO library_index_restore_dispatch + (target_identity, operation_id, window_job_id, plan_digest, index_name, document_id, phase, binding_digest, state) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'prepared') +ON CONFLICT ON CONSTRAINT library_index_restore_dispatch_identity DO NOTHING`, + b.Key.TargetIdentity, b.Key.OperationID, b.Key.WindowJobID, b.Key.PlanDigest, + b.Key.Index, b.Key.DocumentID, b.Key.Phase, digest); err != nil { + return libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("record prepared restore dispatch: %w", err) + } + status, found, err := inspectRestoreDispatchTx(ctx, tx, b) + if err != nil { + return libraryrelease.RestoreDispatchStatus{}, err + } + if !found { + return libraryrelease.RestoreDispatchStatus{}, errors.New("prepared restore dispatch was not durable") + } + if status.Held { + return status, fmt.Errorf("%w: %s", libraryrelease.ErrRestoreDispatchHeld, status.Reason) + } + if err := tx.Commit(ctx); err != nil { + return libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("commit prepared restore dispatch: %w", err) + } + return status, nil +} + +// acquireRestoreMarker 的 beforeCommit 是提交结果不明这一档的测试接缝:钩子返回错误时 +// 事务回滚,调用方不得发送。生产路径传 nil。 +func (s *Store) acquireRestoreMarker(ctx context.Context, b libraryrelease.RestoreMarkerBinding, beforeCommit func() error) (*libraryrelease.RestoreSendPermit, libraryrelease.RestoreDispatchStatus, error) { + digest, err := restoreDispatchBindingDigest(b) + if err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, err + } + tx, err := s.db.Begin(ctx) + if err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("dispatch restore marker: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if err := lockRestoreDispatchIdentity(ctx, tx, b); err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, err + } + // 撤销与 CAS 在同一事务线性化:这里拿激活行锁,撤销的 UPDATE 必须排队。 + if err := lockRestoreDispatchActivation(ctx, tx, b.Key.TargetIdentity, b.TargetFingerprint); err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, err + } + // 当前代次必须属于这个原 window 作业,且租户/epoch/租约都仍有效。lease 用 + // clock_timestamp():等锁可能跨越租约到期,事务起始的 now() 不是判据。 + var epoch int64 + var owner, attemptState, attemptJob string + var leaseUntil *time.Time + err = tx.QueryRow(ctx, ` +SELECT epoch, owner, state, job_id, lease_until FROM library_attempts +WHERE operation_id=$1 AND state IN ('claimed','running') FOR UPDATE`, b.Key.OperationID).Scan( + &epoch, &owner, &attemptState, &attemptJob, &leaseUntil) + if errors.Is(err, pgx.ErrNoRows) { + return nil, libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("%w: no active attempt for operation %s", + governance.ErrLibraryEpochStale, b.Key.OperationID) + } + if err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("read active attempt: %w", err) + } + if attemptJob != b.Key.WindowJobID { + return nil, libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("%w: active attempt belongs to job %s, not the original window %s", + governance.ErrLibraryEpochStale, attemptJob, b.Key.WindowJobID) + } + var leaseLive bool + if err := tx.QueryRow(ctx, + `SELECT COALESCE($1::timestamptz > clock_timestamp(), false)`, leaseUntil).Scan(&leaseLive); err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("read attempt lease: %w", err) + } + if owner != b.Owner || epoch != b.Epoch || !leaseLive { + return nil, libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchPrepared, Held: true, + Reason: fmt.Sprintf("attempt %s#%d is not the live authorized owner", b.Owner, b.Epoch)}, + fmt.Errorf("%w: attempt %s#%d is not current", governance.ErrLibraryEpochStale, b.Owner, b.Epoch) + } + if err := rejectRestoreDispatchPlanAlias(ctx, tx, b); err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, err + } + + var id int64 + var state, stored string + err = tx.QueryRow(ctx, ` +SELECT id, state, binding_digest FROM library_index_restore_dispatch +WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 AND plan_digest=$4 + AND index_name=$5 AND document_id=$6 AND phase=$7 FOR UPDATE`, + b.Key.TargetIdentity, b.Key.OperationID, b.Key.WindowJobID, b.Key.PlanDigest, + b.Key.Index, b.Key.DocumentID, b.Key.Phase).Scan(&id, &state, &stored) + if errors.Is(err, pgx.ErrNoRows) { + return nil, libraryrelease.RestoreDispatchStatus{}, errors.New("no prepared restore dispatch record: refusing to send") + } + if err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("lock restore dispatch: %w", err) + } + if stored != digest { + return nil, libraryrelease.RestoreDispatchStatus{State: state, Held: true, BindingConflict: true, + Reason: "restore dispatch binding differs from the immutable plan"}, libraryrelease.ErrRestoreDispatchHeld + } + if state != libraryrelease.RestoreDispatchPrepared { + return nil, libraryrelease.RestoreDispatchStatus{State: state, Held: true, + Reason: "dispatch already claimed; no second send is permitted"}, libraryrelease.ErrRestoreDispatchHeld + } + // effect 行锁是本次 CAS 前最后一个可能阻塞的锁。job/attempt/恢复投递的租约可能 + // 正好在等它的时候过期;前面那几次检查发生在拿锁之前,不能充当 CAS 点的判据。 + // 这些行锁都已被本事务持有,这里只重读、不改变锁序。 + if err := recheckRestoreDispatchLeases(ctx, tx, b); err != nil { + var held *restoreDispatchLeaseExpired + if errors.As(err, &held) { + return nil, libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchPrepared, Held: true, + Reason: held.Error()}, fmt.Errorf("%w: %s", governance.ErrLibraryEpochStale, held.Error()) + } + return nil, libraryrelease.RestoreDispatchStatus{}, err + } + + var raw [16]byte + if _, err := rand.Read(raw[:]); err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, err + } + nonce := hex.EncodeToString(raw[:]) + tag, err := tx.Exec(ctx, ` +UPDATE library_index_restore_dispatch +SET state='dispatching', dispatch_owner=$2, dispatch_epoch=$3, dispatch_nonce=$4, + request_digest=$5, dispatch_committed_at=clock_timestamp(), updated_at=clock_timestamp() +WHERE id=$1 AND state='prepared'`, id, b.Owner, b.Epoch, nonce, b.RequestDigest) + if err != nil { + return nil, libraryrelease.RestoreDispatchStatus{}, fmt.Errorf("claim restore dispatch: %w", err) + } + if tag.RowsAffected() != 1 { + return nil, libraryrelease.RestoreDispatchStatus{State: state, Held: true, + Reason: "dispatch CAS lost"}, libraryrelease.ErrRestoreDispatchHeld + } + if beforeCommit != nil { + if err := beforeCommit(); err != nil { + // 提交结果不明:本调用不发送,也不把状态当成 prepared 重试。 + return nil, libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchDispatching, Held: true, + Reason: "commit outcome unknown"}, fmt.Errorf("commit restore dispatch: %w", err) + } + } + if err := tx.Commit(ctx); err != nil { + return nil, libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchDispatching, Held: true, + Reason: "commit outcome unknown"}, fmt.Errorf("commit restore dispatch: %w", err) + } + return libraryrelease.IssueRestoreSendPermit(b.Key, digest, nonce), + libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchDispatching}, nil +} + +func (s *Store) AcquireRestoreMarker(ctx context.Context, b libraryrelease.RestoreMarkerBinding) (*libraryrelease.RestoreSendPermit, libraryrelease.RestoreDispatchStatus, error) { + return s.acquireRestoreMarker(ctx, b, nil) +} + +// ConfirmRestoreMarker 只记录真实回执(不再发送)。状态仍是 dispatching 时才允许; +// 回执本身来自本次受控发送或同计划标记的实时核实,不由客户端布尔值决定。 +func (s *Store) ConfirmRestoreMarker(ctx context.Context, b libraryrelease.RestoreMarkerBinding, receipt []byte) error { + if len(receipt) == 0 || !json.Valid(receipt) { + return errors.New("restore marker confirmation requires a real receipt") + } + digest, err := restoreDispatchBindingDigest(b) + if err != nil { + return err + } + tx, err := s.db.Begin(ctx) + if err != nil { + return fmt.Errorf("confirm restore marker: %w", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if err := lockRestoreDispatchIdentity(ctx, tx, b); err != nil { + return err + } + if err := lockRestoreDispatchActivation(ctx, tx, b.Key.TargetIdentity, b.TargetFingerprint); err != nil { + return err + } + var epoch int64 + var owner, attemptJob string + var leaseUntil *time.Time + err = tx.QueryRow(ctx, ` +SELECT epoch, owner, job_id, lease_until FROM library_attempts +WHERE operation_id=$1 AND state IN ('claimed','running') FOR UPDATE`, b.Key.OperationID).Scan(&epoch, &owner, &attemptJob, &leaseUntil) + if err != nil { + return fmt.Errorf("confirm restore marker attempt: %w", err) + } + var leaseLive bool + if err := tx.QueryRow(ctx, + `SELECT COALESCE($1::timestamptz > clock_timestamp(), false)`, leaseUntil).Scan(&leaseLive); err != nil { + return fmt.Errorf("confirm restore marker lease: %w", err) + } + if attemptJob != b.Key.WindowJobID || owner != b.Owner || epoch != b.Epoch || !leaseLive { + return fmt.Errorf("%w: confirmation by a stale owner", governance.ErrLibraryEpochStale) + } + // 与 Acquire 同一个顺序:确认前的最后一把锁也要先拿到,再按数据库实时时钟重核 + // 租约。否则"确认"可以在等锁跨过到期之后仍落库,把一次过期 owner 的回执写成事实。 + var effectID int64 + if err := tx.QueryRow(ctx, ` +SELECT id FROM library_index_restore_dispatch +WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 AND plan_digest=$4 + AND index_name=$5 AND document_id=$6 AND phase=$7 FOR UPDATE`, + b.Key.TargetIdentity, b.Key.OperationID, b.Key.WindowJobID, b.Key.PlanDigest, + b.Key.Index, b.Key.DocumentID, b.Key.Phase).Scan(&effectID); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return errors.New("restore marker confirmation did not match a dispatch record") + } + return fmt.Errorf("lock restore marker for confirmation: %w", err) + } + if err := recheckRestoreDispatchLeases(ctx, tx, b); err != nil { + return fmt.Errorf("%w: %s", governance.ErrLibraryEpochStale, err) + } + tag, err := tx.Exec(ctx, ` +UPDATE library_index_restore_dispatch +SET state='marker_confirmed', marker_receipt=$1::jsonb, confirmed_at=clock_timestamp(), updated_at=clock_timestamp() +WHERE target_identity=$2 AND operation_id=$3 AND window_job_id=$4 AND plan_digest=$5 + AND index_name=$6 AND document_id=$7 AND phase=$8 + AND state='dispatching' AND binding_digest=$9`, + string(receipt), b.Key.TargetIdentity, b.Key.OperationID, b.Key.WindowJobID, b.Key.PlanDigest, + b.Key.Index, b.Key.DocumentID, b.Key.Phase, digest) + if err != nil { + return fmt.Errorf("confirm restore marker: %w", err) + } + if tag.RowsAffected() != 1 { + return errors.New("restore marker confirmation did not match a dispatching record") + } + if err := tx.Commit(ctx); err != nil { + return fmt.Errorf("commit restore marker confirmation: %w", err) + } + return nil +} + +// lockRestoreDispatchIdentity 以 job→operation 锁序把"这份许可是不是仍属于原作业" +// 钉死在原持久锚点上:目标/scope/来源快照、写集摘要(若已登记)、维护窗口与实例 +// 指纹、恢复投递的 queue/operation 绑定都必须与不可变绑定一致。 +func lockRestoreDispatchIdentity(ctx context.Context, tx pgx.Tx, b libraryrelease.RestoreMarkerBinding) error { + var operationID, scope, jobSource string + var leaseOwner string + var jobEpoch int64 + var jobLease *time.Time + err := tx.QueryRow(ctx, ` +SELECT operation_id, scope, target_snapshot_id, lease_owner, attempt_epoch, lease_until +FROM library_jobs WHERE id=$1 FOR UPDATE`, b.Key.WindowJobID).Scan( + &operationID, &scope, &jobSource, &leaseOwner, &jobEpoch, &jobLease) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("window job %s not found", b.Key.WindowJobID) + } + if err != nil { + return fmt.Errorf("lock window job: %w", err) + } + if operationID != b.Key.OperationID { + return errors.New("window job belongs to another operation") + } + if scope != b.Scope { + return fmt.Errorf("window job scope %s does not match binding %s", scope, b.Scope) + } + if jobSource == "" || jobSource != b.SourceSnapshot { + return fmt.Errorf("window job source snapshot %q does not match binding %q", jobSource, b.SourceSnapshot) + } + if leaseOwner != b.Owner || jobEpoch != b.Epoch || jobLease == nil { + return fmt.Errorf("%w: window job lease is not held by attempt %s#%d", governance.ErrLibraryEpochStale, b.Owner, b.Epoch) + } + var jobLeaseLive bool + if err := tx.QueryRow(ctx, `SELECT COALESCE($1::timestamptz > clock_timestamp(), false)`, jobLease).Scan(&jobLeaseLive); err != nil { + return fmt.Errorf("read window job lease: %w", err) + } + if !jobLeaseLive { + return fmt.Errorf("%w: window job lease expired while waiting for the dispatch CAS", governance.ErrLibraryEpochStale) + } + + var opScope, opKind, opSource, requestDigest, writesetDigest, firstBackup string + err = tx.QueryRow(ctx, ` +SELECT scope, kind, target_snapshot_id, request_digest, COALESCE(writeset_digest,''), COALESCE(first_backup_snapshot_id,'') +FROM library_operations WHERE id=$1 FOR UPDATE`, b.Key.OperationID).Scan( + &opScope, &opKind, &opSource, &requestDigest, &writesetDigest, &firstBackup) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("operation %s not found", b.Key.OperationID) + } + if err != nil { + return fmt.Errorf("lock operation: %w", err) + } + if opScope != b.Scope { + return fmt.Errorf("operation scope %s does not match binding %s", opScope, b.Scope) + } + if opSource == "" || opSource != b.SourceSnapshot { + return fmt.Errorf("operation source snapshot %q does not match binding %q", opSource, b.SourceSnapshot) + } + if requestDigest == "" { + return errors.New("operation has no request digest anchor") + } + if writesetDigest != "" && writesetDigest != b.Key.PlanDigest { + return fmt.Errorf("operation plan digest %s does not match binding %s", writesetDigest, b.Key.PlanDigest) + } + if firstBackup != "" && firstBackup != b.BackupSnapshot { + return fmt.Errorf("operation backup snapshot %s does not match binding %s", firstBackup, b.BackupSnapshot) + } + _ = opKind + + if b.TargetInstance != "" { + var ownerJob, ownerScope string + var released *time.Time + var state string + err = tx.QueryRow(ctx, ` +SELECT owner_job_id, owner_scope, state, released_at +FROM library_instance_maintenance WHERE instance=$1 FOR UPDATE`, b.TargetInstance).Scan( + &ownerJob, &ownerScope, &state, &released) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("target instance %s has no maintenance window", b.TargetInstance) + } + if err != nil { + return fmt.Errorf("lock instance maintenance: %w", err) + } + if released != nil || state == "released" { + return errors.New("target instance maintenance window is already released") + } + if ownerJob != b.Key.WindowJobID || ownerScope != b.Scope { + return fmt.Errorf("maintenance window belongs to %s (scope=%s), not window %s", ownerJob, ownerScope, b.Key.WindowJobID) + } + } + + if b.RecoveryJobID != "" { + if err := lockAndVerifyRecoveryDelivery(ctx, tx, b); err != nil { + return err + } + } + return nil +} + +func inspectRestoreDispatchTx(ctx context.Context, tx pgx.Tx, b libraryrelease.RestoreMarkerBinding) (libraryrelease.RestoreDispatchStatus, bool, error) { + digest, err := restoreDispatchBindingDigest(b) + if err != nil { + return libraryrelease.RestoreDispatchStatus{}, false, err + } + var state, stored string + err = tx.QueryRow(ctx, ` +SELECT state, binding_digest FROM library_index_restore_dispatch +WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 AND plan_digest=$4 + AND index_name=$5 AND document_id=$6 AND phase=$7`, + b.Key.TargetIdentity, b.Key.OperationID, b.Key.WindowJobID, b.Key.PlanDigest, + b.Key.Index, b.Key.DocumentID, b.Key.Phase).Scan(&state, &stored) + if errors.Is(err, pgx.ErrNoRows) { + return libraryrelease.RestoreDispatchStatus{}, false, nil + } + if err != nil { + return libraryrelease.RestoreDispatchStatus{}, false, fmt.Errorf("inspect restore dispatch: %w", err) + } + if stored != digest { + return libraryrelease.RestoreDispatchStatus{State: state, Held: true, + Reason: "restore dispatch binding differs from the immutable plan"}, true, nil + } + return libraryrelease.RestoreDispatchStatus{State: state, + Held: state != libraryrelease.RestoreDispatchPrepared}, true, nil +} diff --git a/internal/platform/postgres/library_restore_dispatch_activation.go b/internal/platform/postgres/library_restore_dispatch_activation.go new file mode 100644 index 0000000..1ff0c44 --- /dev/null +++ b/internal/platform/postgres/library_restore_dispatch_activation.go @@ -0,0 +1,331 @@ +package postgres + +import ( + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "sort" + "strings" + "time" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/libraryfreeze" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/version" +) + +// 激活门的唯一证据链(DS01-F3): +// +// 调用方声明(身份/作业/摘要/writer 集合) +// → 维护窗口写下的 journal 字节(sha256 必须等于声明值) +// → journal 事实(窗口 held、入口 closed+drained、active_at_close=0、quiesce 零点、 +// 每个 writer 有 stop_requested + exit_code) +// → 治理库 library_instance_maintenance 行(同一作业/实例/指纹/level=instance、 +// 未释放、services 集合等于声明的 writer 名) +// → 现场身份(current_database()、运行构建、调用方重观察的指纹) +// +// 任何一环缺失都不建 active 行。这里不再接受"stopped/queue_drained 布尔 + 一个 +// 调用方字符串摘要":那些字段在 v2 证据里根本不存在。 + +// ErrRestoreDispatchActivationDisabled 表示没有配置受信维护证据根:能力整体关闭。 +var ErrRestoreDispatchActivationDisabled = errors.New("restore dispatch activation is disabled: no trusted maintenance evidence root is configured") + +type restoreDispatchVerifiedView struct { + MaintenanceJob string `json:"maintenance_job"` + MaintenanceSource string `json:"maintenance_source"` + MaintenanceState string `json:"maintenance_state"` + MaintenanceJournalSHA256 string `json:"maintenance_journal_sha256"` + TargetFingerprint string `json:"target_fingerprint"` + RestoreTargetFingerprint string `json:"restore_target_fingerprint"` + IngressGate restoreDispatchGateView `json:"ingress_gate"` + Quiesce restoreDispatchQuiesceView `json:"quiesce"` + Writers []restoreDispatchWriterView `json:"writers"` + GovernanceDatabase string `json:"governance_database"` + // 治理权威域是现场读回的 PG 事实:集群 system_identifier + 库 OID + 是否 primary。 + // 激活与每次使用点都重读比较,库名只作可读标签。 + GovernanceAuthority restoreDispatchAuthorityView `json:"governance_authority"` + GovernancePrimary bool `json:"governance_primary"` + ProtocolBuild string `json:"protocol_build"` + ProtocolBuildSHA string `json:"protocol_build_sha"` + ProtocolEpoch int `json:"protocol_epoch"` + CompatibleUpgrade bool `json:"compatible_upgrade"` + ObservedAt time.Time `json:"observed_at"` +} + +// restoreDispatchAuthorityView 只放可比较的权威域字段;不含密钥/连接串。 +type restoreDispatchAuthorityView struct { + SystemIdentifier string `json:"system_identifier"` + DatabaseOID string `json:"database_oid"` +} + +// lockRestoreDispatchActivationVerification 是使用点重核所需的最小事实。 +type restoreDispatchActivationVerification struct { + Authority restoreDispatchAuthorityView + Primary bool + ProtocolBuild string + ProtocolBuildSHA string + ProtocolEpoch int + TargetFingerprint string +} + +// observedGovernanceAuthority 读回当前连接的治理库权威域。pg_control_system() 的 +// system_identifier 是集群级、跨备份/克隆仍不同的身份;库 OID 在同一集群内区分同名库。 +// 没有权限读它时返回错误(能力失败关闭),绝不退回"库名相同就算同一个库"。 +func observedGovernanceAuthority(ctx context.Context, q interface { + QueryRow(ctx context.Context, sql string, args ...any) pgx.Row +}) (restoreDispatchAuthorityView, bool, string, error) { + var authority restoreDispatchAuthorityView + var database string + var inRecovery bool + err := q.QueryRow(ctx, ` +SELECT current_database(), + (SELECT system_identifier::text FROM pg_control_system()), + (SELECT oid::text FROM pg_database WHERE datname = current_database()), + pg_is_in_recovery()`).Scan(&database, &authority.SystemIdentifier, &authority.DatabaseOID, &inRecovery) + if err != nil { + return authority, false, "", fmt.Errorf("observe governance authority: %w", err) + } + return authority, !inRecovery, database, nil +} + +type restoreDispatchGateView struct { + Closed bool `json:"closed"` + Drained bool `json:"drained"` + ActiveAtClose int `json:"active_at_close"` + Served int `json:"served"` + Detail string `json:"detail"` +} + +type restoreDispatchQuiesceView struct { + Depth int64 `json:"depth"` + PendingOps int64 `json:"pending_ops"` + Unsettled int64 `json:"unsettled"` + Digest string `json:"digest"` + StableMS int64 `json:"stable_ms"` + Samples int `json:"samples"` + ProvenAt time.Time `json:"proven_at"` + PostStopAt time.Time `json:"post_stop_at"` +} + +type restoreDispatchWriterView struct { + Name string `json:"name"` + Kind string `json:"kind"` + InstanceID string `json:"instance_id"` + StopRequested bool `json:"stop_requested"` + ExitCode int `json:"exit_code"` +} + +// restoreDispatchActivationRecord 是写进 activation.evidence 的规范字节: +// request 是调用方声明,verified 是本进程从 journal/治理库/现场实际读到并核对的事实。 +// 二者分开,事后方能区分"谁声明了什么"与"代码核实了什么"。 +type restoreDispatchActivationRecord struct { + Request libraryrelease.RestoreDispatchActivationEvidence `json:"request"` + Verified restoreDispatchVerifiedView `json:"verified"` +} + +func (s *Store) verifyRestoreDispatchEvidence(ctx context.Context, evidence libraryrelease.RestoreDispatchActivationEvidence, + targetFingerprint string, now time.Time) (restoreDispatchVerifiedView, error) { + var verified restoreDispatchVerifiedView + if s.restoreDispatchEvidenceRoot == "" { + return verified, ErrRestoreDispatchActivationDisabled + } + journal, err := libraryfreeze.ReadJournal(s.restoreDispatchEvidenceRoot, evidence.MaintenanceJob) + if err != nil { + return verified, fmt.Errorf("read maintenance journal: %w", err) + } + if journal.Digest != evidence.MaintenanceJournalSHA256 { + return verified, errors.New("maintenance journal digest does not match the activation evidence") + } + if journal.State != "held" { + return verified, fmt.Errorf("maintenance journal state %q is not a held window", journal.State) + } + if journal.Level != "instance" { + return verified, fmt.Errorf("maintenance journal level %q is not an instance window", journal.Level) + } + if journal.Source != evidence.TargetInstance { + return verified, fmt.Errorf("maintenance journal source %q is not target instance %q", journal.Source, evidence.TargetInstance) + } + if journal.TargetFingerprint == "" || journal.TargetFingerprint != evidence.TargetFingerprint { + return verified, errors.New("maintenance journal target fingerprint does not match the activation evidence") + } + if !journal.IngressClosed { + return verified, errors.New("maintenance journal does not prove the target ingress was closed") + } + if !journal.DrainVerified { + return verified, errors.New("maintenance journal does not prove the controlled writers drained") + } + if journal.Gate == nil || !journal.Gate.Closed || !journal.Gate.Drained || journal.Gate.ActiveAtClose != 0 { + return verified, errors.New("maintenance journal does not prove the ingress drained to zero in-flight requests") + } + if journal.Quiesce == nil || journal.Quiesce.PostStopAt.IsZero() { + return verified, errors.New("maintenance journal has no post-stop background quiesce observation") + } + if journal.Quiesce.ProvenAt.Before(journal.StartedAt) || journal.Quiesce.PostStopAt.Before(journal.Quiesce.ProvenAt) { + return verified, errors.New("maintenance journal quiesce timestamps are not ordered") + } + // "旧 writer 已退出并排空"必须是一次近期观察:两个月前的窗口不能给今天的激活作证。 + if now.Sub(journal.Quiesce.PostStopAt) > libraryrelease.RestoreDispatchActivationMaxAge { + return verified, errors.New("maintenance journal stop/drain observation is older than the activation validity window") + } + if evidence.AttestedAt.Before(journal.Quiesce.PostStopAt) { + return verified, errors.New("restore dispatch attestation predates the maintenance stop observation") + } + authority, primary, database, err := observedGovernanceAuthority(ctx, s.db) + if err != nil { + return verified, err + } + if authority != (restoreDispatchAuthorityView{SystemIdentifier: evidence.GovernanceAuthority.SystemIdentifier, + DatabaseOID: evidence.GovernanceAuthority.DatabaseOID}) { + return verified, fmt.Errorf("restore dispatch activation names governance authority %s/%s, live is %s/%s", + evidence.GovernanceAuthority.SystemIdentifier, evidence.GovernanceAuthority.DatabaseOID, + authority.SystemIdentifier, authority.DatabaseOID) + } + if !primary { + return verified, errors.New("restore dispatch activation requires the governance database to be primary, not a replica") + } + if database != evidence.GovernanceDatabase { + return verified, fmt.Errorf("restore dispatch activation evidence names governance database %q, live is %q", + evidence.GovernanceDatabase, database) + } + build, buildSHA, compatible, err := verifyRestoreDispatchBuild(evidence) + if err != nil { + return verified, err + } + // 维护窗口指纹与恢复目标指纹是两层:前者已与 journal/维护行比对,后者必须等于 + // 激活方刚刚对恢复目标做的那次只读观察。用一个值同时顶替两者会掩盖"配置指向 + // 另一个目标实例"的漂移。 + if targetFingerprint != evidence.RestoreTargetFingerprint { + return verified, errors.New("restore dispatch activation evidence does not match the live restore target fingerprint") + } + + // 治理库维护行由维护链在开窗口时写入,不是激活调用方写的:用它把作业/实例/ + // 指纹/writer 集合钉死,防止"一份别的实例的合法 journal"被拿来激活本目标。 + var ownerJob, ownerScope, rowFingerprint, level, servicesRaw, state string + var released *time.Time + var acquiredAt time.Time + err = s.db.QueryRow(ctx, ` +SELECT owner_job_id, owner_scope, target_fingerprint, level, services::text, state, released_at, acquired_at +FROM library_instance_maintenance WHERE instance=$1`, evidence.TargetInstance).Scan( + &ownerJob, &ownerScope, &rowFingerprint, &level, &servicesRaw, &state, &released, &acquiredAt) + if errors.Is(err, pgx.ErrNoRows) { + return verified, fmt.Errorf("target instance %q has no maintenance window", evidence.TargetInstance) + } + if err != nil { + return verified, fmt.Errorf("read instance maintenance window: %w", err) + } + if ownerJob != evidence.MaintenanceJob { + return verified, fmt.Errorf("maintenance window belongs to job %q, not %q", ownerJob, evidence.MaintenanceJob) + } + if level != "instance" { + return verified, fmt.Errorf("maintenance window level %q is not instance", level) + } + if released != nil || state == "released" { + return verified, errors.New("maintenance window is already released: it cannot prove the old writers are still stopped") + } + if rowFingerprint != evidence.TargetFingerprint { + return verified, errors.New("maintenance window target fingerprint does not match the activation evidence") + } + if acquiredAt.After(journal.Quiesce.ProvenAt) { + return verified, errors.New("maintenance window was acquired after the drain observation") + } + var services []string + if err := json.Unmarshal([]byte(servicesRaw), &services); err != nil { + return verified, fmt.Errorf("parse maintenance writer set: %w", err) + } + registered := map[string]bool{} + for _, name := range services { + registered[name] = true + } + if len(registered) != len(evidence.Writers) { + return verified, fmt.Errorf("maintenance window lists %d writers, activation declares %d", len(registered), len(evidence.Writers)) + } + byInstance := map[string]libraryfreeze.JournalService{} + for _, service := range journal.Services { + byInstance[service.ID] = service + } + if len(byInstance) != len(evidence.Writers) { + return verified, fmt.Errorf("maintenance journal lists %d writers, activation declares %d", len(byInstance), len(evidence.Writers)) + } + verifiedWriters := make([]restoreDispatchWriterView, 0, len(evidence.Writers)) + for _, writer := range evidence.Writers { + if !registered[writer.Name] { + return verified, fmt.Errorf("writer %q is not part of the maintenance window writer set", writer.Name) + } + service, ok := byInstance[writer.InstanceID] + if !ok { + return verified, fmt.Errorf("writer %q instance %q is not in the maintenance journal", writer.Name, writer.InstanceID) + } + if !service.StopRequested { + return verified, fmt.Errorf("writer %q was never asked to stop", writer.Name) + } + if service.ExitCode == nil { + return verified, fmt.Errorf("writer %q has no observed exit code", writer.Name) + } + if *service.ExitCode != 0 && !journal.DrainVerified { + return verified, fmt.Errorf("writer %q exited with %d without a drain proof", writer.Name, *service.ExitCode) + } + verifiedWriters = append(verifiedWriters, restoreDispatchWriterView{Name: writer.Name, Kind: writer.Kind, + InstanceID: writer.InstanceID, StopRequested: service.StopRequested, ExitCode: *service.ExitCode}) + } + sort.Slice(verifiedWriters, func(i, j int) bool { return verifiedWriters[i].Name < verifiedWriters[j].Name }) + verified = restoreDispatchVerifiedView{ + MaintenanceJob: journal.Job, MaintenanceSource: journal.Source, MaintenanceState: journal.State, + MaintenanceJournalSHA256: journal.Digest, TargetFingerprint: journal.TargetFingerprint, + RestoreTargetFingerprint: evidence.RestoreTargetFingerprint, + IngressGate: restoreDispatchGateView{Closed: journal.Gate.Closed, Drained: journal.Gate.Drained, + ActiveAtClose: journal.Gate.ActiveAtClose, Served: journal.Gate.Served, Detail: journal.Gate.Detail}, + Quiesce: restoreDispatchQuiesceView{Depth: journal.Quiesce.Depth, PendingOps: journal.Quiesce.PendingOps, + Unsettled: journal.Quiesce.Unsettled, Digest: journal.Quiesce.Digest, StableMS: journal.Quiesce.StableMS, + Samples: journal.Quiesce.Samples, ProvenAt: journal.Quiesce.ProvenAt.UTC(), PostStopAt: journal.Quiesce.PostStopAt.UTC()}, + Writers: verifiedWriters, GovernanceDatabase: database, + GovernanceAuthority: authority, GovernancePrimary: primary, + ProtocolBuild: build, ProtocolBuildSHA: buildSHA, + ProtocolEpoch: evidence.ProtocolEpoch, CompatibleUpgrade: compatible, + ObservedAt: now.UTC(), + } + return verified, nil +} + +// verifyRestoreDispatchBuild 是构建身份的兼容策略: +// - 运行中的二进制必须有注入的**完整 40 位 SHA**,否则 unknown —— 拒绝; +// - 证据的构建 SHA 也必须是完整 SHA; +// - 构建身份**精确绑定**运行 SHA:同一 SHA 时必须与运行 display 相符(防止同一 +// 二进制自称别的版本);不同 SHA 一律拒绝。 +// +// ProtocolEpoch 只说明派发协议语义批次,不能证明某个 SHA 属于该批次;系统里没有 +// 受信的批次成员清单或构建证明。跨 SHA 自动兼容因此保持关闭,而不是拿 epoch 相等 +// 当证明、再引入一份声明式 allowlist。将来若有可核的受信构建证明,再单独接入。 +func verifyRestoreDispatchBuild(evidence libraryrelease.RestoreDispatchActivationEvidence) (string, string, bool, error) { + build := version.DisplayVersion() + runningSHA := version.CommitSHA + if !version.HasInjection() || build == "" || build == "dev" || !isFullHexSHA(runningSHA) { + return "", "", false, errors.New("restore dispatch activation requires a build with an injected full commit sha") + } + if !isFullHexSHA(evidence.ProtocolBuildSHA) { + return "", "", false, errors.New("restore dispatch activation evidence carries no full build sha") + } + if evidence.ProtocolEpoch != libraryrelease.RestoreDispatchProtocolEpoch { + return "", "", false, fmt.Errorf("restore dispatch activation build epoch %d is incompatible with %d", + evidence.ProtocolEpoch, libraryrelease.RestoreDispatchProtocolEpoch) + } + if evidence.ProtocolBuildSHA != runningSHA { + return "", "", false, fmt.Errorf("restore dispatch activation build sha %s is not the running commit %s: cross-sha compatible activation is disabled without a verifiable protocol build membership proof", + evidence.ProtocolBuildSHA, runningSHA) + } + if evidence.ProtocolBuild != build { + return "", "", false, fmt.Errorf("restore dispatch activation claims build %q for the running commit, display is %q", + evidence.ProtocolBuild, build) + } + return build, runningSHA, false, nil +} + +func isFullHexSHA(value string) bool { + if len(value) != 40 || strings.ToLower(value) != value { + return false + } + _, err := hex.DecodeString(value) + return err == nil +} diff --git a/internal/platform/postgres/library_restore_dispatch_binding.go b/internal/platform/postgres/library_restore_dispatch_binding.go new file mode 100644 index 0000000..be84bdc --- /dev/null +++ b/internal/platform/postgres/library_restore_dispatch_binding.go @@ -0,0 +1,220 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" +) + +// DS01-F2.a:CAS 点的实时租约判据。 +// +// 授权事务里的前几次租约检查发生在**拿 effect 行锁之前**;等锁可以跨过租约到期。 +// 因此拿到最后一个可能阻塞的锁之后必须按数据库时钟重读一次。这里的行都已经在 +// 本事务里持有锁,重读不会新增等待,也不改变 job→operation→maintenance→attempt→effect +// 的锁序。 +type restoreDispatchLeaseExpired struct { + reason string +} + +func (e *restoreDispatchLeaseExpired) Error() string { return e.reason } + +func restoreDispatchLeaseLive(ctx context.Context, tx pgx.Tx, until *time.Time) (bool, error) { + var live bool + if err := tx.QueryRow(ctx, + `SELECT COALESCE($1::timestamptz > clock_timestamp(), false)`, until).Scan(&live); err != nil { + return false, fmt.Errorf("read lease clock: %w", err) + } + return live, nil +} + +func recheckRestoreDispatchLeases(ctx context.Context, tx pgx.Tx, b libraryrelease.RestoreMarkerBinding) error { + var owner string + var epoch int64 + var leaseUntil *time.Time + err := tx.QueryRow(ctx, ` +SELECT lease_owner, attempt_epoch, lease_until FROM library_jobs WHERE id=$1`, + b.Key.WindowJobID).Scan(&owner, &epoch, &leaseUntil) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("window job %s disappeared", b.Key.WindowJobID) + } + if err != nil { + return fmt.Errorf("recheck window job lease: %w", err) + } + if owner != b.Owner || epoch != b.Epoch { + return &restoreDispatchLeaseExpired{reason: fmt.Sprintf( + "window job lease now belongs to %s#%d, not %s#%d", owner, epoch, b.Owner, b.Epoch)} + } + live, err := restoreDispatchLeaseLive(ctx, tx, leaseUntil) + if err != nil { + return err + } + if !live { + return &restoreDispatchLeaseExpired{reason: "window job lease expired while waiting for the dispatch CAS"} + } + + var attemptOwner string + var attemptEpoch int64 + var attemptLease *time.Time + err = tx.QueryRow(ctx, ` +SELECT owner, epoch, lease_until FROM library_attempts +WHERE operation_id=$1 AND state IN ('claimed','running') FOR UPDATE`, b.Key.OperationID).Scan( + &attemptOwner, &attemptEpoch, &attemptLease) + if errors.Is(err, pgx.ErrNoRows) { + return &restoreDispatchLeaseExpired{reason: fmt.Sprintf("no active attempt for operation %s", b.Key.OperationID)} + } + if err != nil { + return fmt.Errorf("recheck active attempt lease: %w", err) + } + if attemptOwner != b.Owner || attemptEpoch != b.Epoch { + return &restoreDispatchLeaseExpired{reason: fmt.Sprintf( + "active attempt is now %s#%d, not %s#%d", attemptOwner, attemptEpoch, b.Owner, b.Epoch)} + } + live, err = restoreDispatchLeaseLive(ctx, tx, attemptLease) + if err != nil { + return err + } + if !live { + return &restoreDispatchLeaseExpired{reason: "attempt lease expired while waiting for the dispatch CAS"} + } + + if b.RecoveryJobID != "" { + var deliveryOwner string + var deliveryAttempt int + var deliveryLease *time.Time + err = tx.QueryRow(ctx, `SELECT lease_owner, attempt, lease_until FROM jobs WHERE id=$1`, + b.RecoveryJobID).Scan(&deliveryOwner, &deliveryAttempt, &deliveryLease) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("recovery queue job %s disappeared", b.RecoveryJobID) + } + if err != nil { + return fmt.Errorf("recheck recovery queue lease: %w", err) + } + worker, ok := governance.ParseLibraryDeliveryOwner(b.Owner, b.RecoveryJobID, deliveryAttempt) + if !ok || worker != deliveryOwner { + return &restoreDispatchLeaseExpired{reason: fmt.Sprintf( + "recovery delivery %s attempt %d is not owned by %s", b.RecoveryJobID, deliveryAttempt, b.Owner)} + } + live, err = restoreDispatchLeaseLive(ctx, tx, deliveryLease) + if err != nil { + return err + } + if !live { + return &restoreDispatchLeaseExpired{reason: "recovery queue lease expired while waiting for the dispatch CAS"} + } + } + return nil +} + +// DS01-F2.b:恢复投递身份必须在**同一个 CAS 事务**里锁定并复核: +// queue → operation → 原 window/request_digest,再核当前 owner/attempt/lease。 +// +// 只验"queue 是 running 且 operation 是 recover 类型"会让一条本属于别的窗口的 +// 恢复投递借用本次 effect 的许可;worker 入口的先验校验(ValidateLibraryRecoveryQueue) +// 不能替代 CAS 点的实时授权。 +func lockAndVerifyRecoveryDelivery(ctx context.Context, tx pgx.Tx, b libraryrelease.RestoreMarkerBinding) error { + window := b.Key.WindowJobID + if b.RecoveryJobID != governance.LibraryRecoveryQueueID(window) { + return fmt.Errorf("recovery queue %s is not the registered queue for window %s", b.RecoveryJobID, window) + } + var queueType, queueState, payloadRaw, idempotency string + var leaseOwner string + var attempt int + var leaseUntil *time.Time + err := tx.QueryRow(ctx, ` +SELECT type, state, payload::text, COALESCE(lease_owner,''), attempt, lease_until, idempotency_key +FROM jobs WHERE id=$1 FOR UPDATE`, b.RecoveryJobID).Scan( + &queueType, &queueState, &payloadRaw, &leaseOwner, &attempt, &leaseUntil, &idempotency) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("recovery queue job %s does not exist", b.RecoveryJobID) + } + if err != nil { + return fmt.Errorf("lock recovery queue job: %w", err) + } + if queueType != "library.recover" || queueState != "running" { + return fmt.Errorf("recovery queue job %s is not a running delivery (type=%s state=%s)", + b.RecoveryJobID, queueType, queueState) + } + if idempotency != "library.recover:"+window { + return fmt.Errorf("recovery queue %s is not idempotency-bound to window %s", b.RecoveryJobID, window) + } + var payload map[string]string + if err := json.Unmarshal([]byte(payloadRaw), &payload); err != nil { + return fmt.Errorf("recovery queue payload is not a delivery claim: %w", err) + } + if payload["scope"] != b.Scope || payload["window_job_id"] != window { + return fmt.Errorf("recovery queue %s carries window %s/%s, not %s/%s", + b.RecoveryJobID, payload["window_job_id"], payload["scope"], window, b.Scope) + } + // 可选的锚点只要出现就必须与不可变绑定相同;缺省表示"由 journal/写集合决定"。 + for key, want := range map[string]string{ + "source_snapshot_id": b.SourceSnapshot, + "target_id": b.Key.TargetIdentity, + "original_operation_id": b.Key.OperationID, + "backup_snapshot_id": b.BackupSnapshot, + "plan_digest": b.Key.PlanDigest, + } { + if got := payload[key]; got != "" && got != want { + return fmt.Errorf("recovery queue %s declares %s=%s, binding is %s", + b.RecoveryJobID, key, got, want) + } + } + if _, ok := governance.ParseLibraryDeliveryOwner(b.Owner, b.RecoveryJobID, attempt); !ok { + return fmt.Errorf("recovery queue %s attempt %d is not the current delivery of %s", + b.RecoveryJobID, attempt, b.Owner) + } + if ownerWorker, _ := governance.ParseLibraryDeliveryOwner(b.Owner, b.RecoveryJobID, attempt); ownerWorker != leaseOwner { + return fmt.Errorf("recovery queue %s is leased by %q, not by the attempt owner %q", + b.RecoveryJobID, leaseOwner, ownerWorker) + } + live, err := restoreDispatchLeaseLive(ctx, tx, leaseUntil) + if err != nil { + return err + } + if !live { + return fmt.Errorf("recovery queue %s lease is expired", b.RecoveryJobID) + } + + var recoveryKind, recoveryScope, recoveryTarget, requestDigest, operationTarget string + err = tx.QueryRow(ctx, ` +SELECT kind, scope, target_snapshot_id, request_digest, COALESCE(target_id,'') +FROM library_operations WHERE id=$1 FOR UPDATE`, b.RecoveryOperationID).Scan( + &recoveryKind, &recoveryScope, &recoveryTarget, &requestDigest, &operationTarget) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("recovery operation %s does not exist", b.RecoveryOperationID) + } + if err != nil { + return fmt.Errorf("lock recovery operation: %w", err) + } + if recoveryKind != string(governance.LibraryJobRecover) || recoveryScope != b.Scope { + return fmt.Errorf("recovery operation %s is not a recover operation for scope %s", b.RecoveryOperationID, b.Scope) + } + if recoveryTarget != b.BackupSnapshot { + return fmt.Errorf("recovery operation %s restores %s, not the window backup %s", + b.RecoveryOperationID, recoveryTarget, b.BackupSnapshot) + } + if operationTarget != "" && operationTarget != b.Key.TargetIdentity { + return fmt.Errorf("recovery operation %s targets %s, not %s", + b.RecoveryOperationID, operationTarget, b.Key.TargetIdentity) + } + if requestDigest == "" { + return fmt.Errorf("recovery operation %s has no request digest anchor", b.RecoveryOperationID) + } + // 恢复请求摘要只能由原 window 的不可变锚点重算:queue/operation/window/原 operation/ + // 目标/来源/备份/写集合摘要。换任何一项都会得到另一份摘要。 + expected, err := governance.LibraryRecoveryDigest(b.Scope, b.RecoveryJobID, window, b.Key.OperationID, + b.Key.TargetIdentity, b.SourceSnapshot, b.BackupSnapshot, b.Key.PlanDigest) + if err != nil { + return fmt.Errorf("recompute recovery request digest: %w", err) + } + if requestDigest != expected { + return fmt.Errorf("recovery operation %s request digest is bound to another window/plan", b.RecoveryOperationID) + } + return nil +} diff --git a/internal/platform/postgres/library_restore_dispatch_final_binding_test.go b/internal/platform/postgres/library_restore_dispatch_final_binding_test.go new file mode 100644 index 0000000..c632da8 --- /dev/null +++ b/internal/platform/postgres/library_restore_dispatch_final_binding_test.go @@ -0,0 +1,349 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/version" +) + +// DS01-F2.b:恢复投递必须在 CAS 事务里与 queue→operation→原 window/摘要绑定。 +func TestRestoreDispatchRecoveryDeliveryIsBoundInTheCASTransaction(t *testing.T) { + type fixture struct { + store *Store + pool *pgxpool.Pool + binding libraryrelease.RestoreMarkerBinding + } + seeded := func(t *testing.T, jobID string) fixture { + t.Helper() + store, pool := newIdentityStore(t) + now := time.Now().UTC() + windowOp := seedOperationJob(t, store, pool, "internal", jobID, "sync", now) + queueID := governance.LibraryRecoveryQueueID(jobID) + owner := governance.LibraryDeliveryOwner("worker-r", queueID, 1) + if _, err := store.BeginLibraryAttempt(context.Background(), jobID, owner, 10*time.Minute, now); err != nil { + t.Fatalf("begin attempt: %v", err) + } + payload, _ := json.Marshal(map[string]string{"scope": "internal", "window_job_id": jobID}) + if _, err := pool.Exec(context.Background(), ` +INSERT INTO jobs (id, type, payload, state, lease_owner, lease_until, attempt, idempotency_key) +VALUES ($1,'library.recover',$2::jsonb,'running','worker-r',$3,1,$4)`, + queueID, string(payload), now.Add(10*time.Minute), "library.recover:"+jobID); err != nil { + t.Fatalf("seed recovery queue: %v", err) + } + recoveryOp := governance.LibraryOperationID("internal", governance.LibraryJobRecover, queueID) + digest, err := governance.LibraryRecoveryDigest("internal", queueID, jobID, windowOp, "target-ds01", + "snap-target", "snap-backup", "plan-1") + if err != nil { + t.Fatal(err) + } + if _, _, err := store.EnsureLibraryOperation(context.Background(), governance.LibraryOperation{ + ID: recoveryOp, Scope: "internal", Kind: governance.LibraryJobRecover, + TargetSnapshotID: "snap-backup", RequestDigest: digest, OperationKey: queueID, + Actor: "worker-r", CreatedAt: now, + }); err != nil { + t.Fatalf("seed recovery operation: %v", err) + } + binding := ds01Binding() + binding.Key.WindowJobID = jobID + binding.Key.OperationID = windowOp + binding.RecoveryJobID = queueID + binding.RecoveryOperationID = recoveryOp + binding.Owner = owner + binding.Epoch = 1 + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatalf("activate: %v", err) + } + return fixture{store: store, pool: pool, binding: binding} + } + expectRejected := func(t *testing.T, fx fixture) { + t.Helper() + if _, err := fx.store.PrepareRestoreMarker(context.Background(), fx.binding); err == nil { + t.Fatal("recovery delivery mismatch was accepted") + } + } + + t.Run("positive real recovery delivery prepares and acquires", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-ok") + if _, err := fx.store.PrepareRestoreMarker(context.Background(), fx.binding); err != nil { + t.Fatalf("valid recovery delivery: %v", err) + } + permit, _, err := fx.store.AcquireRestoreMarker(context.Background(), fx.binding) + if err != nil || permit == nil { + t.Fatalf("valid recovery delivery acquire: permit=%v err=%v", permit, err) + } + }) + t.Run("queue for another window is rejected", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-wrongqueue") + fx.binding.RecoveryJobID = governance.LibraryRecoveryQueueID("another-window") + expectRejected(t, fx) + }) + t.Run("payload window differs", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-wrongwindow") + if _, err := fx.pool.Exec(context.Background(), + `UPDATE jobs SET payload=jsonb_set(payload,'{window_job_id}','"other-window"') WHERE id=$1`, + fx.binding.RecoveryJobID); err != nil { + t.Fatal(err) + } + expectRejected(t, fx) + }) + t.Run("request digest belongs to another plan", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-wrongdigest") + if _, err := fx.pool.Exec(context.Background(), + `UPDATE library_operations SET request_digest='digest-other' WHERE id=$1`, fx.binding.RecoveryOperationID); err != nil { + t.Fatal(err) + } + expectRejected(t, fx) + }) + t.Run("queue leased by another worker", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-owner") + if _, err := fx.pool.Exec(context.Background(), + `UPDATE jobs SET lease_owner='intruder' WHERE id=$1`, fx.binding.RecoveryJobID); err != nil { + t.Fatal(err) + } + expectRejected(t, fx) + }) + t.Run("expired queue lease", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-expired") + if _, err := fx.pool.Exec(context.Background(), + `UPDATE jobs SET lease_until=now()-interval '1 minute' WHERE id=$1`, fx.binding.RecoveryJobID); err != nil { + t.Fatal(err) + } + expectRejected(t, fx) + }) + t.Run("operation restores another backup", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-backup") + if _, err := fx.pool.Exec(context.Background(), + `UPDATE library_operations SET target_snapshot_id='snap-other' WHERE id=$1`, fx.binding.RecoveryOperationID); err != nil { + t.Fatal(err) + } + expectRejected(t, fx) + }) + t.Run("binding plan differs from the recovery request", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-plan") + fx.binding.Key.PlanDigest = "plan-other" + expectRejected(t, fx) + }) + t.Run("queue is not running", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-state") + if _, err := fx.pool.Exec(context.Background(), + `UPDATE jobs SET state='pending', lease_owner='', lease_until=NULL WHERE id=$1`, fx.binding.RecoveryJobID); err != nil { + t.Fatal(err) + } + expectRejected(t, fx) + }) + t.Run("operation is not a recovery", func(t *testing.T) { + fx := seeded(t, "libsync-ds01-recovery-kind") + if _, err := fx.pool.Exec(context.Background(), + `UPDATE library_operations SET kind='sync' WHERE id=$1`, fx.binding.RecoveryOperationID); err != nil { + t.Fatal(err) + } + expectRejected(t, fx) + }) +} + +// DS01-F3.identity:激活与使用点都必须核治理权威域(集群+库 OID)、primary 与完整 +// 构建 SHA;同 display 不同不兼容 SHA、unknown、同名错域、错目标一律零激活/零许可。 +func TestRestoreDispatchGovernanceAuthorityAndBuildIdentity(t *testing.T) { + store, pool := newIdentityStore(t) + // 使用点会读运行构建身份:测试进程由 runner 注入完整 SHA,这里核一下前提。 + if !version.HasInjection() || len(version.CommitSHA) != 40 { + t.Skip("requires an injected full commit sha (run via the version-injecting runner)") + } + ctx := context.Background() + now := time.Now().UTC() + job := "authority-window" + if _, err := pool.Exec(ctx, ` +INSERT INTO library_instance_maintenance (instance, owner_job_id, owner_scope, target_fingerprint, level, + services, ingress_state, state, original_service_state, note, acquired_at, updated_at) +VALUES ($1,$2,'internal',$3,'instance',$4::jsonb,'closed','needs_restore','','',now()-interval '20 minutes',now())`, + ds01TestInstance, job, ds01TestFingerprint, `["`+ds01TestWriter+`"]`); err != nil { + t.Fatalf("seed maintenance window: %v", err) + } + dir, _, journalDigest := ds01Journal(t, job, nil) + toStore := store.WithRestoreDispatchEvidence(dir) + target := "target-ds01-authority" + // 维护窗口指纹(journal/维护行)与恢复目标指纹是两层:本用例刻意让它们不同, + // 使用点必须核恢复目标指纹,不能拿窗口指纹顶替。 + const restoreTargetFingerprint = ds01TestFingerprintOther + base := func() libraryrelease.RestoreDispatchActivationEvidence { + evidence := ds01ActivationEvidence(t, store, target, ds01TestFingerprint, job, journalDigest) + evidence.RestoreTargetFingerprint = restoreTargetFingerprint + return evidence + } + activate := func(evidence libraryrelease.RestoreDispatchActivationEvidence) error { + t.Helper() + path, digest := writeDS01ActivationEvidence(t, evidence) + return toStore.ActivateRestoreDispatch(ctx, path, digest, target, restoreTargetFingerprint, now) + } + count := func() int { + t.Helper() + var n int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM library_index_restore_dispatch_activation`).Scan(&n); err != nil { + t.Fatal(err) + } + return n + } + + // 1) 同名库、不同集群:库名相同但 system_identifier 不同。 + evidence := base() + evidence.GovernanceAuthority.SystemIdentifier = "1" + if err := activate(evidence); err == nil || !strings.Contains(err.Error(), "governance authority") { + t.Fatalf("same-name other-cluster evidence = %v", err) + } + // 2) 同集群、另一个同名库(OID 不同)。 + evidence = base() + evidence.GovernanceAuthority.DatabaseOID = "1" + if err := activate(evidence); err == nil || !strings.Contains(err.Error(), "governance authority") { + t.Fatalf("same-name other-database evidence = %v", err) + } + // 3) unknown 构建身份。 + evidence = base() + evidence.ProtocolBuildSHA = "unknown" + if err := activate(evidence); err == nil || !strings.Contains(err.Error(), "commit sha") { + t.Fatalf("unknown build sha evidence = %v", err) + } + // 4) 同 display、不同 SHA、不同协议批次:不兼容,必须拒绝。 + evidence = base() + evidence.ProtocolBuild = version.DisplayVersion() + evidence.ProtocolBuildSHA = strings.Repeat("b", 40) + evidence.ProtocolEpoch = libraryrelease.RestoreDispatchProtocolEpoch - 1 + if err := activate(evidence); err == nil || !strings.Contains(err.Error(), "epoch") { + t.Fatalf("same-display incompatible build = %v", err) + } + if n := count(); n != 0 { + t.Fatalf("rejected evidence created %d activation rows", n) + } + + // 5) 同一协议批次、任意 40 位 SHA:epoch 相等不能替代构建身份证明,必须拒绝。 + // 原实现只凭 epoch==3 就接受任何 SHA(compatible_upgrade=true),换一个 SHA 即可 + // 绕开同 SHA display 绑定;本轮关闭这条无证据的跨 SHA 自动兼容。 + evidence = base() + evidence.ProtocolBuild = version.DisplayVersion() + evidence.ProtocolBuildSHA = strings.Repeat("b", 40) + if err := activate(evidence); err == nil || !strings.Contains(err.Error(), "cross-sha") { + t.Fatalf("same-epoch unknown build sha was accepted: %v", err) + } + + // 6) 同 SHA、错 display:运行二进制身份必须自洽。 + evidence = base() + evidence.ProtocolBuild = "0.1.999-wrong" + if err := activate(evidence); err == nil || !strings.Contains(err.Error(), "display") { + t.Fatalf("same-sha wrong display = %v", err) + } + if n := count(); n != 0 { + t.Fatalf("rejected evidence created %d activation rows", n) + } + + // 7) 同 SHA、同 display:唯一允许的绑定;台账不得再声明 compatible_upgrade。 + if err := activate(base()); err != nil { + t.Fatalf("same-sha activation: %v", err) + } + var stored string + if err := pool.QueryRow(ctx, `SELECT evidence::text FROM library_index_restore_dispatch_activation WHERE target_identity=$1`, target).Scan(&stored); err != nil { + t.Fatal(err) + } + compact := strings.ReplaceAll(stored, " ", "") + if !strings.Contains(compact, `"compatible_upgrade":false`) || + !strings.Contains(compact, `"protocol_build_sha":"`+version.CommitSHA+`"`) || + !strings.Contains(compact, `"system_identifier":"`+base().GovernanceAuthority.SystemIdentifier+`"`) { + t.Fatalf("activation record does not state the exact build/authority: %s", stored) + } + + // 使用点正例:与激活相同的 SHA 下真实窗口可以准备/取得许可。 + windowOp := seedOperationJob(t, store, pool, "internal", "libsync-ds01-authority", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-authority", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-authority" + binding.Key.OperationID = windowOp + binding.Key.TargetIdentity = target + // 本次恢复对目标的现场观察是 restoreTargetFingerprint(不是维护窗口指纹)。 + binding.TargetFingerprint = restoreTargetFingerprint + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatalf("use point rejected a compatible build: %v", err) + } + if permit, _, err := store.AcquireRestoreMarker(ctx, binding); err != nil || permit == nil { + t.Fatalf("use point acquire under compatible build: permit=%v err=%v", permit, err) + } + + // 使用点反例:把登记行篡改成错域/错批次/unknown 构建,Prepare 必须零许可失败。 + tamperTargets := map[string]func(map[string]any){ + "target-ds01-tamper-domain": func(v map[string]any) { + authority, _ := v["governance_authority"].(map[string]any) + authority["system_identifier"] = "1" + }, + "target-ds01-tamper-epoch": func(v map[string]any) { + v["protocol_epoch"] = float64(libraryrelease.RestoreDispatchProtocolEpoch - 1) + }, + "target-ds01-tamper-sha": func(v map[string]any) { + v["protocol_build_sha"] = "unknown" + }, + "target-ds01-tamper-cross-sha": func(v map[string]any) { + // 同一协议批次下换一个合法 40 位 SHA:使用点必须与激活点同样拒绝。 + v["protocol_build_sha"] = strings.Repeat("c", 40) + }, + "target-ds01-tamper-display": func(v map[string]any) { + // 同 SHA、错 display:使用点也必须核运行 display,不能只看 SHA。 + v["protocol_build"] = "0.1.999-wrong" + }, + } + for tamperTarget, mutate := range tamperTargets { + var record map[string]any + if err := json.Unmarshal([]byte(stored), &record); err != nil { + t.Fatal(err) + } + verified, _ := record["verified"].(map[string]any) + mutate(verified) + raw, err := json.Marshal(record) + if err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, ` +INSERT INTO library_index_restore_dispatch_activation + (target_identity, protocol_version, target_fingerprint, target_instance, governance_database, + protocol_build, activated_by, drain_evidence_digest, evidence, attested_at, activated_at) +SELECT $1, protocol_version, target_fingerprint, target_instance, governance_database, + protocol_build, activated_by, drain_evidence_digest, $2::jsonb, attested_at, activated_at +FROM library_index_restore_dispatch_activation WHERE target_identity=$3`, + tamperTarget, string(raw), target); err != nil { + t.Fatalf("insert tampered activation %s: %v", tamperTarget, err) + } + tampered := binding + tampered.Key.TargetIdentity = tamperTarget + if permit, _, err := store.AcquireRestoreMarker(ctx, tampered); permit != nil || err == nil { + t.Fatalf("use point accepted tampered activation %s: permit=%v err=%v", tamperTarget, permit, err) + } + } + + // 使用点错目标:同一激活行但本次观察的目标指纹不同(第三个指纹,既非窗口也非登记值)。 + wrongTarget := binding + wrongTarget.Key.DocumentID = "doc-other-target" + wrongTarget.TargetFingerprint = strings.Repeat("3", 64) + if permit, _, err := store.AcquireRestoreMarker(ctx, wrongTarget); permit != nil || err == nil { + t.Fatalf("use point accepted another target fingerprint: permit=%v err=%v", permit, err) + } + + // 运行构建 unknown:即使已有合法登记,使用点也必须失败关闭。 + originalSHA := version.CommitSHA + version.CommitSHA = "unknown" + t.Cleanup(func() { version.CommitSHA = originalSHA }) + unknown := binding + unknown.Key.DocumentID = "doc-unknown-build" + permit, _, err := store.AcquireRestoreMarker(ctx, unknown) + if permit != nil || err == nil { + t.Fatalf("use point accepted an unknown running build: permit=%v err=%v", permit, err) + } + if errors.Is(err, libraryrelease.ErrRestoreDispatchHeld) { + t.Log("unknown build rejected as held (expected fail-closed)") + } +} diff --git a/internal/platform/postgres/library_restore_dispatch_g1_test.go b/internal/platform/postgres/library_restore_dispatch_g1_test.go new file mode 100644 index 0000000..f37daa5 --- /dev/null +++ b/internal/platform/postgres/library_restore_dispatch_g1_test.go @@ -0,0 +1,255 @@ +package postgres + +import ( + "context" + "encoding/binary" + "errors" + "io" + "net" + "net/url" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/libraryrelease" +) + +// G1:真实 PG 的"COMMIT 已到服务端、客户端收不到成功回包"。beforeCommit 钩子做不到 +// 这一点(它根本没调用 Commit)。这里用专用 TCP 转发代理:看到客户端 commit 帧后 +// 原样转发,然后立刻切断连接——服务端已提交,客户端拿到的是错误。 + +func startCommitAckDropProxy(t *testing.T, upstreamHostPort string) (string, *sync.WaitGroup) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for { + client, err := listener.Accept() + if err != nil { + return + } + go func() { + defer client.Close() + server, err := net.Dial("tcp", upstreamHostPort) + if err != nil { + return + } + defer server.Close() + var once sync.Once + go func() { + // 服务端 -> 客户端:正常转发;代理被关闭后自然结束。 + _, _ = io.Copy(client, server) + }() + buffer := make([]byte, 32*1024) + for { + n, err := client.Read(buffer) + if n > 0 { + chunk := buffer[:n] + drop := onceFrames(chunk, &once) + if _, werr := server.Write(chunk); werr != nil { + return + } + if drop { + // commit 已经交给服务端;不给客户端任何成功回包。 + _ = client.Close() + return + } + } + if err != nil { + return + } + } + }() + } + }() + t.Cleanup(func() { + _ = listener.Close() + wg.Wait() + }) + return "127.0.0.1:" + strings.Split(listener.Addr().String(), ":")[1], nil +} + +// onceFrames 在客户端字节流里找简单查询帧 'Q' 且语句以 commit 开头。找到一次就返回 +// true(后续帧不再触发)。 +func onceFrames(chunk []byte, once *sync.Once) bool { + for i := 0; i+5 <= len(chunk); i++ { + if chunk[i] != 'Q' { + continue + } + length := int(binary.BigEndian.Uint32(chunk[i+1 : i+5])) + if length < 5 || i+1+length > len(chunk) { + continue + } + sql := strings.TrimSpace(strings.ToLower(string(chunk[i+5 : i+1+length]))) + if strings.HasPrefix(sql, "commit") { + triggered := false + once.Do(func() { triggered = true }) + return triggered + } + } + return false +} + +func proxyStore(t *testing.T, direct *pgxpool.Pool) (*Store, *pgxpool.Pool) { + t.Helper() + conn := direct.Config().ConnConfig + address, _ := startCommitAckDropProxy(t, net.JoinHostPort(conn.Host, strconv.Itoa(int(conn.Port)))) + target := url.URL{Scheme: "postgres", User: url.UserPassword(conn.User, conn.Password), + Host: address, Path: "/" + conn.Database} + query := target.Query() + for key, value := range conn.RuntimeParams { + query.Set(key, value) + } + query.Set("sslmode", "disable") + target.RawQuery = query.Encode() + pool, err := pgxpool.New(context.Background(), target.String()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + return NewStore(pool), pool +} + +func TestRestoreDispatchCommitAckLossKeepsDispatchingAndNoPermit(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-ackloss", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-ackloss", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-ackloss" + binding.Key.OperationID = seededOperationID(t, pool, binding.Key.WindowJobID) + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + + proxied, _ := proxyStore(t, pool) + permit, status, err := proxied.AcquireRestoreMarker(ctx, binding) + if err == nil { + t.Fatal("commit acknowledgement loss reported success") + } + if permit != nil { + t.Fatal("a send permit was issued although the client never saw COMMIT succeed") + } + if status.State != libraryrelease.RestoreDispatchDispatching || !status.Held { + t.Fatalf("status after ack loss = %+v", status) + } + // 服务端确实已提交:换一条直连读回 durable dispatching。 + time.Sleep(300 * time.Millisecond) + var state string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&state); err != nil { + t.Fatal(err) + } + if state != libraryrelease.RestoreDispatchDispatching { + t.Fatalf("server-side state after committed-but-unacknowledged commit = %s", state) + } + // 下一次调用(直连)不能把 dispatching 当 prepared 再发一次。 + permit, _, err = store.AcquireRestoreMarker(ctx, binding) + if permit != nil || !errors.Is(err, libraryrelease.ErrRestoreDispatchHeld) { + t.Fatalf("next call after ack loss = permit=%v err=%v", permit, err) + } +} + +func TestRestoreDispatchUndecidedTransactionBlocksThenFollowsRealOutcome(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-undecided", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-undecided", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-undecided" + binding.Key.OperationID = seededOperationID(t, pool, binding.Key.WindowJobID) + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + + // 原事务仍未决:另一条连接已经把行推进到 dispatching,但没有 commit。 + open, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := open.Exec(ctx, ` +UPDATE library_index_restore_dispatch +SET state='dispatching', dispatch_owner='old', dispatch_epoch=1, dispatch_nonce='old-nonce', + request_digest='old-request', dispatch_committed_at=clock_timestamp() +WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 AND plan_digest=$4 + AND index_name=$5 AND document_id=$6 AND phase=$7`, + binding.Key.TargetIdentity, binding.Key.OperationID, binding.Key.WindowJobID, binding.Key.PlanDigest, + binding.Key.Index, binding.Key.DocumentID, binding.Key.Phase); err != nil { + t.Fatal(err) + } + type result struct { + permit *libraryrelease.RestoreSendPermit + err error + } + done := make(chan result, 1) + go func() { + permit, _, err := store.AcquireRestoreMarker(ctx, binding) + done <- result{permit, err} + }() + select { + case got := <-done: + t.Fatalf("acquire returned while the original transaction was undecided: permit=%v err=%v", got.permit, got.err) + case <-time.After(700 * time.Millisecond): + } + if err := open.Rollback(ctx); err != nil { + t.Fatal(err) + } + got := <-done + if got.err != nil || got.permit == nil { + t.Fatalf("after a real rollback the call should win once: permit=%v err=%v", got.permit, got.err) + } + + // 第二个 effect:原事务选择 COMMIT,后续调用必须看到 dispatching 而不是 prepared。 + second := binding + second.Key.DocumentID = "doc-2" + if _, err := store.PrepareRestoreMarker(ctx, second); err != nil { + t.Fatal(err) + } + open2, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := open2.Exec(ctx, ` +UPDATE library_index_restore_dispatch +SET state='dispatching', dispatch_owner='old', dispatch_epoch=1, dispatch_nonce='old-nonce-2', + request_digest='old-request-2', dispatch_committed_at=clock_timestamp() +WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 AND plan_digest=$4 + AND index_name=$5 AND document_id=$6 AND phase=$7`, + second.Key.TargetIdentity, second.Key.OperationID, second.Key.WindowJobID, second.Key.PlanDigest, + second.Key.Index, second.Key.DocumentID, second.Key.Phase); err != nil { + t.Fatal(err) + } + done2 := make(chan result, 1) + go func() { + permit, _, err := store.AcquireRestoreMarker(ctx, second) + done2 <- result{permit, err} + }() + time.Sleep(500 * time.Millisecond) + if err := open2.Commit(ctx); err != nil { + t.Fatal(err) + } + got2 := <-done2 + if got2.permit != nil || !errors.Is(got2.err, libraryrelease.ErrRestoreDispatchHeld) { + t.Fatalf("after a real commit the call must not treat dispatching as prepared: permit=%v err=%v", got2.permit, got2.err) + } +} diff --git a/internal/platform/postgres/library_restore_dispatch_linearization_test.go b/internal/platform/postgres/library_restore_dispatch_linearization_test.go new file mode 100644 index 0000000..aa7b1fd --- /dev/null +++ b/internal/platform/postgres/library_restore_dispatch_linearization_test.go @@ -0,0 +1,585 @@ +package postgres + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" +) + +// DS01-F2:授权必须在**同一个 CAS 事务**里与撤销线性化,lease 必须用数据库实时 +// 时钟。以下都用真 PG 的锁等待,不用 scripted fake。 + +// 撤销先完成:Acquire 已经在事务里排队等 job 锁,撤销此时提交。CAS 不得再发许可。 +func TestRestoreDispatchRevocationWinsBeforeCASIsRejected(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-revoke-race", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-revoke-race", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-revoke-race" + binding.Key.OperationID = seededOperationID(t, pool, binding.Key.WindowJobID) + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + + lock, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := lock.Exec(ctx, `SELECT id FROM library_jobs WHERE id=$1 FOR UPDATE`, binding.Key.WindowJobID); err != nil { + t.Fatal(err) + } + type result struct { + permit *libraryrelease.RestoreSendPermit + err error + } + done := make(chan result, 1) + go func() { + permit, _, err := store.AcquireRestoreMarker(ctx, binding) + done <- result{permit, err} + }() + time.Sleep(400 * time.Millisecond) + if err := store.RevokeRestoreDispatch(ctx, "target-ds01", now); err != nil { + t.Fatalf("revoke: %v", err) + } + if err := lock.Rollback(ctx); err != nil { + t.Fatal(err) + } + got := <-done + if got.permit != nil { + t.Fatal("revocation committed before the CAS but a send permit was still issued") + } + if !errors.Is(got.err, libraryrelease.ErrRestoreDispatchUnavailable) { + t.Fatalf("revocation race error = %v", got.err) + } + var state string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&state); err != nil { + t.Fatal(err) + } + if state != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("row advanced to %s after a winning revocation", state) + } +} + +// CAS 先线性化:Acquire 已经锁住激活行、正在等 effect 行;撤销必须排队。CAS 提交后 +// 许可属于一次已派发,第二次调用必须 held。 +func TestRestoreDispatchCASWinsBeforeRevocationIssuesOnePermit(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-cas-race", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-cas-race", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-cas-race" + binding.Key.OperationID = seededOperationID(t, pool, binding.Key.WindowJobID) + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + + lock, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := lock.Exec(ctx, `SELECT id FROM library_index_restore_dispatch WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 AND plan_digest=$4 AND index_name=$5 AND document_id=$6 AND phase=$7 FOR UPDATE`, + binding.Key.TargetIdentity, binding.Key.OperationID, binding.Key.WindowJobID, binding.Key.PlanDigest, + binding.Key.Index, binding.Key.DocumentID, binding.Key.Phase); err != nil { + t.Fatal(err) + } + type result struct { + permit *libraryrelease.RestoreSendPermit + err error + } + acquired := make(chan result, 1) + go func() { + permit, _, err := store.AcquireRestoreMarker(ctx, binding) + acquired <- result{permit, err} + }() + time.Sleep(400 * time.Millisecond) + revoked := make(chan error, 1) + go func() { revoked <- store.RevokeRestoreDispatch(ctx, "target-ds01", now) }() + time.Sleep(400 * time.Millisecond) + if err := lock.Commit(ctx); err != nil { + t.Fatal(err) + } + got := <-acquired + if got.err != nil || got.permit == nil { + t.Fatalf("CAS should have won: permit=%v err=%v", got.permit, got.err) + } + if err := <-revoked; err != nil { + t.Fatalf("revocation after CAS: %v", err) + } + permit, _, err := store.AcquireRestoreMarker(ctx, binding) + if permit != nil || err == nil { + t.Fatalf("second acquire after dispatching = permit=%v err=%v", permit, err) + } + var state string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&state); err != nil { + t.Fatal(err) + } + if state != libraryrelease.RestoreDispatchDispatching { + t.Fatalf("state = %s", state) + } +} + +// 等锁跨过租约:事务开始时刻仍有效、真正做 CAS 时已过期。必须用数据库实时时钟拒绝。 +func TestRestoreDispatchLeaseExpiryWhileWaitingForLockIsRejected(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-lease", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-lease", "worker-a#q1#0", 500*time.Millisecond, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-lease" + binding.Key.OperationID = seededOperationID(t, pool, binding.Key.WindowJobID) + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + lock, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := lock.Exec(ctx, `SELECT id FROM library_jobs WHERE id=$1 FOR UPDATE`, binding.Key.WindowJobID); err != nil { + t.Fatal(err) + } + type result struct { + permit *libraryrelease.RestoreSendPermit + err error + } + done := make(chan result, 1) + go func() { + permit, _, err := store.AcquireRestoreMarker(ctx, binding) + done <- result{permit, err} + }() + time.Sleep(900 * time.Millisecond) + if err := lock.Rollback(ctx); err != nil { + t.Fatal(err) + } + got := <-done + if got.permit != nil { + t.Fatal("permit issued although the attempt lease expired while waiting for the job lock") + } + if got.err == nil || (!strings.Contains(got.err.Error(), "not current") && + !strings.Contains(got.err.Error(), "lease expired")) { + t.Fatalf("expired lease error = %v", got.err) + } +} + +// 等锁跨过租约(effect 行):前面的检查发生在拿 effect 锁之前,全部通过;真正等 +// effect 行锁时租约到期。CAS 点必须按数据库实时时钟重核,零许可、状态保持 prepared。 +func TestRestoreDispatchLeaseExpiryWhileWaitingForEffectLockIsRejected(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-effect-lease", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-effect-lease", "worker-a#q1#0", 1500*time.Millisecond, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-effect-lease" + binding.Key.OperationID = seededOperationID(t, pool, binding.Key.WindowJobID) + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + lock, err := pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := lock.Exec(ctx, `SELECT id FROM library_index_restore_dispatch WHERE target_identity=$1 AND operation_id=$2 AND window_job_id=$3 AND plan_digest=$4 AND index_name=$5 AND document_id=$6 AND phase=$7 FOR UPDATE`, + binding.Key.TargetIdentity, binding.Key.OperationID, binding.Key.WindowJobID, binding.Key.PlanDigest, + binding.Key.Index, binding.Key.DocumentID, binding.Key.Phase); err != nil { + t.Fatal(err) + } + type result struct { + permit *libraryrelease.RestoreSendPermit + err error + } + done := make(chan result, 1) + go func() { + permit, _, err := store.AcquireRestoreMarker(ctx, binding) + done <- result{permit, err} + }() + time.Sleep(2200 * time.Millisecond) + if err := lock.Rollback(ctx); err != nil { + t.Fatal(err) + } + got := <-done + if got.permit != nil { + t.Fatal("permit issued although the attempt lease expired while waiting for the effect row lock") + } + if got.err == nil || !strings.Contains(got.err.Error(), "expired while waiting for the dispatch CAS") { + t.Fatalf("expired effect-lock wait error = %v", got.err) + } + var state string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&state); err != nil { + t.Fatal(err) + } + if state != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("state = %s after a rejected CAS", state) + } +} + +// 错目标/错来源/换 plan 别名/错 UUID 都必须在 CAS 前失败,且台账不动。 +func TestRestoreDispatchRejectsWrongAnchorsAndPlanAlias(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-anchors", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-anchors", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-anchors" + binding.Key.OperationID = seededOperationID(t, pool, binding.Key.WindowJobID) + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + + wrongSource := binding + wrongSource.SourceSnapshot = "snap-other" + if permit, _, err := store.AcquireRestoreMarker(ctx, wrongSource); permit != nil || err == nil { + t.Fatalf("wrong source acquired: permit=%v err=%v", permit, err) + } + wrongUUID := binding + wrongUUID.IndexUUID = "uuid-replaced" + if permit, _, err := store.AcquireRestoreMarker(ctx, wrongUUID); permit != nil || + !errors.Is(err, libraryrelease.ErrRestoreDispatchHeld) { + t.Fatalf("replaced index uuid acquired: permit=%v err=%v", permit, err) + } + wrongFingerprint := binding + wrongFingerprint.TargetFingerprint = ds01TestFingerprintOther + if permit, _, err := store.AcquireRestoreMarker(ctx, wrongFingerprint); permit != nil || err == nil { + t.Fatalf("replaced target fingerprint acquired: permit=%v err=%v", permit, err) + } + alias := binding + alias.Key.PlanDigest = "plan-alias" + if _, err := store.PrepareRestoreMarker(ctx, alias); err == nil || + !strings.Contains(err.Error(), "another plan") { + t.Fatalf("plan alias was accepted: %v", err) + } + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM library_index_restore_dispatch`).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 1 { + t.Fatalf("dispatch rows = %d, want exactly the original plan row", count) + } + // 恢复投递身份缺失:Prepare 就必须失败,不能等到发送前。 + recovery := binding + recovery.RecoveryJobID = "queue-missing" + recovery.RecoveryOperationID = "op-missing" + if _, err := store.PrepareRestoreMarker(ctx, recovery); err == nil { + t.Fatal("unknown recovery delivery identity was accepted") + } + // 形状合法但与本 window 无关的 recovery queue/operation:同样零许可。 + // 真正绑定成功的正例在 TestRestoreDispatchRecoveryDeliveryIsBoundInTheCASTransaction。 + queueID := governance.LibraryRecoveryQueueID(binding.Key.WindowJobID) + if _, err := pool.Exec(ctx, `INSERT INTO jobs (id, type, payload, state, lease_owner, idempotency_key) +VALUES ($1,'library.recover',$2::jsonb,'running','worker-a',$3)`, + "queue-recovery-unrelated", `{"scope":"internal","window_job_id":"another-window"}`, + "library.recover:another-window"); err != nil { + t.Fatal(err) + } + if _, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ + ID: "op-recovery-unrelated", Scope: "internal", Kind: governance.LibraryJobRecover, + TargetSnapshotID: "snap-backup", RequestDigest: "digest-recovery", OperationKey: "recovery-unrelated", + Actor: "tester", CreatedAt: now.UTC(), + }); err != nil { + t.Fatal(err) + } + unrelated := binding + unrelated.Key.DocumentID = "doc-recovery" + unrelated.RecoveryJobID = "queue-recovery-unrelated" + unrelated.RecoveryOperationID = "op-recovery-unrelated" + if _, err := store.PrepareRestoreMarker(ctx, unrelated); err == nil { + t.Fatal("recovery delivery for another window was accepted") + } + // 正确 queue 但 recovery operation 指向原业务 operation:不是恢复请求,必须拒绝。 + wrongOperation := binding + wrongOperation.Key.DocumentID = "doc-recovery-2" + wrongOperation.RecoveryJobID = queueID + wrongOperation.RecoveryOperationID = binding.Key.OperationID + if _, err := store.PrepareRestoreMarker(ctx, wrongOperation); err == nil { + t.Fatal("non-recovery operation was accepted as a recovery delivery") + } +} + +// DS01-F3:撤销是终局——SQL 不能把 revoked_at 改回 NULL,也不能删掉整行;down 在 +// 只有 activation 证据时同样拒绝。 +func TestRestoreDispatchActivationCannotBeResetOrDeleted(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + if err := store.RevokeRestoreDispatch(ctx, "target-ds01", now); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `UPDATE library_index_restore_dispatch_activation SET revoked_at=NULL WHERE target_identity=$1`, "target-ds01"); err == nil { + t.Fatal("revoked_at was reset to NULL") + } + if _, err := pool.Exec(ctx, `DELETE FROM library_index_restore_dispatch_activation WHERE target_identity=$1`, "target-ds01"); err == nil { + t.Fatal("activation row was deleted") + } + down, err := os.ReadFile("migrations/000078_library_restore_dispatch.down.sql") + if err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, string(down)); err == nil || + !strings.Contains(err.Error(), "activation evidence") { + t.Fatalf("down with activation-only evidence = %v", err) + } + var revoked *time.Time + if err := pool.QueryRow(ctx, `SELECT revoked_at FROM library_index_restore_dispatch_activation WHERE target_identity=$1`, "target-ds01").Scan(&revoked); err != nil { + t.Fatal(err) + } + if revoked == nil { + t.Fatal("revocation evidence did not survive") + } +} + +// DS01-F3:激活门只消费真实维护 journal + 治理库维护行。下面每个反例都只改 +// 原始证据的一个真实维度(摘要、文件字节、writer 集合、退出、排空、时间、库身份、 +// 维护窗口状态),并且都要求"零 activation 行"。 +func TestRestoreDispatchActivationRequiresVerifiableEvidence(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + job := "activation-window" + if _, err := pool.Exec(ctx, ` +INSERT INTO library_instance_maintenance (instance, owner_job_id, owner_scope, target_fingerprint, level, + services, ingress_state, state, original_service_state, note, acquired_at, updated_at) +VALUES ($1,$2,'internal',$3,'instance',$4::jsonb,'closed','needs_restore','','',now()-interval '20 minutes',now())`, + ds01TestInstance, job, ds01TestFingerprint, `["`+ds01TestWriter+`"]`); err != nil { + t.Fatalf("seed maintenance window: %v", err) + } + dir, _, digest := ds01Journal(t, job, nil) + toStore := store.WithRestoreDispatchEvidence(dir) + target := "target-ds01-b" + validB := func() libraryrelease.RestoreDispatchActivationEvidence { + return ds01ActivationEvidence(t, store, target, ds01TestFingerprint, job, digest) + } + activateB := func(t *testing.T, evidence libraryrelease.RestoreDispatchActivationEvidence, evidenceDigest, fingerprint string) error { + t.Helper() + path, d := writeDS01ActivationEvidence(t, evidence) + if evidenceDigest != "" { + d = evidenceDigest + } + if fingerprint == "" { + fingerprint = ds01TestFingerprint + } + return toStore.ActivateRestoreDispatch(ctx, path, d, target, fingerprint, now) + } + // 未配置受信 journal 根:必须明确关闭,而不是退回只看字符串。 + noRootPath, noRootDigest := writeDS01ActivationEvidence(t, validB()) + if err := store.ActivateRestoreDispatch(ctx, noRootPath, noRootDigest, target, ds01TestFingerprint, now); !errors.Is(err, ErrRestoreDispatchActivationDisabled) { + t.Fatalf("activation without a trusted evidence root = %v", err) + } + // 证据文件摘要错误 + if err := activateB(t, validB(), "deadbeef", ""); err == nil { + t.Fatal("wrong evidence digest was accepted") + } + assertActivationCount(t, pool, 0) + forged := strings.Repeat("ab", 32) + evidence := validB() + evidence.MaintenanceJournalSHA256 = forged + if err := activateB(t, evidence, "", ""); err == nil { + t.Fatal("forged journal digest was accepted") + } + assertActivationCount(t, pool, 0) + + // 真实文件在摘要计算后被替换:摘要必须打在磁盘字节上。 + evidence = validB() + replacedDir := t.TempDir() + if err := os.Chmod(replacedDir, 0o700); err != nil { + t.Fatal(err) + } + original, _ := os.ReadFile(dir + "/" + job + ".json") + if err := os.WriteFile(replacedDir+"/"+job+".json", original, 0o600); err != nil { + t.Fatal(err) + } + replacedSum := sha256.Sum256(original) + evidence.MaintenanceJournalSHA256 = hex.EncodeToString(replacedSum[:]) + replacement, _, _ := ds01Journal(t, job, func(j map[string]any) { + j["gate"].(map[string]any)["served"] = 99 + }) + replacementBytes, _ := os.ReadFile(replacement + "/" + job + ".json") + if err := os.WriteFile(replacedDir+"/"+job+".json", replacementBytes, 0o600); err != nil { + t.Fatal(err) + } + if err := store.WithRestoreDispatchEvidence(replacedDir).ActivateRestoreDispatch(ctx, + func() string { p, _ := writeDS01ActivationEvidence(t, evidence); return p }(), + func() string { _, d := writeDS01ActivationEvidence(t, evidence); return d }(), target, ds01TestFingerprint, now); err == nil { + t.Fatal("journal replaced after the digest was computed was accepted") + } + assertActivationCount(t, pool, 0) + + // 错 writer 集合:名字不在治理库维护行里 / 实例不在 journal 里。 + evidence = validB() + evidence.Writers[0].Name = "writer-2" + if err := activateB(t, evidence, "", ""); err == nil { + t.Fatal("writer outside the maintenance window set was accepted") + } + evidence = validB() + evidence.Writers[0].InstanceID = "writer-9" + if err := activateB(t, evidence, "", ""); err == nil { + t.Fatal("writer instance absent from the journal was accepted") + } + // 未退出:没有退出码 / 从未要求停。 + noExitDir, _, noExitDigest := ds01Journal(t, job, func(j map[string]any) { + delete(j["services"].([]any)[0].(map[string]any), "exit_code") + }) + evidence = validB() + evidence.MaintenanceJournalSHA256 = noExitDigest + if err := store.WithRestoreDispatchEvidence(noExitDir).ActivateRestoreDispatch(ctx, + func() string { p, _ := writeDS01ActivationEvidence(t, evidence); return p }(), + func() string { _, d := writeDS01ActivationEvidence(t, evidence); return d }(), target, ds01TestFingerprint, now); err == nil { + t.Fatal("writer without an observed exit code was accepted") + } + notAskedDir, _, notAskedDigest := ds01Journal(t, job, func(j map[string]any) { + j["services"].([]any)[0].(map[string]any)["stop_requested"] = false + delete(j["services"].([]any)[0].(map[string]any), "exit_code") + }) + evidence = validB() + evidence.MaintenanceJournalSHA256 = notAskedDigest + if err := store.WithRestoreDispatchEvidence(notAskedDir).ActivateRestoreDispatch(ctx, + func() string { p, _ := writeDS01ActivationEvidence(t, evidence); return p }(), + func() string { _, d := writeDS01ActivationEvidence(t, evidence); return d }(), target, ds01TestFingerprint, now); err == nil { + t.Fatal("writer never asked to stop was accepted") + } + // 未排空:入口未耗尽 / 关闭时仍有在途。 + for _, mutate := range []func(map[string]any){ + func(j map[string]any) { j["gate"].(map[string]any)["drained"] = false }, + func(j map[string]any) { j["gate"].(map[string]any)["active_at_close"] = 1 }, + func(j map[string]any) { j["drain_verified"] = false }, + } { + drainedDir, _, drainedDigest := ds01Journal(t, job, mutate) + evidence = validB() + evidence.MaintenanceJournalSHA256 = drainedDigest + if err := store.WithRestoreDispatchEvidence(drainedDir).ActivateRestoreDispatch(ctx, + func() string { p, _ := writeDS01ActivationEvidence(t, evidence); return p }(), + func() string { _, d := writeDS01ActivationEvidence(t, evidence); return d }(), target, ds01TestFingerprint, now); err == nil { + t.Fatal("journal without a zero-in-flight drain was accepted") + } + } + // 过期:停写/排空观察早于有效期(attestation 仍是新的)。 + staleDir, _, staleDigest := ds01Journal(t, job, func(j map[string]any) { + q := j["quiesce"].(map[string]any) + q["proven_at"] = now.Add(-3 * time.Hour).Format(time.RFC3339Nano) + q["post_stop_at"] = now.Add(-3*time.Hour + time.Minute).Format(time.RFC3339Nano) + q["after_ingress"] = now.Add(-4 * time.Hour).Format(time.RFC3339Nano) + j["started_at"] = now.Add(-4 * time.Hour).Format(time.RFC3339Nano) + }) + evidence = validB() + evidence.MaintenanceJournalSHA256 = staleDigest + if err := store.WithRestoreDispatchEvidence(staleDir).ActivateRestoreDispatch(ctx, + func() string { p, _ := writeDS01ActivationEvidence(t, evidence); return p }(), + func() string { _, d := writeDS01ActivationEvidence(t, evidence); return d }(), target, ds01TestFingerprint, now); err == nil { + t.Fatal("stale maintenance observation was accepted") + } + // 证据本身过期 + evidence = validB() + evidence.AttestedAt = now.Add(-24 * time.Hour) + if err := activateB(t, evidence, "", ""); err == nil { + t.Fatal("stale activation attestation was accepted") + } + // 治理库身份不符 + evidence = validB() + evidence.GovernanceDatabase = "some-other-database" + if err := activateB(t, evidence, "", ""); err == nil { + t.Fatal("evidence for another governance database was accepted") + } + // 现场指纹不符 + if err := activateB(t, validB(), "", ds01TestFingerprintOther); err == nil { + t.Fatal("evidence for another target fingerprint was accepted") + } + // 构建身份不符 + evidence = validB() + evidence.ProtocolBuild = "0.1.0-other-build" + if err := activateB(t, evidence, "", ""); err == nil { + t.Fatal("evidence from another build was accepted") + } + // 窗口已释放 / 作业不属于该窗口 + if _, err := pool.Exec(ctx, `UPDATE library_instance_maintenance SET released_at=now(), state='released' WHERE instance=$1`, ds01TestInstance); err != nil { + t.Fatal(err) + } + if err := activateB(t, validB(), "", ""); err == nil { + t.Fatal("released maintenance window was accepted") + } + if _, err := pool.Exec(ctx, `UPDATE library_instance_maintenance SET released_at=NULL, state='needs_restore', owner_job_id='other-window' WHERE instance=$1`, ds01TestInstance); err != nil { + t.Fatal(err) + } + if err := activateB(t, validB(), "", ""); err == nil { + t.Fatal("maintenance window for another job was accepted") + } + // journal 已 recovered(旧 writer 已被重启,不再是"已退出"的现场) + recoveredDir, _, recoveredDigest := ds01Journal(t, job, func(j map[string]any) { j["state"] = "recovered" }) + evidence = validB() + evidence.MaintenanceJournalSHA256 = recoveredDigest + if err := store.WithRestoreDispatchEvidence(recoveredDir).ActivateRestoreDispatch(ctx, + func() string { p, _ := writeDS01ActivationEvidence(t, evidence); return p }(), + func() string { _, d := writeDS01ActivationEvidence(t, evidence); return d }(), target, ds01TestFingerprint, now); err == nil { + t.Fatal("recovered maintenance window was accepted as stopped writers") + } + assertActivationCount(t, pool, 0) + + // 正例:恢复维护行绑定后同一份真实 journal 可以激活;台账里保留已核事实。 + if _, err := pool.Exec(ctx, `UPDATE library_instance_maintenance SET owner_job_id=$2, released_at=NULL, state='needs_restore' WHERE instance=$1`, ds01TestInstance, job); err != nil { + t.Fatal(err) + } + if err := activateB(t, validB(), "", ""); err != nil { + t.Fatalf("valid evidence rejected: %v", err) + } + var evidenceJSON string + if err := pool.QueryRow(ctx, `SELECT evidence::text FROM library_index_restore_dispatch_activation WHERE target_identity=$1`, target).Scan(&evidenceJSON); err != nil { + t.Fatal(err) + } + compact := strings.ReplaceAll(evidenceJSON, " ", "") + if !strings.Contains(compact, `"maintenance_journal_sha256":"`+digest+`"`) || !strings.Contains(compact, `"exit_code":0`) || + !strings.Contains(compact, `"active_at_close":0`) { + t.Fatalf("activation record lacks the verified journal facts: %s", evidenceJSON) + } +} + +func assertActivationCount(t *testing.T, pool *pgxpool.Pool, want int) { + t.Helper() + var count int + if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM library_index_restore_dispatch_activation`).Scan(&count); err != nil { + t.Fatal(err) + } + if count != want { + t.Fatalf("activation rows = %d, want %d", count, want) + } +} diff --git a/internal/platform/postgres/library_restore_dispatch_test.go b/internal/platform/postgres/library_restore_dispatch_test.go new file mode 100644 index 0000000..1137f37 --- /dev/null +++ b/internal/platform/postgres/library_restore_dispatch_test.go @@ -0,0 +1,507 @@ +package postgres + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/version" +) + +// DS01 的许可竞争必须是真库行为:内存 fake 无法证明"只有唯一赢家拿到许可", +// 也无法证明触发器拒绝回退/删行。 + +func seededOperationID(t *testing.T, pool *pgxpool.Pool, jobID string) string { + t.Helper() + var operationID string + if err := pool.QueryRow(context.Background(), `SELECT operation_id FROM library_jobs WHERE id=$1`, jobID).Scan(&operationID); err != nil { + t.Fatalf("read seeded operation: %v", err) + } + return operationID +} + +func ds01Binding() libraryrelease.RestoreMarkerBinding { + return libraryrelease.RestoreMarkerBinding{ + Key: libraryrelease.RestoreMarkerKey{ + TargetIdentity: "target-ds01", OperationID: "op", WindowJobID: "job", + PlanDigest: "plan-1", Index: "kg-index", DocumentID: "doc-1", + Phase: libraryrelease.RestoreMarkerPhaseCreate, + }, + Scope: "internal", SourceSnapshot: "snap-target", BackupSnapshot: "snap-backup", + TargetInstance: "inst-1", TargetFingerprint: ds01TestFingerprint, IndexUUID: "uuid-1", + ChangeDigest: "change-1", MarkerDigest: "marker-1", RequestDigest: "request-1", + Owner: "worker-a#q1#0", Epoch: 1, + } +} + +func TestRestoreDispatchRequiresActivation(t *testing.T) { + store, _ := newIdentityStore(t) + ctx := context.Background() + binding := ds01Binding() + if _, err := store.PrepareRestoreMarker(ctx, binding); !errors.Is(err, libraryrelease.ErrRestoreDispatchUnavailable) { + t.Fatalf("prepare without activation = %v", err) + } + var count int + if err := store.db.QueryRow(ctx, `SELECT count(*) FROM library_index_restore_dispatch`).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 0 { + t.Fatalf("prepared rows without activation = %d", count) + } +} + +func TestRestoreDispatchPrepareIsUniqueAndBindingBound(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-prep", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-prep", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-prep" + binding.Key.OperationID = seededOperationID(t, pool, "libsync-ds01-prep") + for i := 0; i < 2; i++ { + status, err := store.PrepareRestoreMarker(ctx, binding) + if err != nil || status.State != libraryrelease.RestoreDispatchPrepared || status.Held { + t.Fatalf("prepare #%d = %+v %v", i, status, err) + } + } + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM library_index_restore_dispatch`).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 1 { + t.Fatalf("prepared rows = %d", count) + } + other := binding + other.MarkerDigest = "marker-2" + if _, err := store.PrepareRestoreMarker(ctx, other); err == nil { + t.Fatal("binding change reused the prepared row") + } + status, found, err := store.InspectRestoreMarker(ctx, other) + if err != nil || !found || !status.Held { + t.Fatalf("binding conflict inspect = %+v found=%v err=%v", status, found, err) + } +} + +func TestRestoreDispatchConcurrentAcquireHasSingleWinner(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-race", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-race", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-race" + binding.Key.OperationID = seededOperationID(t, pool, "libsync-ds01-race") + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + permits := make(chan *libraryrelease.RestoreSendPermit, 2) + errs := make(chan error, 2) + for i := 0; i < 2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + permit, _, err := store.AcquireRestoreMarker(ctx, binding) + permits <- permit + errs <- err + }() + } + wg.Wait() + close(permits) + close(errs) + winners := 0 + for permit := range permits { + if permit != nil { + winners++ + } + } + for err := range errs { + if err != nil && !errors.Is(err, libraryrelease.ErrRestoreDispatchHeld) { + t.Fatalf("loser error = %v", err) + } + } + if winners != 1 { + t.Fatalf("dispatch winners = %d", winners) + } + var state string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&state); err != nil { + t.Fatal(err) + } + if state != libraryrelease.RestoreDispatchDispatching { + t.Fatalf("state = %s", state) + } +} + +func TestRestoreDispatchIsMonotoneAndAppendOnly(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-mono", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-mono", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-mono" + binding.Key.OperationID = seededOperationID(t, pool, "libsync-ds01-mono") + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + permit, _, err := store.AcquireRestoreMarker(ctx, binding) + if err != nil || permit == nil { + t.Fatalf("acquire = %v", err) + } + if permit, _, err = store.AcquireRestoreMarker(ctx, binding); permit != nil || !errors.Is(err, libraryrelease.ErrRestoreDispatchHeld) { + t.Fatalf("second acquire permit=%v err=%v", permit, err) + } + if _, err := pool.Exec(ctx, `UPDATE library_index_restore_dispatch SET state='prepared'`); err == nil || + !strings.Contains(err.Error(), "not monotone") { + t.Fatalf("state regression accepted: %v", err) + } + if _, err := pool.Exec(ctx, `DELETE FROM library_index_restore_dispatch`); err == nil || + !strings.Contains(err.Error(), "append-only") { + t.Fatalf("evidence delete accepted: %v", err) + } + if _, err := pool.Exec(ctx, `UPDATE library_index_restore_dispatch SET document_id='doc-2'`); err == nil || + !strings.Contains(err.Error(), "immutable") { + t.Fatalf("binding rewrite accepted: %v", err) + } + var state, owner string + if err := pool.QueryRow(ctx, `SELECT state, dispatch_owner FROM library_index_restore_dispatch`).Scan(&state, &owner); err != nil { + t.Fatal(err) + } + if state != libraryrelease.RestoreDispatchDispatching || owner != "worker-a#q1#0" { + t.Fatalf("row after rejected rewrites = %s/%s", state, owner) + } + // down 迁移不能把这些行当"没有证据"抹掉。 + migrations, err := loadMigrations() + if err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, migrations[len(migrations)-1].DownSQL); err == nil || + !strings.Contains(err.Error(), "refusing to drop restore dispatch evidence") { + t.Fatalf("dangerous down accepted: %v", err) + } +} + +func TestRestoreDispatchRejectsStaleEpochBeforeSend(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-epoch", "sync", now) + first, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-epoch", "worker-a#q1#0", time.Minute, now) + if err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-epoch" + binding.Key.OperationID = first.OperationID + binding.Owner, binding.Epoch = first.Owner, int64(first.Epoch) + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + // A 还没赢 CAS,租约过期,B 接管成新 epoch。 + second, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-epoch", "worker-b#q2#0", 10*time.Minute, now.Add(2*time.Minute)) + if err != nil { + t.Fatalf("takeover: %v", err) + } + if second.Epoch <= first.Epoch { + t.Fatalf("epoch did not advance: %d -> %d", first.Epoch, second.Epoch) + } + if permit, _, err := store.AcquireRestoreMarker(ctx, binding); permit != nil || !errors.Is(err, governance.ErrLibraryEpochStale) { + t.Fatalf("stale owner acquired permit=%v err=%v", permit, err) + } + var state string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&state); err != nil { + t.Fatal(err) + } + if state != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("stale owner moved state to %s", state) + } + current := binding + current.Owner, current.Epoch = second.Owner, int64(second.Epoch) + permit, _, err := store.AcquireRestoreMarker(ctx, current) + if err != nil || permit == nil { + t.Fatalf("current owner acquire = %v", err) + } + if permit, _, err = store.AcquireRestoreMarker(ctx, current); permit != nil || err == nil { + t.Fatalf("current owner acquired twice: permit=%v err=%v", permit, err) + } +} + +// 这个用例是"**未提交**回滚":beforeCommit 钩子在 COMMIT 之前返回错误,事务回滚, +// 账仍是 prepared。它不是"COMMIT 已在服务端完成、客户端回执丢失"——后者由 G1 的 +// 专用 TCP 代理用例(CommitAckLoss / UndecidedTransaction)在真 PG 上覆盖。 +func TestRestoreDispatchRollbackBeforeCommitYieldsNoPermit(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-commit", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-commit", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-commit" + binding.Key.OperationID = seededOperationID(t, pool, "libsync-ds01-commit") + if _, err := store.PrepareRestoreMarker(ctx, binding); err != nil { + t.Fatal(err) + } + permit, status, err := store.acquireRestoreMarker(ctx, binding, func() error { + return errors.New("commit acknowledgement lost") + }) + if permit != nil || err == nil || !status.Held { + t.Fatalf("commit-unknown returned permit=%v status=%+v err=%v", permit, status, err) + } + var state string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&state); err != nil { + t.Fatal(err) + } + if state != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("uncommitted CAS leaked into durable state: %s", state) + } + // 回滚干净之后,下一调用仍可竞争同一条 prepared(活性下降,安全性不变)。 + permit, _, err = store.AcquireRestoreMarker(ctx, binding) + if err != nil || permit == nil { + t.Fatalf("post-rollback acquire = %v", err) + } + receipt := []byte(`{"_index":"kg-index","_id":"doc-1","result":"created","_seq_no":7,"_primary_term":1}`) + if err := store.ConfirmRestoreMarker(ctx, binding, receipt); err != nil { + t.Fatalf("confirm: %v", err) + } + var confirmed string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&confirmed); err != nil { + t.Fatal(err) + } + if confirmed != libraryrelease.RestoreDispatchMarkerConfirmed { + t.Fatalf("confirmed state = %s", confirmed) + } + if err := store.ConfirmRestoreMarker(ctx, binding, []byte(`{"partial":true}`)); err == nil { + t.Fatal("second confirmation accepted") + } +} + +// 撤销是终局:不能用同一条旧证据把已撤销目标重新打开(否则"撤销"只是界面动作)。 +func TestRestoreDispatchRevocationIsFinal(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + seedOperationJob(t, store, pool, "internal", "libsync-ds01-revoke", "sync", now) + if _, err := store.BeginLibraryAttempt(ctx, "libsync-ds01-revoke", "worker-a#q1#0", 10*time.Minute, now); err != nil { + t.Fatal(err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err != nil { + t.Fatal(err) + } + if err := store.RevokeRestoreDispatch(ctx, "target-ds01", now); err != nil { + t.Fatal(err) + } + binding := ds01Binding() + binding.Key.WindowJobID = "libsync-ds01-revoke" + binding.Key.OperationID = seededOperationID(t, pool, "libsync-ds01-revoke") + if _, err := store.PrepareRestoreMarker(ctx, binding); !errors.Is(err, libraryrelease.ErrRestoreDispatchUnavailable) { + t.Fatalf("revoked target still prepared: %v", err) + } + if err := activateRestoreDispatchForTest(t, store, "target-ds01", ds01TestFingerprint); err == nil { + t.Fatal("revoked activation was reopened with the same evidence") + } + var revoked *time.Time + if err := pool.QueryRow(ctx, `SELECT revoked_at FROM library_index_restore_dispatch_activation`).Scan(&revoked); err != nil { + t.Fatal(err) + } + if revoked == nil { + t.Fatal("revocation was silently cleared") + } +} + +// ---- DS01-F3 测试夹具:真实 journal + 治理库维护行 ---- +// +// 激活门现在只接受"维护窗口写下的 journal + 治理库维护行"这一条证据链。 +// 夹具必须按同一结构造证据;它不替产品函数做判断,只提供可被独立篡改的原始文件, +// 让负例(伪造摘要/替换文件/错 writer 集合/未退出/未排空/过期/治理库不符)真的打在 +// 校验点上。 + +const ( + ds01TestFingerprint = "1111111111111111111111111111111111111111111111111111111111111111" + ds01TestFingerprintOther = "2222222222222222222222222222222222222222222222222222222222222222" + ds01TestInstance = "inst-1" + ds01TestWriter = "writer-1" +) + +// ds01Journal 生成一份结构合法的 held 维护 journal;mutate 用于制造反例。 +// 返回的 raw 是写入磁盘的字节(摘要必须按它算,而不是按重新序列化的对象算)。 +func ds01Journal(t *testing.T, job string, mutate func(map[string]any)) (string, []byte, string) { + t.Helper() + now := time.Now().UTC() + journal := map[string]any{ + "version": 1, "source": ds01TestInstance, "job": job, "state": "held", "level": "instance", + "ingress": "http://127.0.0.1:18080/", "ingress_closed": true, "drain_verified": true, + "target_fingerprint": ds01TestFingerprint, + "started_at": now.Add(-10 * time.Minute).Format(time.RFC3339Nano), + "gate": map[string]any{"closed": true, "drained": true, "active_at_close": 0, "served": 3, + "detail": "gate exit=0 phase=drained drain_ms=1 active_at_close=0"}, + "quiesce": map[string]any{ + "after_ingress": now.Add(-9 * time.Minute).Format(time.RFC3339Nano), "samples": 3, "stable_ms": 1600, + "depth": 0, "pending_ops": 0, "unsettled": 0, + "digest": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "proven_at": now.Add(-8 * time.Minute).Format(time.RFC3339Nano), + "post_stop_depth": 0, "post_stop_at": now.Add(-7 * time.Minute).Format(time.RFC3339Nano), + "post_stop_digest": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + }, + "services": []any{map[string]any{"id": ds01TestWriter, "running": true, "healthy": true, + "exit_code": 0, "stop_requested": true, "stop_verified": false, "restored": false}}, + } + if mutate != nil { + mutate(journal) + } + raw, err := json.Marshal(journal) + if err != nil { + t.Fatalf("marshal journal: %v", err) + } + dir := t.TempDir() + if err := os.Chmod(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, job+".json"), raw, 0o600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(raw) + return dir, raw, hex.EncodeToString(sum[:]) +} + +// updateDS01MaintenanceRow 让隔离治理库的维护行与 journal 绑定一致。 +// owner_job_id 必须由调用方给出:维护行本来由 seedOperationJob 建立。 +func updateDS01MaintenanceRow(t *testing.T, store *Store, job, fingerprint string, services []string, state string) { + t.Helper() + raw, err := json.Marshal(services) + if err != nil { + t.Fatal(err) + } + if _, err := store.db.Exec(context.Background(), ` +UPDATE library_instance_maintenance +SET owner_job_id=$1, target_fingerprint=$2, level='instance', services=$3::jsonb, state=$4, + ingress_state='closed', released_at=NULL, acquired_at=LEAST(acquired_at, now()-interval '20 minutes'), + updated_at=now() +WHERE instance=$5`, job, fingerprint, string(raw), state, ds01TestInstance); err != nil { + t.Fatalf("update maintenance row: %v", err) + } +} + +func ds01JournalRowJob(t *testing.T, store *Store) string { + t.Helper() + var job string + err := store.db.QueryRow(context.Background(), + `SELECT owner_job_id FROM library_instance_maintenance WHERE instance=$1`, ds01TestInstance).Scan(&job) + if errors.Is(err, pgx.ErrNoRows) { + return "" + } + if err != nil { + t.Fatalf("read maintenance job: %v", err) + } + return job +} + +// ds01ActivationEvidence 组装 v3 证据:身份/作业/摘要/writer 集合 + 治理权威域 + 构建 SHA。 +func ds01ActivationEvidence(t *testing.T, store *Store, targetIdentity, fingerprint, job, journalDigest string) libraryrelease.RestoreDispatchActivationEvidence { + t.Helper() + authority, primary, database := ds01ObservedAuthority(t, store) + if !primary { + t.Fatal("governance database is not primary") + } + return libraryrelease.RestoreDispatchActivationEvidence{ + ProtocolVersion: libraryrelease.RestoreDispatchActivationProtocolVersion, + ProtocolEpoch: libraryrelease.RestoreDispatchProtocolEpoch, + TargetIdentity: targetIdentity, TargetFingerprint: fingerprint, + RestoreTargetFingerprint: fingerprint, TargetInstance: ds01TestInstance, GovernanceDatabase: database, + GovernanceAuthority: authority, ProtocolBuild: version.DisplayVersion(), ProtocolBuildSHA: version.CommitSHA, + AttestedBy: "ds01-test", AttestedAt: time.Now().UTC(), + MaintenanceJob: job, MaintenanceJournal: job + ".json", MaintenanceJournalSHA256: journalDigest, + Writers: []libraryrelease.RestoreDispatchWriterDrain{{Name: ds01TestWriter, Kind: "worker", InstanceID: ds01TestWriter}}, + } +} + +// ds01ObservedAuthority 读回测试进程实际连接的治理库权威域;证据必须携带它, +// 否则"同名异集群"永远无法被拒绝。 +func ds01ObservedAuthority(t *testing.T, store *Store) (libraryrelease.RestoreDispatchGovernanceAuthority, bool, string) { + t.Helper() + var authority libraryrelease.RestoreDispatchGovernanceAuthority + var inRecovery bool + var database string + if err := store.db.QueryRow(context.Background(), ` +SELECT current_database(), + (SELECT system_identifier::text FROM pg_control_system()), + (SELECT oid::text FROM pg_database WHERE datname = current_database()), + pg_is_in_recovery()`).Scan(&database, &authority.SystemIdentifier, &authority.DatabaseOID, &inRecovery); err != nil { + t.Fatalf("observe governance authority: %v", err) + } + return authority, !inRecovery, database +} + +func writeDS01ActivationEvidence(t *testing.T, evidence libraryrelease.RestoreDispatchActivationEvidence) (string, string) { + t.Helper() + raw, err := json.Marshal(evidence) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "activation.json") + if err := os.WriteFile(path, raw, 0o600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(raw) + return path, hex.EncodeToString(sum[:]) +} + +// activateRestoreDispatchForTest 用真实 journal + 治理库维护行登记激活。 +// 它把 store 复制成带受信 journal 根的实例:激活门没有这个根就必须失败关闭。 +func activateRestoreDispatchForTest(t *testing.T, store *Store, targetIdentity, fingerprint string) error { + t.Helper() + job := ds01JournalRowJob(t, store) + if job == "" { + job = "activation-window" + if _, err := store.db.Exec(context.Background(), ` +INSERT INTO library_instance_maintenance (instance, owner_job_id, owner_scope, target_fingerprint, level, + services, ingress_state, state, original_service_state, note, acquired_at, updated_at) +VALUES ($1,$2,'internal',$3,'instance','[]'::jsonb,'closed','needs_restore','','', + now()-interval '20 minutes',now())`, ds01TestInstance, job, fingerprint); err != nil { + t.Fatalf("seed maintenance row: %v", err) + } + } + dir, _, digest := ds01Journal(t, job, nil) + updateDS01MaintenanceRow(t, store, job, fingerprint, []string{ds01TestWriter}, "needs_restore") + evidence := ds01ActivationEvidence(t, store, targetIdentity, fingerprint, job, digest) + path, evidenceDigest := writeDS01ActivationEvidence(t, evidence) + return store.WithRestoreDispatchEvidence(dir).ActivateRestoreDispatch( + context.Background(), path, evidenceDigest, targetIdentity, fingerprint, time.Now().UTC()) +} diff --git a/internal/platform/postgres/library_resume_r25_test.go b/internal/platform/postgres/library_resume_r25_test.go new file mode 100644 index 0000000..ad611c3 --- /dev/null +++ b/internal/platform/postgres/library_resume_r25_test.go @@ -0,0 +1,257 @@ +package postgres + +import ( + "context" + "encoding/json" + + "errors" + "github.com/jackc/pgx/v5/pgxpool" + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +// seedResumableJob 建一条 failed/rollback 的库作业,并按 QueueJobIDFor 预置"上一次执行"留下的队列行, +// 复现线上真实形态:队列行主键已存在、idempotency_key 与续作不同(因此旧实现 INSERT 撞主键)。 +func seedResumableJob(t *testing.T, pool *pgxpool.Pool, jobID, stage, state string, queueLease *time.Time) string { + t.Helper() + ctx := context.Background() + now := time.Now().UTC() + if _, err := pool.Exec(ctx, ` +INSERT INTO library_jobs (id, scope, kind, state, stage, idempotency_key, request_digest, request, + queue_job_id, snapshot_id, target_snapshot_id, actor, error, recovery, created_at, updated_at, operation_id) +VALUES ($1::text,'internal','restore',$2::text,$3::text,'idem-'||$1::text,'digest-'||$1::text,'{}'::jsonb, + $4::text,'snap-before','snap-target','tester','boom','', $5::timestamptz, $5::timestamptz, 'op-'||$1::text)`, + jobID, state, stage, governance.QueueJobIDFor(jobID), now); err != nil { + t.Fatalf("seed library job: %v", err) + } + if _, err := pool.Exec(ctx, ` +INSERT INTO jobs (id, type, payload, state, priority, available_at, max_attempts, idempotency_key, + created_at, updated_at, lease_owner, lease_until, attempt) +VALUES ($1::text,'library.restore','{}'::jsonb,'failed',0,$2::timestamptz,1,'library.restore.queue:'||$3::text,$2::timestamptz,$2::timestamptz,'old-worker',$4::timestamptz,1)`, + governance.QueueJobIDFor(jobID), now, jobID, queueLease); err != nil { + t.Fatalf("seed queue job: %v", err) + } + return governance.QueueJobIDFor(jobID) +} + +// RED 的真实形态:队列行已存在时,续作必须成功复用该行;旧实现会在 Enqueue 撞主键后 +// 留下 state=pending 且没有可用队列行的假 active。 +func TestR25ResumeReusesExistingQueueRowAtomically(t *testing.T) { + store, pool := newIdentityStore(t) + jobID := "librestore-internal-r25-atomic" + past := time.Now().UTC().Add(-time.Minute) + queueID := seedResumableJob(t, pool, jobID, "resources", "failed", &past) + + job, resumed, err := store.ResumeLibraryJob(context.Background(), jobID, "library.restore", time.Now().UTC()) + if err != nil { + t.Fatalf("resume with existing queue row: %v", err) + } + if !resumed || job.State != governance.LibraryJobPending { + t.Fatalf("resume did not take effect: resumed=%v state=%s", resumed, job.State) + } + row := pool.QueryRow(context.Background(), + `SELECT state, attempt, coalesce(lease_owner,'') FROM jobs WHERE id=$1`, queueID) + var state, owner string + var attempt int + if err := row.Scan(&state, &attempt, &owner); err != nil { + t.Fatalf("queue row missing after resume: %v", err) + } + if state != "pending" || attempt != 0 || owner != "" { + t.Fatalf("queue row not reset for resume: state=%s attempt=%d owner=%q", state, attempt, owner) + } + if job.QueueJobID != queueID { + t.Fatalf("library job not attached to queue row: %q", job.QueueJobID) + } +} + +// 有有效租约时必须整笔回滚:不能出现"业务作业 pending、队列仍被别人持有"的半态。 +func TestR25ResumeBusyLeaseDoesNotMutateState(t *testing.T) { + store, pool := newIdentityStore(t) + jobID := "librestore-internal-r25-busy" + future := time.Now().UTC().Add(10 * time.Minute) + queueID := seedResumableJob(t, pool, jobID, "resources", "failed", &future) + + _, resumed, err := store.ResumeLibraryJob(context.Background(), jobID, "library.restore", time.Now().UTC()) + if !errors.Is(err, ErrLibraryResumeBusy) { + t.Fatalf("want ErrLibraryResumeBusy, got %v (resumed=%v)", err, resumed) + } + var state, stage string + if err := pool.QueryRow(context.Background(), + `SELECT state, stage FROM library_jobs WHERE id=$1`, jobID).Scan(&state, &stage); err != nil { + t.Fatalf("reload: %v", err) + } + if state != "failed" || stage != "resources" { + t.Fatalf("busy resume mutated job: state=%s stage=%s", state, stage) + } + var qState string + if err := pool.QueryRow(context.Background(), `SELECT state FROM jobs WHERE id=$1`, queueID).Scan(&qState); err != nil { + t.Fatalf("queue: %v", err) + } + if qState != "failed" { + t.Fatalf("busy resume mutated queue row: %s", qState) + } +} + +// 非失败/取消状态不得被续作改写(并发接管后的保护)。 +func TestR25ResumeRejectsNonFailedStateWithoutMutation(t *testing.T) { + store, pool := newIdentityStore(t) + jobID := "librestore-internal-r25-succeeded" + seedResumableJob(t, pool, jobID, "finalize", "succeeded", ptrTime(time.Now().UTC().Add(-time.Minute))) + + _, resumed, err := store.ResumeLibraryJob(context.Background(), jobID, "library.restore", time.Now().UTC()) + if err != nil { + t.Fatalf("resume on succeeded job: %v", err) + } + if resumed { + t.Fatal("succeeded job must not be resumed") + } + var state string + if err := pool.QueryRow(context.Background(), `SELECT state FROM library_jobs WHERE id=$1`, jobID).Scan(&state); err != nil { + t.Fatalf("reload: %v", err) + } + if state != "succeeded" { + t.Fatalf("state changed on rejected resume: %s", state) + } +} + +// 入队真的失败(数据库层拒绝写队列)时,attempt / job / queue 必须全部回到原值: +// 不能留下"state=pending 却没有队列行"的假 active。 +func TestR26ResumeEnqueueFailureRollsBackEveryField(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + jobID := "librestore-internal-r26-rollback-all" + past := time.Now().UTC().Add(-time.Minute) + queueID := seedResumableJob(t, pool, jobID, "resources", "failed", &past) + if _, err := pool.Exec(ctx, `UPDATE library_jobs SET error='boom', recovery='rolled back', + lease_owner='old', lease_until=$2, attempt_epoch=3 WHERE id=$1`, jobID, past.Add(30*time.Second)); err != nil { + t.Fatalf("seed fields: %v", err) + } + before := rowJSON(t, pool, `SELECT to_jsonb(j) FROM library_jobs j WHERE id=$1`, jobID) + queueBefore := rowJSON(t, pool, `SELECT to_jsonb(j) FROM jobs j WHERE id=$1`, queueID) + if _, err := pool.Exec(ctx, `CREATE FUNCTION r26_reject_queue() RETURNS trigger AS $$ BEGIN + RAISE EXCEPTION 'r26 injected queue write failure'; END; $$ LANGUAGE plpgsql; + CREATE TRIGGER r26_reject BEFORE INSERT OR UPDATE ON jobs FOR EACH ROW EXECUTE FUNCTION r26_reject_queue();`); err != nil { + t.Fatalf("install trigger: %v", err) + } + t.Cleanup(func() { + _, _ = pool.Exec(context.Background(), `DROP TRIGGER IF EXISTS r26_reject ON jobs; + DROP FUNCTION IF EXISTS r26_reject_queue();`) + }) + if _, resumed, err := store.ResumeLibraryJob(ctx, jobID, "library.restore", time.Now().UTC()); err == nil || resumed { + t.Fatalf("resume must fail when queue write is rejected: resumed=%v err=%v", resumed, err) + } + if after := rowJSON(t, pool, `SELECT to_jsonb(j) FROM library_jobs j WHERE id=$1`, jobID); after != before { + t.Fatalf("library_jobs changed after failed enqueue:\n before=%s\n after=%s", before, after) + } + if after := rowJSON(t, pool, `SELECT to_jsonb(j) FROM jobs j WHERE id=$1`, queueID); after != queueBefore { + t.Fatalf("queue row changed after failed enqueue:\n before=%s\n after=%s", queueBefore, after) + } +} + +// 回滚阶段的作业必须在事务内被拒绝(不是靠 handler 读到的旧快照)。 +func TestR26ResumeRejectsRollbackStageInsideTransaction(t *testing.T) { + store, pool := newIdentityStore(t) + jobID := "librestore-internal-r26-rollback-stage" + seedResumableJob(t, pool, jobID, "rollback", "failed", ptrTime(time.Now().UTC().Add(-time.Minute))) + before := rowJSON(t, pool, `SELECT to_jsonb(j) FROM library_jobs j WHERE id=$1`, jobID) + _, resumed, err := store.ResumeLibraryJob(context.Background(), jobID, "library.restore", time.Now().UTC()) + if !errors.Is(err, ErrLibraryResumeRequiresRecover) || resumed { + t.Fatalf("want ErrLibraryResumeRequiresRecover, got resumed=%v err=%v", resumed, err) + } + if after := rowJSON(t, pool, `SELECT to_jsonb(j) FROM library_jobs j WHERE id=$1`, jobID); after != before { + t.Fatalf("rollback rejection mutated job:\n before=%s\n after=%s", before, after) + } +} + +// 并发重复续作只允许一个成功,队列只有一条投递(不能双投)。 +func TestR26ResumeConcurrentDuplicateDeliversOnce(t *testing.T) { + store, pool := newIdentityStore(t) + jobID := "librestore-internal-r26-concurrent" + past := time.Now().UTC().Add(-time.Minute) + queueID := seedResumableJob(t, pool, jobID, "resources", "failed", &past) + + type res struct { + resumed bool + err error + } + ch := make(chan res, 2) + start := make(chan struct{}) + for i := 0; i < 2; i++ { + go func() { + <-start + _, resumed, err := store.ResumeLibraryJob(context.Background(), jobID, "library.restore", time.Now().UTC()) + ch <- res{resumed, err} + }() + } + close(start) + ok, busy := 0, 0 + for i := 0; i < 2; i++ { + r := <-ch + switch { + case r.resumed && r.err == nil: + ok++ + case errors.Is(r.err, ErrLibraryResumeBusy) || (r.err == nil && !r.resumed): + busy++ + case r.err != nil: + t.Fatalf("unexpected error: %v", r.err) + } + } + if ok != 1 || busy != 1 { + t.Fatalf("want exactly one resume and one refusal, got ok=%d refused=%d", ok, busy) + } + var state string + var attempt int + if err := pool.QueryRow(context.Background(), `SELECT state, attempt FROM jobs WHERE id=$1`, queueID).Scan(&state, &attempt); err != nil { + t.Fatalf("queue: %v", err) + } + if state != "pending" || attempt != 0 { + t.Fatalf("queue not reset exactly once: state=%s attempt=%d", state, attempt) + } + var pending int + if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM library_jobs WHERE id=$1 AND state='pending'`, jobID).Scan(&pending); err != nil { + t.Fatalf("job: %v", err) + } + if pending != 1 { + t.Fatalf("job not pending: %d", pending) + } +} + +// 载荷必须来自事务内锁定行:finalize 阶段续作要带 finalize_only,而不是调用方旧快照。 +func TestR26ResumePayloadComesFromLockedRow(t *testing.T) { + store, pool := newIdentityStore(t) + ctx := context.Background() + jobID := "librestore-internal-r26-finalize" + past := time.Now().UTC().Add(-time.Minute) + queueID := seedResumableJob(t, pool, jobID, "finalize", "failed", &past) + if _, err := pool.Exec(ctx, `UPDATE library_jobs SET snapshot_id='snap-written' WHERE id=$1`, jobID); err != nil { + t.Fatalf("seed snapshot: %v", err) + } + if _, resumed, err := store.ResumeLibraryJob(ctx, jobID, "library.restore", time.Now().UTC()); err != nil || !resumed { + t.Fatalf("resume: resumed=%v err=%v", resumed, err) + } + var payload []byte + if err := pool.QueryRow(ctx, `SELECT payload FROM jobs WHERE id=$1`, queueID).Scan(&payload); err != nil { + t.Fatalf("payload: %v", err) + } + var decoded map[string]any + if err := json.Unmarshal(payload, &decoded); err != nil { + t.Fatalf("payload json: %v", err) + } + if decoded["finalize_only"] != true || decoded["target_snapshot_id"] != "snap-target" { + t.Fatalf("payload not built from locked row: %v", decoded) + } +} + +// rowJSON 取整行快照(列顺序无关),用于"逐字段前后完全一致"的断言。 +func rowJSON(t *testing.T, pool *pgxpool.Pool, query, id string) string { + t.Helper() + var s string + if err := pool.QueryRow(context.Background(), query, id).Scan(&s); err != nil { + t.Fatalf("row json: %v", err) + } + return s +} + +func ptrTime(t time.Time) *time.Time { return &t } diff --git a/internal/platform/postgres/library_source_candidate.go b/internal/platform/postgres/library_source_candidate.go new file mode 100644 index 0000000..088e8ff --- /dev/null +++ b/internal/platform/postgres/library_source_candidate.go @@ -0,0 +1,26 @@ +package postgres + +import ( + "context" + "errors" + "knowledge-governance/internal/governance" +) + +// Query the source identity before applying LIMIT: target/prebackup events and +// other source instances can never push the candidate out of a history window. +func (s *Store) LibrarySourceCandidate(ctx context.Context, scope, sourceID string) (governance.LibraryVersion, bool, error) { + if sourceID == "" { + return governance.LibraryVersion{}, false, errors.New("source identity required") + } + rows, err := s.db.Query(ctx, `SELECT id,scope,kind,snapshot_id,version_label,source_job_id,operation_id,attempt_epoch,evidence,created_by,created_at,superseded_at + FROM library_versions WHERE scope=$1 AND kind='test_sealed' AND evidence->>'source_id'=$2 + ORDER BY created_at DESC,id DESC LIMIT 1`, scope, sourceID) + if err != nil { + return governance.LibraryVersion{}, false, err + } + items, err := scanLibraryVersions(rows, 1) + if err != nil || len(items) == 0 { + return governance.LibraryVersion{}, false, err + } + return items[0], true, nil +} diff --git a/internal/platform/postgres/library_source_candidate_test.go b/internal/platform/postgres/library_source_candidate_test.go new file mode 100644 index 0000000..67b7374 --- /dev/null +++ b/internal/platform/postgres/library_source_candidate_test.go @@ -0,0 +1,42 @@ +package postgres + +import ( + "context" + "fmt" + "knowledge-governance/internal/governance" + "testing" + "time" +) + +func TestContractSourceCandidateBeyondHistoryWindow(t *testing.T) { + store, _ := newIdentityStore(t) + ctx := context.Background() + now := time.Now().UTC() + source := governance.LibrarySourceIdentity{Project: "source-project", App: "source-app", Scope: "internal", TenantID: 10000, KnowledgeBaseID: "kb-source"} + id, err := source.ID() + if err != nil { + t.Fatal(err) + } + for i := 0; i < 65; i++ { + sid := "other-source" + if i == 0 { + sid = id + } + snapshot := fmt.Sprintf("candidate-%d", i) + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, "internal", snapshot), Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshot, Evidence: map[string]any{"source_id": sid}, CreatedAt: now.Add(time.Duration(i) * time.Second)}); err != nil { + t.Fatal(err) + } + } + candidate, found, err := store.LibrarySourceCandidate(ctx, "internal", id) + if err != nil || !found || candidate.SnapshotID != "candidate-0" { + t.Fatalf("exact candidate missing: %+v %v %v", candidate, found, err) + } + source.KnowledgeBaseID = "new-kb" + newID, _ := source.ID() + if _, found, err = store.LibrarySourceCandidate(ctx, "internal", newID); err != nil || found { + t.Fatalf("new source inherited old candidate: %v %v", found, err) + } + if _, found, err = store.LibrarySourceCandidate(ctx, "external", id); err != nil || found { + t.Fatalf("cross scope candidate: %v %v", found, err) + } +} diff --git a/internal/platform/postgres/library_target_test.go b/internal/platform/postgres/library_target_test.go new file mode 100644 index 0000000..930f681 --- /dev/null +++ b/internal/platform/postgres/library_target_test.go @@ -0,0 +1,166 @@ +package postgres + +import ( + "context" + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +// Exercise the existing SQL against a real disposable PostgreSQL schema. +// Keep the unbound legacy namespace available to prove history survives +// while configured targets cannot adopt it. +func targetTestStore(s *Store, target string) *Store { + return s.WithLibraryTarget(target) +} + +func TestLibraryTargetRejectsForeignEvidenceJobsAndGrants(t *testing.T) { + legacy, _ := openVersionStore(t) + a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b") + ctx := context.Background() + now := time.Now().UTC() + recordPrebackup(t, ctx, a, "internal", "backup-job", "backup", now) + if err := a.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: "source-seal", Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: "source", SourceJobID: "seal-job", CreatedAt: now}); err != nil { + t.Fatal(err) + } + checks := []struct { + name string + run func() bool + }{ + {"version list", func() bool { + rows, err := b.LibraryVersions(ctx, "internal", 100) + return err == nil && len(rows) == 1 && rows[0].Kind == governance.LibraryVersionTestSealed + }}, + {"exact backup", func() bool { + _, found, err := b.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionPrebackup, "backup-job", "backup") + return err == nil && !found + }}, + {"snapshot version", func() bool { + _, found, err := b.LibraryVersionOfSnapshot(ctx, "internal", governance.LibraryVersionProductionPrebackup, "backup") + return err == nil && !found + }}, + {"provenance", func() bool { + rows, err := b.LibraryVersionsBySnapshot(ctx, "internal", "backup") + return err == nil && len(rows) == 0 + }}, + {"snapshot kinds", func() bool { + rows, err := b.LibrarySnapshotKinds(ctx, "internal", "backup") + return err == nil && len(rows) == 0 + }}, + {"reuse sources", func() bool { + rows, err := b.LibraryReuseSources(ctx, "internal", 100) + return err == nil && len(rows) == 0 + }}, + {"handoff candidates", func() bool { + rows, err := b.LibrarySnapshotCandidates(ctx, "internal", time.Time{}, "", 100) + return err == nil && len(rows) == 1 && rows[0].SnapshotID == "source" + }}, + } + for _, check := range checks { + t.Run(check.name, func(t *testing.T) { + if !check.run() { + t.Fatal("foreign target evidence was accepted or source seal was hidden") + } + }) + } + job, _, err := a.CreateLibraryJob(ctx, governance.LibraryJob{ID: "target-a-job", Scope: "internal", Kind: governance.LibraryJobSync, IdempotencyKey: "target-a-job", RequestDigest: "digest", TargetSnapshotID: "source"}, governance.SyncStages(), now) + if err != nil { + t.Fatal(err) + } + if _, err := b.LibraryJob(ctx, job.ID); err == nil { + t.Error("new executor admitted old target job") + } + if _, _, err := b.PrepareLibraryJobResume(ctx, job.ID, now); err == nil { + t.Error("new target resumed old target job") + } + grant := governance.LibraryReleaseAuthorization{ID: "grant-a", Scope: "internal", SnapshotID: "source", ParamsDigest: "same-input", AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now} + if err := a.CreateLibraryAuthorization(ctx, grant); err != nil { + t.Fatal(err) + } + if _, found, err := b.ActiveLibraryAuthorization(ctx, "internal", "source", "same-input", now); err != nil || found { + t.Errorf("foreign grant accepted: found=%v err=%v", found, err) + } + if rows, err := b.LibraryAuthorizations(ctx, "internal", 100); err != nil || len(rows) != 0 { + t.Errorf("foreign grant listed: rows=%v err=%v", rows, err) + } + if err := b.RevokeLibraryAuthorization(ctx, grant.ID, now); err == nil { + t.Error("foreign grant revoked") + } + if _, found, err := a.ActiveLibraryAuthorization(ctx, "internal", "source", "same-input", now); err != nil || !found { + t.Errorf("original grant must remain valid: found=%v err=%v", found, err) + } +} + +func TestLibraryTargetRejectsForeignOperationReplay(t *testing.T) { + legacy, _ := openVersionStore(t) + a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b") + ctx := context.Background() + op := governance.LibraryOperation{ID: "operation", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: "snapshot", RequestDigest: "digest", OperationKey: "same-key", CreatedAt: time.Now(), Actor: "admin"} + if _, _, err := a.EnsureLibraryOperation(ctx, op); err != nil { + t.Fatal(err) + } + if _, _, err := b.EnsureLibraryOperation(ctx, op); err == nil { + t.Error("new target replayed foreign operation") + } + if _, err := b.LibraryOperation(ctx, op.ID); err == nil { + t.Error("new target read foreign operation as its own") + } +} + +func TestLibraryTargetRejectsEventIdentityCollision(t *testing.T) { + legacy, _ := openVersionStore(t) + a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b") + ctx := context.Background() + event := governance.LibraryVersion{ID: "same-event", Scope: "internal", Kind: governance.LibraryVersionProductionEffective, SnapshotID: "snapshot", SourceJobID: "job", CreatedAt: time.Now()} + if err := a.RecordLibraryVersion(ctx, event); err != nil { + t.Fatal(err) + } + if err := b.RecordLibraryVersion(ctx, event); err == nil { + t.Fatal("foreign event collision was silently accepted") + } + event.ID = "seal" + event.Kind = governance.LibraryVersionTestSealed + if err := a.RecordLibraryVersion(ctx, event); err != nil { + t.Fatal(err) + } + if err := b.RecordLibraryVersion(ctx, event); err != nil { + t.Fatalf("source seal replay must remain independent: %v", err) + } +} + +func TestLibraryTargetSeparatesCurrentAndPreservesLegacy(t *testing.T) { + legacy, pool := openVersionStore(t) + a := targetTestStore(legacy, "target-a") + b := targetTestStore(legacy, "target-b") + ctx := context.Background() + now := time.Now().UTC() + record := func(s *Store, id string, at time.Time) { + t.Helper() + if err := s.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: id, Scope: "internal", Kind: governance.LibraryVersionProductionEffective, + SnapshotID: "snapshot-" + id, SourceJobID: "job-" + id, Evidence: map[string]any{"verified": true}, CreatedAt: at, + }); err != nil { + t.Fatal(err) + } + } + record(legacy, "legacy", now) + if _, found, err := b.LibraryCurrentVersion(ctx, "internal"); err != nil || found { + t.Fatalf("new target inherited legacy current: found=%v err=%v", found, err) + } + record(a, "a", now.Add(time.Second)) + record(b, "b", now.Add(2*time.Second)) + for _, tc := range []struct { + s *Store + want string + }{{legacy, "legacy"}, {a, "a"}, {b, "b"}} { + got, found, err := tc.s.LibraryCurrentVersion(ctx, "internal") + if err != nil || !found || got.ID != tc.want || got.SupersededAt != nil { + t.Fatalf("target current must remain independent: want=%s got=%+v found=%v err=%v", tc.want, got, found, err) + } + } + var count int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM library_versions").Scan(&count); err != nil || count != 3 { + t.Fatalf("history changed: count=%d err=%v", count, err) + } +} diff --git a/internal/platform/postgres/library_verification.go b/internal/platform/postgres/library_verification.go new file mode 100644 index 0000000..86cefb9 --- /dev/null +++ b/internal/platform/postgres/library_verification.go @@ -0,0 +1,121 @@ +package postgres + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/governance" +) + +// 恢复验证证据:只由 worker 在真实演练结束后写入;这里只做落库与按当前目标读取。 +// +// 读取永远带 target_id = 当前部署目标:换库/换索引/换桶之后旧证据自动失效, +// 不需要任何人去"记得把开关关掉"。 + +// SaveLibraryRestoreVerification 幂等登记一次演练结果(同一 target+scope+job 只留一条)。 +func (s *Store) SaveLibraryRestoreVerification(ctx context.Context, verification governance.LibraryRestoreVerification) error { + if verification.ID == "" || verification.JobID == "" { + return fmt.Errorf("restore verification requires id and job id") + } + if verification.Scope != "internal" && verification.Scope != "external" { + return fmt.Errorf("restore verification scope %q is invalid", verification.Scope) + } + if verification.Status != governance.LibraryVerificationPassed && verification.Status != governance.LibraryVerificationFailed { + return fmt.Errorf("restore verification status %q is invalid", verification.Status) + } + report, err := json.Marshal(verification.Report) + if err != nil { + return fmt.Errorf("encode restore verification report: %w", err) + } + _, err = s.db.Exec(ctx, ` +INSERT INTO library_restore_verifications (id, target_id, scope, status, snapshot_id, job_id, failure, report, started_at, finished_at) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) +ON CONFLICT (target_id, scope, job_id) DO UPDATE +SET status = EXCLUDED.status, snapshot_id = EXCLUDED.snapshot_id, failure = EXCLUDED.failure, + report = EXCLUDED.report, started_at = EXCLUDED.started_at, finished_at = EXCLUDED.finished_at`, + verification.ID, s.libraryTargetID, verification.Scope, verification.Status, + verification.SnapshotID, verification.JobID, verification.Failure, report, + verification.StartedAt.UTC(), verification.FinishedAt.UTC()) + if err != nil { + return fmt.Errorf("save restore verification: %w", err) + } + return nil +} + +// LatestLibraryRestoreVerification 按完成时间取当前目标该 scope 的最近一条证据。 +// 没有记录返回 (zero,false,nil):那不是错误,页面据此说"还没有验证过"。 +func (s *Store) LatestLibraryRestoreVerification(ctx context.Context, scope string) (governance.LibraryRestoreVerification, bool, error) { + var ( + item governance.LibraryRestoreVerification + report []byte + ) + err := s.db.QueryRow(ctx, ` +SELECT id, scope, status, snapshot_id, job_id, failure, report, started_at, finished_at +FROM library_restore_verifications +WHERE target_id=$1 AND scope=$2 +ORDER BY finished_at DESC, created_at DESC +LIMIT 1`, s.libraryTargetID, scope).Scan(&item.ID, &item.Scope, &item.Status, &item.SnapshotID, + &item.JobID, &item.Failure, &report, &item.StartedAt, &item.FinishedAt) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryRestoreVerification{}, false, nil + } + return governance.LibraryRestoreVerification{}, false, fmt.Errorf("load restore verification: %w", err) + } + item.Report = decodeEvidenceObject(report) + return item, true, nil +} + +// LibraryRestoreVerifications 是页面用的轻量清单(最近 N 条),按目标过滤。 + +// LibraryRestoreVerificationForSnapshot 只按本次精确快照查证据,不能用最近 N 条 +// 扫描代替:旧快照的报告可能已经掉出列表,但仍是该快照真实的恢复演练记录。 +func (s *Store) LibraryRestoreVerificationForSnapshot(ctx context.Context, scope, snapshotID string) (governance.LibraryRestoreVerification, bool, error) { + var item governance.LibraryRestoreVerification + var report []byte + err := s.db.QueryRow(ctx, ` +SELECT id, scope, status, snapshot_id, job_id, failure, report, started_at, finished_at +FROM library_restore_verifications +WHERE target_id=$1 AND scope=$2 AND snapshot_id=$3 +ORDER BY finished_at DESC, created_at DESC +LIMIT 1`, s.libraryTargetID, scope, snapshotID).Scan(&item.ID, &item.Scope, &item.Status, + &item.SnapshotID, &item.JobID, &item.Failure, &report, &item.StartedAt, &item.FinishedAt) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return governance.LibraryRestoreVerification{}, false, nil + } + return governance.LibraryRestoreVerification{}, false, fmt.Errorf("load snapshot restore verification: %w", err) + } + item.Report = decodeEvidenceObject(report) + return item, true, nil +} + +func (s *Store) LibraryRestoreVerifications(ctx context.Context, scope string, limit int) ([]governance.LibraryRestoreVerification, error) { + if limit <= 0 { + limit = 10 + } + rows, err := s.db.Query(ctx, ` +SELECT id, scope, status, snapshot_id, job_id, failure, started_at, finished_at +FROM library_restore_verifications +WHERE target_id=$1 AND scope=$2 +ORDER BY finished_at DESC, created_at DESC +LIMIT $3`, s.libraryTargetID, scope, limit) + if err != nil { + return nil, fmt.Errorf("list restore verifications: %w", err) + } + defer rows.Close() + items := make([]governance.LibraryRestoreVerification, 0, limit) + for rows.Next() { + var item governance.LibraryRestoreVerification + if err := rows.Scan(&item.ID, &item.Scope, &item.Status, &item.SnapshotID, &item.JobID, + &item.Failure, &item.StartedAt, &item.FinishedAt); err != nil { + return nil, err + } + items = append(items, item) + } + return items, rows.Err() +} diff --git a/internal/platform/postgres/library_verification_exact_pg_test.go b/internal/platform/postgres/library_verification_exact_pg_test.go new file mode 100644 index 0000000..459aa97 --- /dev/null +++ b/internal/platform/postgres/library_verification_exact_pg_test.go @@ -0,0 +1,56 @@ +package postgres + +import ( + "context" + "os" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" +) + +// F03 regression against real PostgreSQL: exact snapshot lookup must not fall +// back to the target's newest passed record. Session temp table only. +func TestLibraryRestoreVerificationForSnapshotExactPG(t *testing.T) { + dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database") + } + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") { + t.Fatal("isolated database required") + } + cfg.MaxConns = 1 + cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp" + ctx := context.Background() + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + _, err = pool.Exec(ctx, ` +CREATE TEMP TABLE library_restore_verifications( + id text, target_id text, scope text, status text, snapshot_id text, job_id text, + failure text, report jsonb, started_at timestamptz, finished_at timestamptz, created_at timestamptz DEFAULT now()); +INSERT INTO library_restore_verifications + (id,target_id,scope,status,snapshot_id,job_id,failure,report,started_at,finished_at,created_at) VALUES + ('v-new','target-exact','internal','passed','snap-new','job-new','','{}',now()-interval '1 hour',now()-interval '1 hour',now()), + ('v-old','target-exact','internal','failed','snap-old','job-old','old restore mismatch','{}',now()-interval '2 hour',now()-interval '2 hour',now()-interval '2 hour'), + ('v-other','other-target','internal','passed','snap-old','job-other','','{}',now(),now(),now());`) + if err != nil { + t.Fatal(err) + } + store := NewStore(pool).WithLibraryTarget("target-exact") + item, found, err := store.LibraryRestoreVerificationForSnapshot(ctx, "internal", "snap-old") + if err != nil { + t.Fatal(err) + } + if !found || item.JobID != "job-old" || item.Status != governance.LibraryVerificationFailed { + t.Fatalf("exact snapshot borrowed another record: found=%v item=%+v", found, item) + } + if _, found, err := store.LibraryRestoreVerificationForSnapshot(ctx, "internal", "snap-missing"); err != nil || found { + t.Fatalf("missing snapshot must be explicit no-evidence: found=%v err=%v", found, err) + } +} diff --git a/internal/platform/postgres/library_version_lookup_integration_test.go b/internal/platform/postgres/library_version_lookup_integration_test.go new file mode 100644 index 0000000..05b8e9a --- /dev/null +++ b/internal/platform/postgres/library_version_lookup_integration_test.go @@ -0,0 +1,251 @@ +package postgres + +import ( + "context" + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/platform/postgres/pgtest" +) + +// 版本台账的身份查询必须按 (scope, kind, 作业, 快照) 精确命中: +// 缺 → found=false(调用方失败),冲突 → 错误(调用方拒绝), +// 而不是"读最近 N 条再筛"——历史超过窗口就会把存在读成不存在。 +// 这里跑真实 PostgreSQL,因为契约的一半是 Store 的分页上限与 SQL 条件本身。 + +func openVersionStore(t *testing.T) (*Store, *pgxpool.Pool) { + t.Helper() + databaseURL := pgtest.IsolatedDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if databaseURL == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, databaseURL) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(pool.Close) + if err := ApplyMigrations(ctx, pool); err != nil { + t.Fatalf("migrate: %v", err) + } + return NewStore(pool), pool +} + +func recordPrebackup(t *testing.T, ctx context.Context, store *Store, scope, jobID, snapshot string, created time.Time) { + t.Helper() + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionPrebackup, scope, snapshot), + Scope: scope, Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: snapshot, + SourceJobID: jobID, CreatedBy: "worker", + Evidence: map[string]any{"backup_snapshot": snapshot, "backup_bytes": 4096, "job": jobID}, + CreatedAt: created, + }); err != nil { + t.Fatalf("record prebackup %s: %v", snapshot, err) + } +} + +func TestLibraryVersionByRefSeparatesMissingFromConflict(t *testing.T) { + store, _ := openVersionStore(t) + ctx := context.Background() + now := time.Now().UTC() + recordPrebackup(t, ctx, store, "internal", "job-a", "snap-1", now) + + version, found, err := store.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionPrebackup, "job-a", "snap-1") + if err != nil || !found { + t.Fatalf("本作业的记录必须命中:found=%v err=%v", found, err) + } + if version.Evidence["backup_bytes"] != float64(4096) { + t.Fatalf("命中的记录必须带着原有证据:%v", version.Evidence) + } + + // 同一个快照的台账归别的作业所有:这是冲突,必须报错,不能当成"没有记录"。 + if _, found, err := store.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionPrebackup, "job-b", "snap-1"); err == nil || found { + t.Fatalf("作业不一致时必须报冲突:found=%v err=%v", found, err) + } else if !strings.Contains(err.Error(), "属于作业 job-a") { + t.Fatalf("冲突错误要指明归属,实际:%v", err) + } + + // 真的没有这条记录:found=false 且无错误(调用方据此失败,可重试造记录)。 + if _, found, err := store.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionPrebackup, "job-a", "snap-missing"); err != nil || found { + t.Fatalf("缺失必须是 found=false 且无错误:found=%v err=%v", found, err) + } + // 目标范围隔离:另一个 scope 的同名快照不算命中。 + if _, found, err := store.LibraryVersionByRef(ctx, "external", governance.LibraryVersionProductionPrebackup, "job-a", "snap-1"); err != nil || found { + t.Fatalf("跨 scope 不许命中:found=%v err=%v", found, err) + } + // 同快照但别的类型(例如生效版本)也不算命中。 + if _, found, err := store.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionEffective, "job-a", "snap-1"); err != nil || found { + t.Fatalf("跨 kind 不许命中:found=%v err=%v", found, err) + } +} + +func TestLibraryVersionByRefRejectsAmbiguousIdentity(t *testing.T) { + store, pool := openVersionStore(t) + ctx := context.Background() + now := time.Now().UTC() + recordPrebackup(t, ctx, store, "internal", "job-a", "snap-dup", now) + // 台账被写坏(同 scope+kind+snapshot 两行、不同 id):身份不再唯一。 + if _, err := pool.Exec(ctx, ` +INSERT INTO library_versions (id, scope, kind, snapshot_id, source_job_id, evidence, created_by, created_at) +VALUES ('libver-dup-fixture','internal','production_prebackup','snap-dup','job-a','{}'::jsonb,'worker',$1)`, now); err != nil { + t.Fatalf("insert duplicate row: %v", err) + } + if _, found, err := store.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionPrebackup, "job-a", "snap-dup"); err == nil || found { + t.Fatalf("身份不唯一时必须拒绝:found=%v err=%v", found, err) + } else if !strings.Contains(err.Error(), "拒绝挑选") { + t.Fatalf("错误要说清是重复身份,实际:%v", err) + } +} + +func TestLibraryVersionByRefFindsRowOutsideHistoryWindow(t *testing.T) { + store, _ := openVersionStore(t) + ctx := context.Background() + now := time.Now().UTC() + // 目标记录最老:任何"最近 N 条"(真实上限 100)都看不到它。 + recordPrebackup(t, ctx, store, "internal", "job-old", "snap-old", now.Add(-48*time.Hour)) + for i := 0; i < 150; i++ { + recordPrebackup(t, ctx, store, "internal", fmt.Sprintf("job-new-%03d", i), fmt.Sprintf("snap-new-%03d", i), + now.Add(-time.Duration(i)*time.Minute)) + } + window, err := store.LibraryVersions(ctx, "internal", 100) + if err != nil { + t.Fatalf("list versions: %v", err) + } + for _, item := range window { + if item.SnapshotID == "snap-old" { + t.Fatal("窗口里仍能看到目标记录:本用例证明不了窗口之外仍可精确取回(夹具失效)") + } + } + version, found, err := store.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionPrebackup, "job-old", "snap-old") + if err != nil || !found { + t.Fatalf("窗口之外也必须精确命中:found=%v err=%v", found, err) + } + if version.SourceJobID != "job-old" || version.SnapshotID != "snap-old" { + t.Fatalf("命中的不是目标记录:%+v", version) + } +} + +// 空身份不许被当成"查所有":少一个字段就等于换了一种查询,必须直接拒绝。 +func TestLibraryVersionByRefRejectsIncompleteRef(t *testing.T) { + store, _ := openVersionStore(t) + ctx := context.Background() + cases := []struct{ scope, job, snapshot string }{ + {"", "job-a", "snap-1"}, + {"internal", "", "snap-1"}, + {"internal", "job-a", ""}, + } + for _, item := range cases { + if _, found, err := store.LibraryVersionByRef(ctx, item.scope, + governance.LibraryVersionProductionPrebackup, item.job, item.snapshot); err == nil || found { + t.Fatalf("不完整身份必须拒绝:%+v found=%v err=%v", item, found, err) + } + } +} + +func recordEffective(t *testing.T, ctx context.Context, store *Store, scope, jobID, snapshot string, created time.Time) { + t.Helper() + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ + ID: governance.LibraryVersionID(governance.LibraryVersionProductionEffective, scope, snapshot), + Scope: scope, Kind: governance.LibraryVersionProductionEffective, SnapshotID: snapshot, + SourceJobID: jobID, CreatedBy: "worker", + Evidence: map[string]any{"action": "sync", "job": jobID}, + CreatedAt: created, + }); err != nil { + t.Fatalf("record effective %s: %v", snapshot, err) + } +} + +// 当前生效版本必须按"未顶替"这个事实精确查,不能靠"最近 N 条":历史一旦超过窗口, +// 生效版本会被读成"没有",接管/基线/同步闸口就会把已经生效的目标再写一遍。 +func TestLibraryCurrentVersionFindsEffectiveOutsideHistoryWindow(t *testing.T) { + store, _ := openVersionStore(t) + ctx := context.Background() + now := time.Now().UTC() + // 生效版本登记在很早的时刻,之后同 scope 又写了 300 条其它版本(真实列表上限 100)。 + recordEffective(t, ctx, store, "internal", "job-cur", "snap-cur", now.Add(-72*time.Hour)) + for i := 0; i < 300; i++ { + recordPrebackup(t, ctx, store, "internal", fmt.Sprintf("job-new-%03d", i), fmt.Sprintf("snap-new-%03d", i), + now.Add(-time.Duration(i)*time.Minute)) + } + window, err := store.LibraryVersions(ctx, "internal", 100) + if err != nil { + t.Fatalf("list versions: %v", err) + } + for _, item := range window { + if item.SnapshotID == "snap-cur" { + t.Fatal("窗口里仍能看到生效版本:本用例证明不了窗口之外仍可精确取回(夹具失效)") + } + } + + current, found, err := store.LibraryCurrentVersion(ctx, "internal") + if err != nil || !found { + t.Fatalf("窗口之外也必须取到当前生效版本:found=%v err=%v", found, err) + } + if current.SnapshotID != "snap-cur" || current.SourceJobID != "job-cur" || current.SupersededAt != nil { + t.Fatalf("取到的不是当前生效版本:%+v", current) + } + + // 新版本生效后,旧快照按身份查仍然"存在但已顶替"——接管据此拒绝用旧快照覆盖。 + recordEffective(t, ctx, store, "internal", "job-new", "snap-newest", now) + current, found, err = store.LibraryCurrentVersion(ctx, "internal") + if err != nil || !found || current.SnapshotID != "snap-newest" { + t.Fatalf("当前生效版本必须切到最新一份:found=%v err=%v %+v", found, err, current) + } + previous, found, err := store.LibraryVersionOfSnapshot(ctx, "internal", + governance.LibraryVersionProductionEffective, "snap-cur") + if err != nil || !found { + t.Fatalf("旧快照必须仍能按身份取回:found=%v err=%v", found, err) + } + if previous.SupersededAt == nil { + t.Fatalf("旧快照必须标成已顶替:%+v", previous) + } +} + +// 没有生效版本 ≠ 查询失败:前者是"首次发布",后者必须让调用方 fail closed。 +func TestLibraryCurrentVersionSeparatesMissingFromOtherKinds(t *testing.T) { + store, _ := openVersionStore(t) + ctx := context.Background() + now := time.Now().UTC() + recordPrebackup(t, ctx, store, "internal", "job-a", "snap-1", now) + if _, found, err := store.LibraryCurrentVersion(ctx, "internal"); err != nil || found { + t.Fatalf("只有预备份时不能当成有生效版本:found=%v err=%v", found, err) + } + recordEffective(t, ctx, store, "internal", "job-a", "snap-eff", now) + // 跨 scope 不许命中。 + if _, found, err := store.LibraryCurrentVersion(ctx, "external"); err != nil || found { + t.Fatalf("跨 scope 不许命中:found=%v err=%v", found, err) + } + if _, found, err := store.LibraryVersionOfSnapshot(ctx, "external", + governance.LibraryVersionProductionEffective, "snap-eff"); err != nil || found { + t.Fatalf("跨 scope 的快照查询不许命中:found=%v err=%v", found, err) + } + if _, found, err := store.LibraryVersionOfSnapshot(ctx, "internal", + governance.LibraryVersionProductionEffective, "snap-missing"); err != nil || found { + t.Fatalf("未登记的快照必须 found=false 且无错误:found=%v err=%v", found, err) + } +} + +// 同一快照两行(台账被写坏):按身份查必须拒绝挑选,不许挑一条"看起来对"的。 +func TestLibraryVersionOfSnapshotRejectsAmbiguousRows(t *testing.T) { + store, pool := openVersionStore(t) + ctx := context.Background() + now := time.Now().UTC() + recordPrebackup(t, ctx, store, "internal", "job-a", "snap-dup", now) + if _, err := pool.Exec(ctx, ` +INSERT INTO library_versions (id, scope, kind, snapshot_id, source_job_id, evidence, created_by, created_at) +VALUES ('libver-dup-current','internal','production_prebackup','snap-dup','job-b','{}'::jsonb,'worker',$1)`, now); err != nil { + t.Fatalf("insert duplicate row: %v", err) + } + if _, found, err := store.LibraryVersionOfSnapshot(ctx, "internal", + governance.LibraryVersionProductionPrebackup, "snap-dup"); err == nil || found { + t.Fatalf("同一快照多行时必须拒绝:found=%v err=%v", found, err) + } else if !strings.Contains(err.Error(), "拒绝挑选") { + t.Fatalf("错误要说清是重复身份,实际:%v", err) + } +} diff --git a/internal/platform/postgres/library_write_fence.go b/internal/platform/postgres/library_write_fence.go new file mode 100644 index 0000000..1fe7081 --- /dev/null +++ b/internal/platform/postgres/library_write_fence.go @@ -0,0 +1,249 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/governance" +) + +// 写入栅栏:所有"业务状态 / 维护锁"的写都必须证明调用方仍是**当前活跃代次**。 +// +// 两条条件缺一不可: +// 1. 作业行上的 (attempt_epoch, lease_owner) 就是这次的 (epoch, owner); +// 2. library_attempts 里那一代次仍是 active(claimed/running)。 +// +// 为什么第 2 条不能省(R2):接管/续跑会激活新一代次,而**旧作业行上的 epoch/owner +// 字段仍原样保留**。只比较旧作业行,旧执行器的守卫会继续通过——它就能继续写业务状态、 +// 释放别人刚拿到的锁。把"该代次仍活跃"作为条件后,旧代次被结束的那一刻起, +// 它的所有守卫写都会失败。 +// +// 参数契约(R1):作业 id 取自**被更新行自己的列**(`library_maintenance.owner_job_id` +// 等),不写死 `$1`——维护类更新的 `$1` 是 scope/instance,写死 `$1` 会让守卫永远匹配 +// 不到作业,正常写与释放全部失败。列表达式由调用方传入,序号漂移不可能再发生。 + +// libraryFence 生成"调用方仍是当前活跃代次"的谓词。jobIDExpr 是**列表达式**。 +func libraryFence(jobIDExpr string, epochParam, ownerParam int) string { + return fmt.Sprintf(`EXISTS ( + SELECT 1 FROM library_jobs j + WHERE j.id = %s + AND j.attempt_epoch = $%d + AND j.lease_owner = $%d + AND j.lease_until > clock_timestamp() + AND ( + j.operation_id = '' + OR EXISTS ( + SELECT 1 FROM library_attempts a + WHERE a.operation_id = j.operation_id + AND a.epoch = j.attempt_epoch + AND a.owner = j.lease_owner + AND a.state IN ('claimed','running') + AND a.lease_until > clock_timestamp() + ) + ) + )`, jobIDExpr, epochParam, ownerParam) +} + +// AdvanceLibraryJobGuarded 只在调用方仍是该作业当前代次时写业务状态。 +func (s *Store) AdvanceLibraryJobGuarded(ctx context.Context, attempt governance.LibraryAttempt, + state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error { + finished := any(nil) + if state == governance.LibraryJobSucceeded || state == governance.LibraryJobFailed || state == governance.LibraryJobCancelled { + finished = now.UTC() + } + tag, err := s.db.Exec(ctx, ` +UPDATE library_jobs SET + state=$2::text, + stage = CASE WHEN $3::text='' THEN stage ELSE $3::text END, + error = CASE WHEN $4::text='' THEN error ELSE $4::text END, + recovery = CASE WHEN $5::text='' THEN recovery ELSE $5::text END, + snapshot_id = CASE WHEN $6::text='' THEN snapshot_id ELSE $6::text END, + target_snapshot_id = CASE WHEN $7::text='' THEN target_snapshot_id ELSE $7::text END, + updated_at=$8, + finished_at=COALESCE($9, finished_at) +WHERE id=$1 AND `+libraryFence("$1", 10, 11), + attempt.JobID, string(state), stage, message, recovery, snapshotID, targetSnapshotID, now.UTC(), finished, + attempt.Epoch, attempt.Owner) + if err != nil { + return fmt.Errorf("advance library job (guarded): %w", err) + } + if tag.RowsAffected() != 1 { + return s.fencedWriteError(ctx, attempt, "advance library job") + } + return nil +} + +// UpdateLibraryStageGuarded 是阶段进度的守卫版:失租代次不能再写"我这一阶段成功了"。 +func (s *Store) UpdateLibraryStageGuarded(ctx context.Context, attempt governance.LibraryAttempt, + stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error { + tag, err := s.db.Exec(ctx, ` +UPDATE library_job_stages SET + state = CASE WHEN $3::text='' THEN state ELSE $3::text END, + total = COALESCE($4, total), + completed = COALESCE($5, completed), + bytes_total = COALESCE($6, bytes_total), + bytes_done = COALESCE($7, bytes_done), + detail = CASE WHEN $8::text='' THEN detail ELSE $8::text END, + updated_at = $9 +WHERE job_id=$1 AND stage=$2 AND `+libraryFence("$1", 10, 11), + attempt.JobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC(), + attempt.Epoch, attempt.Owner) + if err != nil { + return fmt.Errorf("update library stage (guarded): %w", err) + } + if tag.RowsAffected() != 1 { + return s.fencedWriteError(ctx, attempt, "update library stage") + } + return nil +} + +// ReleaseLibraryMaintenanceGuarded 释放 scope 维护锁,但只认当前代次。 +func (s *Store) ReleaseLibraryMaintenanceGuarded(ctx context.Context, scope, ownerJobID string, + attempt governance.LibraryAttempt, now time.Time) error { + tag, err := s.db.Exec(ctx, ` +UPDATE library_maintenance SET state='released', released_at=$3, updated_at=$3 +WHERE scope=$1 AND owner_job_id=$2 AND released_at IS NULL + AND `+libraryFence("library_maintenance.owner_job_id", 4, 5), scope, ownerJobID, now.UTC(), + attempt.Epoch, attempt.Owner) + if err != nil { + return fmt.Errorf("release library maintenance (guarded): %w", err) + } + if tag.RowsAffected() == 0 { + if s.releasedByThisJob(ctx, "library_maintenance", "scope", scope, ownerJobID) { + return ErrMaintenanceReleased + } + return s.fencedWriteError(ctx, attempt, "release library maintenance") + } + return nil +} + +// ReleaseInstanceMaintenanceGuarded 释放实例维护锁,但只认当前代次。 +func (s *Store) ReleaseInstanceMaintenanceGuarded(ctx context.Context, instance, ownerJobID string, + attempt governance.LibraryAttempt, now time.Time) error { + tag, err := s.db.Exec(ctx, ` +UPDATE library_instance_maintenance SET state='released', released_at=$3, updated_at=$3 +WHERE instance=$1 AND owner_job_id=$2 AND released_at IS NULL + AND `+libraryFence("library_instance_maintenance.owner_job_id", 4, 5), instance, ownerJobID, now.UTC(), + attempt.Epoch, attempt.Owner) + if err != nil { + return fmt.Errorf("release instance maintenance (guarded): %w", err) + } + if tag.RowsAffected() == 0 { + if s.releasedByThisJob(ctx, "library_instance_maintenance", "instance", instance, ownerJobID) { + return ErrMaintenanceReleased + } + return s.fencedWriteError(ctx, attempt, "release instance maintenance") + } + return nil +} + +// UpdateLibraryMaintenanceStateGuarded / UpdateInstanceMaintenanceStateGuarded 同理: +// 失租代次不能把窗口改成 needs_restore / verified 去影响当前代次的判断。 +func (s *Store) UpdateLibraryMaintenanceStateGuarded(ctx context.Context, scope, ownerJobID, state, note string, + attempt governance.LibraryAttempt, now time.Time) error { + tag, err := s.db.Exec(ctx, ` +UPDATE library_maintenance SET state=$3, note=$4, updated_at=$5 +WHERE scope=$1 AND owner_job_id=$2 AND released_at IS NULL + AND `+libraryFence("library_maintenance.owner_job_id", 6, 7), scope, ownerJobID, state, note, now.UTC(), + attempt.Epoch, attempt.Owner) + if err != nil { + return fmt.Errorf("update library maintenance (guarded): %w", err) + } + if tag.RowsAffected() == 0 { + if s.releasedByThisJob(ctx, "library_maintenance", "scope", scope, ownerJobID) { + return ErrMaintenanceReleased + } + return s.fencedWriteError(ctx, attempt, "update library maintenance") + } + return nil +} + +func (s *Store) UpdateInstanceMaintenanceStateGuarded(ctx context.Context, instance, ownerJobID, state, note string, + attempt governance.LibraryAttempt, now time.Time) error { + tag, err := s.db.Exec(ctx, ` +UPDATE library_instance_maintenance SET state=$3, note=$4, updated_at=$5 +WHERE instance=$1 AND owner_job_id=$2 AND released_at IS NULL + AND `+libraryFence("library_instance_maintenance.owner_job_id", 6, 7), instance, ownerJobID, state, note, + now.UTC(), attempt.Epoch, attempt.Owner) + if err != nil { + return fmt.Errorf("update instance maintenance (guarded): %w", err) + } + if tag.RowsAffected() == 0 { + if s.releasedByThisJob(ctx, "library_instance_maintenance", "instance", instance, ownerJobID) { + return ErrMaintenanceReleased + } + return s.fencedWriteError(ctx, attempt, "update instance maintenance") + } + return nil +} + +// fencedWriteError 区分"作业不存在"与"代次已过期":两者都要停下,但文案不能误导运维。 +func (s *Store) fencedWriteError(ctx context.Context, attempt governance.LibraryAttempt, action string) error { + var epoch int + var owner, operation string + err := s.db.QueryRow(ctx, `SELECT attempt_epoch, lease_owner, operation_id FROM library_jobs WHERE id=$1`, + attempt.JobID).Scan(&epoch, &owner, &operation) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s:作业 %s 不存在", action, attempt.JobID) + } + if err != nil { + return fmt.Errorf("%s:读不到作业代次:%w", action, err) + } + var state string + if operation != "" { + _ = s.db.QueryRow(ctx, `SELECT state FROM library_attempts WHERE operation_id=$1 AND epoch=$2`, + operation, attempt.Epoch).Scan(&state) + } + return fmt.Errorf("%w(%s:本代次 %d/%s,作业行 %d/%s,代次状态 %q)", governance.ErrLibraryEpochStale, + action, attempt.Epoch, attempt.Owner, epoch, owner, state) +} + +func (s *Store) SetInstanceMaintenanceIngressGuarded(ctx context.Context, instance, ownerJobID, state, note string, + attempt governance.LibraryAttempt, now time.Time) error { + if state != "closed" && state != "open" { + return errors.New("invalid ingress state") + } + tag, err := s.db.Exec(ctx, ` +UPDATE library_instance_maintenance SET ingress_state=$3, note=$4, updated_at=$5 +WHERE instance=$1 AND owner_job_id=$2 AND released_at IS NULL + AND `+libraryFence("library_instance_maintenance.owner_job_id", 6, 7), instance, ownerJobID, state, note, + now.UTC(), attempt.Epoch, attempt.Owner) + if err != nil { + return fmt.Errorf("update instance maintenance ingress (guarded): %w", err) + } + if tag.RowsAffected() == 0 { + if s.releasedByThisJob(ctx, "library_instance_maintenance", "instance", instance, ownerJobID) { + return ErrMaintenanceReleased + } + return s.fencedWriteError(ctx, attempt, "update instance maintenance ingress") + } + return nil +} + +// SetLibraryMaintenanceIngressGuarded 记录入口状态也需要代次守卫: +// "入口已关"是隔离证据,失租代次写它等于伪造证据。 +func (s *Store) SetLibraryMaintenanceIngressGuarded(ctx context.Context, scope, ownerJobID, state, note string, + attempt governance.LibraryAttempt, now time.Time) error { + if state != "closed" && state != "open" { + return errors.New("invalid ingress state") + } + tag, err := s.db.Exec(ctx, ` +UPDATE library_maintenance SET ingress_state=$3, note=$4, updated_at=$5 +WHERE scope=$1 AND owner_job_id=$2 AND released_at IS NULL + AND `+libraryFence("library_maintenance.owner_job_id", 6, 7), scope, ownerJobID, state, note, now.UTC(), + attempt.Epoch, attempt.Owner) + if err != nil { + return fmt.Errorf("update library maintenance ingress (guarded): %w", err) + } + if tag.RowsAffected() == 0 { + if s.releasedByThisJob(ctx, "library_maintenance", "scope", scope, ownerJobID) { + return ErrMaintenanceReleased + } + return s.fencedWriteError(ctx, attempt, "update library maintenance ingress") + } + return nil +} diff --git a/internal/platform/postgres/migrate.go b/internal/platform/postgres/migrate.go index a41aad0..829b81f 100644 --- a/internal/platform/postgres/migrate.go +++ b/internal/platform/postgres/migrate.go @@ -3,6 +3,7 @@ package postgres import ( "context" "embed" + "errors" "fmt" "io/fs" "sort" @@ -138,3 +139,46 @@ func RollbackLatestMigration(ctx context.Context, pool *pgxpool.Pool) error { } return nil } + +// PendingMigrations 只读地回答"治理库 schema 落后了没有"。 +// +// 给"不拥有 DDL 的执行器"用(云端发布执行器):启动即校验,落后就拒绝启动, +// 绝不顺手迁移——治理库结构由控制面那个进程决定,不因为多了一台机器就多一个 DDL 源。 +func PendingMigrations(ctx context.Context, pool *pgxpool.Pool) ([]int64, error) { + if pool == nil { + return nil, errors.New("database pool is required") + } + migrations, err := loadMigrations() + if err != nil { + return nil, err + } + var ledgerExists bool + if err := pool.QueryRow(ctx, "SELECT to_regclass('public.schema_migrations') IS NOT NULL").Scan(&ledgerExists); err != nil { + return nil, fmt.Errorf("check migration ledger: %w", err) + } + applied := map[int64]bool{} + if ledgerExists { + rows, err := pool.Query(ctx, "SELECT version FROM schema_migrations") + if err != nil { + return nil, fmt.Errorf("read migration ledger: %w", err) + } + defer rows.Close() + for rows.Next() { + var version int64 + if err := rows.Scan(&version); err != nil { + return nil, err + } + applied[version] = true + } + if err := rows.Err(); err != nil { + return nil, err + } + } + pending := make([]int64, 0, 4) + for _, item := range migrations { + if !applied[item.Version] { + pending = append(pending, item.Version) + } + } + return pending, nil +} diff --git a/internal/platform/postgres/migrations/000076_library_operation_identity.down.sql b/internal/platform/postgres/migrations/000076_library_operation_identity.down.sql new file mode 100644 index 0000000..6fc3aec --- /dev/null +++ b/internal/platform/postgres/migrations/000076_library_operation_identity.down.sql @@ -0,0 +1,29 @@ +-- 回滚:只撤掉 identity/指针这一层。**不删任何版本事件、作业或证据**(历史不可回填)。 +-- 回滚后 library_versions 仍是完整台账;current 重新由 superseded_at 表达。 +DROP TABLE IF EXISTS library_current_versions; + +UPDATE library_versions SET superseded_at = NULL +WHERE id IN ( + SELECT id FROM ( + SELECT id, row_number() OVER (PARTITION BY scope ORDER BY created_at DESC, id DESC) AS rn + FROM library_versions + WHERE kind = 'production_effective' + ) ranked WHERE rn = 1 +); + +ALTER TABLE library_versions DROP CONSTRAINT IF EXISTS library_versions_kind_check; +DELETE FROM library_versions WHERE kind = 'recovery_verified'; +ALTER TABLE library_versions ADD CONSTRAINT library_versions_kind_check + CHECK (kind IN ('test_sealed','production_effective','production_prebackup')); +ALTER TABLE library_versions DROP COLUMN IF EXISTS attempt_epoch; +ALTER TABLE library_versions DROP COLUMN IF EXISTS operation_id; +CREATE UNIQUE INDEX IF NOT EXISTS library_versions_effective ON library_versions(scope) + WHERE kind = 'production_effective' AND superseded_at IS NULL; + +ALTER TABLE library_jobs DROP COLUMN IF EXISTS lease_until; +ALTER TABLE library_jobs DROP COLUMN IF EXISTS lease_owner; +ALTER TABLE library_jobs DROP COLUMN IF EXISTS attempt_epoch; +ALTER TABLE library_jobs DROP COLUMN IF EXISTS operation_id; + +DROP TABLE IF EXISTS library_attempts; +DROP TABLE IF EXISTS library_operations; \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000076_library_operation_identity.up.sql b/internal/platform/postgres/migrations/000076_library_operation_identity.up.sql new file mode 100644 index 0000000..d8a6b20 --- /dev/null +++ b/internal/platform/postgres/migrations/000076_library_operation_identity.up.sql @@ -0,0 +1,110 @@ +-- 发布执行身份:operation(一次意图)/ attempt(执行代次)/ 不可变版本事件 / current 指针。 +-- +-- 为什么现在加、且只加在治理库: +-- · 旧实现把"用户的一次意图"等同于"某个快照的终身幂等键",于是 A→B→A 的第三次请求 +-- 拿到的是第一次的历史成功,什么也不做(F01);版本行主键只由 (kind,scope,快照) 决定, +-- 第二次登记直接覆盖 source_job_id/evidence/created_at(F02/F09)。 +-- · 接管没有代次:两个 worker 可以把同一 pending 作业都认领走,失租的旧执行还能继续 +-- 写业务状态、释放别人的维护锁(F13)。 +-- +-- 这里不修改 WeKnora 的 Schema/源码/镜像,也不声称数据库 CAS 能拦住已经发出去的 +-- S3/ES 请求:跨系统原子性不存在,物理执行域隔离另由部署准入负责。 + +-- ── operation:一次明确意图(不可变)──────────────────────────────────── +CREATE TABLE IF NOT EXISTS library_operations ( + id VARCHAR(64) PRIMARY KEY, + scope VARCHAR(16) NOT NULL CHECK (scope IN ('internal','external')), + kind VARCHAR(16) NOT NULL, + target_snapshot_id VARCHAR(64) NOT NULL DEFAULT '', + request_digest VARCHAR(64) NOT NULL, + -- 客户端可重放的意图键:同一个键 + 同一个摘要 ⇒ 同一次意图(重放幂等); + -- 换一个键 ⇒ 新意图,即使目标快照与历史成功完全相同。 + operation_key VARCHAR(255) NOT NULL, + actor VARCHAR(128) NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL, + -- 不可变首次锚点:由第一次成功拍下预备份/写集合的执行写入,之后只读。 + first_backup_snapshot_id VARCHAR(64), + first_backup_bytes BIGINT, + first_backup_at TIMESTAMPTZ, + writeset_digest VARCHAR(64), + writeset_rows BIGINT, + target_fingerprint VARCHAR(128), + anchors_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS library_operations_key + ON library_operations(scope, kind, operation_key); + +-- ── attempt:执行代次(epoch),同一 operation 只允许一个活跃代次 ───────── +CREATE TABLE IF NOT EXISTS library_attempts ( + operation_id VARCHAR(64) NOT NULL REFERENCES library_operations(id), + epoch INTEGER NOT NULL CHECK (epoch >= 1), + job_id VARCHAR(64) NOT NULL, + queue_job_id VARCHAR(64) NOT NULL DEFAULT '', + owner VARCHAR(128) NOT NULL DEFAULT '', + state VARCHAR(16) NOT NULL CHECK (state IN ('claimed','running','completed','failed','abandoned')), + started_at TIMESTAMPTZ NOT NULL, + heartbeat_at TIMESTAMPTZ, + lease_until TIMESTAMPTZ, + finished_at TIMESTAMPTZ, + outcome TEXT NOT NULL DEFAULT '', + PRIMARY KEY (operation_id, epoch) +); +-- 一个作业行可以有多条**不可变**代次:接管/续跑本身就是"同一作业的新执行", +-- 若按 (job_id) 唯一,第二次接管只能改写旧行 —— 那就不是不可变历史了(R2)。 +-- 这里只保留普通索引,供"这个作业的所有代次"查询。 +CREATE INDEX IF NOT EXISTS library_attempts_job ON library_attempts(job_id); +-- 同一 operation 同时只能有一个活跃代次:第二个 resumer 的失败不能释放另一个代次的锁。 +CREATE UNIQUE INDEX IF NOT EXISTS library_attempts_active + ON library_attempts(operation_id) WHERE state IN ('claimed','running'); + +-- ── 作业行继承 operation/代次与租约(写入守卫读这里)───────────────────── +ALTER TABLE library_jobs ADD COLUMN IF NOT EXISTS operation_id VARCHAR(64) NOT NULL DEFAULT ''; +ALTER TABLE library_jobs ADD COLUMN IF NOT EXISTS attempt_epoch INTEGER NOT NULL DEFAULT 0; +ALTER TABLE library_jobs ADD COLUMN IF NOT EXISTS lease_owner VARCHAR(128) NOT NULL DEFAULT ''; +ALTER TABLE library_jobs ADD COLUMN IF NOT EXISTS lease_until TIMESTAMPTZ; + +-- ── 版本行:不可变事件 + 执行身份;允许 recovery_verified ──────────────── +ALTER TABLE library_versions ADD COLUMN IF NOT EXISTS operation_id VARCHAR(64) NOT NULL DEFAULT ''; +ALTER TABLE library_versions ADD COLUMN IF NOT EXISTS attempt_epoch INTEGER NOT NULL DEFAULT 0; +ALTER TABLE library_versions DROP CONSTRAINT IF EXISTS library_versions_kind_check; +ALTER TABLE library_versions ADD CONSTRAINT library_versions_kind_check + CHECK (kind IN ('test_sealed','production_effective','production_prebackup','recovery_verified')); + +-- 旧唯一索引禁止同一 scope 出现第二条未顶替的生效行——那是"用 UPDATE 顶替"的实现细节。 +-- 现在"谁是当前"由指针表表达,事件本身不再被改写;索引留着反而会逼写入方去 UPDATE 历史。 +DROP INDEX IF EXISTS library_versions_effective; + +-- ── current 指针:单调次序 + 条件更新,不覆盖事件 ─────────────────────── +CREATE TABLE IF NOT EXISTS library_current_versions ( + scope VARCHAR(16) PRIMARY KEY CHECK (scope IN ('internal','external')), + version_id VARCHAR(64) NOT NULL REFERENCES library_versions(id), + snapshot_id VARCHAR(64) NOT NULL, + operation_id VARCHAR(64) NOT NULL DEFAULT '', + attempt_epoch INTEGER NOT NULL DEFAULT 0, + -- 排序键 = (事件登记时间|operation|epoch),见 governance.CurrentOrderKey。 + -- 只有更大的键才能推进指针:更早的事实不能把当前状态拉回历史。 + order_key VARCHAR(255) NOT NULL, + updated_at TIMESTAMPTZ NOT NULL +); + +-- 回填:只搬运"已登记且未被顶替"的既有生效版本(不新造版本行、不改旧证据)。 +INSERT INTO library_current_versions(scope, version_id, snapshot_id, operation_id, attempt_epoch, order_key, updated_at) +SELECT v.scope, v.id, v.snapshot_id, v.operation_id, v.attempt_epoch, + lpad((extract(epoch from v.created_at) * 1000000)::bigint::text, 20, '0') || '|' || v.operation_id || '|' || lpad(v.attempt_epoch::text, 9, '0'), + v.created_at +FROM library_versions v +WHERE v.kind = 'production_effective' AND v.superseded_at IS NULL +ON CONFLICT (scope) DO NOTHING; + +-- 历史行不再靠 superseded_at 表达"当前":把指针指向的那一行标成未顶替,其余保持原值。 +-- 这里只补元数据、不改任何证据字段(source_job_id/evidence/created_at 原样)。 +UPDATE library_versions v +SET superseded_at = NULL +WHERE v.id IN (SELECT version_id FROM library_current_versions) + AND v.superseded_at IS NOT NULL; + +UPDATE library_versions v +SET superseded_at = coalesce(v.superseded_at, now()) +WHERE v.kind = 'production_effective' + AND v.superseded_at IS NULL + AND NOT EXISTS (SELECT 1 FROM library_current_versions c WHERE c.version_id = v.id); \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000077_library_target_identity.down.sql b/internal/platform/postgres/migrations/000077_library_target_identity.down.sql new file mode 100644 index 0000000..c07402e --- /dev/null +++ b/internal/platform/postgres/migrations/000077_library_target_identity.down.sql @@ -0,0 +1,17 @@ +-- 已产生目标绑定证据时不可降级为 scope-only,否则会把不同目标历史混为一谈。 +DO $$ BEGIN + IF EXISTS (SELECT 1 FROM library_versions WHERE target_id <> '') + OR EXISTS (SELECT 1 FROM library_operations WHERE target_id <> '') + OR EXISTS (SELECT 1 FROM library_jobs WHERE target_id <> '') + OR EXISTS (SELECT 1 FROM library_release_authorizations WHERE target_id <> '') THEN + RAISE EXCEPTION 'target-bound release evidence exists; restore the verified control-plane backup instead of downgrading'; + END IF; +END $$; +ALTER TABLE library_current_versions DROP CONSTRAINT library_current_versions_pkey; +ALTER TABLE library_current_versions DROP COLUMN target_id; +ALTER TABLE library_current_versions ADD PRIMARY KEY (scope); +DROP INDEX library_versions_target; +ALTER TABLE library_versions DROP COLUMN target_id; +ALTER TABLE library_operations DROP COLUMN target_id; +ALTER TABLE library_jobs DROP COLUMN target_id; +ALTER TABLE library_release_authorizations DROP COLUMN target_id; diff --git a/internal/platform/postgres/migrations/000077_library_target_identity.up.sql b/internal/platform/postgres/migrations/000077_library_target_identity.up.sql new file mode 100644 index 0000000..846d176 --- /dev/null +++ b/internal/platform/postgres/migrations/000077_library_target_identity.up.sql @@ -0,0 +1,9 @@ +-- 旧记录无法证明属于新配置目标;保留在空身份的历史空间,不猜测回填。 +ALTER TABLE library_operations ADD COLUMN target_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE library_jobs ADD COLUMN target_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE library_release_authorizations ADD COLUMN target_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE library_versions ADD COLUMN target_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE library_current_versions ADD COLUMN target_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE library_current_versions DROP CONSTRAINT library_current_versions_pkey; +ALTER TABLE library_current_versions ADD PRIMARY KEY (scope, target_id); +CREATE INDEX library_versions_target ON library_versions (target_id, scope, kind, created_at DESC); diff --git a/internal/platform/postgres/migrations/000078_library_restore_dispatch.down.sql b/internal/platform/postgres/migrations/000078_library_restore_dispatch.down.sql new file mode 100644 index 0000000..fdb5094 --- /dev/null +++ b/internal/platform/postgres/migrations/000078_library_restore_dispatch.down.sql @@ -0,0 +1,23 @@ +-- 已有派发记录或激活/撤销证据时拒绝自动回滚:这些行是"是否发送过 / 是否曾被授权" +-- 的唯一证明,用 down 抹掉等于把 unknown 重新伪装成 prepared,或把已撤销的激活 +-- 悄悄删掉。人工处置必须先导出并存档。仅有一条已撤销 activation、尚无任何 effect +-- 行时同样拒绝——撤销事实本身也是证据。 +DO $$ +BEGIN + IF to_regclass('library_index_restore_dispatch') IS NOT NULL + AND EXISTS (SELECT 1 FROM library_index_restore_dispatch LIMIT 1) THEN + RAISE EXCEPTION 'refusing to drop restore dispatch evidence with recorded rows'; + END IF; + IF to_regclass('library_index_restore_dispatch_activation') IS NOT NULL + AND EXISTS (SELECT 1 FROM library_index_restore_dispatch_activation LIMIT 1) THEN + RAISE EXCEPTION 'refusing to drop restore dispatch activation evidence'; + END IF; +END $$; + +DROP TRIGGER IF EXISTS library_index_restore_dispatch_monotone ON library_index_restore_dispatch; +DROP FUNCTION IF EXISTS library_index_restore_dispatch_guard(); +DROP TABLE IF EXISTS library_index_restore_dispatch; + +DROP TRIGGER IF EXISTS library_index_restore_dispatch_activation_guard_trg ON library_index_restore_dispatch_activation; +DROP FUNCTION IF EXISTS library_index_restore_dispatch_activation_guard(); +DROP TABLE IF EXISTS library_index_restore_dispatch_activation; \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000078_library_restore_dispatch.up.sql b/internal/platform/postgres/migrations/000078_library_restore_dispatch.up.sql new file mode 100644 index 0000000..0f74e21 --- /dev/null +++ b/internal/platform/postgres/migrations/000078_library_restore_dispatch.up.sql @@ -0,0 +1,118 @@ +-- DS01:恢复标记派发的唯一持久台账。 +-- +-- 它记录的是"这个固定 effect 是否已经有人取得过向索引发送一次 `_create` 的许可", +-- 不是"ES 历史上没写过这个 ID"。判据只有单调状态:prepared -> dispatching -> +-- marker_confirmed。行不可删、绑定不可改、状态不可回退;删除型恢复的新能力只在 +-- 这张表里 prepared 的区段可跨进程续作。 +CREATE TABLE IF NOT EXISTS library_index_restore_dispatch ( + id bigserial PRIMARY KEY, + protocol_version integer NOT NULL DEFAULT 1 CHECK (protocol_version = 1), + target_identity text NOT NULL, + operation_id text NOT NULL, + window_job_id text NOT NULL, + plan_digest text NOT NULL, + index_name text NOT NULL, + document_id text NOT NULL, + phase text NOT NULL CHECK (phase = 'restore-marker-create'), + binding_digest text NOT NULL CHECK (binding_digest <> ''), + state text NOT NULL CHECK (state IN ('prepared','dispatching','marker_confirmed')), + failure_reason text NOT NULL DEFAULT '', + dispatch_owner text NOT NULL DEFAULT '', + dispatch_epoch integer NOT NULL DEFAULT 0, + dispatch_nonce text NOT NULL DEFAULT '', + request_digest text NOT NULL DEFAULT '', + marker_receipt jsonb, + prepared_at timestamptz NOT NULL DEFAULT now(), + dispatch_committed_at timestamptz, + confirmed_at timestamptz, + updated_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT library_index_restore_dispatch_identity UNIQUE + (target_identity, operation_id, window_job_id, plan_digest, index_name, document_id, phase), + -- dispatching 及之后必须留着当时的派发身份:没有它就不能证明许可属于谁。 + CONSTRAINT library_index_restore_dispatch_dispatch_proof CHECK ( + state = 'prepared' OR ( + dispatch_owner <> '' AND dispatch_epoch > 0 AND dispatch_nonce <> '' AND + request_digest <> '' AND dispatch_committed_at IS NOT NULL + ) + ) +); + +CREATE OR REPLACE FUNCTION library_index_restore_dispatch_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'restore dispatch evidence is append-only'; + END IF; + IF NEW.target_identity <> OLD.target_identity OR NEW.operation_id <> OLD.operation_id OR + NEW.window_job_id <> OLD.window_job_id OR NEW.plan_digest <> OLD.plan_digest OR + NEW.index_name <> OLD.index_name OR NEW.document_id <> OLD.document_id OR + NEW.phase <> OLD.phase OR NEW.binding_digest <> OLD.binding_digest OR + NEW.protocol_version <> OLD.protocol_version THEN + RAISE EXCEPTION 'restore dispatch binding is immutable'; + END IF; + IF NEW.state = OLD.state THEN + RETURN NEW; + END IF; + IF OLD.state = 'prepared' AND NEW.state = 'dispatching' THEN + RETURN NEW; + END IF; + IF OLD.state = 'dispatching' AND NEW.state = 'marker_confirmed' THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'restore dispatch state % -> % is not monotone', OLD.state, NEW.state; +END; +$$ LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS library_index_restore_dispatch_monotone ON library_index_restore_dispatch; +CREATE TRIGGER library_index_restore_dispatch_monotone + BEFORE UPDATE OR DELETE ON library_index_restore_dispatch + FOR EACH ROW EXECUTE FUNCTION library_index_restore_dispatch_guard(); + +-- 激活登记:配置开关不是独占证明。只有部署流程把一份可核验的"旧 writer 已退出并 +-- 排空"证据文件登记到这个目标上,协议才对该目标生效。 +-- +-- 除 revoked_at 外全部不可变;撤销是终局(NULL -> 时间戳之后不能再改回 NULL、不能 +-- 改时间、不能删除整行)。要重新开放同一物理目标,只能换新的目标身份并重新登记, +-- 不能"把旧行归档/删掉再插一行"。 +CREATE TABLE IF NOT EXISTS library_index_restore_dispatch_activation ( + target_identity text PRIMARY KEY, + protocol_version integer NOT NULL CHECK (protocol_version = 1), + target_fingerprint text NOT NULL CHECK (target_fingerprint <> ''), + target_instance text NOT NULL CHECK (target_instance <> ''), + governance_database text NOT NULL CHECK (governance_database <> ''), + protocol_build text NOT NULL CHECK (protocol_build <> ''), + activated_by text NOT NULL CHECK (activated_by <> ''), + drain_evidence_digest text NOT NULL CHECK (drain_evidence_digest <> ''), + evidence jsonb NOT NULL, + attested_at timestamptz NOT NULL, + activated_at timestamptz NOT NULL DEFAULT now(), + revoked_at timestamptz +); + +CREATE OR REPLACE FUNCTION library_index_restore_dispatch_activation_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'restore dispatch activation evidence is append-only'; + END IF; + IF NEW.target_identity <> OLD.target_identity OR NEW.protocol_version <> OLD.protocol_version OR + NEW.target_fingerprint <> OLD.target_fingerprint OR NEW.target_instance <> OLD.target_instance OR + NEW.governance_database <> OLD.governance_database OR NEW.protocol_build <> OLD.protocol_build OR + NEW.activated_by <> OLD.activated_by OR + NEW.drain_evidence_digest <> OLD.drain_evidence_digest OR NEW.evidence <> OLD.evidence OR + NEW.attested_at <> OLD.attested_at OR NEW.activated_at <> OLD.activated_at THEN + RAISE EXCEPTION 'restore dispatch activation is immutable except revocation'; + END IF; + -- 终局:已撤销行既不能改回 NULL,也不能改写成另一个时间。 + IF OLD.revoked_at IS NOT NULL THEN + IF NEW.revoked_at IS NULL OR NEW.revoked_at <> OLD.revoked_at THEN + RAISE EXCEPTION 'restore dispatch activation revocation is final'; + END IF; + RETURN NEW; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS library_index_restore_dispatch_activation_guard_trg ON library_index_restore_dispatch_activation; +CREATE TRIGGER library_index_restore_dispatch_activation_guard_trg + BEFORE UPDATE OR DELETE ON library_index_restore_dispatch_activation + FOR EACH ROW EXECUTE FUNCTION library_index_restore_dispatch_activation_guard(); \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000079_library_restore_verification.down.sql b/internal/platform/postgres/migrations/000079_library_restore_verification.down.sql new file mode 100644 index 0000000..ea41c58 --- /dev/null +++ b/internal/platform/postgres/migrations/000079_library_restore_verification.down.sql @@ -0,0 +1,13 @@ +DROP INDEX IF EXISTS library_restore_verifications_latest; +DROP TABLE IF EXISTS library_restore_verifications; + +-- 先把 verify 作业清掉(它没有历史数据,只可能来自本版本),再恢复旧的 kind 约束。 +DELETE FROM library_jobs WHERE kind = 'verify'; +ALTER TABLE library_jobs DROP CONSTRAINT IF EXISTS library_jobs_kind_check; +ALTER TABLE library_jobs ADD CONSTRAINT library_jobs_kind_check + CHECK (kind IN ('seal','sync','restore','baseline')); + +DROP INDEX IF EXISTS library_jobs_write_target; +CREATE UNIQUE INDEX library_jobs_write_target + ON library_jobs(scope) + WHERE state IN ('pending','running') AND kind IN ('sync','restore','baseline'); \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000079_library_restore_verification.up.sql b/internal/platform/postgres/migrations/000079_library_restore_verification.up.sql new file mode 100644 index 0000000..72a7398 --- /dev/null +++ b/internal/platform/postgres/migrations/000079_library_restore_verification.up.sql @@ -0,0 +1,37 @@ +-- 恢复验证成为一种独立业务作业,并且它的证据只能由真实演练写入。 +-- +-- 为什么需要:闸门原来读 PRODUCTION_BACKUP_RESTORE_VERIFIED 这个纯 env 开关, +-- 谁把它写成 true 都能"证明"生产可恢复;页面也没有入口去真跑一次恢复。 +-- 现在 verified 只能来自 library_restore_verifications 里 passed 的真实记录。 +-- +-- verify 与 sync/restore/baseline 共用同一把写互斥:它同样要停写入者、开维护窗口、 +-- 在目标上写 canary 再恢复,不能和别的写作业并发。 +ALTER TABLE library_jobs DROP CONSTRAINT IF EXISTS library_jobs_kind_check; +ALTER TABLE library_jobs ADD CONSTRAINT library_jobs_kind_check + CHECK (kind IN ('seal','sync','restore','baseline','verify')); + +DROP INDEX IF EXISTS library_jobs_write_target; +CREATE UNIQUE INDEX library_jobs_write_target + ON library_jobs(scope) + WHERE state IN ('pending','running') AND kind IN ('sync','restore','baseline','verify'); + +-- target_id 是 appconfig.LibraryTargetIdentity():换目标(库/索引/桶/实例)后旧证据不再适用, +-- 这是"证据必须对得上当前目标"的落库形态。 +CREATE TABLE IF NOT EXISTS library_restore_verifications ( + id text PRIMARY KEY, + target_id text NOT NULL CHECK (target_id <> ''), + scope text NOT NULL CHECK (scope IN ('internal','external')), + status text NOT NULL CHECK (status IN ('passed','failed')), + snapshot_id text NOT NULL DEFAULT '', + job_id text NOT NULL CHECK (job_id <> ''), + failure text NOT NULL DEFAULT '', + report jsonb, + started_at timestamptz NOT NULL, + finished_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + -- 同一作业只留一条;重复上报是幂等重放,不是新证据。 + CONSTRAINT library_restore_verifications_job UNIQUE (target_id, scope, job_id) +); + +CREATE INDEX IF NOT EXISTS library_restore_verifications_latest + ON library_restore_verifications (target_id, scope, status, finished_at DESC); \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000080_library_job_repair_audit.down.sql b/internal/platform/postgres/migrations/000080_library_job_repair_audit.down.sql new file mode 100644 index 0000000..1ff3720 --- /dev/null +++ b/internal/platform/postgres/migrations/000080_library_job_repair_audit.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS library_job_repairs; diff --git a/internal/platform/postgres/migrations/000080_library_job_repair_audit.up.sql b/internal/platform/postgres/migrations/000080_library_job_repair_audit.up.sql new file mode 100644 index 0000000..6362738 --- /dev/null +++ b/internal/platform/postgres/migrations/000080_library_job_repair_audit.up.sql @@ -0,0 +1,19 @@ +-- Immutable audit for the only permitted automatic/system-misclassification repair. +CREATE TABLE library_job_repairs ( + id VARCHAR(64) PRIMARY KEY, + job_id VARCHAR(64) NOT NULL, + scope VARCHAR(16) NOT NULL, + kind VARCHAR(16) NOT NULL, + queue_job_id VARCHAR(64) NOT NULL, + snapshot_id VARCHAR(64) NOT NULL, + original_state VARCHAR(16) NOT NULL, + original_stage VARCHAR(32) NOT NULL DEFAULT '', + original_error TEXT NOT NULL DEFAULT '', + original_recovery VARCHAR(255) NOT NULL DEFAULT '', + original_finished_at TIMESTAMPTZ, + reason VARCHAR(255) NOT NULL, + actor VARCHAR(128) NOT NULL DEFAULT '', + evidence JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL +); +CREATE UNIQUE INDEX library_job_repairs_identity ON library_job_repairs(job_id, snapshot_id); diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index e638bba..e3e11ec 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -11,51 +11,79 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) { if err != nil { t.Fatalf("loadMigrations() error = %v", err) } - if len(migrations) != 75 { - t.Fatalf("migration count = %d, want 75", len(migrations)) + if len(migrations) != 80 { + t.Fatalf("migration count = %d, want 80", len(migrations)) + } + // 79 是恢复验证:verify 成为独立业务作业并与写作业共用互斥, + // 证据按 target_id 落库(换目标旧证据自动失效)。 + if repair := migrations[79]; repair.Version != 80 { + t.Fatalf("migration 80 = %#v", repair) + } + if verification := migrations[78]; verification.Version != 79 || + !strings.Contains(verification.UpSQL, "library_restore_verifications") || + !strings.Contains(verification.UpSQL, "'verify'") { + t.Fatalf("migration 79 = %#v", verification) + } + // 78 是 DS01 恢复标记派发台账:唯一 key、单调状态与激活登记;只动治理库。 + if dispatch := migrations[77]; dispatch.Version != 78 || + !strings.Contains(dispatch.UpSQL, "library_index_restore_dispatch") || + !strings.Contains(dispatch.UpSQL, "restore-marker-create") || + !strings.Contains(dispatch.DownSQL, "refusing to drop restore dispatch evidence") { + t.Fatalf("migration 78 = %#v", dispatch) + } + if target := migrations[76]; target.Version != 77 || !strings.Contains(target.UpSQL, "PRIMARY KEY (scope, target_id)") { + t.Fatalf("migration 77 = %#v", target) + } + // 76 是发布执行身份:operation / attempt(epoch) / 不可变事件 + current 指针。 + // 它只动治理库,不碰 WeKnora Schema。 + if identity := migrations[75]; identity.Version != 76 || + !strings.Contains(identity.UpSQL, "library_operations") || + !strings.Contains(identity.UpSQL, "library_attempts") || + !strings.Contains(identity.UpSQL, "library_current_versions") { + t.Fatalf("migration 76 = %#v", identity) } // 75 允许"建立目标权威基线"作为独立业务作业,并与 sync/restore 共用写互斥。 - if baseline := migrations[len(migrations)-1]; baseline.Version != 75 || + if baseline := migrations[74]; baseline.Version != 75 || !strings.Contains(baseline.UpSQL, "library_jobs_write_target") || !strings.Contains(baseline.UpSQL, "'baseline'") { t.Fatalf("migration 75 = %#v", baseline) } // 74 记录封存执行器的运行时状态:页面可用性来自真实观测,不来自配置字符串。 - if executor := migrations[len(migrations)-2]; executor.Version != 74 || + if executor := migrations[73]; executor.Version != 74 || !strings.Contains(executor.UpSQL, "library_executor_status") { t.Fatalf("migration 74 = %#v", executor) } // 73 记录死信精确解除:保留上游行,只绑定指纹、重放引用与观测摘要。 - if release := migrations[len(migrations)-3]; release.Version != 73 || + if release := migrations[72]; release.Version != 73 || !strings.Contains(release.UpSQL, "library_dead_letter_releases") { t.Fatalf("migration 73 = %#v", release) } // 72 让维护占用按实例互斥(internal/external 不再各有各的锁)。 - if instance := migrations[len(migrations)-4]; instance.Version != 72 || + if instance := migrations[71]; instance.Version != 72 || !strings.Contains(instance.UpSQL, "library_instance_maintenance") { t.Fatalf("migration 72 = %#v", instance) } // 71 让维护记录能区分实例级维护与仅治理库互斥。 - if level := migrations[len(migrations)-5]; level.Version != 71 || + if level := migrations[70]; level.Version != 71 || !strings.Contains(level.UpSQL, "level") || !strings.Contains(level.UpSQL, "ingress_state") { t.Fatalf("migration 71 = %#v", level) } - if maint := migrations[len(migrations)-6]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") { + if maint := migrations[69]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") { t.Fatalf("migration 70 = %#v", maint) } - if tail := migrations[len(migrations)-7]; tail.Version != 69 || + if tail := migrations[68]; tail.Version != 69 || !strings.Contains(tail.UpSQL, "library_jobs_write_target") { t.Fatalf("migration 69 = %#v", tail) } - if restore := migrations[len(migrations)-8]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") { + if restore := migrations[67]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") { t.Fatalf("migration 68 = %#v", restore) } - if last := migrations[len(migrations)-9]; last.Version != 67 || + if last := migrations[66]; last.Version != 67 || !strings.Contains(last.UpSQL, "library_release_authorizations") || !strings.Contains(last.UpSQL, "params_digest") { t.Fatalf("migration 67 = %#v", last) } - if flow := migrations[len(migrations)-10]; flow.Version != 66 || + if flow := migrations[65]; flow.Version != 66 || !strings.Contains(flow.UpSQL, "CREATE TABLE library_versions") || !strings.Contains(flow.UpSQL, "library_jobs_active") { t.Fatalf("migration 66 = %#v", flow) diff --git a/internal/platform/postgres/monitor_catalog_path_integration_test.go b/internal/platform/postgres/monitor_catalog_path_integration_test.go new file mode 100644 index 0000000..1bfc407 --- /dev/null +++ b/internal/platform/postgres/monitor_catalog_path_integration_test.go @@ -0,0 +1,217 @@ +package postgres + +import ( + "context" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" +) + +// F14:来源目录在取件/路由时写入 source_items;对历史行(当时没写)只在读时 +// 按「同一连接 + 同一 item」的 catalog intent 补齐,绝不按文件名猜配。 +func TestMonitorTaskCatalogDirectoryIdentityIntegration(t *testing.T) { + url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if url == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, url) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if err = ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + exec := func(query string, args ...any) { + t.Helper() + if _, err := pool.Exec(ctx, query, args...); err != nil { + t.Fatalf("%v: %s", err, query) + } + } + now := time.Date(2026, 11, 5, 2, 0, 0, 0, time.UTC) + exec(`INSERT INTO source_connections (id,source_type,name) VALUES + ('conn-atom','dingtalk','ATOM知识库'),('conn-pp','pp','PP资料下载中心')`) + for index, connection := range []struct{ id, snapshot, folder, file string }{ + {"conn-atom", "snap-atom", "node-atom-folder", "node-atom-file"}, + {"conn-pp", "snap-pp", "node-pp-folder", "node-pp-file"}, + } { + exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at) + VALUES ($1,$2,repeat($3,64),'fixture',2,1,1,$4)`, + connection.snapshot, connection.id, string(rune('a'+index)), now) + exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash) + VALUES ($1,$2,NULL,'folder','售后机器出厂问题整改','售后机器出厂问题整改',repeat($3,64))`, + connection.snapshot, connection.folder, "b") + exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash) + VALUES ($1,$2,$3,'file','末端航插线序问题.adoc.docx',$4,repeat($5,64))`, + connection.snapshot, connection.file, connection.folder, + map[string]string{"conn-atom": "售后机器出厂问题整改/末端航插线序问题.adoc.docx", "conn-pp": "PP公开资料/末端航插线序问题.adoc.docx"}[connection.id], + "c") + exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ($1,$2,$3)`, + connection.id, connection.snapshot, now) + } + // 两条来源的标题完全相同、来源不同;路径必须各自来自自己的 intent。 + insertItem := func(id, connection, title, storedPath, parent string) { + exec(`INSERT INTO source_items (id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,parent_external_id,title,item_type,revision,visibility,visibility_origin,source_change,policy_state,updated_at) + VALUES ($1,$2,$7,repeat('d',64),$3,$4,$5,'file','sha:1','internal','configured_scope','added','internal',$6)`, + id, connection, storedPath, parent, title, now, id) + exec(`INSERT INTO source_item_versions (id,source_item_id,revision,content_state,raw_record_summary,updated_at) + VALUES ('sv-'||$1,$1,'sha:1','verified','{}'::jsonb,$2)`, id, now) + } + insertItem("si-atom", "conn-atom", "末端航插线序问题.adoc.docx", "", "") + insertItem("si-pp", "conn-pp", "末端航插线序问题.adoc.docx", "", "") + insertItem("si-unbound", "conn-pp", "未登记目录文件.adoc.docx", "", "") + insertItem("si-stored", "conn-atom", "已登记目录文件.adoc.docx", "既有登记/已登记目录文件.adoc.docx", "node-atom-folder") + exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at) + VALUES ('conn-atom','node-atom-file','internal','si-atom','fixture','售后机器出厂问题整改/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('e',64),$1)`, now) + exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at) + VALUES ('conn-pp','node-pp-file','internal','si-pp','fixture','PP公开资料/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('f',64),$1)`, now) + exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at) + VALUES ('conn-atom','node-atom-folder','internal','si-stored','fixture','售后机器出厂问题整改/已登记目录文件.adoc.docx','已登记目录文件.adoc.docx',repeat('1',64),$1)`, now) + for index, publication := range []struct{ id, item, kb, scope string }{ + {"tp-atom", "si-atom", "kb-internal-a", "internal"}, + {"tp-pp", "si-pp", "kb-internal-b", "internal"}, + {"tp-unbound", "si-unbound", "kb-internal-b", "internal"}, + {"tp-stored", "si-stored", "kb-internal-a", "internal"}, + } { + exec(`INSERT INTO test_publications (id,source_item_version_id,test_kb_id,ingest_state,processing_state,retrieval_state,target_scope,updated_at) + VALUES ($1,'sv-'||$2,$3,'uploaded','completed','unpublished',$4,$5)`, + publication.id, publication.item, publication.kb, publication.scope, now.Add(time.Duration(index)*time.Minute)) + } + store := NewStore(pool) + page, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Limit: 20}) + if err != nil { + t.Fatal(err) + } + byID := map[string]MonitorTask{} + for _, item := range page.Items { + byID[item.ID] = item + } + atom := byID["tp-atom"] + if atom.Path != "售后机器出厂问题整改/末端航插线序问题.adoc.docx" || atom.ParentNodeID != "node-atom-folder" || atom.NodeID != "node-atom-file" { + t.Fatalf("historical item lost its catalog directory: %#v", atom) + } + pp := byID["tp-pp"] + if pp.Path != "PP公开资料/末端航插线序问题.adoc.docx" || pp.ParentNodeID != "node-pp-folder" { + t.Fatalf("same-title item took another source's path: %#v", pp) + } + if byID["tp-unbound"].Path != "" || byID["tp-unbound"].ParentNodeID != "" { + t.Fatalf("missing intent must not invent a directory: %#v", byID["tp-unbound"]) + } + if stored := byID["tp-stored"]; stored.Path != "既有登记/已登记目录文件.adoc.docx" { + t.Fatalf("stored path must win over the intent snapshot: %#v", stored) + } + searched, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: "售后机器出厂问题整改", Limit: 20}) + if err != nil { + t.Fatal(err) + } + if searched.Total != 1 || len(searched.Items) != 1 || searched.Items[0].SourceID != "conn-atom" { + t.Fatalf("directory search total=%d items=%#v, want exactly the ATOM row", searched.Total, searched.Items) + } + // 同名文件在另一来源下不应被这条目录搜索带出来(同名异源隔离)。 + other, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: "PP公开资料", Limit: 20}) + if err != nil { + t.Fatal(err) + } + if other.Total != 1 || len(other.Items) != 1 || other.Items[0].SourceID != "conn-pp" { + t.Fatalf("cross-source search leaked: %#v", other.Items) + } + // F15:目标选项带 scope(同名知识库靠短 ID + scope 区分),筛选总数由后端全量算。 + if len(page.Targets) != 2 { + t.Fatalf("target options = %#v", page.Targets) + } + for _, option := range page.Targets { + if option.Scope != "internal" || len(option.ID) < 8 { + t.Fatalf("target option missing identity: %#v", option) + } + } + filtered, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Target: "kb-internal-b", Limit: 20}) + if err != nil { + t.Fatal(err) + } + if filtered.Total != 2 || len(filtered.Items) != 2 { + t.Fatalf("target filter total=%d items=%d, want 2", filtered.Total, len(filtered.Items)) + } +} + +// F14 写入侧:路由/取件时就把来源路径与父目录写进 source_items; +// 对已存在但当时没写的行,只在同一 intent 绑定的 item 上补空值,绝不覆盖既有值。 +func TestCatalogRoutePersistsSourceDirectoryIntegration(t *testing.T) { + url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL")) + if url == "" { + t.Skip("TEST_DATABASE_URL is not set") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, url) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if err = ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + exec := func(query string, args ...any) { + t.Helper() + if _, err := pool.Exec(ctx, query, args...); err != nil { + t.Fatalf("%v: %s", err, query) + } + } + now := time.Date(2026, 11, 5, 3, 0, 0, 0, time.UTC) + exec(`INSERT INTO source_connections (id,source_type,name) VALUES ('conn-route','dingtalk','路由来源')`) + exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at) + VALUES ('snap-route','conn-route',repeat('9',64),'fixture',2,1,1,$1)`, now) + exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash) + VALUES ('snap-route','node-route-folder',NULL,'folder','售后机器出厂问题整改','售后机器出厂问题整改',repeat('8',64))`) + exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash) + VALUES ('snap-route','node-route-file','node-route-folder','file','末端航插线序问题.adoc.docx','售后机器出厂问题整改/末端航插线序问题.adoc.docx',repeat('7',64))`) + exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ('conn-route','snap-route',$1)`, now) + // 历史行:当时没写路径,但 intent 已把它绑定到本 item。 + exec(`INSERT INTO source_items (id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,revision,visibility,visibility_origin,source_change,policy_state,updated_at) + VALUES ('si-route-old','conn-route','legacy-item',repeat('6',64),'末端航插线序问题.adoc.docx','file','','internal','configured_scope','unchanged','internal',$1)`, now) + exec(`INSERT INTO source_item_versions (id,source_item_id,revision,content_state,raw_record_summary,updated_at) + VALUES ('sv-route-old','si-route-old','','unknown','{}'::jsonb,$1)`, now) + exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at) + VALUES ('conn-route','node-route-file','internal','si-route-old','fixture','售后机器出厂问题整改/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('5',64),$1)`, now) + store := NewStore(pool) + if _, err := store.RouteCatalogFiles(ctx, governance.CatalogRouteRequest{ + ConnectionID: "conn-route", + NodeIDs: []string{"node-route-file"}, + Visibility: governance.VisibilityInternal, + TargetKnowledgeBaseID: "kb-route", + OperatorRef: "fixture", + Reason: "fixture", + Now: now, + }); err != nil { + t.Fatal(err) + } + var path, parent string + if err := pool.QueryRow(ctx, `SELECT normalized_path,parent_external_id FROM source_items WHERE id='si-route-old'`).Scan(&path, &parent); err != nil { + t.Fatal(err) + } + if path != "售后机器出厂问题整改/末端航插线序问题.adoc.docx" || parent != "node-route-folder" { + t.Fatalf("route did not persist the source directory: path=%q parent=%q", path, parent) + } + // 已有值不被后续路由覆盖(现有目录精确匹配)。 + exec(`UPDATE source_items SET normalized_path='既有登记/保留路径',parent_external_id='node-existing' WHERE id='si-route-old'`) + if _, err := store.RouteCatalogFiles(ctx, governance.CatalogRouteRequest{ + ConnectionID: "conn-route", + NodeIDs: []string{"node-route-file"}, + Visibility: governance.VisibilityInternal, + TargetKnowledgeBaseID: "kb-route", + OperatorRef: "fixture", + Reason: "fixture", + Now: now.Add(time.Minute), + }); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `SELECT normalized_path,parent_external_id FROM source_items WHERE id='si-route-old'`).Scan(&path, &parent); err != nil { + t.Fatal(err) + } + if path != "既有登记/保留路径" || parent != "node-existing" { + t.Fatalf("existing directory was overwritten: path=%q parent=%q", path, parent) + } +} diff --git a/internal/platform/postgres/monitor_tasks.go b/internal/platform/postgres/monitor_tasks.go index 7885c68..3d88794 100644 --- a/internal/platform/postgres/monitor_tasks.go +++ b/internal/platform/postgres/monitor_tasks.go @@ -16,23 +16,27 @@ type MonitorTaskEvent struct { Detail string `json:"detail"` } type MonitorTask struct { - History []MonitorTaskEvent `json:"history"` - ID string `json:"id"` - Title string `json:"title"` - Path string `json:"path"` - SourceID string `json:"source_id"` - SourceName string `json:"source_name"` - TargetScope string `json:"target_scope"` - TargetKB string `json:"target_kb"` - Action string `json:"action"` - Stage string `json:"stage"` - Status string `json:"status"` - Detail string `json:"detail"` - UpdatedAt string `json:"updated_at"` - RetryKind string `json:"retry_kind"` - FailureID string `json:"failure_id"` - RetryCount int `json:"retry_count"` - VersionID string `json:"version_id"` + History []MonitorTaskEvent `json:"history"` + ID string `json:"id"` + Title string `json:"title"` + Path string `json:"path"` + // NodeID/ParentNodeID let the UI return to the exact source directory; + // both come from the catalog snapshot bound to THIS source item. + NodeID string `json:"node_id"` + ParentNodeID string `json:"parent_node_id"` + SourceID string `json:"source_id"` + SourceName string `json:"source_name"` + TargetScope string `json:"target_scope"` + TargetKB string `json:"target_kb"` + Action string `json:"action"` + Stage string `json:"stage"` + Status string `json:"status"` + Detail string `json:"detail"` + UpdatedAt string `json:"updated_at"` + RetryKind string `json:"retry_kind"` + FailureID string `json:"failure_id"` + RetryCount int `json:"retry_count"` + VersionID string `json:"version_id"` } type MonitorTaskPage struct { Items []MonitorTask `json:"items"` @@ -42,10 +46,18 @@ type MonitorTaskPage struct { Sources []MonitorOption `json:"sources"` Targets []MonitorOption `json:"targets"` Retryable int `json:"retryable"` + // Bindings is the effective (persisted, env-fallback aware) target for each + // scope. The UI marks rows/options against it; counts stay this page's totals. + Bindings MonitorBindings `json:"bindings"` } type MonitorOption struct { - ID string `json:"id"` - Name string `json:"name"` + ID string `json:"id"` + Name string `json:"name"` + Scope string `json:"scope,omitempty"` +} +type MonitorBindings struct { + Internal string `json:"internal"` + External string `json:"external"` } // Reduce publication versions before filtering; totals and pages share one snapshot. @@ -62,7 +74,11 @@ const monitorTasksCTE = `WITH history_publications AS ( WHERE p.superseded_at IS NULL ORDER BY v.source_item_id,p.test_kb_id,p.created_at DESC,p.id DESC ), base AS ( - SELECT p.id,si.title,si.normalized_path AS path,c.id AS source_id,c.name AS source_name, + SELECT p.id,si.title, + COALESCE(NULLIF(si.normalized_path,''),ci.relative_path,'') AS path, + COALESCE(NULLIF(si.parent_external_id,''),cn.parent_node_id,'') AS parent_node_id, + COALESCE(ci.node_id,'') AS node_id, + c.id AS source_id,c.name AS source_name, p.target_scope,p.test_kb_id AS target_kb,p.source_item_version_id AS version_id,p.retry_count, GREATEST(p.updated_at,j.updated_at,f.created_at) AS updated_at, p.processing_state,p.ingest_state,p.retrieval_state,p.last_error,p.knowledge_id, @@ -72,6 +88,13 @@ const monitorTasksCTE = `WITH history_publications AS ( COALESCE(j.type,'') AS job_type,COALESCE(j.state,'') AS job_state,COALESCE(j.attempt,0) AS job_attempt,j.available_at, COALESCE(f.id,'') AS failure_id,COALESCE(f.job_type,'') AS failure_type,COALESCE(NULLIF(f.last_error,''),f.error_code,'') AS failure_error FROM latest p JOIN source_items si ON si.id=p.source_item_id JOIN source_connections c ON c.id=si.source_connection_id + -- 历史行路径为空时,只用「同一连接 + 同一 item」的取件意图补齐:不按文件名猜配。 + LEFT JOIN LATERAL(SELECT intent.relative_path,intent.node_id FROM catalog_import_intents intent + WHERE intent.source_item_id=si.id AND intent.source_connection_id=si.source_connection_id + ORDER BY intent.updated_at DESC,intent.node_id LIMIT 1) ci ON TRUE + LEFT JOIN LATERAL(SELECT node.parent_node_id FROM source_catalog_heads head + JOIN source_catalog_nodes node ON node.snapshot_id=head.snapshot_id + WHERE head.source_connection_id=si.source_connection_id AND node.node_id=ci.node_id LIMIT 1) cn ON TRUE LEFT JOIN content_objects co ON co.id=p.content_object_id LEFT JOIN LATERAL(SELECT j.type,j.state,j.attempt,j.available_at,j.updated_at FROM jobs j WHERE (j.payload->>'publication_id'=p.id OR (j.type='artifact.fetch' AND j.payload->>'version_id'=p.source_item_version_id)) @@ -101,7 +124,7 @@ const monitorTasksCTE = `WITH history_publications AS ( ELSE 'waiting' END AS stage FROM base ), projected AS ( - SELECT id,title,path,source_id,source_name,target_scope,target_kb,version_id,retry_count,updated_at,action,stage,status,failure_id, + SELECT id,title,path,parent_node_id,node_id,source_id,source_name,target_scope,target_kb,version_id,retry_count,updated_at,action,stage,status,failure_id, CASE WHEN status<>'attention' THEN '' WHEN action='remove' THEN CASE WHEN job_type='test.remove' AND job_state='failed' AND retrieval_state IN ('failed','disabling') AND policy_state='blocked' THEN 'remove' ELSE '' END WHEN failure_type='artifact.fetch' THEN 'fetch' @@ -130,7 +153,7 @@ func (s *Store) ListMonitorTasks(ctx context.Context, f MonitorTaskFilter) (Moni return MonitorTaskPage{}, errors.New("invalid monitor pagination") } var raw []byte - err := s.db.QueryRow(ctx, monitorTasksCTE+`SELECT jsonb_build_object('items',COALESCE((SELECT jsonb_agg(to_jsonb(x)||jsonb_build_object('history',COALESCE((SELECT jsonb_agg(e ORDER BY e.at DESC,e.kind,e.detail) FROM (SELECT * FROM history_events ORDER BY at DESC,kind,detail LIMIT 50)e),'[]'::jsonb)) ORDER BY x.updated_at DESC,x.id) FROM (SELECT * FROM filtered ORDER BY updated_at DESC,id LIMIT $8 OFFSET $9)x),'[]'::jsonb),'total',(SELECT count(*) FROM filtered),'limit',$8::int,'offset',$9::int,'retryable',(SELECT count(*) FROM filtered WHERE retry_kind<>''),'sources',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT source_id AS id,source_name AS name FROM projected)x),'[]'::jsonb),'targets',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT target_kb AS id,target_kb AS name FROM projected)x),'[]'::jsonb))`, f.Search, f.Source, f.Scope, f.Action, f.Status, f.Stage, f.ID, f.Limit, f.Offset, f.Target, f.Since, f.Until).Scan(&raw) + err := s.db.QueryRow(ctx, monitorTasksCTE+`SELECT jsonb_build_object('items',COALESCE((SELECT jsonb_agg(to_jsonb(x)||jsonb_build_object('history',COALESCE((SELECT jsonb_agg(e ORDER BY e.at DESC,e.kind,e.detail) FROM (SELECT * FROM history_events ORDER BY at DESC,kind,detail LIMIT 50)e),'[]'::jsonb)) ORDER BY x.updated_at DESC,x.id) FROM (SELECT * FROM filtered ORDER BY updated_at DESC,id LIMIT $8 OFFSET $9)x),'[]'::jsonb),'total',(SELECT count(*) FROM filtered),'limit',$8::int,'offset',$9::int,'retryable',(SELECT count(*) FROM filtered WHERE retry_kind<>''),'sources',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT source_id AS id,source_name AS name FROM projected)x),'[]'::jsonb),'targets',COALESCE((SELECT jsonb_agg(x ORDER BY x.scope,x.id) FROM (SELECT target_kb AS id,MIN(target_scope) AS scope FROM projected GROUP BY target_kb)x),'[]'::jsonb))`, f.Search, f.Source, f.Scope, f.Action, f.Status, f.Stage, f.ID, f.Limit, f.Offset, f.Target, f.Since, f.Until).Scan(&raw) if err != nil { return MonitorTaskPage{}, err } diff --git a/internal/platform/postgres/operation_requests.go b/internal/platform/postgres/operation_requests.go index 2562ffe..133661d 100644 --- a/internal/platform/postgres/operation_requests.go +++ b/internal/platform/postgres/operation_requests.go @@ -35,7 +35,7 @@ func (s *Store) RouteCatalogFilesWithOperation(ctx context.Context, request gove return governance.CatalogRouteResult{}, false, err } resultJSON, replayed, err := s.executeOperation(ctx, "catalog.route", operationID, fingerprint, request.Now, func(tx pgx.Tx) (json.RawMessage, error) { - result, err := routeCatalogFilesTx(ctx, tx, request) + result, err := routeCatalogFilesTx(ctx, tx, s, request) if err != nil { return nil, err } diff --git a/internal/platform/postgres/pgtest/isolated.go b/internal/platform/postgres/pgtest/isolated.go new file mode 100644 index 0000000..066c39c --- /dev/null +++ b/internal/platform/postgres/pgtest/isolated.go @@ -0,0 +1,65 @@ +// Package pgtest 给真实 PostgreSQL 集成用例提供"一个用例一个 schema"的隔离入口。 +// +// 为什么要单独成包:postgres 与 cmd/worker 的集成用例都要连真库,隔离逻辑只该有一份; +// 复制一份到另一个包里,迟早只改一边(AGENTS.md 硬约束 1:同一含义的代码只准有一份)。 +package pgtest + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "net/url" + "os" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// IsolatedDatabaseURL 为当前用例建一个独立 schema 并返回指向它的连接串; +// 用例结束自动 DROP。基地址为空时返回空串(调用方据此 Skip)。 +func IsolatedDatabaseURL(t *testing.T, databaseURL string) string { + t.Helper() + if databaseURL == "" { + return "" + } + parsed, err := url.Parse(databaseURL) + if err != nil || parsed.Scheme == "" || parsed.Host == "" { + t.Fatalf("TEST_DATABASE_URL must be a PostgreSQL URL: %v", err) + } + // 护栏:这些用例会在目标库里建/删 schema。指到业务库上就会在业务库里反复 + // 建表删表(哪怕只删自己的 schema,也是在业务库上动 DDL)。所以库名必须明确 + // 是一次性的(含 test),否则要求显式声明,绝不"顺便"跑在业务库上。 + if databaseName := strings.TrimPrefix(parsed.Path, "/"); !strings.Contains(strings.ToLower(databaseName), "test") && + os.Getenv("KG_ALLOW_NON_TEST_DATABASE_URL") != "1" { + t.Fatalf("TEST_DATABASE_URL 指向的库 %q 看起来不是一次性测试库:拒绝在其中建/删 schema"+ + "(确属一次性库请设 KG_ALLOW_NON_TEST_DATABASE_URL=1)", databaseName) + } + digest := sha256.Sum256([]byte(t.Name())) + schema := "kgtest_" + hex.EncodeToString(digest[:8]) + ctx := context.Background() + admin, err := pgxpool.New(ctx, databaseURL) + if err != nil { + t.Fatalf("connect integration database: %v", err) + } + defer admin.Close() + // 上一次被 kill 的运行可能留下同名 schema(cleanup 没跑到):先清掉自己的, + // 否则紧接着的 CREATE 会撞名,整包用例连"跑起来"都做不到。只清本用例自己的名字。 + if _, err := admin.Exec(ctx, "DROP SCHEMA IF EXISTS "+schema+" CASCADE"); err != nil { + t.Fatalf("drop stale isolated schema: %v", err) + } + if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil { + t.Fatalf("create isolated integration schema: %v", err) + } + t.Cleanup(func() { + cleanup, err := pgxpool.New(context.Background(), databaseURL) + if err == nil { + _, _ = cleanup.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+schema+" CASCADE") + cleanup.Close() + } + }) + query := parsed.Query() + query.Set("search_path", schema) + parsed.RawQuery = query.Encode() + return parsed.String() +} diff --git a/internal/platform/postgres/policy_intents.go b/internal/platform/postgres/policy_intents.go index e0e6e92..eca58e0 100644 --- a/internal/platform/postgres/policy_intents.go +++ b/internal/platform/postgres/policy_intents.go @@ -23,14 +23,14 @@ import ( // 开始处理 promotes them within the configured concurrency budget. Blocked // intents retire any planned publication and flip the item policy so the // knowledge-base diff demands removal of anything still live. -func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, files []governance.CatalogRouteFile, now time.Time) (governance.CatalogRouteResult, error) { +func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest, files []governance.CatalogRouteFile, now time.Time) (governance.CatalogRouteResult, error) { targetKnowledgeBaseIDs := request.TargetKnowledgeBaseIDs if len(targetKnowledgeBaseIDs) == 0 && request.TargetKnowledgeBaseID != "" { targetKnowledgeBaseIDs = []string{request.TargetKnowledgeBaseID} } result := governance.CatalogRouteResult{SelectedFiles: len(files)} for _, file := range files { - recorded, fetchQueued, planned, blocked, err := fulfillCatalogIntent(ctx, tx, request, file, targetKnowledgeBaseIDs, now) + recorded, fetchQueued, planned, blocked, err := fulfillCatalogIntent(ctx, tx, store, request, file, targetKnowledgeBaseIDs, now) if err != nil { return governance.CatalogRouteResult{}, err } @@ -54,7 +54,7 @@ func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, request governance. // fulfillCatalogIntent applies one file decision. It returns recorded=false // only when the node vanished mid-transaction; fetchQueued reports a newly // enqueued artifact.fetch job and planned the number of publications created. -func fulfillCatalogIntent(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, file governance.CatalogRouteFile, targetKnowledgeBaseIDs []string, now time.Time) (bool, bool, int, bool, error) { +func fulfillCatalogIntent(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest, file governance.CatalogRouteFile, targetKnowledgeBaseIDs []string, now time.Time) (bool, bool, int, bool, error) { policy := string(request.Visibility) if _, err := tx.Exec(ctx, `INSERT INTO catalog_import_intents( source_connection_id,node_id,visibility,decided_by,reason,relative_path,name,size_bytes,modified_at,content_sha256, @@ -118,11 +118,11 @@ ORDER BY head.activated_at DESC NULLS LAST LIMIT 1 FOR UPDATE OF node`, request. if _, err := tx.Exec(ctx, `INSERT INTO source_items( id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,revision, visibility,visibility_origin,source_change,absence_streak,identity_confidence, - policy_state,created_at,updated_at) -VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id',$6,NOW(),NOW())`, + policy_state,normalized_path,parent_external_id,created_at,updated_at) +VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id',$6,$8,$9,NOW(),NOW())`, newItemID, request.ConnectionID, "cat:"+file.NodeID, sha256Hex("policy:"+request.ConnectionID+"\x00"+file.NodeID), - file.Name, policy, itemVisibilityFor(request.Visibility)); err != nil { + file.Name, policy, itemVisibilityFor(request.Visibility), file.RelativePath, file.ParentNodeID); err != nil { return false, false, 0, false, fmt.Errorf("materialize policy source item: %w", err) } if _, err := tx.Exec(ctx, `UPDATE catalog_import_intents SET source_item_id=$3 WHERE source_connection_id=$1 AND node_id=$2`, @@ -131,6 +131,15 @@ VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id', } itemID = newItemID } + // 历史行(当时没写来源路径)只补空值:意图已把 item 绑定到本连接的这个 node, + // 身份可证;已有路径绝不被覆盖,避免把下架连接重绑成当前来源。 + if _, err := tx.Exec(ctx, `UPDATE source_items SET + normalized_path=CASE WHEN normalized_path='' THEN $2 ELSE normalized_path END, + parent_external_id=CASE WHEN parent_external_id='' THEN $3 ELSE parent_external_id END, + updated_at=CASE WHEN normalized_path='' OR parent_external_id='' THEN NOW() ELSE updated_at END +WHERE id=$1`, itemID, file.RelativePath, file.ParentNodeID); err != nil { + return false, false, 0, false, fmt.Errorf("persist policy source path: %w", err) + } // Bind the snapshot nodes too (new or reused item): the browser's // 已导入/已解析 counters join source_catalog_nodes.source_item_id; without // this write every catalog-only source keeps showing "尚未导入" even after @@ -231,6 +240,11 @@ ON CONFLICT (source_item_version_id,test_kb_id) DO NOTHING`, } planned += int(tag.RowsAffected()) } + if contentState == string(governance.ContentVerified) { + if err := store.autoStartVerifiedPublicationsTx(ctx, tx, versionID, now); err != nil { + return false, false, 0, false, err + } + } fetchQueued := false if contentState != string(governance.ContentVerified) { @@ -286,6 +300,97 @@ func sha256Hex(value string) string { return hex.EncodeToString(sum[:]) } +// autoStartVerifiedPublicationsTx continues the normal ingestion chain in the +// SAME transaction that made the bytes verified. It deliberately re-checks the +// saved policy, the current binding and the live source state: a file routed +// before a policy/binding change must not be uploaded to a stale target. +func (s *Store) autoStartVerifiedPublicationsTx(ctx context.Context, tx pgx.Tx, versionID string, now time.Time) error { + if versionID == "" { + return errors.New("auto-start requires a version") + } + rows, err := tx.Query(ctx, ` +WITH binding AS ( + SELECT COALESCE(NULLIF(internal_kb_id,''), $3::text) AS internal_kb_id, + COALESCE(NULLIF(external_kb_id,''), $4::text) AS external_kb_id + FROM routing_kb_bindings WHERE id='active' +), eligible AS ( + SELECT publication.id + FROM test_publications publication + JOIN source_item_versions version ON version.id=publication.source_item_version_id + JOIN content_objects content ON content.id=version.content_object_id + JOIN source_items item ON item.id=version.source_item_id + JOIN source_connections connection ON connection.id=item.source_connection_id + LEFT JOIN LATERAL ( + SELECT intent.visibility FROM catalog_import_intents intent + WHERE intent.source_item_id=item.id AND intent.source_connection_id=item.source_connection_id + ORDER BY intent.updated_at DESC,intent.node_id LIMIT 1 + ) intent ON TRUE + CROSS JOIN binding + WHERE version.id=$1 + AND publication.superseded_at IS NULL + AND publication.processing_state='planned' + AND publication.ingest_state='pending' + AND publication.knowledge_id='' + AND publication.retrieval_state='unpublished' + AND version.content_state='verified' + AND content.content_state='verified' + AND content.local_spool_ref<>'' + AND content.size_bytes>0 + AND connection.enabled + AND item.policy_state IN (publication.target_scope,'both') + AND intent.visibility IN (publication.target_scope,'both') + AND NOT filename_is_filtered(item.source_connection_id,item.normalized_path,item.title) + AND NOT EXISTS (SELECT 1 FROM jobs job WHERE job.type='test.upload' AND job.payload->>'publication_id'=publication.id) + AND ((publication.target_scope='internal' AND binding.internal_kb_id<>'' AND publication.test_kb_id=binding.internal_kb_id) + OR (publication.target_scope='external' AND binding.external_kb_id<>'' AND publication.test_kb_id=binding.external_kb_id)) +) +UPDATE test_publications publication SET processing_state='pending',updated_at=$2 +FROM eligible WHERE publication.id=eligible.id +RETURNING publication.id`, versionID, now, s.defaultInternalKBID, s.defaultExternalKBID) + if err != nil { + return fmt.Errorf("auto-start verified publications: %w", err) + } + ids := make([]string, 0, 2) + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + rows.Close() + return fmt.Errorf("scan auto-started publication: %w", err) + } + ids = append(ids, id) + } + if err := rows.Err(); err != nil { + rows.Close() + return fmt.Errorf("iterate auto-started publications: %w", err) + } + rows.Close() + for _, publicationID := range ids { + confirmationID, err := newOpaqueID("pc-") + if err != nil { + return err + } + jobID, err := newOpaqueID("job-") + if err != nil { + return err + } + payload, err := json.Marshal(map[string]string{"publication_id": publicationID}) + if err != nil { + return errors.New("encode auto upload job") + } + if _, err := tx.Exec(ctx, `INSERT INTO processing_confirmations(id,publication_id,operator_ref,reason,confirmed_at,created_at) +VALUES($1,$2,'system:auto','取件 verified 自动接续',$3,$3) +ON CONFLICT (publication_id) DO NOTHING`, confirmationID, publicationID, now); err != nil { + return fmt.Errorf("record auto processing confirmation: %w", err) + } + if _, err := tx.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,priority,available_at,max_attempts,idempotency_key,created_at,updated_at) +VALUES($1,'test.upload',$2::jsonb,'pending',10,$3,5,$4,$3,$3) +ON CONFLICT (idempotency_key) DO NOTHING`, jobID, payload, now, "auto-test-upload:"+publicationID); err != nil { + return fmt.Errorf("enqueue auto upload: %w", err) + } + } + return nil +} + // MarkArtifactFetched finalizes one artifact.fetch success: it (re)uses the // content_objects row for the verified hash (content-level dedupe), attaches it // to the pending version and flips the intent to ready. matchedLocal records @@ -349,6 +454,9 @@ WHERE id=$1`, WHERE source_connection_id=$1 AND node_id=$2`, connectionID, nodeID); err != nil { return fmt.Errorf("mark intent fetched: %w", err) } + if err := s.autoStartVerifiedPublicationsTx(ctx, tx, versionID, now); err != nil { + return fmt.Errorf("continue fetched artifact into upload: %w", err) + } if ownsTransaction { if err := tx.Commit(ctx); err != nil { return fmt.Errorf("commit artifact fetch: %w", err) diff --git a/internal/platform/postgres/queue_sql.go b/internal/platform/postgres/queue_sql.go index e2c0c80..909e3f5 100644 --- a/internal/platform/postgres/queue_sql.go +++ b/internal/platform/postgres/queue_sql.go @@ -134,6 +134,14 @@ SELECT id FROM updated // One job type, newest first: a caller which needs "the recent jobs of MY type" // must not page the global queue (other traffic would hide its own rows). +const jobByIDSQL = ` +SELECT id, type, payload, state, priority, available_at, + lease_owner, lease_until, attempt, max_attempts, + last_error, idempotency_key, created_at, updated_at +FROM jobs +WHERE id = $1 +` + const listJobsByTypeSQL = ` SELECT id, type, payload, state, priority, available_at, lease_owner, lease_until, attempt, max_attempts, diff --git a/internal/platform/postgres/store.go b/internal/platform/postgres/store.go index a045abe..ae10e5c 100644 --- a/internal/platform/postgres/store.go +++ b/internal/platform/postgres/store.go @@ -23,13 +23,47 @@ type database interface { } type Store struct { - db database + db database + libraryTargetID string + defaultInternalKBID string + defaultExternalKBID string + // restoreDispatchEvidenceRoot 是激活门唯一允许读取维护 journal 的根目录。 + // 空值表示没有配置受信证据源:激活必须失败关闭,而不是退回"只看字符串"。 + restoreDispatchEvidenceRoot string +} + +// WithLibraryTarget isolates release facts without mutating a shared Store. +// The empty namespace retains legacy evidence; live API/workers bind a nonempty +// identity before exposing library operations. Source seals remain independent. +func (s *Store) WithLibraryTarget(id string) *Store { + copy := *s + copy.libraryTargetID = id + return © } func NewStore(db database) *Store { return &Store{db: db} } +// WithRoutingDefaults supplies the deployment's bootstrap bindings. The UI +// binding row still wins; defaults are only the unbound fallback, exactly like +// the route/readiness resolvers. Auto-continuation uses them only to prove the +// publication still targets the CURRENT effective knowledge base. +func (s *Store) WithRoutingDefaults(internal, external string) *Store { + copy := *s + copy.defaultInternalKBID = strings.TrimSpace(internal) + copy.defaultExternalKBID = strings.TrimSpace(external) + return © +} + +// WithRestoreDispatchEvidence 绑定维护 journal 的受信根目录(部署配置 +// LIBRARY_TARGET_JOURNAL_ROOT)。没有它时激活门一律失败关闭。 +func (s *Store) WithRestoreDispatchEvidence(root string) *Store { + copy := *s + copy.restoreDispatchEvidenceRoot = root + return © +} + func (s *Store) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) { job, err := scanJob(s.db.QueryRow( ctx, @@ -67,6 +101,21 @@ func (s *Store) Claim(ctx context.Context, workerID string, allowedTypes []strin // ListByType lists only the requested job type, so a busy queue cannot hide the // caller's own recent jobs behind unrelated traffic. +// QueueJob reads one queue row by exact id (no window / no type filter). +func (s *Store) QueueJob(ctx context.Context, id string) (jobs.Job, bool, error) { + if strings.TrimSpace(id) == "" { + return jobs.Job{}, false, errors.New("queue job id required") + } + job, err := scanJob(s.db.QueryRow(ctx, jobByIDSQL, id)) + if errors.Is(err, pgx.ErrNoRows) { + return jobs.Job{}, false, nil + } + if err != nil { + return jobs.Job{}, false, fmt.Errorf("read queue job: %w", err) + } + return *job, true, nil +} + func (s *Store) ListByType(ctx context.Context, jobType string, limit int) ([]jobs.Job, error) { if strings.TrimSpace(jobType) == "" || limit < 1 || limit > 200 { return nil, errors.New("list jobs by type requires a type and a bounded limit") diff --git a/internal/platform/postgres/version_history.go b/internal/platform/postgres/version_history.go index 511c530..9f838e2 100644 --- a/internal/platform/postgres/version_history.go +++ b/internal/platform/postgres/version_history.go @@ -171,11 +171,14 @@ WHERE repo_key = $1 AND status = 'completed' ORDER BY id DESC LIMIT 1`, repoKey) func (s *Store) LoadVersionHistorySyncState(ctx context.Context, repoKey string) (governance.VersionHistorySyncRun, error) { var run governance.VersionHistorySyncRun var expected *int + // finished_at 在"进行中"的 run 上是 NULL(列可空)。用指针接再判空: + // 直接扫进 time.Time 会让整页 500,而部署重启本身就会触发一次同步。 + var finishedAt *time.Time err := s.db.QueryRow(ctx, ` SELECT id, job_id, status, source_head_sha, started_at, finished_at, complete, fetched_count, expected_count, error_code, triggered_by FROM version_history_sync_runs WHERE repo_key = $1 ORDER BY id DESC LIMIT 1`, repoKey). - Scan(&run.ID, &run.JobID, &run.Status, &run.SourceHeadSHA, &run.StartedAt, &run.FinishedAt, + Scan(&run.ID, &run.JobID, &run.Status, &run.SourceHeadSHA, &run.StartedAt, &finishedAt, &run.Complete, &run.FetchedCount, &expected, &run.ErrorCode, &run.TriggeredBy) if err != nil && !errors.Is(err, pgx.ErrNoRows) { return governance.VersionHistorySyncRun{}, fmt.Errorf("查询同步状态:%w", err) @@ -183,6 +186,9 @@ FROM version_history_sync_runs WHERE repo_key = $1 ORDER BY id DESC LIMIT 1`, re if errors.Is(err, pgx.ErrNoRows) { return governance.VersionHistorySyncRun{}, nil } + if finishedAt != nil { + run.FinishedAt = *finishedAt + } run.ExpectedCount = expected if snapshot, err := s.ActiveVersionHistorySnapshot(ctx, repoKey); err != nil { return governance.VersionHistorySyncRun{}, err diff --git a/internal/platform/postgres/version_history_sync_state_integration_test.go b/internal/platform/postgres/version_history_sync_state_integration_test.go new file mode 100644 index 0000000..8ad90e6 --- /dev/null +++ b/internal/platform/postgres/version_history_sync_state_integration_test.go @@ -0,0 +1,80 @@ +package postgres + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// 真实缺陷:同步进行中的 run(finished_at 为 NULL)会让 LoadVersionHistorySyncState +// 扫描失败,整个版本记录页 500。部署重启会自动触发一次同步,所以页面第一次打开就撞上。 +func TestVersionHistorySyncStateToleratesRunningRunWithoutFinishTime(t *testing.T) { + dsn := os.Getenv("KG_VERSION_HISTORY_TEST_DSN") + if dsn == "" { + t.Skip("explicit disposable version-history DB required") + } + if !strings.Contains(dsn, "127.0.0.1") || !strings.Contains(dsn, "/kg_version_history_test_") { + t.Fatal("refusing shared database") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if err = ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + repo := "fixture/repo" + if _, err = pool.Exec(ctx, `DELETE FROM version_history_sync_runs WHERE repo_key = $1`, repo); err != nil { + t.Fatal(err) + } + // 一条已完成的历史 run(提供 last_success_at 与快照) + if _, err = pool.Exec(ctx, ` +INSERT INTO version_history_sync_runs + (repo_key, job_id, status, source_head_sha, started_at, finished_at, last_success_at, + complete, fetched_count, expected_count, error_code, triggered_by) +VALUES ($1,'job-1','completed',$2, now() - interval '2 hours', now() - interval '2 hours', + now() - interval '2 hours', true, 10, 10, '', 'fixture')`, repo, strings.Repeat("a", 40)); err != nil { + t.Fatal(err) + } + // 一条正在跑的 run:finished_at 必须是 NULL(这正是线上触发 500 的行) + if _, err = pool.Exec(ctx, ` +INSERT INTO version_history_sync_runs + (repo_key, job_id, status, source_head_sha, started_at, finished_at, + complete, fetched_count, expected_count, error_code, triggered_by) +VALUES ($1,'job-2','running',$2, now(), NULL, false, 3, 12, '', 'fixture')`, repo, strings.Repeat("b", 40)); err != nil { + t.Fatal(err) + } + + store := NewStore(pool) + state, err := store.LoadVersionHistorySyncState(ctx, repo) + if err != nil { + t.Fatalf("同步进行中读取同步状态不应失败:%v", err) + } + if state.Status != "running" { + t.Fatalf("应读到最新(进行中)的 run,实际 status=%q", state.Status) + } + if !state.FinishedAt.IsZero() { + t.Fatalf("进行中的 run 不应有结束时间,实际 %v", state.FinishedAt) + } + if state.LastSuccessAt.IsZero() { + t.Fatal("应保留上一次成功时间") + } + if !state.LastSuccessAt.Before(time.Now()) { + t.Fatalf("上次成功时间异常:%v", state.LastSuccessAt) + } + + // 列表读取同样不能因为这一行而失败 + items, _, _, snapshot, err := store.LoadVersionHistoryPage(ctx, repo, "all", "", 5) + if err != nil { + t.Fatalf("进行中读取分页也不应失败:%v", err) + } + if len(items) != 0 || snapshot == 0 { + t.Fatalf("空快照应返回空页与快照号,实际 items=%d snapshot=%d", len(items), snapshot) + } +} diff --git a/internal/platform/postgres/worker_heartbeat.go b/internal/platform/postgres/worker_heartbeat.go new file mode 100644 index 0000000..ec208d4 --- /dev/null +++ b/internal/platform/postgres/worker_heartbeat.go @@ -0,0 +1,40 @@ +package postgres + +import ( + "context" + "strings" + "time" +) + +// WorkerHeartbeat 是队列认领时顺手写下的存活记录(P10)。 +// 它本来就带 job_types:页面用它判断“这个 worker 有没有注册上传/解析链”, +// 不需要再开一张表,也不该拿 readiness 或 env 去猜。 +type WorkerHeartbeat struct { + WorkerID string + JobTypes []string + StartedAt time.Time + LastSeenAt time.Time +} + +func (s *Store) ListWorkerHeartbeats(ctx context.Context) ([]WorkerHeartbeat, error) { + rows, err := s.db.Query(ctx, ` +SELECT worker_id, job_types, started_at, last_seen_at +FROM worker_heartbeats ORDER BY last_seen_at DESC`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []WorkerHeartbeat + for rows.Next() { + var hb WorkerHeartbeat + var types string + if err := rows.Scan(&hb.WorkerID, &types, &hb.StartedAt, &hb.LastSeenAt); err != nil { + return nil, err + } + if types != "" { + hb.JobTypes = strings.Split(types, ",") + } + out = append(out, hb) + } + return out, rows.Err() +} diff --git a/internal/ppauth/manager.go b/internal/ppauth/manager.go new file mode 100644 index 0000000..9deedbf --- /dev/null +++ b/internal/ppauth/manager.go @@ -0,0 +1,356 @@ +package ppauth + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + "syscall" + "time" +) + +type Credentials struct { + ID string `json:"id"` + BaseURL string `json:"base_url"` + Username string `json:"username"` + Password string `json:"password"` +} +type Draft struct { + BaseURL string `json:"base_url"` + Username string `json:"username"` + Password string `json:"password,omitempty"` + PendingID string `json:"pending_id,omitempty"` + Revision int `json:"revision"` +} +type Observation struct { + State string `json:"state"` + Message string `json:"message"` + CheckedAt string `json:"checked_at"` + Previous *Observation `json:"previous,omitempty"` +} +type Metadata struct { + ID string `json:"id"` + BaseURL string `json:"base_url"` + Username string `json:"username"` + PasswordConfigured bool `json:"password_configured"` +} +type View struct { + Revision int `json:"revision"` + Active *Metadata `json:"active"` + Pending *Metadata `json:"pending"` + Observation *Observation `json:"observation"` + PendingObservation *Observation `json:"pending_observation"` +} +type AuditEvent struct { + ID string `json:"id"` + SourceName string `json:"source_name"` + Action string `json:"action"` + Actor string `json:"actor"` + CreatedAt time.Time `json:"created_at"` + Detail string `json:"detail"` +} +type State struct { + Revision int `json:"revision"` + Active *Credentials `json:"active"` + Pending *Credentials `json:"pending"` + Observation *Observation `json:"observation"` + PendingObservation *Observation `json:"pending_observation"` + Audit []AuditEvent `json:"audit"` +} +type Manager struct { + Path string + LegacyPath string + Probe func(context.Context, Credentials) Observation +} + +var ErrRejected = errors.New("PP 配置校验未通过,原配置保留") +var ErrInvalid = errors.New("API 地址必须为 HTTPS 根地址,且不能包含凭据、查询参数或片段") +var ErrConflict = errors.New("配置已被更新,请刷新后重新提交") + +func ValidateBaseURL(raw string) bool { + u, err := url.Parse(raw) + return err == nil && len(raw) <= 300 && strings.TrimSpace(raw) == raw && u.Scheme == "https" && u.Host != "" && u.Hostname() != "" && u.Opaque == "" && u.User == nil && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.Contains(raw, "#") && (u.Path == "" || u.Path == "/") +} +func metadata(c *Credentials) *Metadata { + if c == nil { + return nil + } + return &Metadata{ID: c.ID, BaseURL: c.BaseURL, Username: c.Username, PasswordConfigured: c.Password != ""} +} +func view(s State) View { + return View{Revision: s.Revision, Active: metadata(s.Active), Pending: metadata(s.Pending), Observation: s.Observation, PendingObservation: s.PendingObservation} +} +func randomID() string { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + panic("secure random unavailable") + } + return hex.EncodeToString(b[:]) +} +func (m *Manager) locked(ctx context.Context, fn func(*State) (bool, error)) error { + if !filepath.IsAbs(m.Path) { + return errors.New("PP credential storage path is invalid") + } + dir := filepath.Dir(m.Path) + if err := os.MkdirAll(dir, 0700); err != nil { + return errors.New("PP 配置存储不可用") + } + info, err := os.Lstat(dir) + if err != nil || !info.IsDir() || info.Mode().Perm()&0077 != 0 { + return errors.New("PP 配置目录权限必须为 0700") + } + lockPath := m.Path + ".lock" + if info, e := os.Lstat(lockPath); e == nil && (info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0077 != 0) { + return errors.New("PP 配置锁权限不安全") + } + lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return errors.New("PP 配置存储不可用") + } + defer lock.Close() + for { + err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if err == nil { + break + } + if err != syscall.EWOULDBLOCK { + return errors.New("PP 配置锁不可用") + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(20 * time.Millisecond): + } + } + defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) + var s State + info, err = os.Lstat(m.Path) + if err == nil { + if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > 16<<20 { + return errors.New("PP 凭据文件权限或格式不安全") + } + raw, e := os.ReadFile(m.Path) + if e != nil || json.Unmarshal(raw, &s) != nil { + return errors.New("无法读取 PP 配置") + } + } else if !errors.Is(err, os.ErrNotExist) { + return errors.New("无法读取 PP 配置") + } else if m.LegacyPath != "" { + raw, e := os.ReadFile(m.LegacyPath) + if e == nil { + var c Credentials + if json.Unmarshal(raw, &c) != nil { + return errors.New("旧 PP 配置格式不正确") + } + if c.BaseURL == "" { + c.BaseURL = "https://api.dobot.cn" + } + c.ID = "legacy" + s.Active = &c + } else if !errors.Is(e, os.ErrNotExist) { + return errors.New("无法读取旧 PP 配置") + } + } + changed, err := fn(&s) + if err != nil || !changed { + return err + } + raw, err := json.Marshal(s) + if err != nil { + return errors.New("PP 配置保存失败") + } + f, err := os.CreateTemp(dir, ".pp-next-") + if err != nil { + return errors.New("PP 配置保存失败") + } + tmp := f.Name() + defer os.Remove(tmp) + if err = f.Chmod(0600); err == nil { + _, err = f.Write(raw) + } + if err == nil { + err = f.Sync() + } + closeErr := f.Close() + if err == nil { + err = closeErr + } + if err == nil { + err = os.Rename(tmp, m.Path) + } + if err != nil { + return errors.New("PP 配置保存失败") + } + d, e := os.Open(dir) + if e != nil { + return errors.New("PP 配置持久化未确认") + } + defer d.Close() + if d.Sync() != nil { + return errors.New("PP 配置持久化未确认") + } + return nil +} +func (m *Manager) View() (v View, err error) { + err = m.locked(context.Background(), func(s *State) (bool, error) { v = view(*s); return false, nil }) + return +} +func (m *Manager) snapshot(ctx context.Context) (s State, err error) { + err = m.locked(ctx, func(state *State) (bool, error) { s = *state; return false, nil }) + return +} +func candidate(s State, d Draft) (Credentials, error) { + if !ValidateBaseURL(d.BaseURL) { + return Credentials{}, ErrInvalid + } + if len(d.Username) > 255 || strings.ContainsAny(d.Username, "\n\r\x00") || len(d.Password) > 8192 { + return Credentials{}, errors.New("账号或密码格式不正确") + } + c := Credentials{ID: randomID(), BaseURL: strings.TrimRight(d.BaseURL, "/"), Username: strings.TrimSpace(d.Username), Password: d.Password} + if c.Password == "" && d.PendingID != "" { + if s.Pending == nil || s.Pending.ID != d.PendingID { + return Credentials{}, ErrConflict + } + c.Password = s.Pending.Password + } else if c.Password == "" && s.Active != nil { + c.Password = s.Active.Password + } + return c, nil +} +func same(a, b *Credentials) bool { + return a != nil && b != nil && a.BaseURL == b.BaseURL && a.Username == b.Username && a.Password == b.Password +} +func (m *Manager) probe(ctx context.Context, c Credentials) Observation { + o := Observation{State: "incomplete", Message: "配置未完成,请填写账号和密码"} + if c.Username != "" && c.Password != "" { + if m.Probe == nil { + o = Observation{State: "unavailable", Message: "PP 检查服务未接通"} + } else { + o = m.Probe(ctx, c) + } + } + switch o.State { + case "valid", "auth_failed", "permission_denied", "incomplete", "unavailable", "invalid_response": + default: + o = Observation{State: "unavailable", Message: "检查结果不可识别,请重试"} + } + if o.CheckedAt == "" { + o.CheckedAt = time.Now().UTC().Format(time.RFC3339Nano) + } + return o +} +func addAudit(s *State, source, action, actor, detail string) { + s.Audit = append(s.Audit, AuditEvent{ID: "auth-" + randomID(), SourceName: source, Action: action, Actor: actor, CreatedAt: time.Now().UTC(), Detail: detail}) +} +func retainObservation(old *Observation, next Observation) *Observation { + if next.State == "unavailable" && old != nil { + if old.State == "unavailable" && old.Previous != nil { + next.Previous = old.Previous + } else { + next.Previous = old + } + } + return &next +} +func (m *Manager) Save(ctx context.Context, d Draft, actor string) (v View, err error) { + s, err := m.snapshot(ctx) + if err != nil { + return v, err + } + if s.Revision != d.Revision { + return v, ErrConflict + } + c, err := candidate(s, d) + if err != nil { + return v, err + } + o := m.probe(ctx, c) + rejected := o.State == "auth_failed" || o.State == "permission_denied" || o.State == "invalid_response" + err = m.locked(ctx, func(current *State) (bool, error) { + if current.Revision != s.Revision { + return false, ErrConflict + } + if rejected { + if same(current.Active, &c) { + current.Observation = retainObservation(current.Observation, o) + } + addAudit(current, "PP 资料下载中心", "credential_rejected", actor, o.Message) + v = view(*current) + return true, nil + } + current.Revision++ + if o.State == "valid" { + current.Active = &c + current.Pending = nil + current.Observation = retainObservation(current.Observation, o) + current.PendingObservation = nil + } else { + current.Pending = &c + current.PendingObservation = &o + } + detail := "认证配置已保存并生效" + if o.State != "valid" { + detail = "修改已保存为待验证,未替换生效配置" + } + if d.Password != "" { + detail += ";密码已更新" + } + addAudit(current, "PP 资料下载中心", "credential_configured", actor, detail) + v = view(*current) + return true, nil + }) + if err == nil && rejected { + err = fmt.Errorf("%w:%s", ErrRejected, o.Message) + } + return +} +func (m *Manager) Test(ctx context.Context, d Draft, actor string) (o Observation, err error) { + s, err := m.snapshot(ctx) + if err != nil { + return o, err + } + if s.Revision != d.Revision { + return o, ErrConflict + } + c, err := candidate(s, d) + if err != nil { + return o, err + } + o = m.probe(ctx, c) + err = m.locked(ctx, func(current *State) (bool, error) { + if current.Revision != s.Revision { + return false, ErrConflict + } + if same(current.Active, &c) { + current.Observation = retainObservation(current.Observation, o) + } + addAudit(current, "PP 资料下载中心", "credential_test", actor, o.Message) + return true, nil + }) + return +} +func (m *Manager) Audit(ctx context.Context, source, action, actor, detail string) error { + return m.locked(ctx, func(s *State) (bool, error) { addAudit(s, source, action, actor, detail); return true, nil }) +} +func (m *Manager) AuditOnce(ctx context.Context, id, source, action, actor, detail string) error { + return m.locked(ctx, func(s *State) (bool, error) { + for _, e := range s.Audit { + if e.ID == id { + return false, nil + } + } + addAudit(s, source, action, actor, detail) + s.Audit[len(s.Audit)-1].ID = id + return true, nil + }) +} +func (m *Manager) Events(ctx context.Context) (events []AuditEvent, err error) { + err = m.locked(ctx, func(s *State) (bool, error) { events = append(events, s.Audit...); return false, nil }) + return +} diff --git a/internal/ppauth/manager_test.go b/internal/ppauth/manager_test.go new file mode 100644 index 0000000..e078b78 --- /dev/null +++ b/internal/ppauth/manager_test.go @@ -0,0 +1,35 @@ +package ppauth + +import ( + "context" + "errors" + "testing" +) + +func TestSaveValidatesBeforeActivationAndTransientKeepsActive(t *testing.T) { + state := "valid" + seen := "" + manager := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation { + seen = c.Password + return Observation{State: state, Message: state} + }} + view, err := manager.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-password", Revision: 0}, "tester") + if err != nil || view.Active == nil || view.Active.Username != "example" || !view.Active.PasswordConfigured || seen != "example-password" { + t.Fatalf("validated save did not activate: %+v %v", view, err) + } + activeID := view.Active.ID + state = "unavailable" + view, err = manager.Save(context.Background(), Draft{BaseURL: "https://changed.example.invalid", Username: "changed", Revision: view.Revision}, "tester") + if err != nil || view.Active == nil || view.Active.ID != activeID || view.Pending == nil || view.Pending.Username != "changed" || seen != "example-password" { + t.Fatalf("transient save replaced active or lost password: %+v %v", view, err) + } + state = "auth_failed" + _, err = manager.Save(context.Background(), Draft{BaseURL: "https://changed.example.invalid", Username: "changed", Password: "bad-example", Revision: view.Revision}, "tester") + if !errors.Is(err, ErrRejected) { + t.Fatalf("explicit rejection allowed activation: %v", err) + } + after, _ := manager.View() + if after.Active.ID != activeID { + t.Fatal("rejection changed active config") + } +} diff --git a/internal/ppauth/persistence_test.go b/internal/ppauth/persistence_test.go new file mode 100644 index 0000000..d795bdc --- /dev/null +++ b/internal/ppauth/persistence_test.go @@ -0,0 +1,104 @@ +package ppauth + +import ( + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "strings" + "sync" + "sync/atomic" + "testing" +) + +func TestPendingPasswordSurvivesRevalidationWithoutReturningSecrets(t *testing.T) { + state := "valid" + seen := "" + m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation { + seen = c.Password + return Observation{State: state, Message: state} + }} + v, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-old"}, "tester") + if err != nil { + t.Fatal(err) + } + state = "unavailable" + v, err = m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-new", Revision: v.Revision}, "tester") + if err != nil || v.Pending == nil { + t.Fatalf("pending save: %v", err) + } + state = "valid" + v, err = m.Save(context.Background(), Draft{BaseURL: v.Pending.BaseURL, Username: v.Pending.Username, PendingID: v.Pending.ID, Revision: v.Revision}, "tester") + if err != nil || seen != "example-new" || v.Pending != nil { + t.Fatal("saved pending password was not reused") + } + raw, _ := json.Marshal(v) + if strings.Contains(string(raw), "example-new") || strings.Contains(string(raw), `"password":`) { + t.Fatal("metadata leaked secret") + } + info, err := os.Stat(m.Path) + if err != nil || info.Mode().Perm() != 0600 { + t.Fatal("secret file not mode 0600") + } +} +func TestConcurrentSavesCannotOverwriteANewerRevision(t *testing.T) { + var calls atomic.Int32 + barrier := make(chan struct{}) + m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation { + if calls.Add(1) == 2 { + close(barrier) + } + <-barrier + return Observation{State: "valid", Message: "valid"} + }} + outcomes := make(chan error, 2) + var wg sync.WaitGroup + for _, name := range []string{"example-one", "example-two"} { + wg.Add(1) + go func(user string) { + defer wg.Done() + _, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: user, Password: "example-password"}, "tester") + outcomes <- err + }(name) + } + wg.Wait() + close(outcomes) + success, conflict := 0, 0 + for err := range outcomes { + if err == nil { + success++ + } else if errors.Is(err, ErrConflict) { + conflict++ + } else { + t.Fatal(err) + } + } + if success != 1 || conflict != 1 { + t.Fatalf("success=%d conflict=%d", success, conflict) + } +} +func TestFailedObservationRetainsPreviousSuccess(t *testing.T) { + state := "valid" + m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation { return Observation{State: state, Message: state} }} + v, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-password"}, "tester") + if err != nil { + t.Fatal(err) + } + state = "unavailable" + _, err = m.Test(context.Background(), Draft{BaseURL: v.Active.BaseURL, Username: v.Active.Username, Revision: v.Revision}, "tester") + if err != nil { + t.Fatal(err) + } + v, err = m.View() + if err != nil || v.Observation.Previous == nil || v.Observation.Previous.State != "valid" { + t.Fatal("failed check erased previous successful observation") + } +} +func TestPPPythonProtocolAndConfigurationConsumers(t *testing.T) { + command := exec.Command("python3", "-m", "unittest", "discover", "-s", "../../scripts", "-p", "test_pp_client.py", "-v") + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("PP protocol regression: %v\n%s", err, output) + } +} diff --git a/internal/ppauth/probe.go b/internal/ppauth/probe.go new file mode 100644 index 0000000..7b3a672 --- /dev/null +++ b/internal/ppauth/probe.go @@ -0,0 +1,31 @@ +package ppauth + +import ( + "bytes" + "context" + "encoding/json" + "os" + "os/exec" + "time" +) + +// CommandProbe reuses the worker's read-only PP adapter; secrets travel on stdin. +func CommandProbe(python, script string) func(context.Context, Credentials) Observation { + return func(ctx context.Context, c Credentials) Observation { + ctx, cancel := context.WithTimeout(ctx, 45*time.Second) + defer cancel() + raw, _ := json.Marshal(c) + command := exec.CommandContext(ctx, python, script) + command.Stdin = bytes.NewReader(raw) + command.Env = []string{"PATH=" + os.Getenv("PATH"), "PYTHONUNBUFFERED=1"} + out, err := command.Output() + if err != nil || len(out) > 8192 { + return Observation{State: "unavailable", Message: "PP 检查服务暂不可用,请重试"} + } + var o Observation + if json.Unmarshal(out, &o) != nil { + return Observation{State: "unavailable", Message: "PP 检查结果不可识别"} + } + return o + } +} diff --git a/internal/qawemail/resend_integration_test.go b/internal/qawemail/resend_integration_test.go new file mode 100644 index 0000000..99d412a --- /dev/null +++ b/internal/qawemail/resend_integration_test.go @@ -0,0 +1,463 @@ +package qawemail + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// countingMailer records real deliveries instead of talking to SMTP. It is shared by the +// concurrency case, so every observation happens under the mutex. +type countingMailer struct { + mu sync.Mutex + calls int + delay time.Duration + err error + subjects []string + to [][]string + cc [][]string + html []string + messageIDs []string +} + +func (m *countingMailer) Send(_ context.Context, _ SMTPConfig, msg Message) (string, error) { + if m.delay > 0 { + time.Sleep(m.delay) + } + m.mu.Lock() + defer m.mu.Unlock() + m.calls++ + if m.err != nil { + return "", m.err + } + id := fmt.Sprintf("", m.calls) + m.subjects = append(m.subjects, msg.Subject) + m.to = append(m.to, msg.To) + m.cc = append(m.cc, msg.Cc) + m.html = append(m.html, msg.HTML) + m.messageIDs = append(m.messageIDs, id) + return id, nil +} + +func (m *countingMailer) count() int { + m.mu.Lock() + defer m.mu.Unlock() + return m.calls +} + +func weeklyMailFixture(t *testing.T) (*Store, *pgxpool.Pool, *countingMailer) { + t.Helper() + mailer := &countingMailer{} + store, pool := weeklyMailFixtureWith(t, mailer) + return store, pool, mailer +} + +// weeklyMailFixtureWith applies the real schema to an explicitly disposable database. Refusing to +// run without KG_WEEKLY_MAIL_TEST_DSN keeps CI honest: a skip there is not a pass. +func weeklyMailFixtureWith(t *testing.T, mailer Mailer) (*Store, *pgxpool.Pool) { + t.Helper() + dsn := os.Getenv("KG_WEEKLY_MAIL_TEST_DSN") + if dsn == "" { + t.Skip("显式一次性周报邮件数据库未提供(KG_WEEKLY_MAIL_TEST_DSN):跳过不等于通过") + } + // The name is the only proof this is disposable; never touch a governance database. + if !strings.Contains(dsn, "/kg_weekly_mail_test_") || strings.Contains(dsn, "/governance?") { + t.Fatal("拒绝非一次性周报测试库") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + // Deliberately do not print the DSN (it carries a password). + t.Fatal("测试库连接参数无效(详情省略)") + } + t.Cleanup(pool.Close) + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + store := NewStore(pool, "fixture-weekly-resend", os.Getenv("KG_WEEKLY_MAIL_TEST_KEY"), mailer) + for _, statement := range []string{ + `DELETE FROM qa_weekly_email_sends WHERE tenant_key=$1`, + `DELETE FROM qa_weekly_confirmations WHERE tenant_key=$1`, + `DELETE FROM qa_weekly_email_settings WHERE tenant_key=$1`, + `DELETE FROM qa_ops_weekly_drafts WHERE tenant_key=$1`, + } { + if _, err := pool.Exec(ctx, statement, store.tenant); err != nil { + t.Fatal(err) + } + } + return store, pool +} + +func seedWeeklyDraft(t *testing.T, pool *pgxpool.Pool, tenant, week string, revision int64, markdown string) { + t.Helper() + if _, err := pool.Exec(context.Background(), `INSERT INTO qa_ops_weekly_drafts(tenant_key,week,revision,markdown,seed,updated_by,updated_at) + VALUES($1,$2,$3,$4,'{}'::jsonb,'fixture-admin',now()) + ON CONFLICT (tenant_key,week) DO UPDATE SET revision=excluded.revision,markdown=excluded.markdown`, tenant, week, revision, markdown); err != nil { + t.Fatal(err) + } +} + +func enabledWeeklySettings(t *testing.T, store *Store, weekday, hour int) Settings { + t.Helper() + settings, err := store.SaveSettings(context.Background(), "fixture-admin", SettingsInput{ + BaseRevision: 0, Host: "localhost", Port: 465, Username: "kb@example.com", Password: "app-password", + From: "kb@example.com", Recipients: []string{"lead@example.com", "pm@example.com"}, + Cc: []string{"qa@example.com"}, Review: "owner@example.com", Weekday: weekday, Hour: hour, Enabled: true, + }) + if err != nil { + t.Fatal(err) + } + return settings +} + +func weekLocal(t *testing.T, year int, month time.Month, day, hour int) time.Time { + t.Helper() + return time.Date(year, month, day, hour, 5, 0, 0, time.FixedZone("CST", 8*3600)) +} + +// A: the reported week closes at the end of its own Sunday; the 周日23点 configuration must mail +// that week inside the slot instead of waiting for the next Monday (where the slot is gone). +func TestAutoSendAtSundaySlotMailsTheWeekThatEndsThatDay(t *testing.T) { + store, pool, mailer := weeklyMailFixture(t) + md := "# 知识库周报 2026-W45\n\n## 二、核心指标\n\n正确率:91.20%\n" + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) + if _, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin"); err != nil { + t.Fatal(err) + } + enabledWeeklySettings(t, store, 7, 23) + + // 周六同一小时、周日22点:都还没到配置时点,不许提前发。 + if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 7, 23)); err != nil || result.State != "not_due" { + t.Fatalf("周六不是配置发送日,必须 not_due,got %+v %v", result, err) + } + if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 22)); err != nil || result.State != "not_due" { + t.Fatalf("到点前必须 not_due,got %+v %v", result, err) + } + if mailer.count() != 0 { + t.Fatal("到点前不得投递") + } + + sent, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)) + if err != nil || sent.State != "sent" || sent.Week != "2026-W45" { + t.Fatalf("周日23点必须发出当周 2026-W45,got %+v %v", sent, err) + } + if mailer.count() != 1 || sent.MessageID == "" { + t.Fatalf("应只投递一次并记录 message_id,calls=%d message_id=%q", mailer.count(), sent.MessageID) + } + message := mailer.to[0] + if len(message) != 2 || message[0] != "lead@example.com" { + t.Fatalf("自动发送必须用正式收件人而不是测试地址:%v", message) + } + if len(mailer.cc[0]) != 1 || mailer.cc[0][0] != "qa@example.com" { + t.Fatalf("自动发送必须带上抄送:%v", mailer.cc[0]) + } + + // 同一时段重复触发幂等;周一00:00已不在时段内,绝不能补发。 + again, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)) + if err != nil || again.State != "already_sent" { + t.Fatalf("同一时段重复触发必须 already_sent,got %+v %v", again, err) + } + if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 9, 0)); err != nil || result.State != "not_due" { + t.Fatalf("周一00:00已过时段,必须 not_due,got %+v %v", result, err) + } + if mailer.count() != 1 { + t.Fatalf("重复/越界触发造成了重复投递:calls=%d", mailer.count()) + } + var sentRows int + if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM qa_weekly_email_sends WHERE tenant_key=$1 AND status='sent'`, store.tenant).Scan(&sentRows); err != nil { + t.Fatal(err) + } + if sentRows != 1 { + t.Fatalf("sends 表应只有一条 sent,got %d", sentRows) + } +} + +// A: an unconfirmed week, a changed body and a future week must never be mailed automatically. +func TestAutoSendRefusesUnconfirmedChangedAndFutureWeeks(t *testing.T) { + store, pool, mailer := weeklyMailFixture(t) + enabledWeeklySettings(t, store, 7, 23) + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, "# 知识库周报 2026-W45\n\n正确率:91.20%\n") + // 未确认:不能发。 + if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)); err != nil || result.State != "nothing_confirmed" { + t.Fatalf("未确认的周报必须 nothing_confirmed,got %+v %v", result, err) + } + if _, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin"); err != nil { + t.Fatal(err) + } + // 已确认后改正文:确认失效,不能发。 + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 17, "# 知识库周报 2026-W45\n\n正确率:92.00%\n") + if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)); err != nil || result.State != "nothing_confirmed" { + t.Fatalf("正文变化后必须 nothing_confirmed,got %+v %v", result, err) + } + // 未来周(W46)即使已确认也不能在 W45 的时段被自动投递。 + seedWeeklyDraft(t, pool, store.tenant, "2026-W46", 1, "# 知识库周报 2026-W46\n") + if _, err := store.Confirm(context.Background(), "2026-W46", "fixture-admin"); err != nil { + t.Fatal(err) + } + if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)); err != nil || result.State != "nothing_confirmed" { + t.Fatalf("未来周不得被自动发送,got %+v %v", result, err) + } + if mailer.count() != 0 { + t.Fatalf("不该有任何投递,calls=%d", mailer.count()) + } +} + +// Monday slots keep their old meaning: mail the week that ended, not the one that just began. +func TestAutoSendOnMondayStillMailsThePreviousCompleteWeek(t *testing.T) { + store, pool, mailer := weeklyMailFixture(t) + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, "# 知识库周报 2026-W45\n\n正确率:91.20%\n") + if _, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin"); err != nil { + t.Fatal(err) + } + enabledWeeklySettings(t, store, 1, 9) + result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 9, 9)) + if err != nil || result.State != "sent" || result.Week != "2026-W45" { + t.Fatalf("周一09点应发送上一完整周 W45,got %+v %v", result, err) + } + if mailer.count() != 1 { + t.Fatalf("calls=%d, want 1", mailer.count()) + } +} + +// B/C: the manual resend uses the frozen confirmed revision and is idempotent. +func TestManualResendSendsFrozenRevisionOnceAndReadsBackMessageID(t *testing.T) { + store, pool, mailer := weeklyMailFixture(t) + md := "# 知识库周报 2026-W45\n\n## 二、核心指标\n\n正确率:91.20%\n" + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) + confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") + if err != nil { + t.Fatal(err) + } + enabledWeeklySettings(t, store, 7, 23) + png := []byte("\x89PNG\r\n\x1a\nweekly-dashboard-fixture") + if err := store.SaveDashboardImage(context.Background(), "2026-W45", png); err != nil { + t.Fatal(err) + } + now := weekLocal(t, 2026, 11, 9, 0) // 周一00:32,真实故障时刻 + + preview, err := store.PreviewSend(context.Background(), "2026-W45", 16, confirmation.BodySHA256, now) + if err != nil { + t.Fatal(err) + } + if preview.Status != "ready" || preview.Recipients != 2 || preview.Cc != 1 || preview.Revision != 16 { + t.Fatalf("补发预览必须给出真实收件人数与版本:%+v", preview) + } + if mailer.count() != 0 { + t.Fatal("预览不得投递") + } + + sent, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now) + if err != nil || sent.Status != "sent" { + t.Fatalf("正式补发必须成功:%+v %v", sent, err) + } + if sent.MessageID == "" || sent.Recipients != 2 || sent.Cc != 1 { + t.Fatalf("补发结果缺少 message_id 或收件人数:%+v", sent) + } + if mailer.count() != 1 { + t.Fatalf("calls=%d, want 1", mailer.count()) + } + if strings.Contains(mailer.subjects[0], "测试发送") || strings.Contains(mailer.subjects[0], "2026-W45") == false { + t.Fatalf("正式补发主题不对:%q", mailer.subjects[0]) + } + if len(mailer.to[0]) != 2 || mailer.to[0][0] == "owner@example.com" { + t.Fatalf("正式补发必须发给正式收件人,而不是 review 地址:%v", mailer.to[0]) + } + if !strings.Contains(mailer.html[0], "91.20%") || !strings.Contains(mailer.html[0], "cid:weekly-dashboard@knowledge-governance") { + t.Fatal("正式补发必须使用冻结的已确认正文和看板图片") + } + var status, messageID string + var revision int64 + if err := pool.QueryRow(context.Background(), `SELECT status,message_id,draft_revision FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45'`, store.tenant).Scan(&status, &messageID, &revision); err != nil { + t.Fatal(err) + } + if status != "sent" || messageID != sent.MessageID || revision != 16 { + t.Fatalf("发送记录必须可读回真实结果:status=%q message_id=%q revision=%d", status, messageID, revision) + } + + // 重复点击:幂等,不再投递,并读回同一条 message_id。 + again, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now) + if err != nil || again.Status != "already_sent" || again.MessageID != sent.MessageID { + t.Fatalf("重复补发必须 already_sent 且回同一 message_id:%+v %v", again, err) + } + if mailer.count() != 1 { + t.Fatalf("重复补发造成了重复投递:calls=%d", mailer.count()) + } + + // 版本或正文不匹配:拒绝,不投递。 + if _, err := store.SendManual(context.Background(), "2026-W45", 15, confirmation.BodySHA256, "fixture-admin", now); !errors.Is(err, ErrNotCurrent) { + t.Fatalf("错误版本必须 ErrNotCurrent,got %v", err) + } + if _, err := store.SendManual(context.Background(), "2026-W45", 16, strings.Repeat("0", 64), "fixture-admin", now); !errors.Is(err, ErrNotCurrent) { + t.Fatalf("错误正文 hash 必须 ErrNotCurrent,got %v", err) + } + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 17, md+"\n改过的正文\n") + if _, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now); !errors.Is(err, ErrNotCurrent) { + t.Fatalf("正文已改必须 ErrNotCurrent,got %v", err) + } + if mailer.count() != 1 { + t.Fatalf("被拒绝的补发不得投递:calls=%d", mailer.count()) + } +} + +// B: the manual window — no future week, and the running week only after its configured slot. +func TestManualResendWindowRejectsFutureAndTooEarlyWeeks(t *testing.T) { + store, pool, mailer := weeklyMailFixture(t) + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, "# 知识库周报 2026-W45\n") + seedWeeklyDraft(t, pool, store.tenant, "2026-W46", 1, "# 知识库周报 2026-W46\n") + confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") + if err != nil { + t.Fatal(err) + } + enabledWeeklySettings(t, store, 7, 23) + // 未来周 W46(即便已确认)明确拒绝。 + if _, err := store.Confirm(context.Background(), "2026-W46", "fixture-admin"); err != nil { + t.Fatal(err) + } + var hash46 string + if err := pool.QueryRow(context.Background(), `SELECT body_sha256 FROM qa_weekly_confirmations WHERE tenant_key=$1 AND week='2026-W46'`, store.tenant).Scan(&hash46); err != nil { + t.Fatal(err) + } + if _, err := store.SendManual(context.Background(), "2026-W46", 1, hash46, "fixture-admin", weekLocal(t, 2026, 11, 8, 23)); !errors.Is(err, ErrFutureWeek) { + t.Fatalf("未来周必须 ErrFutureWeek,got %v", err) + } + // 当前周 W45 在 22:05 尚未到配置时点:拒绝。 + if _, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 8, 22)); !errors.Is(err, ErrSlotPending) { + t.Fatalf("当前周未到配置时点必须 ErrSlotPending,got %v", err) + } + // 到点后允许。 + if result, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 8, 23)); err != nil || result.Status != "sent" { + t.Fatalf("到点后当前周应允许补发:%+v %v", result, err) + } + // 未确认的周没有 confirmation:拒绝。 + seedWeeklyDraft(t, pool, store.tenant, "2026-W44", 3, "# 知识库周报 2026-W44\n") + if _, err := store.SendManual(context.Background(), "2026-W44", 3, strings.Repeat("a", 64), "fixture-admin", weekLocal(t, 2026, 11, 9, 0)); !errors.Is(err, ErrNotCurrent) { + t.Fatalf("未确认周必须 ErrNotCurrent,got %v", err) + } + if mailer.count() != 1 { + t.Fatalf("被拒绝的补发不得投递:calls=%d", mailer.count()) + } +} + +// C: automatic and manual paths racing on the same week+revision deliver exactly once. +func TestConcurrentAutoAndManualSendDeliverOnce(t *testing.T) { + store, pool, mailer := weeklyMailFixture(t) + md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) + confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") + if err != nil { + t.Fatal(err) + } + enabledWeeklySettings(t, store, 7, 23) + mailer.delay = 150 * time.Millisecond + now := weekLocal(t, 2026, 11, 8, 23) + var wg sync.WaitGroup + states := make([]string, 6) + for i := 0; i < 6; i++ { + wg.Add(1) + go func(index int) { + defer wg.Done() + if index%2 == 0 { + result, callErr := store.SendDue(context.Background(), now) + if callErr != nil { + states[index] = "error:" + callErr.Error() + return + } + states[index] = result.State + return + } + result, callErr := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now) + if callErr != nil { + states[index] = "error:" + callErr.Error() + return + } + states[index] = result.Status + }(i) + } + wg.Wait() + if mailer.count() != 1 { + t.Fatalf("并发自动/手动必须只投递一次,calls=%d states=%v", mailer.count(), states) + } + var sentRows int + if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45' AND status='sent'`, store.tenant).Scan(&sentRows); err != nil { + t.Fatal(err) + } + if sentRows != 1 { + t.Fatalf("sends 表必须有且只有一条 sent:%d states=%v", sentRows, states) + } +} + +// C: a send whose outcome is unknown stays unknown — never blindly retried, never marked sent. +func TestUnknownSendingIsNotResentAndNotMarkedSent(t *testing.T) { + store, pool, mailer := weeklyMailFixture(t) + md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) + confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") + if err != nil { + t.Fatal(err) + } + enabledWeeklySettings(t, store, 7, 23) + if _, err := pool.Exec(context.Background(), `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,created_at,updated_at) + VALUES($1,'2026-W45',16,$2,'sending',1,now(),now())`, store.tenant, confirmation.BodySHA256); err != nil { + t.Fatal(err) + } + if _, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 0)); !errors.Is(err, ErrSendInFlight) { + t.Fatalf("结果未知的 sending 必须拒绝重发,got %v", err) + } + if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)); err != nil || result.State != "in_flight" { + t.Fatalf("自动路径必须识别 in_flight,got %+v %v", result, err) + } + if mailer.count() != 0 { + t.Fatalf("未知结果不得盲重发:calls=%d", mailer.count()) + } + var status string + if err := pool.QueryRow(context.Background(), `SELECT status FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45'`, store.tenant).Scan(&status); err != nil { + t.Fatal(err) + } + if status != "sending" { + t.Fatalf("未知结果不得被改写:status=%q", status) + } +} + +// C: a failed attempt is recorded as failed (never sent) and is the only reclaimable state. +func TestFailedSendIsRecordedThenRetriedOnce(t *testing.T) { + store, pool, mailer := weeklyMailFixture(t) + md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) + confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") + if err != nil { + t.Fatal(err) + } + enabledWeeklySettings(t, store, 7, 23) + mailer.err = errors.New("smtp 连接失败: dial tcp: connection refused") + failed, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 0)) + if err != nil { + t.Fatal(err) + } + if failed.Status != "failed" || failed.MessageID != "" { + t.Fatalf("SMTP 失败必须如实记录为 failed:%+v", failed) + } + var status, lastError string + if err := pool.QueryRow(context.Background(), `SELECT status,last_error FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45'`, store.tenant).Scan(&status, &lastError); err != nil { + t.Fatal(err) + } + if status != "failed" || lastError == "" { + t.Fatalf("失败记录不得假写 sent:status=%q last_error=%q", status, lastError) + } + mailer.err = nil + retried, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 0)) + if err != nil || retried.Status != "sent" || retried.MessageID == "" { + t.Fatalf("failed 记录应允许一次真实重试:%+v %v", retried, err) + } + if mailer.count() != 2 { + t.Fatalf("calls=%d, want 2", mailer.count()) + } +} diff --git a/internal/qawemail/scheduling_integration_test.go b/internal/qawemail/scheduling_integration_test.go index f387c19..c0e8c21 100644 --- a/internal/qawemail/scheduling_integration_test.go +++ b/internal/qawemail/scheduling_integration_test.go @@ -105,9 +105,13 @@ func TestScheduledSendRequiresConfirmationAndSendsExactlyOnce(t *testing.T) { t.Fatal("the sealed password must be unsealed for the SMTP call") } again, err := store.SendDue(ctx, slot) - if err != nil || again.State != "nothing_confirmed" { + // 同一时段第二次触发必须幂等:已 sent 就不再投递,也不谎报成“没有可发的周报”。 + if err != nil || again.State != "already_sent" { t.Fatalf("a second attempt in the same slot must not resend, got %+v %v", again, err) } + if again.MessageID == "" { + t.Fatal("already_sent 必须带回第一次真实发送的 message_id") + } if len(mailer.sent) != 1 { t.Fatal("duplicate send detected") } diff --git a/internal/qawemail/sends_readback_integration_test.go b/internal/qawemail/sends_readback_integration_test.go new file mode 100644 index 0000000..7cd53cc --- /dev/null +++ b/internal/qawemail/sends_readback_integration_test.go @@ -0,0 +1,54 @@ +package qawemail + +import ( + "context" + "testing" +) + +// 产品读回入口:页面 reload / GET /weekly-mail/sends 都走 store.Sends()。 +// 旧实现 SELECT 只有 6 列却 Scan 7 个字段(多出 message_id),任何一条历史行都会让整个 +// 列表返回 ErrUnavailable —— 发送成功后刷新页面必然报错。这里用真实 PG 的非空历史复现。 +func TestSendsReadsBackMessageIDFromNonEmptyHistory(t *testing.T) { + store, pool, _ := weeklyMailFixture(t) + ctx := context.Background() + md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) + confirmation, err := store.Confirm(ctx, "2026-W45", "fixture-admin") + if err != nil { + t.Fatal(err) + } + enabledWeeklySettings(t, store, 7, 23) + now := weekLocal(t, 2026, 11, 9, 0) + sent, err := store.SendManual(ctx, "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now) + if err != nil || sent.Status != "sent" || sent.MessageID == "" { + t.Fatalf("准备真实发送记录失败:%+v %v", sent, err) + } + + // 单周读回(页面 reload 的真实入口)。 + list, err := store.Sends(ctx, "2026-W45") + if err != nil { + t.Fatalf("非空历史下 Sends(week) 必须成功,got err=%v", err) + } + if len(list) != 1 || list[0].Status != "sent" || list[0].MessageID != sent.MessageID { + t.Fatalf("发送记录必须带回 message_id:%+v(期望 %q)", list, sent.MessageID) + } + + // 全量列表(不带 week 的历史视图)。 + all, err := store.Sends(ctx, "") + if err != nil { + t.Fatalf("非空历史下 Sends(all) 必须成功,got err=%v", err) + } + if len(all) != 1 || all[0].MessageID != sent.MessageID || all[0].Revision != 16 { + t.Fatalf("全量发送记录内容不符:%+v", all) + } + + // 历史里已存在 failed 行(last_error 非空)也不能让读取失败。 + if _, err := pool.Exec(ctx, `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,last_error,created_at,updated_at) + VALUES($1,'2026-W44',3,$2,'failed',2,'smtp 登录失败: 535',now(),now())`, store.tenant, confirmation.BodySHA256); err != nil { + t.Fatal(err) + } + list, err = store.Sends(ctx, "2026-W44") + if err != nil || len(list) != 1 || list[0].LastError == "" || list[0].MessageID != "" { + t.Fatalf("failed 历史行必须可读且不假造 message_id:%+v %v", list, err) + } +} diff --git a/internal/qawemail/smtp_delivery_integration_test.go b/internal/qawemail/smtp_delivery_integration_test.go new file mode 100644 index 0000000..0125f92 --- /dev/null +++ b/internal/qawemail/smtp_delivery_integration_test.go @@ -0,0 +1,111 @@ +package qawemail + +import ( + "context" + "crypto/tls" + "errors" + "strings" + "testing" +) + +func stubSMTPSettings(t *testing.T, store *Store, port int) { + t.Helper() + if _, err := store.SaveSettings(context.Background(), "fixture-admin", SettingsInput{ + BaseRevision: 0, Host: "127.0.0.1", Port: port, Password: "app-password", + From: "kb@example.com", Recipients: []string{"lead@example.com", "pm@example.com"}, + Cc: []string{"qa@example.com"}, Weekday: 7, Hour: 23, Enabled: true, + }); err != nil { + t.Fatal(err) + } +} + +// 真实 SMTPMailer + 真实 deliver + 真实 PG:DATA 提交后最终确认丢失 ⇒ 记录留 sending、 +// 手动/自动都不得再投一次。这不是“随便造一个 error”,桩必须真的收到 DATA。 +func TestRealSMTPUnknownAfterDataStaysSendingAndNeverRetries(t *testing.T) { + stub := newSMTPStub(t) + stub.setMode(smtpStubLostAck) + store, pool := weeklyMailFixtureWith(t, SMTPMailer{TLS: &tls.Config{InsecureSkipVerify: true}}) + ctx := context.Background() + md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) + confirmation, err := store.Confirm(ctx, "2026-W45", "fixture-admin") + if err != nil { + t.Fatal(err) + } + stubSMTPSettings(t, store, stub.port()) + + result, err := store.SendManual(ctx, "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 0)) + if !errors.Is(err, ErrDeliveryUnknown) { + t.Fatalf("最终确认丢失必须 ErrDeliveryUnknown,got %+v %v", result, err) + } + if result.Status != "unknown" || result.MessageID != "" { + t.Fatalf("unknown 结果不得带 message_id:%+v", result) + } + if stub.deliveries() != 1 { + t.Fatalf("桩必须真的收到 1 次 DATA,got %d", stub.deliveries()) + } + var status, messageID, lastError string + if err := pool.QueryRow(ctx, `SELECT status,message_id,last_error FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45'`, store.tenant).Scan(&status, &messageID, &lastError); err != nil { + t.Fatal(err) + } + if status != "sending" || messageID != "" || !strings.Contains(lastError, "最终确认") { + t.Fatalf("未知结果必须留在 sending 并记录原因:status=%q message_id=%q last_error=%q", status, messageID, lastError) + } + + stub.setMode(smtpStubAccept) + if again, err := store.SendDue(ctx, weekLocal(t, 2026, 11, 8, 23)); err != nil || again.State != "in_flight" { + t.Fatalf("未知结果后自动路径必须 in_flight,got %+v %v", again, err) + } + if _, err := store.SendManual(ctx, "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 9)); !errors.Is(err, ErrSendInFlight) { + t.Fatalf("未知结果后手动补发必须拒绝,got %v", err) + } + if stub.deliveries() != 1 { + t.Fatalf("未知结果不得重发:DATA 次数 %d", stub.deliveries()) + } +} + +// 明确拒绝(RCPT 550)是确定失败:记 failed、可重试一次;重试成功后写 sent + message_id。 +func TestRealSMTPExplicitRejectionIsFailedAndRetryOnce(t *testing.T) { + stub := newSMTPStub(t) + stub.setMode(smtpStubRejectRcpt) + store, pool := weeklyMailFixtureWith(t, SMTPMailer{TLS: &tls.Config{InsecureSkipVerify: true}}) + ctx := context.Background() + md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" + seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) + confirmation, err := store.Confirm(ctx, "2026-W45", "fixture-admin") + if err != nil { + t.Fatal(err) + } + stubSMTPSettings(t, store, stub.port()) + + failed, err := store.SendManual(ctx, "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 0)) + if err != nil || failed.Status != "failed" || failed.MessageID != "" { + t.Fatalf("明确拒绝必须如实 failed:%+v %v", failed, err) + } + if !strings.Contains(failed.Reason, "550") { + t.Fatalf("失败原因必须带真实 SMTP 回复:%q", failed.Reason) + } + if stub.rejections() != 1 || stub.deliveries() != 0 { + t.Fatalf("拒绝场景不应产生 DATA:rejections=%d datas=%d", stub.rejections(), stub.deliveries()) + } + var status, lastError string + if err := pool.QueryRow(ctx, `SELECT status,last_error FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45'`, store.tenant).Scan(&status, &lastError); err != nil { + t.Fatal(err) + } + if status != "failed" || !strings.Contains(lastError, "550") { + t.Fatalf("failed 记录不符:status=%q last_error=%q", status, lastError) + } + + stub.setMode(smtpStubAccept) + retried, err := store.SendManual(ctx, "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 9)) + if err != nil || retried.Status != "sent" || retried.MessageID == "" { + t.Fatalf("failed 记录应允许重试并成功:%+v %v", retried, err) + } + if stub.deliveries() != 1 { + t.Fatalf("重试应恰好产生 1 次 DATA,got %d", stub.deliveries()) + } + sends, err := store.Sends(ctx, "2026-W45") + if err != nil || len(sends) != 1 || sends[0].MessageID != retried.MessageID || sends[0].Status != "sent" { + t.Fatalf("产品读回入口必须返回 sent + message_id:%+v %v", sends, err) + } +} diff --git a/internal/qawemail/smtp_mailer_test.go b/internal/qawemail/smtp_mailer_test.go new file mode 100644 index 0000000..7373ad1 --- /dev/null +++ b/internal/qawemail/smtp_mailer_test.go @@ -0,0 +1,84 @@ +package qawemail + +import ( + "context" + "crypto/tls" + "testing" + "time" +) + +// 真实 SMTPMailer 打真实 TCP/TLS 桩:证明“成功 / 明确拒绝 / DATA 后最终确认丢失 / DATA 阶段卡死” +// 四类结果被正确分类——只有后两类里“结果可能已被接受”的那一类才算 unknown。 +func TestSMTPMailerClassifiesDeliveryOutcomes(t *testing.T) { + stub := newSMTPStub(t) + mailer := SMTPMailer{TLS: &tls.Config{InsecureSkipVerify: true}} // 仅测试桩:自签证书 + cfg := SMTPConfig{Host: "127.0.0.1", Port: stub.port()} + message := Message{From: "kb@example.com", To: []string{"lead@example.com"}, Subject: "知识库周报 2026-W45", HTML: "

91.20%

", Text: "91.20%"} + + t.Run("server_accepted", func(t *testing.T) { + stub.setMode(smtpStubAccept) + id, err := mailer.Send(context.Background(), cfg, message) + if err != nil || id == "" { + t.Fatalf("成功投递必须返回 message-id:%q %v", id, err) + } + if IsUnknownDelivery(err) { + t.Fatal("成功不能标记为 unknown") + } + if stub.deliveries() != 1 { + t.Fatalf("桩应收到 1 次 DATA,got %d", stub.deliveries()) + } + }) + + t.Run("rcpt_explicitly_rejected", func(t *testing.T) { + stub.setMode(smtpStubRejectRcpt) + before := stub.deliveries() + _, err := mailer.Send(context.Background(), cfg, message) + if err == nil { + t.Fatal("RCPT 550 必须报错") + } + if IsUnknownDelivery(err) { + t.Fatalf("明确拒绝不是 unknown:%v", err) + } + if stub.deliveries() != before { + t.Fatal("被拒的收件人不应产生 DATA") + } + }) + + t.Run("final_ack_lost_after_data", func(t *testing.T) { + stub.setMode(smtpStubLostAck) + before := stub.deliveries() + _, err := mailer.Send(context.Background(), cfg, message) + if err == nil || !IsUnknownDelivery(err) { + t.Fatalf("DATA 已提交但最终 250 丢失必须 unknown,got %v (unknown=%v)", err, IsUnknownDelivery(err)) + } + if stub.deliveries() != before+1 { + t.Fatal("桩必须真的收到了 DATA,否则这不是“提交后丢失确认”的场景") + } + }) + + t.Run("data_stage_stall_is_bounded_and_unknown", func(t *testing.T) { + stub.setMode(smtpStubStall) + ctx, cancel := context.WithTimeout(context.Background(), 800*time.Millisecond) + defer cancel() + start := time.Now() + _, err := mailer.Send(ctx, cfg, message) + elapsed := time.Since(start) + if err == nil || !IsUnknownDelivery(err) { + t.Fatalf("DATA 阶段超时必须 unknown,got %v (unknown=%v)", err, IsUnknownDelivery(err)) + } + if elapsed > 10*time.Second { + t.Fatalf("SMTP 必须受 ctx 期限约束,实际耗时 %s", elapsed) + } + }) + + // 连接建立前的失败仍可安全重试:不是 unknown。 + t.Run("connection_refused_is_retryable_failure", func(t *testing.T) { + closed := newSMTPStub(t) + port := closed.port() + closed.Close() + _, err := mailer.Send(context.Background(), SMTPConfig{Host: "127.0.0.1", Port: port}, message) + if err == nil || IsUnknownDelivery(err) { + t.Fatalf("连接失败必须如实 failed(非 unknown),got %v", err) + } + }) +} diff --git a/internal/qawemail/smtp_stub_test.go b/internal/qawemail/smtp_stub_test.go new file mode 100644 index 0000000..e7b1633 --- /dev/null +++ b/internal/qawemail/smtp_stub_test.go @@ -0,0 +1,224 @@ +package qawemail + +import ( + "bufio" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "net" + "strings" + "sync" + "testing" + "time" +) + +// smtpStub is a real TCP/TLS SMTP server for tests: it exercises the production SMTPMailer +// instead of mocking the Mailer interface, so the DATA-phase classification is proven end to end. +type smtpStub struct { + ln net.Listener + cert tls.Certificate + + mu sync.Mutex + mode string + datas int + rejected int + + closed chan struct{} + once sync.Once +} + +const ( + smtpStubAccept = "accept" + smtpStubRejectRcpt = "reject_rcpt" + smtpStubLostAck = "lost_ack" + smtpStubStall = "stall" +) + +func newSMTPStub(t *testing.T) *smtpStub { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + stub := &smtpStub{ln: listener, cert: stubCertificate(t), mode: smtpStubAccept, closed: make(chan struct{})} + go stub.serve() + t.Cleanup(stub.Close) + return stub +} + +func (s *smtpStub) Close() { + s.once.Do(func() { + close(s.closed) + _ = s.ln.Close() + }) +} + +func (s *smtpStub) port() int { return s.ln.Addr().(*net.TCPAddr).Port } + +func (s *smtpStub) setMode(mode string) { + s.mu.Lock() + s.mode = mode + s.mu.Unlock() +} + +func (s *smtpStub) currentMode() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.mode +} + +// deliveries counts completed DATA uploads, whether or not the final 250 was delivered. +func (s *smtpStub) deliveries() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.datas +} + +func (s *smtpStub) rejections() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.rejected +} + +func (s *smtpStub) serve() { + for { + conn, err := s.ln.Accept() + if err != nil { + return + } + go s.handle(conn) + } +} + +func (s *smtpStub) handle(raw net.Conn) { + defer raw.Close() + conn := raw + reader := bufio.NewReader(conn) + writer := bufio.NewWriter(conn) + reply := func(line string) error { + if _, err := writer.WriteString(line + "\r\n"); err != nil { + return err + } + return writer.Flush() + } + if reply("220 stub ESMTP") != nil { + return + } + secured := false + for { + line, err := reader.ReadString('\n') + if err != nil { + return + } + upper := strings.ToUpper(strings.TrimSpace(line)) + switch { + case strings.HasPrefix(upper, "EHLO"), strings.HasPrefix(upper, "HELO"): + lines := []string{"250-stub"} + if !secured { + lines = append(lines, "250-STARTTLS") + } + lines = append(lines, "250 OK") + for _, item := range lines { + if reply(item) != nil { + return + } + } + case upper == "STARTTLS": + if reply("220 ready to start TLS") != nil { + return + } + securedConn := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{s.cert}, MinVersion: tls.VersionTLS12}) + if err := securedConn.Handshake(); err != nil { + return + } + conn = securedConn + reader = bufio.NewReader(conn) + writer = bufio.NewWriter(conn) + secured = true + case strings.HasPrefix(upper, "MAIL FROM"): + _ = reply("250 OK") + case strings.HasPrefix(upper, "RCPT TO"): + if s.currentMode() == smtpStubRejectRcpt { + s.mu.Lock() + s.rejected++ + s.mu.Unlock() + _ = reply("550 5.1.1 mailbox unavailable") + continue + } + _ = reply("250 OK") + case upper == "DATA": + if reply("354 end data with .") != nil { + return + } + if err := readSMTPData(reader); err != nil { + return + } + s.mu.Lock() + s.datas++ + s.mu.Unlock() + switch s.currentMode() { + case smtpStubLostAck: + // Drop the connection instead of the final 250: the client cannot know whether + // the server queued the message. + return + case smtpStubStall: + select { + case <-s.closed: + case <-time.After(30 * time.Second): + } + return + default: + if reply("250 2.0.0 Ok: queued as stub-1") != nil { + return + } + } + case upper == "QUIT": + _ = reply("221 Bye") + return + default: + _ = reply("250 OK") + } + } +} + +func readSMTPData(reader *bufio.Reader) error { + for { + line, err := reader.ReadString('\n') + if err != nil { + return err + } + if strings.TrimRight(line, "\r\n") == "." { + return nil + } + } +} + +// stubCertificate builds a throwaway self-signed cert for 127.0.0.1. Tests trust it explicitly; +// production never sees it. +func stubCertificate(t *testing.T) tls.Certificate { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "kg-smtp-stub"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + IsCA: true, + BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} +} diff --git a/internal/qawemail/store.go b/internal/qawemail/store.go index 3ec5d70..592898c 100644 --- a/internal/qawemail/store.go +++ b/internal/qawemail/store.go @@ -29,8 +29,32 @@ var ( ErrInvalid = errors.New("weekly mail invalid input") ErrConflict = errors.New("weekly mail settings changed") ErrNoPassword = errors.New("weekly mail password missing") + // Manual resend has its own refusals: an operator must be told which rule failed instead of + // seeing a generic SMTP error for something SMTP never saw. + ErrNotCurrent = errors.New("weekly mail confirmation is not current") + ErrFutureWeek = errors.New("weekly mail week is in the future") + ErrSlotPending = errors.New("weekly mail slot has not arrived for the running week") + ErrNotConfigured = errors.New("weekly mail transport is not configured") + ErrSendInFlight = errors.New("weekly mail send outcome is unknown") + // ErrDeliveryUnknown is the honest answer when the SMTP exchange ended without a final + // verdict: the server may already have queued the message, so retrying could duplicate it. + ErrDeliveryUnknown = errors.New("weekly mail delivery outcome is unknown") ) +// unknownDeliveryError marks a failure where the server may already have accepted the message. +// Only the caller that knows the SMTP phase can raise it, so a plain I/O error never silently +// becomes "unknown" (and never silently becomes a retryable failure either). +type unknownDeliveryError struct{ err error } + +func (e *unknownDeliveryError) Error() string { return e.err.Error() } +func (e *unknownDeliveryError) Unwrap() error { return e.err } + +// IsUnknownDelivery reports whether the send may have reached the recipients. +func IsUnknownDelivery(err error) bool { + var unknown *unknownDeliveryError + return errors.As(err, &unknown) +} + // Settings never carries the SMTP password; HasPassword only says whether one is stored. type Settings struct { Host string `json:"host"` @@ -81,6 +105,7 @@ type Send struct { Status string `json:"status"` Attempts int `json:"attempts"` LastError string `json:"last_error"` + MessageID string `json:"message_id"` UpdatedAt time.Time `json:"updated_at"` } @@ -406,7 +431,7 @@ func (s *Store) Sends(ctx context.Context, week string) ([]Send, error) { if !s.valid() { return nil, ErrUnavailable } - rows, err := s.pool.Query(ctx, `SELECT week,draft_revision,status,attempts,last_error,updated_at FROM qa_weekly_email_sends WHERE tenant_key=$1 AND ($2='' OR week=$2) ORDER BY updated_at DESC LIMIT 50`, s.tenant, week) + rows, err := s.pool.Query(ctx, `SELECT week,draft_revision,status,attempts,last_error,message_id,updated_at FROM qa_weekly_email_sends WHERE tenant_key=$1 AND ($2='' OR week=$2) ORDER BY updated_at DESC LIMIT 50`, s.tenant, week) if err != nil { return nil, ErrUnavailable } @@ -414,19 +439,24 @@ func (s *Store) Sends(ctx context.Context, week string) ([]Send, error) { out := []Send{} for rows.Next() { var item Send - if err := rows.Scan(&item.Week, &item.Revision, &item.Status, &item.Attempts, &item.LastError, &item.UpdatedAt); err != nil { + if err := rows.Scan(&item.Week, &item.Revision, &item.Status, &item.Attempts, &item.LastError, &item.MessageID, &item.UpdatedAt); err != nil { return nil, ErrUnavailable } out = append(out, item) } + // A read that stopped early is not a successful list: callers would silently show partial history. + if err := rows.Err(); err != nil { + return nil, ErrUnavailable + } return out, nil } type DueResult struct { - State string `json:"state"` - Week string `json:"week,omitempty"` - SentAt time.Time `json:"sent_at,omitempty"` - Reason string `json:"reason,omitempty"` + State string `json:"state"` + Week string `json:"week,omitempty"` + MessageID string `json:"message_id,omitempty"` + SentAt time.Time `json:"sent_at,omitempty"` + Reason string `json:"reason,omitempty"` } // weekStart resolves the Beijing Monday of an ISO week label; reports are due after that week closes. @@ -445,9 +475,11 @@ func weekStart(week string) (time.Time, error) { return start, nil } +var cstZone = time.FixedZone("CST", 8*3600) + // slotMatches is the single definition of "the configured weekly slot is now". func slotMatches(settings Settings, now time.Time) bool { - local := now.In(time.FixedZone("CST", 8*3600)) + local := now.In(cstZone) weekday := int(local.Weekday()) if weekday == 0 { weekday = 7 @@ -455,6 +487,25 @@ func slotMatches(settings Settings, now time.Time) bool { return weekday == settings.Weekday && local.Hour() == settings.Hour } +// slotWeek names the report week the configured slot stands for. +// +// A slot on the week's last day (周日) reports the week that ends that same day; on every other +// weekday the week has already ended, which is what "周一 09:00 发上一个完整周" has always meant. +// Deriving the week from the slot — instead of asking reportClosed whether the week has ended — +// is what the 周日23点 configuration needs: that slot sits inside its own week, so waiting for the +// next Monday 00:00 would always miss the window it was configured for. +func slotWeek(settings Settings, now time.Time) (string, bool) { + if !slotMatches(settings, now) { + return "", false + } + day := now.In(cstZone) + if settings.Weekday != 7 { + day = day.AddDate(0, 0, -7) + } + year, number := day.ISOWeek() + return fmt.Sprintf("%04d-W%02d", year, number), true +} + // reportClosed reports whether the ISO week is over and its report may go out. func reportClosed(week string, now time.Time) bool { start, err := weekStart(week) @@ -464,7 +515,7 @@ func reportClosed(week string, now time.Time) bool { return !now.Before(start.AddDate(0, 0, 7)) } -// SendDue mails only a confirmed, still-current, already-closed week at the configured slot. +// SendDue mails only the confirmed, still-current week the configured slot stands for. // Every skip path returns a reason instead of pretending a message went out. func (s *Store) SendDue(ctx context.Context, now time.Time) (DueResult, error) { if !s.valid() { @@ -477,49 +528,31 @@ func (s *Store) SendDue(ctx context.Context, now time.Time) (DueResult, error) { if !settings.Enabled { return DueResult{State: "disabled", Reason: "未启用自动发送"}, nil } - if !slotMatches(settings, now) { + week, ok := slotWeek(settings, now) + if !ok { return DueResult{State: "not_due", Reason: "未到设定发送时段"}, nil } - rows, err := s.pool.Query(ctx, `SELECT c.week,c.draft_revision,c.body_sha256,d.revision,d.markdown + // Only the week this slot stands for may go out automatically. Replaying every older + // confirmed week would turn one missed run into an unbounded backfill. + var revision, draftRevision int64 + var hash, markdown string + err = s.pool.QueryRow(ctx, `SELECT c.draft_revision,c.body_sha256,d.revision,d.markdown FROM qa_weekly_confirmations c JOIN qa_ops_weekly_drafts d ON d.tenant_key=c.tenant_key AND d.week=c.week - WHERE c.tenant_key=$1 ORDER BY c.week DESC`, s.tenant) + WHERE c.tenant_key=$1 AND c.week=$2`, s.tenant, week).Scan(&revision, &hash, &draftRevision, &markdown) + if errors.Is(err, pgx.ErrNoRows) { + return DueResult{State: "nothing_confirmed", Week: week, Reason: "该周没有已确认的周报"}, nil + } if err != nil { return DueResult{}, ErrUnavailable } - type candidate struct { - week string - revision int64 - hash string - markdown string + if draftRevision != revision || bodyHash(markdown) != hash || strings.TrimSpace(markdown) == "" { + return DueResult{State: "nothing_confirmed", Week: week, Reason: "已确认的正文或版本已变化,需重新确认"}, nil } - candidates := []candidate{} - for rows.Next() { - var c candidate - var draftRevision int64 - if err := rows.Scan(&c.week, &c.revision, &c.hash, &draftRevision, &c.markdown); err != nil { - rows.Close() - return DueResult{}, ErrUnavailable - } - if draftRevision != c.revision || bodyHash(c.markdown) != c.hash { - continue - } - candidates = append(candidates, c) + delivered, err := s.deliver(ctx, settings, week, revision, markdown, now, fmt.Sprintf("知识库周报 %s", week)) + if err != nil { + return DueResult{}, err } - rows.Close() - for _, c := range candidates { - if !reportClosed(c.week, now) { - continue - } - var sent bool - if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week=$2 AND draft_revision=$3 AND status='sent')`, s.tenant, c.week, c.revision).Scan(&sent); err != nil { - return DueResult{}, ErrUnavailable - } - if sent { - continue - } - return s.send(ctx, settings, c.week, c.revision, c.markdown, now) - } - return DueResult{State: "nothing_confirmed", Reason: "没有已确认且已结束的周报"}, nil + return DueResult{State: delivered.state, Week: week, MessageID: delivered.messageID, SentAt: delivered.sentAt, Reason: delivered.reason}, nil } // SaveDashboardImage stores the dashboard PNG that belongs to the currently confirmed revision, @@ -597,25 +630,42 @@ func (s *Store) TestSend(ctx context.Context, week string) (string, error) { Message{To: target, Cc: nil, From: settings.From, Subject: fmt.Sprintf("知识库周报 %s(测试发送)", week), HTML: html, Text: text, Images: images}) } -func (s *Store) send(ctx context.Context, settings Settings, week string, revision int64, markdown string, now time.Time) (DueResult, error) { +// delivery is what one attempt at a single (week, revision) proved: a state, never an assumption. +type delivery struct { + state string + messageID string + reason string + sentAt time.Time +} + +// deliver is the only place a weekly report is rendered, claimed and handed to the mailer, so the +// automatic slot and the manual resend can never drift apart. +// +// The claim is also the concurrency control: only a brand-new row or a 'failed' row may be taken. +// A 'sent' row is idempotent, and a 'sending' row means the previous outcome is unknown — resending +// it could deliver the report twice, so it is reported instead of retried. (SMTP offers no exactly +// -once primitive; this is the strongest honest guarantee.) +func (s *Store) deliver(ctx context.Context, settings Settings, week string, revision int64, markdown string, now time.Time, subject string) (delivery, error) { password, err := s.password(ctx, settings.Revision) if err != nil { - return DueResult{State: "blocked", Week: week, Reason: "SMTP 密码未配置或无法解密"}, nil + return delivery{state: "blocked", reason: "SMTP 密码未配置或无法解密"}, nil } html, text := renderReport(markdown) images, err := s.inlineImages(ctx, week, &html) if err != nil { - return DueResult{}, err + return delivery{}, err } - subject := fmt.Sprintf("知识库周报 %s", week) var sendID string err = s.pool.QueryRow(ctx, `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,created_at,updated_at) VALUES($1,$2,$3,$4,'sending',1,now(),now()) ON CONFLICT (tenant_key,week,draft_revision) DO UPDATE SET status='sending',attempts=qa_weekly_email_sends.attempts+1,updated_at=now() - WHERE qa_weekly_email_sends.status<>'sent' + WHERE qa_weekly_email_sends.status='failed' RETURNING id::text`, s.tenant, week, revision, bodyHash(markdown)).Scan(&sendID) + if errors.Is(err, pgx.ErrNoRows) { + return s.existingDelivery(ctx, week, revision) + } if err != nil { - return DueResult{}, ErrUnavailable + return delivery{}, ErrUnavailable } messageID, sendErr := s.mailer.Send(ctx, SMTPConfig{Host: settings.Host, Port: settings.Port, Username: settings.Username, Password: password}, Message{To: settings.Recipients, Cc: settings.Cc, From: settings.From, Subject: subject, HTML: html, Text: text, Images: images}) @@ -624,13 +674,167 @@ func (s *Store) send(ctx context.Context, settings Settings, week string, revisi if len(reason) > 400 { reason = reason[:400] } + if IsUnknownDelivery(sendErr) { + // The message may already be queued at the server. Leaving the row in 'sending' makes + // every later attempt (automatic or manual) refuse instead of blindly re-delivering. + _, _ = s.pool.Exec(ctx, `UPDATE qa_weekly_email_sends SET last_error=$2,updated_at=now() WHERE id=$1`, sendID, reason) + return delivery{state: "unknown", reason: "SMTP 已提交但未收到最终确认,投递结果未知;为避免重复已停止自动重发,请核对已发出的邮件:" + reason}, nil + } _, _ = s.pool.Exec(ctx, `UPDATE qa_weekly_email_sends SET status='failed',last_error=$2,updated_at=now() WHERE id=$1`, sendID, reason) - return DueResult{State: "failed", Week: week, Reason: "发送失败,稍后重试"}, nil + return delivery{state: "failed", reason: "发送失败:" + reason}, nil } if _, err = s.pool.Exec(ctx, `UPDATE qa_weekly_email_sends SET status='sent',message_id=$2,last_error='',updated_at=now() WHERE id=$1`, sendID, messageID); err != nil { - return DueResult{}, ErrUnavailable + return delivery{}, ErrUnavailable } - return DueResult{State: "sent", Week: week, SentAt: now}, nil + return delivery{state: "sent", messageID: messageID, sentAt: now}, nil +} + +// existingDelivery explains why this attempt could not claim the row, instead of guessing. +func (s *Store) existingDelivery(ctx context.Context, week string, revision int64) (delivery, error) { + var status, messageID, lastError string + var updatedAt time.Time + err := s.pool.QueryRow(ctx, `SELECT status,message_id,last_error,updated_at FROM qa_weekly_email_sends + WHERE tenant_key=$1 AND week=$2 AND draft_revision=$3`, s.tenant, week, revision).Scan(&status, &messageID, &lastError, &updatedAt) + if err != nil { + return delivery{}, ErrUnavailable + } + switch status { + case "sent": + return delivery{state: "already_sent", messageID: messageID, reason: "该周该版本已发送,未重复投递", sentAt: updatedAt}, nil + case "sending": + return delivery{state: "in_flight", reason: "上次发送结果未知(记录停在 sending),为避免重复投递未重发;请先核对已发出的邮件"}, nil + default: + return delivery{state: "in_flight", reason: "发送记录状态与本次认领冲突(" + status + "),未重复投递"}, nil + } +} + +type ManualResult struct { + Week string `json:"week"` + Revision int64 `json:"draft_revision"` + Status string `json:"status"` + MessageID string `json:"message_id,omitempty"` + Recipients int `json:"recipients"` + Cc int `json:"cc_recipients"` + Reason string `json:"reason,omitempty"` + SentAt time.Time `json:"sent_at,omitempty"` +} + +// SendPreview is what the confirmation dialog must show before an operator commits: the exact +// week/revision and the real distribution counts the send would use. +type SendPreview struct { + Week string `json:"week"` + Revision int64 `json:"draft_revision"` + BodySHA256 string `json:"body_sha256"` + Recipients int `json:"recipients"` + Cc int `json:"cc_recipients"` + Status string `json:"status"` + MessageID string `json:"message_id,omitempty"` + SentAt time.Time `json:"sent_at,omitempty"` +} + +// manualWindow decides whether a week may be sent by hand right now: a week that has ended is +// always fair game; the running week only once its own configured slot has arrived; a future week +// never. +func manualWindow(week string, settings Settings, now time.Time) error { + start, err := weekStart(week) + if err != nil { + return ErrInvalid + } + local := now.In(cstZone) + if start.After(local) { + return ErrFutureWeek + } + if !local.Before(start.AddDate(0, 0, 7)) { + return nil + } + slot := start.AddDate(0, 0, settings.Weekday-1).Add(time.Duration(settings.Hour) * time.Hour) + if local.Before(slot) { + return ErrSlotPending + } + return nil +} + +// prepareManual binds a manual request to the confirmed revision and body that are live right now. +func (s *Store) prepareManual(ctx context.Context, week string, revision int64, hash string, now time.Time) (Settings, string, error) { + settings, err := s.ReadSettings(ctx) + if err != nil { + return settings, "", err + } + if settings.Host == "" || settings.From == "" || len(settings.Recipients) == 0 { + return settings, "", ErrNotConfigured + } + if err := manualWindow(week, settings, now); err != nil { + return settings, "", err + } + var confirmedRevision, draftRevision int64 + var confirmedHash, markdown string + err = s.pool.QueryRow(ctx, `SELECT c.draft_revision,c.body_sha256,d.revision,d.markdown + FROM qa_weekly_confirmations c JOIN qa_ops_weekly_drafts d ON d.tenant_key=c.tenant_key AND d.week=c.week + WHERE c.tenant_key=$1 AND c.week=$2`, s.tenant, week).Scan(&confirmedRevision, &confirmedHash, &draftRevision, &markdown) + if errors.Is(err, pgx.ErrNoRows) { + return settings, "", ErrNotCurrent + } + if err != nil { + return settings, "", ErrUnavailable + } + if confirmedRevision != revision || confirmedHash != hash || draftRevision != revision || + strings.TrimSpace(markdown) == "" || bodyHash(markdown) != hash { + return settings, "", ErrNotCurrent + } + return settings, markdown, nil +} + +// PreviewSend validates a manual resend without sending or writing anything. +func (s *Store) PreviewSend(ctx context.Context, week string, revision int64, hash string, now time.Time) (SendPreview, error) { + if !s.valid() || revision <= 0 || len(strings.TrimSpace(hash)) != 64 { + return SendPreview{}, ErrInvalid + } + settings, _, err := s.prepareManual(ctx, week, revision, hash, now) + if err != nil { + return SendPreview{}, err + } + out := SendPreview{Week: week, Revision: revision, BodySHA256: hash, Recipients: len(settings.Recipients), Cc: len(settings.Cc), Status: "ready"} + var status, messageID string + var updatedAt time.Time + err = s.pool.QueryRow(ctx, `SELECT status,message_id,updated_at FROM qa_weekly_email_sends + WHERE tenant_key=$1 AND week=$2 AND draft_revision=$3`, s.tenant, week, revision).Scan(&status, &messageID, &updatedAt) + switch { + case errors.Is(err, pgx.ErrNoRows): + case err != nil: + return SendPreview{}, ErrUnavailable + case status == "sent": + out.Status, out.MessageID, out.SentAt = "already_sent", messageID, updatedAt + case status == "sending": + out.Status = "in_flight" + } + return out, nil +} + +// SendManual is the explicit operator path for a missed or refused automatic run. It reuses the +// automatic render/claim/deliver path, so body, chart, To/Cc and idempotency are identical. +func (s *Store) SendManual(ctx context.Context, week string, revision int64, hash, actor string, now time.Time) (ManualResult, error) { + if !s.valid() || strings.TrimSpace(actor) == "" || revision <= 0 || len(strings.TrimSpace(hash)) != 64 { + return ManualResult{}, ErrInvalid + } + settings, markdown, err := s.prepareManual(ctx, week, revision, hash, now) + if err != nil { + return ManualResult{}, err + } + delivered, err := s.deliver(ctx, settings, week, revision, markdown, now, fmt.Sprintf("知识库周报 %s", week)) + if err != nil { + return ManualResult{}, err + } + out := ManualResult{Week: week, Revision: revision, Status: delivered.state, MessageID: delivered.messageID, + Recipients: len(settings.Recipients), Cc: len(settings.Cc), Reason: delivered.reason, SentAt: delivered.sentAt} + switch delivered.state { + case "blocked": + return out, ErrNoPassword + case "in_flight": + return out, ErrSendInFlight + case "unknown": + return out, ErrDeliveryUnknown + } + return out, nil } const dashboardImageCID = "weekly-dashboard@knowledge-governance" @@ -674,24 +878,56 @@ table{border-collapse:collapse}h1:first-child{margin-top:0} } // SMTPMailer speaks SMTP directly: implicit TLS on 465, STARTTLS elsewhere. Plaintext is refused. -type SMTPMailer struct{} +// TLS is nil in production (system roots); an in-process test stub injects its own trust so the +// real mailer — not a mock — can be exercised end to end. +type SMTPMailer struct{ TLS *tls.Config } -func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string, error) { +// smtpExchangeTimeout bounds the whole SMTP conversation. Without it a server that accepts DATA +// and then stops responding would hang the worker (and hold the send row) indefinitely. +const smtpExchangeTimeout = 90 * time.Second + +func (m SMTPMailer) tlsConfig(host string) *tls.Config { + cfg := &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12} + if m.TLS != nil { + cfg = m.TLS.Clone() + if cfg.ServerName == "" { + cfg.ServerName = host + } + if cfg.MinVersion == 0 { + cfg.MinVersion = tls.VersionTLS12 + } + } + return cfg +} + +func (m SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string, error) { if cfg.Host == "" || cfg.Port <= 0 || len(msg.To) == 0 || !validAddress(msg.From) { return "", ErrInvalid } + deadline := time.Now().Add(smtpExchangeTimeout) + if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) { + deadline = ctxDeadline + } address := net.JoinHostPort(cfg.Host, fmt.Sprint(cfg.Port)) - dialer := &net.Dialer{Timeout: 15 * time.Second} + dialer := &net.Dialer{Timeout: 15 * time.Second, Deadline: deadline} var conn net.Conn var err error if cfg.Port == 465 { - conn, err = tls.DialWithDialer(dialer, "tcp", address, &tls.Config{ServerName: cfg.Host, MinVersion: tls.VersionTLS12}) + conn, err = tls.DialWithDialer(dialer, "tcp", address, m.tlsConfig(cfg.Host)) } else { conn, err = dialer.DialContext(ctx, "tcp", address) } if err != nil { + // The connection never opened: nothing was submitted, so this is a retryable failure. return "", fmt.Errorf("smtp 连接失败: %w", err) } + if err := conn.SetDeadline(deadline); err != nil { + conn.Close() + return "", fmt.Errorf("smtp 设置超时失败: %w", err) + } + // Cancellation must interrupt a blocked read/write, not just the dial. + stop := context.AfterFunc(ctx, func() { _ = conn.SetDeadline(time.Now()) }) + defer stop() client, err := smtp.NewClient(conn, cfg.Host) if err != nil { conn.Close() @@ -702,7 +938,7 @@ func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string if ok, _ := client.Extension("STARTTLS"); !ok { return "", errors.New("smtp 服务器不支持 STARTTLS,已拒绝明文发送") } - if err := client.StartTLS(&tls.Config{ServerName: cfg.Host, MinVersion: tls.VersionTLS12}); err != nil { + if err := client.StartTLS(m.tlsConfig(cfg.Host)); err != nil { return "", fmt.Errorf("smtp STARTTLS 失败: %w", err) } } @@ -726,10 +962,14 @@ func (SMTPMailer) Send(ctx context.Context, cfg SMTPConfig, msg Message) (string messageID := fmt.Sprintf("<%s@%s>", hex.EncodeToString(randomBytes(12)), domainOf(msg.From)) boundary := hex.EncodeToString(randomBytes(10)) if _, err = writer.Write([]byte(buildMIME(msg, messageID, boundary))); err != nil { + // The body never finished uploading, so the server cannot have accepted it. return "", fmt.Errorf("smtp 写入失败: %w", err) } if err = writer.Close(); err != nil { - return "", fmt.Errorf("smtp 提交失败: %w", err) + // Close() sends the terminating "." and waits for the final 250. Losing that exchange + // (dropped connection, timeout) means the message may already be queued: it must stay + // unknown rather than be retried as a plain failure. + return "", &unknownDeliveryError{err: fmt.Errorf("smtp 提交后未收到最终确认: %w", err)} } _ = client.Quit() return messageID, nil diff --git a/internal/qawemail/store_test.go b/internal/qawemail/store_test.go index 9a94d18..e8c8281 100644 --- a/internal/qawemail/store_test.go +++ b/internal/qawemail/store_test.go @@ -35,6 +35,35 @@ func TestReportClosedOnlyAfterTheISOWeekEnds(t *testing.T) { } } +// 时段自身决定要发哪一周:周日时段发当天结束的那一周,其它工作日发已经结束的上一周。 +// 旧实现只在“周已结束(下周一00:00)”时发,而周日23点这个时段在周内 ⇒ 当周永远发不出去。 +func TestSlotWeekDerivesTheReportWeekFromTheSlot(t *testing.T) { + cst := time.FixedZone("CST", 8*3600) + sunday := Settings{Weekday: 7, Hour: 23} + week, ok := slotWeek(sunday, time.Date(2026, 11, 8, 23, 5, 0, 0, cst)) + if !ok || week != "2026-W45" { + t.Fatalf("周日23点必须对应当周 2026-W45,got %q %v", week, ok) + } + if _, ok := slotWeek(sunday, time.Date(2026, 11, 8, 22, 5, 0, 0, cst)); ok { + t.Fatal("到点前不得认为时段已到") + } + if _, ok := slotWeek(sunday, time.Date(2026, 11, 7, 23, 5, 0, 0, cst)); ok { + t.Fatal("周六23点不是配置的周日时段") + } + // 周一09点保持旧语义:发上一完整周。 + monday := Settings{Weekday: 1, Hour: 9} + week, ok = slotWeek(monday, time.Date(2026, 11, 9, 9, 5, 0, 0, cst)) + if !ok || week != "2026-W45" { + t.Fatalf("周一09点必须对应上一完整周 2026-W45,got %q %v", week, ok) + } + // 周三09点同理:该周尚未结束,不能提前发。 + wednesday := Settings{Weekday: 3, Hour: 9} + week, ok = slotWeek(wednesday, time.Date(2026, 11, 11, 9, 5, 0, 0, cst)) + if !ok || week != "2026-W45" { + t.Fatalf("周三09点必须仍指向 2026-W45,got %q %v", week, ok) + } +} + func TestNormalizeRefusesEnabledSettingsWithoutTransportAndBadRecipients(t *testing.T) { if _, err := normalize(SettingsInput{Host: "", From: "", Recipients: nil, Enabled: true}); err != ErrInvalid { t.Fatalf("enabled without host/from/recipients must be invalid, got %v", err) diff --git a/internal/qawemail/sunday_slot_test.go b/internal/qawemail/sunday_slot_test.go new file mode 100644 index 0000000..08a3d1a --- /dev/null +++ b/internal/qawemail/sunday_slot_test.go @@ -0,0 +1,79 @@ +package qawemail + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + postgresstore "knowledge-governance/internal/platform/postgres" +) + +type slotMailer struct { + sent []Message +} + +func (m *slotMailer) Send(_ context.Context, _ SMTPConfig, msg Message) (string, error) { + m.sent = append(m.sent, msg) + return "", nil +} + +// 现场形状:send_weekday=7 / send_hour=23(周日23点),正文已确认。 +// 旧实现的 reportClosed 要求「周已结束 = 下周一00:00」,而时段只存在于周日23点这一小时内, +// 于是当周周报在它自己的发送窗口里永远不满足条件,只能等周一——那时时段已过 ⇒ 永不发送。 +// 判据:周日23点这个时段必须发出当周(2026-W45),而不是等到周一。 +func TestSundaySlotMailsItsOwnWeekBeforeMonday(t *testing.T) { + dsn := os.Getenv("KG_WEEKLY_MAIL_TEST_DSN") + if dsn == "" { + t.Skip("显式一次性周报邮件数据库未提供(KG_WEEKLY_MAIL_TEST_DSN):跳过不等于通过") + } + if !strings.Contains(dsn, "/kg_weekly_mail_test_") || strings.Contains(dsn, "/governance?") { + t.Fatal("拒绝非一次性周报测试库") + } + ctx := context.Background() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal("测试库连接参数无效(详情省略)") + } + defer pool.Close() + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + t.Fatal(err) + } + mailer := &slotMailer{} + store := NewStore(pool, "fixture-sunday-slot", os.Getenv("KG_WEEKLY_MAIL_TEST_KEY"), mailer) + for _, statement := range []string{ + `DELETE FROM qa_weekly_email_sends WHERE tenant_key=$1`, + `DELETE FROM qa_weekly_confirmations WHERE tenant_key=$1`, + `DELETE FROM qa_weekly_email_settings WHERE tenant_key=$1`, + `DELETE FROM qa_ops_weekly_drafts WHERE tenant_key=$1`, + } { + if _, err := pool.Exec(ctx, statement, store.tenant); err != nil { + t.Fatal(err) + } + } + if _, err := pool.Exec(ctx, `INSERT INTO qa_ops_weekly_drafts(tenant_key,week,revision,markdown,seed,updated_by,updated_at) + VALUES($1,'2026-W45',16,$2,'{}'::jsonb,'fixture-admin',now())`, store.tenant, + "# 知识库周报 2026-W45\n\n## 二、核心指标\n\n正确率:91.20%\n"); err != nil { + t.Fatal(err) + } + if _, err := store.SaveSettings(ctx, "fixture-admin", SettingsInput{ + BaseRevision: 0, Host: "localhost", Port: 465, From: "kb@example.com", Password: "app-password", + Recipients: []string{"lead@example.com"}, Weekday: 7, Hour: 23, Enabled: true, + }); err != nil { + t.Fatal(err) + } + if _, err := store.Confirm(ctx, "2026-W45", "fixture-admin"); err != nil { + t.Fatal(err) + } + sunday := time.Date(2026, 11, 8, 23, 5, 0, 0, time.FixedZone("CST", 8*3600)) + result, err := store.SendDue(ctx, sunday) + if err != nil || result.State != "sent" || result.Week != "2026-W45" { + t.Fatalf("周日23点必须发出当周 2026-W45(旧实现在此只报 nothing_confirmed),got %+v %v", result, err) + } + if len(mailer.sent) != 1 { + t.Fatalf("calls=%d, want 1", len(mailer.sent)) + } +} diff --git a/internal/readiness/weknora.go b/internal/readiness/weknora.go new file mode 100644 index 0000000..6e30105 --- /dev/null +++ b/internal/readiness/weknora.go @@ -0,0 +1,148 @@ +package readiness + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "knowledge-governance/internal/platform/weknora" +) + +// WeKnora 的 readiness 探测必须与业务执行链看同一个目标:网页保存的端点、 +// 当前生效的知识库绑定、同一份 API Key。任何一项在启动时被捕获成常量, +// 都会在管理员改绑之后继续探测旧库(F13:旧库 404 被当成整个服务不可用)。 + +var ( + ErrNotConfigured = errors.New("WeKnora 就绪探测未配置") + ErrKnowledgeBaseMissing = errors.New("WeKnora 探测目标知识库不存在") + ErrNoPermission = errors.New("WeKnora 探测目标知识库无读取权限") +) + +type Target struct { + BaseURL string + KnowledgeBaseID string + APIKey string +} + +type Result struct { + // Target 是脱敏后的探测对象(实例 + 短 ID),用于界面说明“探的是谁”。 + Target string + Err error +} + +// Prober 每次 Check 都重新解析目标并新建客户端:端点、凭据、绑定都允许 +// 在进程运行期间变化,不能缓存成启动快照。 +// Resolver is the single source for the effective WeKnora target: endpoint +// saved in the console (env fallback), current persisted binding (env fallback) +// and the same key file. API probes and worker clients both use it, so a +// runtime settings/binding change cannot leave one side on the old value. +type Resolver struct { + Endpoint func(context.Context) string + LoadBinding func(context.Context) (string, error) + ReadKey func() (string, error) + DefaultKB string +} + +func (resolver Resolver) Resolve(ctx context.Context) (Target, error) { + knowledgeBaseID := strings.TrimSpace(resolver.DefaultKB) + if resolver.LoadBinding != nil { + stored, err := resolver.LoadBinding(ctx) + if err != nil { + return Target{}, fmt.Errorf("读取当前知识库绑定失败") + } + if stored = strings.TrimSpace(stored); stored != "" { + knowledgeBaseID = stored + } + } + apiKey := "" + if resolver.ReadKey != nil { + value, err := resolver.ReadKey() + if err != nil { + return Target{}, fmt.Errorf("读取 WeKnora API 凭据失败") + } + apiKey = strings.TrimSpace(value) + } + baseURL := "" + if resolver.Endpoint != nil { + baseURL = strings.TrimSpace(resolver.Endpoint(ctx)) + } + return Target{BaseURL: baseURL, KnowledgeBaseID: knowledgeBaseID, APIKey: apiKey}, nil +} + +type Prober struct { + Resolve func(context.Context) (Target, error) + Timeout time.Duration + AllowDockerHTTP bool +} + +func (prober Prober) Check(ctx context.Context) Result { + if prober.Resolve == nil { + return Result{Err: ErrNotConfigured} + } + target, err := prober.Resolve(ctx) + if err != nil { + return Result{Err: err} + } + described := describe(target) + if strings.TrimSpace(target.BaseURL) == "" || strings.TrimSpace(target.KnowledgeBaseID) == "" || strings.TrimSpace(target.APIKey) == "" { + return Result{Target: described, Err: ErrNotConfigured} + } + timeout := prober.Timeout + if timeout <= 0 || timeout > 10*time.Second { + timeout = 10 * time.Second + } + client, err := weknora.NewClient(weknora.ClientConfig{ + BaseURL: target.BaseURL, + APIKey: target.APIKey, + Timeout: timeout, + AllowDockerHTTP: prober.AllowDockerHTTP, + }) + if err != nil { + return Result{Target: described, Err: err} + } + if _, _, err := client.ListKnowledge(ctx, target.KnowledgeBaseID, 1, 1); err != nil { + return Result{Target: described, Err: classify(target, described, err)} + } + return Result{Target: described} +} + +func classify(target Target, described string, err error) error { + var httpErr *weknora.HTTPError + if errors.As(err, &httpErr) { + switch httpErr.StatusCode { + case http.StatusNotFound: + return fmt.Errorf("%w(%s)", ErrKnowledgeBaseMissing, described) + case http.StatusUnauthorized, http.StatusForbidden: + return fmt.Errorf("%w(%s)", ErrNoPermission, described) + case http.StatusTooManyRequests: + return fmt.Errorf("目标知识库读取被限流(HTTP 429,%s)", described) + } + } + return err +} + +// describe 只保留实例主机与知识库短 ID:诊断够用,不输出完整 UUID、路径或凭据。 +func describe(target Target) string { + host := "" + if parsed, err := url.Parse(strings.TrimSpace(target.BaseURL)); err == nil && parsed.Host != "" { + host = parsed.Host + } + id := strings.TrimSpace(target.KnowledgeBaseID) + if len(id) > 8 { + id = id[:8] + } + switch { + case host == "" && id == "": + return "" + case host == "": + return "知识库 " + id + case id == "": + return "实例 " + host + default: + return "实例 " + host + " · 知识库 " + id + } +} diff --git a/internal/readiness/weknora_test.go b/internal/readiness/weknora_test.go new file mode 100644 index 0000000..4efd1c1 --- /dev/null +++ b/internal/readiness/weknora_test.go @@ -0,0 +1,138 @@ +package readiness + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// fakeWeKnora answers /health and /api/v1/knowledge-bases/{kb}/knowledge. +// 404 is how WeKnora says "this knowledge base does not exist" (F13 的旧 env 绑定). +func fakeWeKnora(t *testing.T, known map[string]int, wantKey string) *httptest.Server { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("X-API-Key"); wantKey != "" && got != wantKey { + w.WriteHeader(http.StatusUnauthorized) + return + } + switch { + case r.URL.Path == "/health": + _, _ = w.Write([]byte(`ok`)) + case strings.HasPrefix(r.URL.Path, "/api/v1/knowledge-bases/"): + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/v1/knowledge-bases/"), "/") + total, ok := known[parts[0]] + if !ok || len(parts) != 2 || parts[1] != "knowledge" { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = fmt.Fprintf(w, `{"success":true,"total":%d,"data":[]}`, total) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(server.Close) + return server +} + +func TestProbeFollowsTheCurrentBindingWithinOneProcess(t *testing.T) { + oldKB := "1b52c140-2e18-4676-afc5-4c7d8d190a8c" + currentKB := "0c84a098-d3ed-4b82-a165-e6de9691d6a8" + server := fakeWeKnora(t, map[string]int{currentKB: 4}, "key-1") + var mu sync.Mutex + binding := oldKB + prober := Prober{ + Timeout: 2 * time.Second, + Resolve: func(context.Context) (Target, error) { + mu.Lock() + defer mu.Unlock() + return Target{BaseURL: server.URL, KnowledgeBaseID: binding, APIKey: "key-1"}, nil + }, + } + first := prober.Check(context.Background()) + if !errors.Is(first.Err, ErrKnowledgeBaseMissing) { + t.Fatalf("old binding probe = %v, want ErrKnowledgeBaseMissing", first.Err) + } + if !strings.Contains(first.Target, "1b52c140") || strings.Contains(first.Target, oldKB) { + t.Fatalf("probe target must name the probed KB in short form only: %q", first.Target) + } + mu.Lock() + binding = currentKB + mu.Unlock() + second := prober.Check(context.Background()) + if second.Err != nil { + t.Fatalf("current binding probe = %v, want ready", second.Err) + } + if !strings.Contains(second.Target, "0c84a098") { + t.Fatalf("probe target did not follow the new binding: %q", second.Target) + } +} + +func TestProbeReResolvesEndpointAndCredentialOnEveryCheck(t *testing.T) { + kb := "0c84a098-d3ed-4b82-a165-e6de9691d6a8" + denied := fakeWeKnora(t, map[string]int{kb: 4}, "new-key") + allowed := fakeWeKnora(t, map[string]int{kb: 4}, "new-key") + var mu sync.Mutex + endpoint, key := denied.URL, "old-key" + prober := Prober{ + Timeout: 2 * time.Second, + Resolve: func(context.Context) (Target, error) { + mu.Lock() + defer mu.Unlock() + return Target{BaseURL: endpoint, KnowledgeBaseID: kb, APIKey: key}, nil + }, + } + if err := prober.Check(context.Background()).Err; !errors.Is(err, ErrNoPermission) { + t.Fatalf("stale credential probe = %v, want ErrNoPermission", err) + } + mu.Lock() + endpoint, key = allowed.URL, "new-key" + mu.Unlock() + if err := prober.Check(context.Background()).Err; err != nil { + t.Fatalf("rotated endpoint/credential probe = %v, want ready", err) + } +} + +func TestProbeDistinguishesMissingConfigurationFromUnreachable(t *testing.T) { + missing := Prober{Resolve: func(context.Context) (Target, error) { + return Target{BaseURL: "http://127.0.0.1:1", KnowledgeBaseID: ""}, nil + }} + if !errors.Is(missing.Check(context.Background()).Err, ErrNotConfigured) { + t.Fatalf("blank binding must be ErrNotConfigured, got %v", missing.Check(context.Background()).Err) + } + unreachable := Prober{Timeout: 200 * time.Millisecond, Resolve: func(context.Context) (Target, error) { + return Target{BaseURL: "http://127.0.0.1:1", KnowledgeBaseID: "kb-1", APIKey: "key"}, nil + }} + err := unreachable.Check(context.Background()).Err + if err == nil || errors.Is(err, ErrNotConfigured) || errors.Is(err, ErrKnowledgeBaseMissing) { + t.Fatalf("connection refused must stay a transport failure, got %v", err) + } +} + +func TestProbeSurfaces404AsMissingKnowledgeBaseNotServiceDown(t *testing.T) { + server := fakeWeKnora(t, map[string]int{}, "key") + prober := Prober{Timeout: 2 * time.Second, Resolve: func(context.Context) (Target, error) { + return Target{BaseURL: server.URL, KnowledgeBaseID: "gone-kb", APIKey: "key"}, nil + }} + err := prober.Check(context.Background()).Err + if !errors.Is(err, ErrKnowledgeBaseMissing) { + t.Fatalf("404 = %v, want ErrKnowledgeBaseMissing", err) + } + if strings.Contains(err.Error(), "key") { + t.Fatalf("probe error leaked the credential: %v", err) + } +} + +func TestProbeRejectsAnUnusableResolverResult(t *testing.T) { + prober := Prober{Resolve: func(context.Context) (Target, error) { + return Target{}, errors.New("settings unavailable") + }} + if err := prober.Check(context.Background()).Err; err == nil || errors.Is(err, ErrNotConfigured) { + t.Fatalf("resolver failure must be reported, got %v", err) + } +} diff --git a/internal/releaseadapter/v071/candidate_ui_fixture_test.go b/internal/releaseadapter/v071/candidate_ui_fixture_test.go new file mode 100644 index 0000000..1131b68 --- /dev/null +++ b/internal/releaseadapter/v071/candidate_ui_fixture_test.go @@ -0,0 +1,366 @@ +package v071 + +// 候选页面(空目标首次发布)的夹具准备:只在显式 opt-in 时运行,产物留在运行器登记的 +// 隔离资源里,供父在真实浏览器里点"签发授权 → 启动同步"。 +// +// 与已审 r39 publish-http 的区别(必须写清,避免把两件事混成一件): +// - r39 证明的是"正式 publish HTTP + 同请求幂等",它的目标是非空并先建了基线; +// - 这里只准备一个**空**目标(KB 行存在、十表内容为 0)与一份**独立 fullshape 测试来源**, +// 来源快照由本夹具装配并封存,明确标 fixture,不冒称原 C01 两份封存的云发布; +// - 不做任何发布:写入必须由父在页面上触发,交付前目标保持为空。 + +import ( + "bytes" + "context" + "crypto/ed25519" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/objectgateway" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +func TestCandidateEmptyTargetFixture(t *testing.T) { + if os.Getenv("KG_UI_CANDIDATE_PREP") != "1" { + t.Skip("requires explicit candidate fixture opt-in (KG_UI_CANDIDATE_PREP=1)") + } + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute) + defer cancel() + + out := os.Getenv("KG_UI_PREP_OUT") + if out == "" || !filepath.IsAbs(out) { + t.Fatal("KG_UI_PREP_OUT must be an absolute path") + } + sourceArchive := os.Getenv("KG_UI_SOURCE_ARCHIVE") + govDSN := os.Getenv("KG_UI_GOVERNANCE_DSN") + runtimeIndex := os.Getenv("KG_UI_RUNTIME_INDEX") + if sourceArchive == "" || govDSN == "" || runtimeIndex == "" { + t.Fatal("KG_UI_SOURCE_ARCHIVE / KG_UI_GOVERNANCE_DSN / KG_UI_RUNTIME_INDEX are required") + } + + // 目标指纹必须与 API/release worker 用同一份 env 推导(运行器给三者同一份 env 文件)。 + // 它只绑数据身份(库/租户/知识库/索引/桶),换端点不改指纹。 + // 桶名由夹具分配(reset 时会生成唯一桶),所以指纹必须用夹具真实桶名计算, + // 运行器随后把它写进 API/worker 的 env —— 两边因此得到同一个指纹。 + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, archiveRoot: sourceArchive, embeddingDimension: 1024}) + if err := os.Setenv("LIBRARY_PRODUCTION_S3_BUCKET", fx.bucket); err != nil { + t.Fatal(err) + } + cfg, err := appconfig.Load(os.Getenv) + if err != nil { + t.Fatalf("load product config from candidate env: %v", err) + } + fingerprint := cfg.LibraryTargetIdentity() + if fingerprint == "" { + t.Fatal("candidate target fingerprint is empty: product config is incomplete") + } + // 适配层解析 embedding 模型/向量库需要这两列与两张表(与 r39 fullshape 同一装配)。 + if _, err := fx.pool.Exec(ctx, `ALTER TABLE knowledge_bases ADD COLUMN embedding_model_id text, ADD COLUMN vector_store_id text; +CREATE TABLE models(id text PRIMARY KEY,name text,parameters jsonb,deleted_at timestamptz); +CREATE TABLE vector_stores(id text PRIMARY KEY,engine_type text,index_config jsonb,deleted_at timestamptz); +INSERT INTO models VALUES('candidate-model','text-embedding-v4','{"embedding_parameters":{"dimension":1024}}',NULL); +INSERT INTO vector_stores VALUES('candidate-vector','elasticsearch_v8','{}',NULL); +UPDATE knowledge_bases SET embedding_model_id='candidate-model',vector_store_id='candidate-vector';`); err != nil { + t.Fatalf("seed embedding model/vector store: %v", err) + } + + // 空目标的第一条证据:产品自己的范围探针必须说"空",且逐表计数为 0。 + empty, counts, err := ScopeContentEmpty(ctx, fx.pool, ProductionScope{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}) + if err != nil { + t.Fatalf("product scope probe on empty target: %v", err) + } + if !empty { + t.Fatalf("candidate target scope is not empty: %v", counts) + } + for table, n := range counts { + if n != 0 { + t.Fatalf("candidate target %s has %d rows in scope; the target must be empty before delivery", table, n) + } + } + var kbRows int64 + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM knowledge_bases WHERE id=$1 AND tenant_id=$2`, wsTargetKB, wsTargetTenant).Scan(&kbRows); err != nil { + t.Fatal(err) + } + if kbRows != 1 { + t.Fatalf("empty target still needs its KB skeleton: knowledge_bases rows=%d", kbRows) + } + + mapping, err := fx.target(t).Search().MappingSHA256(ctx) + if err != nil { + t.Fatalf("read fixture index mapping digest: %v", err) + } + + // 独立 fullshape 测试来源:声明行 → 真实 PG schema 落库并读回 → 用读回封存。 + spec := r38LegalSourceSpec(t, fx) + readback, sourceStoreEvidence := r39SeedSourceStore(t, fx, spec) + source := r38SealFullShape(t, fx, ds02Spec{rows: readback, vectors: ds02Vectors, objects: ds02Objects}, mapping) + parts := r38SourcePartCounts(t, fx, source) + if len(parts) != len(ds02TargetTables) { + t.Fatalf("sealed source has %d table parts, want %d", len(parts), len(ds02TargetTables)) + } + + // 运行期索引:夹具索引会在测试结束时被删;用同一份 mapping 另建索引, + // 让封存里的 index_mapping_sha256 与运行期目标索引仍逐字节一致。 + mappingBody, err := candidateIndexMapping(ctx, fx.searchBase, fx.index) + if err != nil { + t.Fatalf("read fixture index mapping: %v", err) + } + if err := candidateCreateIndex(ctx, fx.searchBase, runtimeIndex, mappingBody); err != nil { + t.Fatalf("create candidate runtime index: %v", err) + } + exporter, err := NewSearchExporter(SearchExporterConfig{BaseURL: fx.searchBase, Index: runtimeIndex}) + if err != nil { + t.Fatal(err) + } + runtimeMapping, err := exporter.MappingSHA256(ctx) + if err != nil { + t.Fatalf("read runtime index mapping digest: %v", err) + } + if runtimeMapping != mapping { + t.Fatalf("runtime index mapping %s != sealed %s", runtimeMapping, mapping) + } + + // 一次性治理库:迁移 + 网关 schema,再登记这份 test_sealed 版本。 + gov, err := pgxpool.New(ctx, govDSN) + if err != nil { + t.Fatal(err) + } + defer gov.Close() + if err := postgresstore.ApplyMigrations(ctx, gov); err != nil { + t.Fatalf("apply governance migrations: %v", err) + } + if _, err := gov.Exec(ctx, objectgateway.Schema); err != nil { + t.Fatalf("apply object gateway schema: %v", err) + } + store := postgresstore.NewStore(gov).WithLibraryTarget(fingerprint) + sourceIdentity := governance.LibrarySourceIdentity{Project: os.Getenv("LIBRARY_SOURCE_PROJECT"), + App: os.Getenv("LIBRARY_SOURCE_APP"), Scope: "internal", + TenantID: wsSourceTenant, KnowledgeBaseID: wsSourceKB} + sourceID, err := sourceIdentity.ID() + if err != nil { + t.Fatal(err) + } + versionID := governance.LibraryVersionID(governance.LibraryVersionTestSealed, "internal", source) + if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: versionID, Scope: "internal", + Kind: governance.LibraryVersionTestSealed, SnapshotID: source, + Evidence: map[string]any{ + "source_id": sourceID, "source_identity": sourceIdentity, + "capture_job": "candidate-empty-target-fixture", + "assembly": map[string]any{"kind": "fixture-assembled-legal-fullshape", + "source_store": "r39_source schema in the isolated candidate business DB", + "note": "候选页面的独立 fullshape 测试夹具;不是 WeKnora agent 捕获,也不是原 C01 两份封存,不声称 Capture/Export HTTP 已验收", + "manifest_sha256": source, "source_parts_row_counts": parts}, + }, + CreatedBy: "admin", CreatedAt: time.Now().UTC()}); err != nil { + t.Fatalf("register candidate test_sealed version: %v", err) + } + candidate, found, err := store.LibrarySourceCandidate(ctx, "internal", sourceID) + if err != nil { + t.Fatal(err) + } + if !found || candidate.SnapshotID != source { + t.Fatalf("registered candidate is not readable back by source_id: found=%v snapshot=%v", found, candidate.SnapshotID) + } + + // 网关的只读权威角色:角色名/口令由运行器生成并登记所有权,这里只负责创建与授权。 + // 授权范围与网关真正读取的表一致(jobs / library_*),不给写权限。 + readerRole, readerPassword := os.Getenv("KG_UI_READER_ROLE"), os.Getenv("KG_UI_READER_PASSWORD") + readerDSNFile := os.Getenv("KG_UI_READER_DSN_FILE") + if readerRole == "" || readerPassword == "" || !filepath.IsAbs(readerDSNFile) { + t.Fatal("KG_UI_READER_ROLE / KG_UI_READER_PASSWORD / KG_UI_READER_DSN_FILE are required") + } + quotedRole := pgx.Identifier{readerRole}.Sanitize() + if _, err := gov.Exec(ctx, "CREATE ROLE "+quotedRole+" LOGIN PASSWORD '"+readerPassword+"'"); err != nil { + t.Fatalf("create gateway reader role: %v", err) + } + if _, err := gov.Exec(ctx, "GRANT USAGE ON SCHEMA public TO "+quotedRole); err != nil { + t.Fatalf("grant reader schema usage: %v", err) + } + if _, err := gov.Exec(ctx, "GRANT SELECT ON jobs,library_jobs,library_operations,library_attempts,library_versions TO "+quotedRole); err != nil { + t.Fatalf("grant reader table select: %v", err) + } + readerURL, err := url.Parse(govDSN) + if err != nil { + t.Fatal(err) + } + readerURL.User = url.UserPassword(readerRole, readerPassword) + if err := os.WriteFile(readerDSNFile, []byte(readerURL.String()), 0o600); err != nil { + t.Fatalf("write reader DSN file: %v", err) + } + + report := map[string]any{ + "generated_at": time.Now().UTC().Format(time.RFC3339Nano), + "kind": "candidate-empty-target-fixture", + "target_fingerprint": fingerprint, + "target": map[string]any{"tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, + "database": os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") != "", "empty_probe_counts": counts, + "knowledge_bases_rows": kbRows, + "note": "KB 骨架存在、十表内容为 0:这是首次发布的空目标,不是'没有目标'"}, + "runtime_index": runtimeIndex, + "mapping_sha256": mapping, + "runtime_mapping_sha256": runtimeMapping, + "bucket": fx.bucket, + "s3_endpoint": os.Getenv("KG_LIBRARY_TEST_S3_ENDPOINT"), + "source": map[string]any{"snapshot": source, "source_id": sourceID, + "project": sourceIdentity.Project, "app": sourceIdentity.App, + "tenant_id": sourceIdentity.TenantID, "knowledge_base_id": sourceIdentity.KnowledgeBaseID, + "parts": parts, "assembly": "fixture-assembled-legal-fullshape", + "source_store": sourceStoreEvidence}, + "version": map[string]any{"id": versionID, "kind": string(governance.LibraryVersionTestSealed), + "snapshot": source, "created_by": "admin"}, + } + raw, err := json.MarshalIndent(report, "", " ") + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(out), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(out, raw, 0o600); err != nil { + t.Fatal(err) + } + t.Logf("candidate fixture ready: snapshot=%s source_id=%s version=%s", source, sourceID, versionID) +} + +func TestCandidateAttestation(t *testing.T) { + if os.Getenv("KG_UI_ATTESTATION") != "1" { + t.Skip("requires explicit candidate attestation opt-in (KG_UI_ATTESTATION=1)") + } + // 网关每次请求都重读审计文件,所以刷新只需原子替换该文件:不用重启网关, + // 也不会与正在进行的发布互相干扰。有效期上限是 1 小时(objectgateway.AuditVerifier)。 + seedRaw, err := hex.DecodeString(os.Getenv("KG_UI_ATTESTATION_SEED")) + if err != nil || len(seedRaw) != ed25519.SeedSize { + t.Fatal("KG_UI_ATTESTATION_SEED must be a 32-byte hex seed") + } + path := os.Getenv("KG_UI_AUDIT_FILE") + pubPath := os.Getenv("KG_UI_ATTESTATION_PUB_FILE") + if !filepath.IsAbs(path) || !filepath.IsAbs(pubPath) { + t.Fatal("KG_UI_AUDIT_FILE and KG_UI_ATTESTATION_PUB_FILE must be absolute paths") + } + evidence := map[string]string{} + for key, env := range map[string]string{ + "writer_inventory_sha256": "KG_UI_EVIDENCE_WRITER", + "policy_evidence_sha256": "KG_UI_EVIDENCE_POLICY", + "denial_evidence_sha256": "KG_UI_EVIDENCE_DENIAL", + "drain_evidence_sha256": "KG_UI_EVIDENCE_DRAIN", + } { + value := os.Getenv(env) + if len(value) != 64 { + t.Fatalf("%s must be a 64-hex digest of a real evidence file", env) + } + evidence[key] = value + } + scope := objectgateway.Digest([]byte(os.Getenv("OBJECT_GATEWAY_PROVIDER") + "\x00" + + os.Getenv("OBJECT_GATEWAY_ENDPOINT") + "\x00" + os.Getenv("OBJECT_GATEWAY_BUCKET"))) + now := time.Now().UTC() + key := ed25519.NewKeyFromSeed(seedRaw) + payload, err := json.Marshal(objectgateway.Attestation{Protocol: objectgateway.Protocol, Scope: scope, + GatewayID: os.Getenv("OBJECT_GATEWAY_ID"), IssuedAt: now.Add(-2 * time.Second), ExpiresAt: now.Add(45 * time.Minute), + WriterInventory: evidence["writer_inventory_sha256"], PolicyEvidence: evidence["policy_evidence_sha256"], + DenialEvidence: evidence["denial_evidence_sha256"], DrainEvidence: evidence["drain_evidence_sha256"]}) + if err != nil { + t.Fatal(err) + } + signed, err := json.Marshal(objectgateway.SignedAttestation{Payload: payload, Signature: ed25519.Sign(key, payload)}) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + temp := path + ".new" + if err := os.WriteFile(temp, signed, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(temp, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Rename(temp, path); err != nil { + t.Fatal(err) + } + public := base64.StdEncoding.EncodeToString(key.Public().(ed25519.PublicKey)) + if err := os.WriteFile(pubPath, []byte(public), 0o600); err != nil { + t.Fatalf("write gateway audit public key: %v", err) + } + t.Logf("candidate attestation refreshed: scope=%s gateway=%s expires=%s", scope, os.Getenv("OBJECT_GATEWAY_ID"), now.Add(45*time.Minute).Format(time.RFC3339)) +} + +func candidateIndexMapping(ctx context.Context, base, index string) (map[string]any, error) { + response, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/"+index+"/_mapping", nil) + if err != nil { + return nil, err + } + client := &http.Client{Timeout: 20 * time.Second} + res, err := client.Do(response) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("read mapping %s: HTTP %d", index, res.StatusCode) + } + raw, err := io.ReadAll(io.LimitReader(res.Body, 4<<20)) + if err != nil { + return nil, err + } + var payload map[string]json.RawMessage + if err := json.Unmarshal(raw, &payload); err != nil { + return nil, err + } + mappings, ok := payload[index] + if !ok { + return nil, fmt.Errorf("mapping response does not contain index %s", index) + } + var value map[string]any + if err := json.Unmarshal(mappings, &value); err != nil { + return nil, err + } + return value, nil +} + +func candidateCreateIndex(ctx context.Context, base, index string, body map[string]any) error { + client := &http.Client{Timeout: 20 * time.Second} + check, err := http.NewRequestWithContext(ctx, http.MethodHead, base+"/"+index, nil) + if err != nil { + return err + } + if res, err := client.Do(check); err == nil { + res.Body.Close() + if res.StatusCode == http.StatusOK { + return fmt.Errorf("runtime index %s already exists: refusing to reuse an unknown index", index) + } + } + payload, err := json.Marshal(body) + if err != nil { + return err + } + request, err := http.NewRequestWithContext(ctx, http.MethodPut, base+"/"+index, bytes.NewReader(payload)) + if err != nil { + return err + } + request.Header.Set("Content-Type", "application/json") + res, err := client.Do(request) + if err != nil { + return err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + detail, _ := io.ReadAll(io.LimitReader(res.Body, 4096)) + return fmt.Errorf("create runtime index %s: HTTP %d %s", index, res.StatusCode, detail) + } + return nil +} diff --git a/internal/releaseadapter/v071/contract_inspector.go b/internal/releaseadapter/v071/contract_inspector.go index ac55e6b..e3264d2 100644 --- a/internal/releaseadapter/v071/contract_inspector.go +++ b/internal/releaseadapter/v071/contract_inspector.go @@ -3,10 +3,12 @@ package v071 import ( "context" "errors" + "fmt" "strings" "github.com/jackc/pgx/v5" + "knowledge-governance/internal/libraryprofile" "knowledge-governance/internal/releasebundle" releaseworkflow "knowledge-governance/internal/workflows/release" ) @@ -37,19 +39,23 @@ type TargetContractInspector struct { config TargetContractInspectorConfig } +// targetContractSQL 用 LEFT JOIN 读模型与向量库:命中不到时仍然拿得到"声明了什么", +// 这样缺字段能被点名拒绝,而不是整行查不出来只报一句"读契约失败"。 const targetContractSQL = ` -SELECT migration.version, - migration.dirty, +SELECT COALESCE(migration.version, 0), + COALESCE(migration.dirty, false), knowledge_base.tenant_id, - model.name, + COALESCE(knowledge_base.embedding_model_id, ''), + COALESCE(model.name, ''), COALESCE(NULLIF(model.parameters->'embedding_parameters'->>'dimension', '')::INTEGER, 0), + (model.id IS NOT NULL), COALESCE(vector_store.engine_type, ''), COALESCE(vector_store.index_config->>'index_name', '') FROM knowledge_bases AS knowledge_base -JOIN models AS model +LEFT JOIN models AS model ON model.id = knowledge_base.embedding_model_id AND model.deleted_at IS NULL -JOIN schema_migrations AS migration ON TRUE +LEFT JOIN schema_migrations AS migration ON TRUE LEFT JOIN vector_stores AS vector_store ON vector_store.id = knowledge_base.vector_store_id AND vector_store.deleted_at IS NULL @@ -57,6 +63,25 @@ WHERE knowledge_base.id = $1 AND knowledge_base.deleted_at IS NULL ` +// resolveTargetIndexName 是"索引名从哪来"的唯一判定点。 +// +// 0.9.0 的 KB 不写 vector_store_id(vector_stores 没有对应行),索引名只在部署 +// 配置里(ELASTICSEARCH_INDEX)。两条来源都拿不到时**不许**回退成空串—— +// 空串会让后续过滤条件匹配到任何索引。0.7.1 若两处都有,必须一致。 +func resolveTargetIndexName(fromVectorStore, configured string, profile libraryprofile.Profile) (string, error) { + resolved := fromVectorStore + if resolved == "" { + resolved = configured + } + if !validSearchIdentifier(resolved) { + return "", fmt.Errorf("target WeKnora index name unresolved (contract source: %s): vector_stores.index_config->>'index_name' and the configured index are both empty", profile.IndexContractSource) + } + if fromVectorStore != "" && fromVectorStore != configured { + return "", fmt.Errorf("target WeKnora contract mismatch: vector_stores.index_config.index_name=%q does not match configured index %q", fromVectorStore, configured) + } + return resolved, nil +} + func NewTargetContractInspector(config TargetContractInspectorConfig) (*TargetContractInspector, error) { config.KnowledgeBaseID = strings.TrimSpace(config.KnowledgeBaseID) config.IndexName = strings.TrimSpace(config.IndexName) @@ -85,29 +110,51 @@ func (inspector *TargetContractInspector) Contract(ctx context.Context, item rel migrationVersion int dirty bool tenantID uint64 + declaredModel string embeddingModel string dimension int + modelBound bool engineType string indexName string ) if err := inspector.config.DB.QueryRow(ctx, targetContractSQL, targetKnowledgeBaseID).Scan( - &migrationVersion, &dirty, &tenantID, &embeddingModel, &dimension, &engineType, &indexName, + &migrationVersion, &dirty, &tenantID, &declaredModel, &embeddingModel, &dimension, &modelBound, &engineType, &indexName, ); err != nil { return releasebundle.TargetContract{}, errors.New("read target WeKnora contract") } - if migrationVersion != releasebundle.WeKnoraMigrationV071 || dirty || tenantID != inspector.config.TenantID || - !validSearchIdentifier(embeddingModel) || dimension < 1 || - (engineType != "" && engineType != "elasticsearch") || - (indexName != "" && indexName != inspector.config.IndexName) { - return releasebundle.TargetContract{}, errors.New("target WeKnora contract mismatch") + if dirty { + return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora schema_migrations.version=%d is dirty: refusing to publish", migrationVersion) + } + // 版本号只用来选 profile;未知版本失败关闭,错误里带真实版本号。 + profile, err := libraryprofile.For(migrationVersion) + if err != nil { + return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora: %w", err) + } + if tenantID != inspector.config.TenantID { + return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora contract mismatch: knowledge_bases.tenant_id=%d, expected %d", tenantID, inspector.config.TenantID) + } + if !validSearchIdentifier(declaredModel) { + return releasebundle.TargetContract{}, errors.New("target WeKnora contract mismatch: knowledge_bases.embedding_model_id is empty: embedding dimension is unknowable") + } + if !modelBound { + return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora contract mismatch: models row for knowledge_bases.embedding_model_id %q is missing or deleted", declaredModel) + } + if !validSearchIdentifier(embeddingModel) || dimension < 1 { + return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora contract mismatch: models.parameters.embedding_parameters.dimension is missing for model %q", declaredModel) + } + if engineType != "" && engineType != "elasticsearch" { + return releasebundle.TargetContract{}, fmt.Errorf("target WeKnora contract mismatch: vector_stores.engine_type=%q is not elasticsearch", engineType) + } + if _, err := resolveTargetIndexName(indexName, inspector.config.IndexName, profile); err != nil { + return releasebundle.TargetContract{}, err } mappingSHA256, err := inspector.config.Mapping.MappingSHA256(ctx) if err != nil || !validLowerSHA256(mappingSHA256) { return releasebundle.TargetContract{}, errors.New("read target Elasticsearch mapping contract") } return releasebundle.TargetContract{ - WeKnoraVersion: releasebundle.WeKnoraVersionV071, - MigrationVersion: releasebundle.WeKnoraMigrationV071, + WeKnoraVersion: profile.WeKnoraVersion, + MigrationVersion: profile.SchemaVersion, TenantID: tenantID, KnowledgeBaseID: targetKnowledgeBaseID, RetrieverEngine: "elasticsearch_v8", diff --git a/internal/releaseadapter/v071/contract_inspector_test.go b/internal/releaseadapter/v071/contract_inspector_test.go index 1c89223..d099706 100644 --- a/internal/releaseadapter/v071/contract_inspector_test.go +++ b/internal/releaseadapter/v071/contract_inspector_test.go @@ -9,7 +9,7 @@ import ( ) func TestTargetContractInspectorReadsOnlyCompatibilityFields(t *testing.T) { - db := &contractDB{row: contractRow{values: []any{74, false, uint64(10000), "bge-m3", 1024, "elasticsearch", "chunks"}}} + db := &contractDB{row: contractRow{values: []any{74, false, uint64(10000), "bge-m3", "bge-m3", 1024, true, "elasticsearch", "chunks"}}} mapping := &mappingInspector{sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} inspector, err := NewTargetContractInspector(TargetContractInspectorConfig{DB: db, Mapping: mapping, KnowledgeBaseID: "kb-safe", TenantID: 10000, IndexName: "chunks"}) if err != nil { @@ -36,7 +36,7 @@ func TestTargetContractInspectorReadsOnlyCompatibilityFields(t *testing.T) { } func TestTargetContractInspectorRejectsMismatchedPlanKB(t *testing.T) { - db := &contractDB{row: contractRow{values: []any{74, false, uint64(10000), "bge-m3", 1024, "elasticsearch", "chunks"}}} + db := &contractDB{row: contractRow{values: []any{74, false, uint64(10000), "bge-m3", "bge-m3", 1024, true, "elasticsearch", "chunks"}}} inspector, _ := NewTargetContractInspector(TargetContractInspectorConfig{DB: db, Mapping: &mappingInspector{sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, KnowledgeBaseID: "kb-safe", TenantID: 10000, IndexName: "chunks"}) plan := releasePlanForArchive() plan.TestKnowledgeBaseID = "other-kb" @@ -50,7 +50,7 @@ func TestTargetContractInspectorRejectsMismatchedPlanKB(t *testing.T) { // the mapped base on the source plane made a real release fail with // "source WeKnora release contract mismatch" (the target base is unknown there). func TestTargetContractInspectorSidesPickTheRightBase(t *testing.T) { - row := contractRow{values: []any{74, false, uint64(10000), "bge-m3", 1024, "elasticsearch", "chunks"}} + row := contractRow{values: []any{74, false, uint64(10000), "bge-m3", "bge-m3", 1024, true, "elasticsearch", "chunks"}} mapping := &mappingInspector{sha: strings.Repeat("a", 64)} plan := releasePlanForArchive() plan.TargetKnowledgeBaseID = "prod-kb" diff --git a/internal/releaseadapter/v071/data_admission_fixture_r10_test.go b/internal/releaseadapter/v071/data_admission_fixture_r10_test.go new file mode 100644 index 0000000..2a43b32 --- /dev/null +++ b/internal/releaseadapter/v071/data_admission_fixture_r10_test.go @@ -0,0 +1,82 @@ +package v071 + +import ( + "context" + "net/http/httptest" + "os" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/objectgateway" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/platform/postgres/pgtest" +) + +// Exported only into the test binary, so the external-package test exercises +// librarystack.OpenProductionStack without an import cycle or duplicated fixture. +type R10AdmissionFixture struct { + Context context.Context + Config appconfig.Config + Snapshot string + Exec func(string) + State func() map[string]any + Unchanged func(map[string]any) + Save func(string, any) +} + +func OpenR10AdmissionFixture(t *testing.T) R10AdmissionFixture { + t.Helper() + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, embeddingDimension: 1024}) + seedTargetData(t, fx) + r10Exec(t, fx, `ALTER TABLE knowledge_bases ADD COLUMN embedding_model_id text; ALTER TABLE knowledge_bases ADD COLUMN vector_store_id text; + CREATE TABLE models(id text PRIMARY KEY,name text,parameters jsonb,deleted_at timestamptz); + CREATE TABLE vector_stores(id text PRIMARY KEY,engine_type text,index_config jsonb,deleted_at timestamptz); + INSERT INTO models VALUES('r10-model','text-embedding-v4','{"embedding_parameters":{"dimension":1024}}',NULL); + INSERT INTO vector_stores VALUES('r10-vector','elasticsearch_v8','{}',NULL); + UPDATE knowledge_bases SET embedding_model_id='r10-model',vector_store_id='r10-vector'`) + if _, e := fx.pool.Exec(fx.ctx, `UPDATE vector_stores SET index_config=jsonb_build_object('index_name',$1::text)`, fx.index); e != nil { + t.Fatal(e) + } + dsn := pgtest.IsolatedDatabaseURL(t, os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")) + governancePool, e := pgxpool.New(fx.ctx, dsn) + if e != nil { + t.Fatal(e) + } + t.Cleanup(governancePool.Close) + if e = postgresstore.ApplyMigrations(fx.ctx, governancePool); e != nil { + t.Fatal(e) + } + if _, e = governancePool.Exec(fx.ctx, objectgateway.Schema); e != nil { + t.Fatal(e) + } + reader := gatewayReadOnlyGovernance(t, fx.ctx, governancePool, dsn) + authority := &GatewayGovernanceAuthority{Pool: reader, ArchiveRoot: fx.archiveRoot, TargetID: "r10-admission", Provider: "minio", Bucket: fx.bucket} + endpoint := os.Getenv("KG_LIBRARY_TEST_S3_ENDPOINT") + scope := objectgateway.Digest([]byte("minio\x00" + endpoint + "\x00" + fx.bucket)) + gateway := &objectgateway.Gateway{Pool: governancePool, Scope: scope, Backend: &objectgateway.S3Backend{Client: fx.objects.s3.client, Bucket: fx.bucket, MaxBytes: 1 << 20}, Authority: authority, MaxBytes: 1 << 20} + token := objectgateway.Digest([]byte("r10-admission-data")) + server := httptest.NewServer(objectgateway.HTTPServer{Gateway: gateway, DataToken: token, ControlToken: objectgateway.Digest([]byte("r10-admission-control"))}) + t.Cleanup(server.Close) + config := appconfig.Config{LibraryProductionDatabaseURL: os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), LibraryProductionElasticURL: fx.searchBase, LibraryProductionIndex: fx.index, LibraryProductionTenantID: wsTargetTenant, LibraryProductionInternalKB: wsTargetKB, LibraryProductionS3Endpoint: endpoint, LibraryProductionS3Provider: "minio", LibraryProductionS3Bucket: fx.bucket, LibraryProductionS3AccessKey: os.Getenv("KG_LIBRARY_TEST_S3_ACCESS_KEY"), LibraryProductionS3SecretKey: os.Getenv("KG_LIBRARY_TEST_S3_SECRET_KEY"), LibraryArchiveRoot: fx.archiveRoot, LibraryObjectGatewayURL: server.URL, LibraryObjectGatewayToken: token} + snapshot := sealSourceSnapshot(t, fx, nil) + state := func() map[string]any { + out := r10State(t, fx) + for _, table := range []string{"knowledge_bases", "models", "vector_stores", "schema_migrations"} { + var raw []byte + if e := fx.pool.QueryRow(fx.ctx, "SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]') FROM "+table+" t").Scan(&raw); e != nil { + t.Fatal(e) + } + out[table] = string(raw) + } + for _, table := range []string{"kg_object_gateway_plans", "kg_object_gateway_intents", "kg_object_gateway_receipts", "kg_object_gateway_deliveries", "kg_object_gateway_grants"} { + var count int64 + if e := governancePool.QueryRow(fx.ctx, "SELECT count(*) FROM "+table).Scan(&count); e != nil { + t.Fatal(e) + } + out[table] = count + } + return out + } + return R10AdmissionFixture{Context: fx.ctx, Config: config, Snapshot: snapshot, Exec: func(sql string) { r10Exec(t, fx, sql) }, State: state, Save: func(label string, value any) { r10Save(t, label, value) }} +} diff --git a/internal/releaseadapter/v071/data_admission_r10_test.go b/internal/releaseadapter/v071/data_admission_r10_test.go new file mode 100644 index 0000000..fb95da4 --- /dev/null +++ b/internal/releaseadapter/v071/data_admission_r10_test.go @@ -0,0 +1,51 @@ +package v071_test + +import ( + "reflect" + "strings" + "testing" + + "knowledge-governance/internal/librarystack" + v071 "knowledge-governance/internal/releaseadapter/v071" +) + +func TestR10ProductionAdmissionIsolated(t *testing.T) { + cases := []struct{ name, sql, want string }{ + {"matching", "", ""}, + {"same-dimension-other-model", `UPDATE models SET name='different-embedding-model'`, "不同"}, + {"missing-model", `DELETE FROM models`, "模型"}, + {"empty-model-name", `UPDATE models SET name=''`, "模型"}, + {"graph-enabled", `UPDATE knowledge_bases SET indexing_strategy='{"graph_enabled":true}' WHERE id='kb-target'`, "图谱"}, + {"schema-dirty", `UPDATE schema_migrations SET dirty=true`, "dirty"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + fx := v071.OpenR10AdmissionFixture(t) + if c.sql != "" { + fx.Exec(c.sql) + } + before := fx.State() + target, backups, e := librarystack.OpenProductionStack(fx.Context, fx.Config, "internal", fx.Snapshot, "", nil) + if target != nil { + target.Close() + } + after := fx.State() + fx.Save("before", before) + fx.Save("after", after) + if !reflect.DeepEqual(before, after) { + t.Fatal("actual admission path changed PG/ES/object versions/gateway journal") + } + if c.want == "" { + if e != nil || target == nil || backups == nil { + t.Fatal("positive admission", e) + } + fx.Save("outcome", "matching contract admitted without business writes") + } else { + if e == nil || !strings.Contains(e.Error(), c.want) || target != nil || backups != nil { + t.Fatalf("wrong admission result target=%t backups=%t error=%v", target != nil, backups != nil, e) + } + fx.Save("rejection", e.Error()) + } + }) + } +} diff --git a/internal/releaseadapter/v071/data_boundary_r11_test.go b/internal/releaseadapter/v071/data_boundary_r11_test.go new file mode 100644 index 0000000..d5e6f95 --- /dev/null +++ b/internal/releaseadapter/v071/data_boundary_r11_test.go @@ -0,0 +1,126 @@ +package v071 + +import ( + "bytes" + "context" + "io" + "knowledge-governance/internal/libraryrelease" + "sync" + "testing" + "time" +) + +type r11BackupHook struct { + libraryrelease.BackupStore + after func() +} + +func (b r11BackupHook) Prepare(ctx context.Context, id string, current libraryrelease.CurrentState) (libraryrelease.BackupRef, error) { + ref, e := b.BackupStore.Prepare(ctx, id, current) + if e == nil { + b.after() + } + return ref, e +} + +type r11PlanHook struct { + libraryrelease.NoopRecorder + after func() +} + +func (r r11PlanHook) WriteSetPlanned(_ context.Context, _ libraryrelease.WriteSet) error { + r.after() + return nil +} +func TestR11GrantBoundaryIsolated(t *testing.T) { + for _, mode := range []string{"stale-request-clock", "expires-during-backup", "expires-before-first-apply"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + req := requestFor(snapshot) + req.Grant.ExpiresAt = time.Now().Add(350 * time.Millisecond) + wait := func() { + if d := time.Until(req.Grant.ExpiresAt) + 10*time.Millisecond; d > 0 { + time.Sleep(d) + } + } + var backups libraryrelease.BackupStore = fx.backups(t, target) + var recorder libraryrelease.Recorder + if mode == "stale-request-clock" { + req.Now = time.Now().Add(-time.Hour) + req.Grant.ExpiresAt = time.Now().Add(-time.Second) + } + if mode == "expires-during-backup" { + backups = r11BackupHook{BackupStore: backups, after: wait} + } + if mode == "expires-before-first-apply" { + recorder = r11PlanHook{after: wait} + } + before := r10State(t, fx) + out := libraryrelease.Run(fx.ctx, req, target, backups, recorder) + r10Save(t, "outcome", out) + if out.State != "failed" || out.FailedAt != "" { + t.Errorf("expired authority performed business stages: %+v", out) + } + r10Unchanged(t, fx, before) + }) + } +} + +type r11ObjectReadHook struct { + *flakyStore + once sync.Once + after func(provider, path string) +} + +func (r *r11ObjectReadHook) Open(ctx context.Context, provider, path string) (io.ReadCloser, error) { + stream, e := r.flakyStore.Open(ctx, provider, path) + if e != nil { + return nil, e + } + data, e := io.ReadAll(stream) + stream.Close() + if e != nil { + return nil, e + } + r.once.Do(func() { r.after(provider, path) }) + return io.NopCloser(bytes.NewReader(data)), nil +} +func TestR11BackupMutationIsolated(t *testing.T) { + for _, mode := range []string{"es-body", "object-body", "object-same-bytes-new-version"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + var injected map[string]any + backups.objects = &r11ObjectReadHook{flakyStore: fx.objects, after: func(provider, path string) { + if mode == "es-body" { + fx.indexDoc(t, "chunk-target", wsTargetTenant, wsTargetKB, "doc-target", "external edit") + } else { + body := "87654321" + if mode == "object-same-bytes-new-version" { + body = "12345678" + } + if e := fx.objects.s3.Put(fx.ctx, provider, path, bytes.NewReader([]byte(body)), 8); e != nil { + t.Fatal(e) + } + } + injected = r10State(t, fx) + r10Save(t, "external-change", injected) + }} + out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, backups, nil) + r10Save(t, "outcome", out) + if injected == nil { + t.Fatal("injection not reached") + } + if out.State != "failed" || out.FailedAt != "" { + t.Errorf("changed backup admitted writes: %+v", out) + } + r10Unchanged(t, fx, injected) + }) + } +} diff --git a/internal/releaseadapter/v071/data_closure_r10_test.go b/internal/releaseadapter/v071/data_closure_r10_test.go new file mode 100644 index 0000000..cb498dd --- /dev/null +++ b/internal/releaseadapter/v071/data_closure_r10_test.go @@ -0,0 +1,247 @@ +package v071 + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +func TestR10SourceRelationClosureIsolated(t *testing.T) { + for _, mode := range []string{"missing-tag", "missing-knowledge", "cross-kb", "cross-tenant", "orphan-chunk", "unknown-owner", "missing-resource-owner", "null-owner"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + r10Exec(t, fx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id) VALUES('tag-target',10001,'kb-target'),('tag-other',10001,'kb-other'),('tag-foreign',10002,'kb-foreign')`) + switch mode { + case "missing-tag": + r10Exec(t, fx, `INSERT INTO knowledge_tag_relations VALUES('doc-target','absent')`) + case "missing-knowledge": + r10Exec(t, fx, `INSERT INTO knowledge_tag_relations VALUES('absent','tag-target')`) + case "cross-kb": + r10Exec(t, fx, `INSERT INTO knowledge_tag_relations VALUES('doc-target','tag-other')`) + case "cross-tenant": + r10Exec(t, fx, `INSERT INTO knowledge_tag_relations VALUES('doc-target','tag-foreign')`) + case "orphan-chunk": + r10Exec(t, fx, `UPDATE chunks SET knowledge_id='absent' WHERE id='chunk-target'`) + case "unknown-owner": + r10Exec(t, fx, `UPDATE resource_bindings SET owner_type='unknown-v071-shape' WHERE id='bind-target'`) + case "missing-resource-owner": + r10Exec(t, fx, `UPDATE resource_bindings SET owner_id='absent-owner' WHERE id='bind-target'`) + case "null-owner": + r10Exec(t, fx, `UPDATE resource_bindings SET owner_type=NULL,owner_id='doc-other' WHERE id='bind-target'`) + } + before := r10State(t, fx) + _, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}) + r10Unchanged(t, fx, before) + if e == nil { + t.Fatal("source silently excluded a scoped unresolved relationship") + } + r10Save(t, "rejection", e.Error()) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + r10Save(t, "existing-target-rejection", result) + if result.State != "failed" || result.FailedAt != "" { + t.Fatalf("existing unresolved target relationship reached writes: %+v", result) + } + r10Unchanged(t, fx, before) + }) + } +} +func TestR10IncomingRelationClosureIsolated(t *testing.T) { + for _, mode := range []string{"valid-new", "valid-existing", "missing-tag", "missing-knowledge", "cross-kb", "cross-tenant", "unknown-owner", "missing-resource"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + positive := strings.HasPrefix(mode, "valid-") + if positive { + r10Exec(t, fx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id) VALUES('tag-target',10001,'kb-target'),('tag-other',10001,'kb-other'); INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES('doc-target','tag-target'),('doc-other','tag-other')`) + } + snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { + parts["knowledge_tags"] = []map[string]any{{"id": "tag-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB}} + parts["knowledge_tag_relations"] = []map[string]any{{"knowledge_id": "doc-src", "tag_id": "tag-src"}} + switch mode { + case "valid-existing": + parts["knowledges"][0]["id"] = "doc-target" + parts["chunks"][0]["knowledge_id"] = "doc-target" + parts["resource_bindings"][0]["owner_id"] = "doc-target" + parts["knowledge_tags"][0]["id"] = "tag-target" + parts["knowledge_tag_relations"][0] = map[string]any{"knowledge_id": "doc-target", "tag_id": "tag-target"} + case "missing-tag": + parts["knowledge_tag_relations"][0]["tag_id"] = "missing" + case "missing-knowledge": + parts["knowledge_tag_relations"][0]["knowledge_id"] = "missing" + case "cross-kb": + parts["knowledge_tags"][0]["knowledge_base_id"] = wsOtherKB + case "unknown-owner": + parts["resource_bindings"][0]["owner_type"] = "unknown-v071-shape" + case "cross-tenant": + parts["knowledge_tags"][0]["tenant_id"] = 20000 + case "missing-resource": + parts["resource_bindings"][0]["resource_id"] = "absent-resource" + } + }) + before := r10State(t, fx) + target := fx.target(t) + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + r10Save(t, "outcome", result) + if positive { + if result.State != "succeeded" { + t.Fatalf("nonempty tuple publication: %+v", result) + } + wantID := expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", "doc-src") + ":" + + expectedTargetID(wsTargetTenant, wsTargetKB, "knowledge_tags", "tag-src") + if mode == "valid-existing" { + wantID = expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", "doc-target") + ":" + + expectedTargetID(wsTargetTenant, wsTargetKB, "knowledge_tags", "tag-target") + } + found := false + for _, row := range result.Backup.WriteSet.Rows { + if row.Table == "knowledge_tag_relations" && row.ID == wantID { + found = true + // 映射后所有 tuple 都是目标新身份;即使源 ID 恰是目标库已存在的 + // doc-target/tag-target,它们会被派生成本次的新 ID,写前不存在。 + if row.Existing { + t.Fatal("mapped tuple misclassified as pre-existing", row) + } + } + } + if !found { + t.Fatal("tuple absent from frozen write set") + } + var outside int + if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledge_tag_relations WHERE knowledge_id='doc-other' AND tag_id='tag-other'`).Scan(&outside); e != nil || outside != 1 { + t.Fatal("outside tuple changed", e) + } + if e := target.Restore(fx.ctx, result.Backup); e != nil { + t.Fatal(e) + } + after := r10State(t, fx) + for _, key := range []string{"pg", "versions", "delete_markers"} { + if !reflect.DeepEqual(before[key], after[key]) { + t.Fatal("tuple rollback changed original data", key) + } + } + r10Save(t, "restored", after) + return + } + if result.State != "failed" || result.FailedAt != "" { + t.Fatalf("incoming unresolved reference passed preflight: %+v", result) + } + r10Unchanged(t, fx, before) + }) + } +} +func TestR10BodyOnlyResourceIsolated(t *testing.T) { + for _, mode := range []string{"knowledge-content", "wiki-content", "knowledge-metadata", "wiki-metadata"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + r10Exec(t, fx, `DELETE FROM resource_bindings WHERE owner_id='doc-target'; UPDATE chunks SET content='plain' WHERE id='chunk-target'; ALTER TABLE knowledges ADD COLUMN content text; ALTER TABLE knowledges ADD COLUMN metadata jsonb; ALTER TABLE wiki_pages ADD COLUMN metadata jsonb`) + table, column := "knowledges", "content" + if strings.HasPrefix(mode, "wiki") { + table = "wiki_pages" + } + if strings.HasSuffix(mode, "metadata") { + column = "metadata" + } + value := any("![image](resource://" + wsHandleTarget + ")") + if column == "metadata" { + raw, _ := json.Marshal(map[string]any{"image_info": []any{map[string]string{"url": "resource://" + wsHandleTarget}}}) + value = string(raw) + } + if _, e := fx.pool.Exec(fx.ctx, fmt.Sprintf("UPDATE %s SET %s=$1 WHERE knowledge_base_id=$2", table, column), value, wsTargetKB); e != nil { + t.Fatal(e) + } + before := r10State(t, fx) + pg, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}) + if e != nil { + t.Fatal(e) + } + found := false + for _, row := range pg.Table("resources").Rows { + var id struct { + ID string `json:"id"` + } + _ = json.Unmarshal(row, &id) + if id.ID == "res-target" { + found = true + } + if id.ID == "res-orphan" { + t.Fatal("unowned historical resource adopted into source") + } + } + if !found { + t.Fatal("body/metadata resource not captured without binding") + } + if len(pg.Table("resource_bindings").Rows) != 0 { + t.Fatal("fixture unexpectedly had bindings") + } + r10Save(t, "captured-resources", pg.Table("resources")) + backup, e := exportLibraryBeforeImage(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}) + if e != nil { + t.Fatal(e) + } + found = false + for _, raw := range backup.Table("resources").Rows { + var row struct { + ID string `json:"id"` + } + _ = json.Unmarshal(raw, &row) + if row.ID == "res-target" { + found = true + } + } + if !found { + t.Fatal("body-only target resource missing from before-image") + } + r10Unchanged(t, fx, before) + snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { + parts["resource_bindings"] = []map[string]any{} + parts["chunks"][0]["content"] = "plain source" + parts[table][0][column] = "![image](resource://" + wsHandleSource + ")" + if column == "metadata" { + parts[table][0][column] = map[string]any{"image_info": []any{map[string]string{"url": "resource://" + wsHandleSource}}} + } + }) + target := fx.target(t) + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + r10Save(t, "publication", result) + if result.State != "succeeded" { + t.Fatalf("body-only publication: %+v", result) + } + if err := target.Restore(fx.ctx, result.Backup); err != nil { + t.Fatal(err) + } + after := r10State(t, fx) + for _, key := range []string{"pg", "versions", "delete_markers"} { + if !reflect.DeepEqual(before[key], after[key]) { + t.Fatalf("body-only restore changed %s including historical orphans", key) + } + } + r10Save(t, "restored", after) + }) + } +} +func TestR10UnknownResourceShapeIsolated(t *testing.T) { + for _, body := range []string{"resource://short", "resource://" + wsHandleTarget + "extra", "resource://" + wsHandleTarget + "?download=1", "resource:\\/\\/" + wsHandleTarget} { + t.Run(fmt.Sprint(len(body))+strings.ReplaceAll(body[len(body)-3:], "/", "_"), func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, e := fx.pool.Exec(fx.ctx, `UPDATE wiki_pages SET content=$1 WHERE id='wiki-target'`, body); e != nil { + t.Fatal(e) + } + before := r10State(t, fx) + _, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}) + r10Unchanged(t, fx, before) + if e == nil { + t.Fatal("unknown resource reference shape silently accepted") + } + r10Save(t, "rejection", e.Error()) + }) + } +} diff --git a/internal/releaseadapter/v071/data_contract_r10_test.go b/internal/releaseadapter/v071/data_contract_r10_test.go new file mode 100644 index 0000000..6391f8b --- /dev/null +++ b/internal/releaseadapter/v071/data_contract_r10_test.go @@ -0,0 +1,262 @@ +package v071 + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +func r10Save(t *testing.T, label string, value any) { + t.Helper() + root := os.Getenv("KG_R10_RUN") + if root == "" { + return + } + name := strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()+"-"+label) + ".json" + data, e := json.MarshalIndent(value, "", " ") + if e != nil { + t.Fatal(e) + } + if e = os.WriteFile(filepath.Join(root, name), data, 0600); e != nil { + t.Fatal(e) + } +} +func r10Exec(t *testing.T, fx *writeSetFixture, sql string) { + t.Helper() + if _, e := fx.pool.Exec(fx.ctx, sql); e != nil { + t.Fatal(e) + } +} +func r10State(t *testing.T, fx *writeSetFixture) map[string]any { + t.Helper() + objects, e := fx.objects.s3.client.ListObjectVersions(fx.ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(fx.bucket)}) + if e != nil { + t.Fatal(e) + } + if aws.ToBool(objects.IsTruncated) { + t.Fatal("truncated object evidence") + } + seq := map[string]any{} + for _, name := range []string{"chunks_seq_id_seq", "knowledge_tags_seq_id_seq", "wiki_log_entries_id_seq"} { + var exists bool + if e := fx.pool.QueryRow(fx.ctx, "SELECT to_regclass($1) IS NOT NULL", name).Scan(&exists); e != nil { + t.Fatal(e) + } + if exists { + var last int64 + var called bool + if e := fx.pool.QueryRow(fx.ctx, "SELECT last_value,is_called FROM "+name).Scan(&last, &called); e != nil { + t.Fatal(e) + } + seq[name] = []any{last, called} + } + } + r10Save(t, "namespace", map[string]string{"bucket": fx.bucket, "index": fx.index}) + return map[string]any{"pg": universeDump(t, fx.pool), "index": recoveryIndexReadback(t, fx), "versions": objects.Versions, "delete_markers": objects.DeleteMarkers, "sequences": seq} +} +func r10Unchanged(t *testing.T, fx *writeSetFixture, before map[string]any) { + t.Helper() + after := r10State(t, fx) + r10Save(t, "before", before) + r10Save(t, "after", after) + if !reflect.DeepEqual(before, after) { + t.Fatal("rejected contract changed rows, ES CAS, exact object versions or sequence state") + } +} +func r10Sequences(t *testing.T, fx *writeSetFixture) { + r10Exec(t, fx, `CREATE SEQUENCE chunks_seq_id_seq; ALTER TABLE chunks ADD COLUMN seq_id bigint NOT NULL DEFAULT nextval('chunks_seq_id_seq'); CREATE UNIQUE INDEX r10_chunks_seq ON chunks(seq_id); + CREATE SEQUENCE knowledge_tags_seq_id_seq; ALTER TABLE knowledge_tags ADD COLUMN seq_id bigint NOT NULL DEFAULT nextval('knowledge_tags_seq_id_seq'); CREATE UNIQUE INDEX r10_tags_seq ON knowledge_tags(seq_id); + CREATE SEQUENCE wiki_log_entries_id_seq; ALTER TABLE wiki_log_entries ALTER COLUMN id SET DEFAULT nextval('wiki_log_entries_id_seq'); ALTER SEQUENCE wiki_log_entries_id_seq OWNED BY wiki_log_entries.id; ALTER TABLE wiki_log_entries ADD PRIMARY KEY(id); + INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id) VALUES('tag-other',10001,'kb-other'); INSERT INTO wiki_log_entries(tenant_id,knowledge_base_id) VALUES(10001,'kb-other')`) +} +func r10LocalRows(parts map[string][]map[string]any) { + parts["chunks"][0]["seq_id"] = 10 + parts["knowledge_tags"] = []map[string]any{{"id": "tag-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "seq_id": 10}} + parts["wiki_log_entries"] = []map[string]any{{"id": 100, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB}, {"id": 2, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB}} +} +func TestR10SequenceRejectionIsolated(t *testing.T) { + for _, table := range []string{"chunks", "knowledge_tags", "wiki_log_entries"} { + for _, mode := range []string{"behind", "exhausted", "explicit-null"} { + t.Run(table+"-"+mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + r10Sequences(t, fx) + column := "seq_id" + if table == "wiki_log_entries" { + column = "id" + } + sequence := table + "_" + column + "_seq" + if mode == "behind" { + r10Exec(t, fx, fmt.Sprintf("SELECT setval('%s',1,false)", sequence)) + } + if mode == "exhausted" { + r10Exec(t, fx, fmt.Sprintf("SELECT setval('%s',9223372036854775807,true)", sequence)) + } + snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { + r10LocalRows(parts) + if mode == "explicit-null" { + parts[table][0][column] = nil + } + }) + before := r10State(t, fx) + target := fx.target(t) + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + r10Save(t, "outcome", result) + if result.State != "failed" || result.FailedAt != "" { + t.Fatalf("must reject before a business stage: %+v", result) + } + r10Unchanged(t, fx, before) + }) + } + } +} +func TestR10SequenceOrderingReplayIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + r10Sequences(t, fx) + r10Exec(t, fx, `ALTER TABLE chunks ADD COLUMN chunk_index integer DEFAULT 0; ALTER TABLE knowledge_tags ADD COLUMN sort_order integer DEFAULT 0; ALTER TABLE knowledge_tags ADD COLUMN created_at timestamptz DEFAULT '2026-01-01T00:00:00Z'`) + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { + r10LocalRows(parts) + parts["chunks"][0]["seq_id"] = 100 + parts["chunks"][0]["chunk_index"] = 0 + parts["chunks"] = append(parts["chunks"], map[string]any{"id": "chunk-src-2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "knowledge_id": "doc-src", "content": "second chunk", "seq_id": 2, "chunk_index": 1}) + parts["knowledge_tags"][0]["seq_id"] = 100 + parts["knowledge_tags"] = append(parts["knowledge_tags"], map[string]any{"id": "tag-src-2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "seq_id": 2}) + for _, row := range parts["knowledge_tags"] { + row["sort_order"] = 0 + row["created_at"] = "2026-01-01T00:00:00Z" + } + }) + target := fx.target(t) + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if result.State != "succeeded" { + t.Fatalf("normal allocation: %+v", result) + } + r10Save(t, "plan", result.Backup.WriteSet) + var newest, older int64 + if e := fx.pool.QueryRow(fx.ctx, `SELECT max(id),min(id) FROM wiki_log_entries WHERE knowledge_base_id='kb-target'`).Scan(&newest, &older); e != nil { + t.Fatal(e) + } + if newest <= older { + t.Fatal("numeric log ordering collapsed") + } + var cursor int64 + if e := fx.pool.QueryRow(fx.ctx, `SELECT id FROM wiki_log_entries WHERE knowledge_base_id='kb-target' AND id<$1 ORDER BY id DESC LIMIT 1`, newest).Scan(&cursor); e != nil || cursor != older { + t.Fatal("consumer cursor order", e) + } + mapped := map[string]string{} + for _, m := range result.Backup.WriteSet.LocalIDs { + if m.Table == "wiki_log_entries" { + mapped[m.Source] = m.Target + } + } + if mapped["100"] != fmt.Sprint(newest) || mapped["2"] != fmt.Sprint(older) { + t.Fatal("mapping used lexical instead of numeric order") + } + var tagOrder, chunkOrder []string + if e := fx.pool.QueryRow(fx.ctx, `SELECT array_agg(id ORDER BY sort_order ASC, created_at DESC, seq_id DESC) FROM knowledge_tags WHERE knowledge_base_id='kb-target'`).Scan(&tagOrder); e != nil { + t.Fatal(e) + } + if e := fx.pool.QueryRow(fx.ctx, `SELECT array_agg(id ORDER BY chunk_index ASC) FROM chunks WHERE knowledge_base_id='kb-target'`).Scan(&chunkOrder); e != nil { + t.Fatal(e) + } + wantTags := []string{expectedTargetID(wsTargetTenant, wsTargetKB, "knowledge_tags", "tag-src"), + expectedTargetID(wsTargetTenant, wsTargetKB, "knowledge_tags", "tag-src-2")} + wantChunks := []string{expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-src"), + expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-src-2")} + if !reflect.DeepEqual(tagOrder, wantTags) || !reflect.DeepEqual(chunkOrder, wantChunks) { + t.Fatal("application sort changed after numeric remapping", tagOrder, chunkOrder) + } + for _, m := range result.Backup.WriteSet.LocalIDs { + if m.Table == "chunks" { + var id string + if e := fx.pool.QueryRow(fx.ctx, `SELECT id FROM chunks WHERE tenant_id=$1 AND seq_id=$2::bigint`, wsTargetTenant, m.Target).Scan(&id); e != nil || (m.Source == "100" && id != expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-src")) || (m.Source == "2" && id != expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-src-2")) { + t.Fatal("seq-ID consumer disagrees with frozen map", e) + } + } + } + r10Save(t, "consumer-orders", map[string]any{"tags": tagOrder, "chunks": chunkOrder, "wiki_desc": []int64{newest, older}, "wiki_cursor": cursor}) + published := r10State(t, fx) + next := fx.target(t) + if e := next.AdoptWriteSet(*result.Backup.WriteSet); e != nil { + t.Fatal(e) + } + for _, stage := range libraryrelease.Stages() { + if e := next.Apply(fx.ctx, stage, snapshot); e != nil { + t.Fatal(e) + } + } + r10Unchanged(t, fx, published) + if e := next.Restore(fx.ctx, result.Backup); e != nil { + t.Fatal(e) + } + if !reflect.DeepEqual(before, universeDump(t, fx.pool)) { + t.Fatal("rollback changed original local numbers") + } + if !reflect.DeepEqual(published["sequences"], r10State(t, fx)["sequences"]) { + t.Fatal("rollback rewound sequences") + } +} +func TestR10SourceSchemaBoundIsolated(t *testing.T) { + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, embeddingDimension: 1024}) + seedTargetData(t, fx) + r10Sequences(t, fx) + fx.indexDoc(t, "chunk-target", wsTargetTenant, wsTargetKB, "doc-target", "图:resource://"+wsHandleTarget) + before := r10State(t, fx) + pg, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}) + if e != nil { + t.Fatal(e) + } + target := fx.target(t) + es, e := target.Search().ExportLibrary(fx.ctx, SearchIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}, 100) + if e != nil { + t.Fatal(e) + } + archive, e := librarysnapshot.Open(fx.archiveRoot, 128*1024*1024) + if e != nil { + t.Fatal(e) + } + defer archive.Close() + contract := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256} + id, e := ArchiveLibraryCandidate(fx.ctx, archive, "internal", PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}, contract, pg, es, fx.objects, time.Now().UTC()) + if e != nil { + t.Fatal(e) + } + manifest, e := archive.Load(id) + if e != nil { + t.Fatal(e) + } + r10Save(t, "manifest", manifest) + bound := false + for _, part := range manifest.Parts { + if part.Kind == "schema" && part.Name == "migration-catalog" { + bound = true + } + } + r10Unchanged(t, fx, before) + if !bound { + t.Fatal("captured source has no snapshot-bound schema catalog") + } + if _, e := target.preflightMigrationCatalog(fx.ctx, archive, manifest); e != nil { + t.Fatal("matching source schema rejected", e) + } + r10Exec(t, fx, `ALTER TABLE chunks ADD COLUMN r10_drift text`) + drifted := r10State(t, fx) + if _, e := target.preflightMigrationCatalog(fx.ctx, archive, manifest); e == nil || !strings.Contains(e.Error(), "source/target schema catalog mismatch") { + t.Fatal("source schema drift not rejected", e) + } else { + r10Save(t, "schema-drift-rejection", e.Error()) + } + r10Unchanged(t, fx, drifted) +} diff --git a/internal/releaseadapter/v071/data_matrix_r11_test.go b/internal/releaseadapter/v071/data_matrix_r11_test.go new file mode 100644 index 0000000..d79733b --- /dev/null +++ b/internal/releaseadapter/v071/data_matrix_r11_test.go @@ -0,0 +1,406 @@ +package v071 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "reflect" + "sort" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "knowledge-governance/internal/libraryrelease" +) + +type r11Column struct { + Table string `json:"table_name"` + Name string `json:"column_name"` + Type string `json:"type"` + Default string `json:"default_expr"` + Required bool `json:"not_null"` +} +type r11Catalog struct { + Columns []r11Column `json:"columns"` + Constraints []struct { + Table string `json:"table_name"` + Name string `json:"name"` + Definition string `json:"definition"` + } `json:"constraints"` + Indexes []struct { + Name string `json:"name"` + Definition string `json:"definition"` + } `json:"indexes"` + Sequences []struct { + Name string `json:"sequence"` + Start int64 `json:"seqstart"` + } `json:"sequences"` +} + +func r11CatalogData(t *testing.T) r11Catalog { + t.Helper() + raw, e := os.ReadFile("testdata/catalog-v071-r11.json") + if e != nil { + t.Fatal(e) + } + var c r11Catalog + if e = json.Unmarshal(raw, &c); e != nil { + t.Fatal(e) + } + return c +} +func r11Fill(t *testing.T, fx *writeSetFixture, table string, row map[string]any) map[string]any { + t.Helper() + if table == "resources" && row["location_hash"] == nil { + sum := sha256.Sum256([]byte(fmt.Sprint(row["physical_path"]))) + row["location_hash"] = hex.EncodeToString(sum[:]) + } + for _, c := range r11CatalogData(t).Columns { + if c.Table != table { + continue + } + if v, ok := row[c.Name]; ok && (v != nil || !c.Required) { + continue + } + expr := c.Default + if c.Name == "seq_id" { + expr = "10" + } + if table == "wiki_log_entries" && c.Name == "id" { + expr = "100" + } + if expr == "" { + if !c.Required { + row[c.Name] = nil + continue + } + switch c.Type { + case "bigint", "integer": + expr = "0" + case "boolean": + expr = "false" + default: + expr = "''" + } + } + var raw []byte + if e := fx.pool.QueryRow(fx.ctx, "SELECT to_jsonb(("+expr+")::"+c.Type+")").Scan(&raw); e != nil { + t.Fatal(table, c.Name, e) + } + var v any + dec := json.NewDecoder(strings.NewReader(string(raw))) + dec.UseNumber() + if e := dec.Decode(&v); e != nil { + t.Fatal(e) + } + row[c.Name] = v + } + raw, e := json.Marshal(row) + if e != nil { + t.Fatal(e) + } + var canonical []byte + if e = fx.pool.QueryRow(fx.ctx, "SELECT to_jsonb(jsonb_populate_record(NULL::"+table+",$1::jsonb))", raw).Scan(&canonical); e != nil { + t.Fatal(e) + } + dec := json.NewDecoder(strings.NewReader(string(canonical))) + dec.UseNumber() + if e = dec.Decode(&row); e != nil { + t.Fatal(e) + } + return row +} +func r11Insert(t *testing.T, fx *writeSetFixture, table string, row map[string]any) { + t.Helper() + r11Fill(t, fx, table, row) + keys := []string{} + for k := range row { + keys = append(keys, k) + } + sort.Strings(keys) + cols := []string{} + for _, k := range keys { + cols = append(cols, pgx.Identifier{k}.Sanitize()) + } + raw, e := json.Marshal(row) + if e != nil { + t.Fatal(e) + } + if _, e = fx.pool.Exec(fx.ctx, "INSERT INTO "+table+"("+strings.Join(cols, ",")+") SELECT "+strings.Join(cols, ",")+" FROM jsonb_populate_record(NULL::"+table+",$1::jsonb)", raw); e != nil { + t.Fatal(table, e) + } +} + +// Reconstruct only the ten migration tables from preserved real v071 catalog. +// The grant table is an inbound-FK fixture, not a claimed whole business mirror. +func r11Mirror(t *testing.T, fx *writeSetFixture) { + t.Helper() + old := universeDump(t, fx.pool) + c := r11CatalogData(t) + r10Exec(t, fx, `CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; CREATE EXTENSION IF NOT EXISTS pg_trgm; DROP TABLE IF EXISTS resource_access_grants CASCADE; DROP TABLE `+strings.Join(productionLibraryTables, ",")+` CASCADE`) + for _, s := range c.Sequences { + r10Exec(t, fx, fmt.Sprintf("CREATE SEQUENCE %s START %d", s.Name, s.Start)) + } + for _, table := range productionLibraryTables { + defs := []string{} + for _, col := range c.Columns { + if col.Table != table { + continue + } + d := pgx.Identifier{col.Name}.Sanitize() + " " + col.Type + if col.Required { + d += " NOT NULL" + } + if col.Default != "" { + d += " DEFAULT " + col.Default + } + defs = append(defs, d) + } + r10Exec(t, fx, "CREATE TABLE "+table+"("+strings.Join(defs, ",")+")") + } + r10Exec(t, fx, `ALTER SEQUENCE wiki_log_entries_id_seq OWNED BY wiki_log_entries.id; CREATE TABLE resource_access_grants(id text,resource_id varchar(36))`) + names := map[string]bool{} + sort.SliceStable(c.Constraints, func(i, j int) bool { + return !strings.HasPrefix(c.Constraints[i].Definition, "FOREIGN KEY") && strings.HasPrefix(c.Constraints[j].Definition, "FOREIGN KEY") + }) + for _, constraint := range c.Constraints { + r10Exec(t, fx, "ALTER TABLE "+constraint.Table+" ADD CONSTRAINT "+constraint.Name+" "+constraint.Definition) + names[constraint.Name] = true + } + for _, index := range c.Indexes { + if !names[index.Name] { + r10Exec(t, fx, index.Definition) + } + } + n := int64(100000000) + for _, table := range []string{"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", "resources", "resource_bindings", "wiki_folders", "wiki_pages", "wiki_page_issues", "wiki_log_entries"} { + for _, raw := range old[table] { + row := map[string]any{} + dec := json.NewDecoder(strings.NewReader(raw)) + dec.UseNumber() + if e := dec.Decode(&row); e != nil { + t.Fatal(e) + } + allowed := map[string]bool{} + for _, col := range c.Columns { + if col.Table == table { + allowed[col.Name] = true + } + } + for k := range row { + if !allowed[k] { + delete(row, k) + } + } + if table == "chunks" || table == "knowledge_tags" { + n++ + row["seq_id"] = n + } + r11Insert(t, fx, table, row) + } + } + r10Exec(t, fx, fmt.Sprintf("SELECT setval('chunks_seq_id_seq',%d,true);SELECT setval('knowledge_tags_seq_id_seq',%d,true)", n, n)) +} +func r11Source(t *testing.T, fx *writeSetFixture, tweak func(map[string][]map[string]any)) string { + return sealSourceSnapshot(t, fx, func(p map[string][]map[string]any) { + p["knowledge_tags"] = []map[string]any{{"id": "tag-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "name": "source-tag"}} + p["knowledge_tag_relations"] = []map[string]any{{"knowledge_id": "doc-src", "tag_id": "tag-src"}} + p["wiki_folders"] = []map[string]any{{"id": "folder-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "name": "folder", "parent_id": ""}} + p["wiki_pages"][0]["folder_id"] = "folder-src" + p["wiki_page_issues"] = []map[string]any{{"id": "issue-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "slug": "index", "issue_type": "review", "reported_by": "fixture", "description": "example"}} + p["wiki_log_entries"] = []map[string]any{{"id": 100, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "action": "ingest", "knowledge_id": "doc-src", "pages_affected": []any{map[string]any{"slug": "index", "title": "historic title"}}}} + if tweak != nil { + tweak(p) + } + for table, rows := range p { + for _, row := range rows { + r11Fill(t, fx, table, row) + } + } + }) +} +func r11RejectNatural(t *testing.T, fx *writeSetFixture, snapshot string) { + t.Helper() + before := r10State(t, fx) + target := fx.target(t) + out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + r10Save(t, "outcome", out) + if out.State != "failed" || out.FailedAt != "" { + t.Errorf("expected pre-stage rejection: %+v", out) + } + r10Unchanged(t, fx, before) +} + +func r11Reject(t *testing.T, fx *writeSetFixture, snapshot, table, sourceID string) { + t.Helper() + before := r10State(t, fx) + var beforeRow string + if e := fx.pool.QueryRow(fx.ctx, `SELECT to_jsonb(x)::text FROM `+table+` AS x WHERE id=$1`, sourceID).Scan(&beforeRow); e != nil { + t.Fatalf("read foreign row before publish: %v", e) + } + beforeState := map[string]string{"row:" + table: beforeRow} + target := fx.target(t) + out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + r10Save(t, "outcome", out) + if table == "resources" { + // 资源是共享字节,不参与 UUID 映射:同 ID 属于他库必须继续拒绝。 + if out.State != "failed" || out.FailedAt != "" { + t.Errorf("shared resource id collision must be rejected pre-stage: %+v", out) + } + r10Unchanged(t, fx, before) + return + } + if out.State != "succeeded" { + t.Fatalf("mapped identity publish should succeed: %+v", out) + } + // 旧库原行必须保留,且计划里不得再出现源 ID。 + for _, row := range out.Backup.WriteSet.Rows { + if row.Table == table && row.ID == sourceID { + t.Fatalf("writeset still carries source identity %s/%s", table, sourceID) + } + } + mapped := expectedTargetID(wsTargetTenant, wsTargetKB, table, sourceID) + var foreign, targetRows int + if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM `+table+` WHERE id=$1`, sourceID).Scan(&foreign); e != nil || foreign != 1 { + t.Fatalf("foreign row %s/%s changed or lost: %d %v", table, sourceID, foreign, e) + } + // 旧库行必须逐列字节不变(不只是"还在")。 + beforeRow, afterRow := "", "" + if e := fx.pool.QueryRow(fx.ctx, `SELECT to_jsonb(x)::text FROM `+table+` AS x WHERE id=$1`, sourceID).Scan(&afterRow); e != nil { + t.Fatalf("read foreign row %s: %v", table, e) + } + beforeRow = beforeState["row:"+table] + if beforeRow != "" && beforeRow != afterRow { + t.Fatalf("foreign row %s/%s content changed", table, sourceID) + } + if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM `+table+` WHERE id=$1`, mapped).Scan(&targetRows); e != nil || targetRows != 1 { + t.Fatalf("mapped row %s/%s missing: %d %v", table, mapped, targetRows, e) + } + if tablesWithKB[table] { + var tenant int64 + var kb string + if e := fx.pool.QueryRow(fx.ctx, `SELECT tenant_id, knowledge_base_id FROM `+table+` WHERE id=$1`, mapped).Scan(&tenant, &kb); e != nil || tenant != int64(wsTargetTenant) || kb != wsTargetKB { + t.Fatalf("mapped row %s landed at %d/%s", table, tenant, kb) + } + } +} +func TestR11StableIdentityMatrixIsolated(t *testing.T) { + for _, table := range []string{"knowledges", "chunks", "knowledge_tags", "resources", "resource_bindings", "wiki_folders", "wiki_pages", "wiki_page_issues"} { + for _, foreign := range []string{"same-tenant-other-kb", "other-tenant"} { + t.Run(table+"/"+foreign, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + r11Mirror(t, fx) + tenant := uint64(wsTargetTenant) + kb := wsOtherKB + if foreign == "other-tenant" { + tenant = 10003 + kb = "kb-alien" + } + id := map[string]string{"knowledges": "doc-src", "chunks": "chunk-src", "knowledge_tags": "tag-src", "resources": "res-src", "resource_bindings": "bind-src", "wiki_folders": "folder-src", "wiki_pages": "wiki-src", "wiki_page_issues": "issue-src"}[table] + row := map[string]any{"id": id, "tenant_id": tenant, "knowledge_base_id": kb} + switch table { + case "chunks": + row["knowledge_id"] = "doc-other" + case "resources": + delete(row, "knowledge_base_id") + row["handle"] = strings.Repeat("x", 22) + row["provider"] = "minio" + row["physical_path"] = "outside" + row["location_hash"] = "outside" + case "resource_bindings": + delete(row, "knowledge_base_id") + row["resource_id"] = "res-other" + row["owner_type"] = "knowledge" + row["owner_id"] = "doc-other" + row["relation"] = "preview" + case "wiki_pages", "wiki_page_issues": + row["slug"] = "foreign" + } + r11Insert(t, fx, table, row) + snapshot := r11Source(t, fx, nil) + r11Reject(t, fx, snapshot, table, id) + }) + } + } +} +func TestR11NaturalKeyMatrixIsolated(t *testing.T) { + for _, mode := range []string{"valid", "tag-name", "tag-name-soft-deleted", "binding-tuple", "folder-name", "folder-deleted-positive", "folder-parent-distinct-positive", "page-slug", "page-deleted-positive", "resource-handle", "resource-location", "resource-location-deleted-positive", "physical-key"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + r11Mirror(t, fx) + if mode == "resource-handle" { + r10Exec(t, fx, `UPDATE resources SET handle='`+wsHandleSource+`' WHERE id='res-other'`) + } + if strings.HasPrefix(mode, "resource-location") { + path := wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, "res-src") + sum := sha256.Sum256([]byte(path)) + deleted := "NULL" + if strings.HasSuffix(mode, "positive") { + deleted = "now()" + } + r10Exec(t, fx, `UPDATE resources SET location_hash='`+hex.EncodeToString(sum[:])+`',deleted_at=`+deleted+` WHERE id='res-other'`) + } + if mode == "physical-key" { + if e := fx.objects.s3.Put(fx.ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, "res-src"), strings.NewReader("foreign-data"), 12); e != nil { + t.Fatal(e) + } + } + snapshot := r11Source(t, fx, func(p map[string][]map[string]any) { + table := "" + switch mode { + case "tag-name", "tag-name-soft-deleted": + table = "knowledge_tags" + case "binding-tuple": + table = "resource_bindings" + case "folder-name", "folder-deleted-positive", "folder-parent-distinct-positive": + table = "wiki_folders" + case "page-slug", "page-deleted-positive": + table = "wiki_pages" + } + if table == "" { + return + } + cp := map[string]any{} + for k, v := range p[table][0] { + cp[k] = v + } + cp["id"] = cp["id"].(string) + "-second" + if table == "knowledge_tags" { + cp["seq_id"] = 11 + } + if strings.Contains(mode, "deleted") { + cp["deleted_at"] = "2026-01-01T00:00:00Z" + } + if mode == "folder-parent-distinct-positive" { + cp["parent_id"] = "folder-src" + } + p[table] = append(p[table], cp) + }) + if mode != "valid" && !strings.HasSuffix(mode, "positive") { + r11RejectNatural(t, fx, snapshot) + return + } + before := r10State(t, fx) + target := fx.target(t) + out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + r10Save(t, "outcome", out) + if out.State != "succeeded" { + t.Fatalf("normal admitted data must succeed: %+v", out) + } + if e := target.Restore(fx.ctx, out.Backup); e != nil { + t.Fatal(e) + } + after := r10State(t, fx) + for _, key := range []string{"pg", "versions", "delete_markers"} { + if !reflect.DeepEqual(before[key], after[key]) { + t.Fatal("restore changed", key) + } + } + r10Save(t, "restored", after) + }) + } +} diff --git a/internal/releaseadapter/v071/data_orphan_r13_test.go b/internal/releaseadapter/v071/data_orphan_r13_test.go new file mode 100644 index 0000000..4371454 --- /dev/null +++ b/internal/releaseadapter/v071/data_orphan_r13_test.go @@ -0,0 +1,71 @@ +package v071 + +import ( + "fmt" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// B21:孤儿校验的三条"不许假绿"路径——索引文档缺 knowledge_id、未知 knowledge_id +// 必须如实报孤儿、以及查询在迭代中途失败时必须冒泡成错误(而不是"没有孤儿")。 +func TestR13OrphanOracleRejectsMalformedAndUnknownDocumentsIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + target := fx.target(t) + // 1) 缺 knowledge_id:必须报错,不能当作"无孤儿"。 + broken := []SearchDocument{{ID: "chunk-broken", Source: []byte(`{"chunk_id":"chunk-broken","content":"x"}`)}} + if _, err := target.orphanIndexDocuments(fx.ctx, broken); err == nil || + !strings.Contains(err.Error(), "knowledge_id") { + t.Fatalf("缺失 knowledge_id 未被判为错误:%v", err) + } + // 2) knowledge_id 指向本次范围外的文档:必须如实列出孤儿,而不是被静默忽略。 + unknown := []SearchDocument{{ID: "chunk-unknown", Source: []byte(`{"chunk_id":"chunk-unknown","knowledge_id":"doc-not-in-scope"}`)}} + orphans, err := target.orphanIndexDocuments(fx.ctx, unknown) + if err != nil { + t.Fatalf("未知 knowledge_id 不应变成基础设施错误:%v", err) + } + if len(orphans) != 1 || orphans[0] != "chunk-unknown" { + t.Fatalf("孤儿列表 = %v,want [chunk-unknown]", orphans) + } + // 3) 范围内文档不能被误报成孤儿。 + known := []SearchDocument{{ID: "chunk-target", Source: []byte(`{"chunk_id":"chunk-target","knowledge_id":"doc-target"}`)}} + if orphans, err := target.orphanIndexDocuments(fx.ctx, known); err != nil || len(orphans) != 0 { + t.Fatalf("正常文档被误报:%v %v", orphans, err) + } + r10Save(t, "orphan-paths", map[string]any{"missing_knowledge_id": "rejected", "unknown_reported": orphans}) +} + +// B21:真实驱动层失败(数据库 statement timeout 让 SELECT 在迭代中途中断)必须 +// 返回错误。这条替换"用假 rows 造 Scan 错误"的做法:错误来自真实 PG。 +func TestR13OrphanOraclePropagatesDriverFailureIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + // 足够多的行,保证 SELECT 一定超过下面的超时。 + r10Exec(t, fx, `INSERT INTO knowledges(id,tenant_id,knowledge_base_id,parse_status,pending_subtasks_count,file_path,deleted_at) + SELECT 'bulk-'||i, 10001, 'kb-target', 'completed', 0, '', NULL FROM generate_series(1,200000) i`) + dbName := fx.pool.Config().ConnConfig.Database + r10Exec(t, fx, fmt.Sprintf(`ALTER DATABASE "%s" SET statement_timeout = '5ms'`, dbName)) + t.Cleanup(func() { + if _, err := fx.pool.Exec(fx.ctx, fmt.Sprintf(`ALTER DATABASE "%s" RESET statement_timeout`, dbName)); err != nil { + t.Logf("reset statement_timeout: %v", err) + } + }) + // ALTER DATABASE 只影响新会话:用一条新连接池执行被测查询。 + slowPool, err := pgxpool.New(fx.ctx, fx.pool.Config().ConnString()) + if err != nil { + t.Fatalf("open timing pool: %v", err) + } + defer slowPool.Close() + target := fx.target(t) + original := target.pool + target.pool = slowPool + defer func() { target.pool = original }() + documents := []SearchDocument{{ID: "chunk-target", Source: []byte(`{"chunk_id":"chunk-target","knowledge_id":"doc-target"}`)}} + if _, err := target.orphanIndexDocuments(fx.ctx, documents); err == nil { + t.Fatal("数据库迭代失败被当成'没有孤儿'") + } else { + r10Save(t, "orphan-driver-error", err.Error()) + } +} diff --git a/internal/releaseadapter/v071/data_resource_restore_r10_test.go b/internal/releaseadapter/v071/data_resource_restore_r10_test.go new file mode 100644 index 0000000..c173d10 --- /dev/null +++ b/internal/releaseadapter/v071/data_resource_restore_r10_test.go @@ -0,0 +1,42 @@ +package v071 + +import ( + "knowledge-governance/internal/libraryrelease" + "testing" +) + +func TestR10RestoreForeignResourceReferencesIsolated(t *testing.T) { + for _, mode := range []string{"unknown-binding", "foreign-wiki-body", "foreign-knowledge-metadata"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + r10Exec(t, fx, `ALTER TABLE knowledges ADD COLUMN metadata jsonb`) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if result.State != "succeeded" { + t.Fatalf("prepare publication: %+v", result) + } + switch mode { + case "unknown-binding": + r10Exec(t, fx, `INSERT INTO resource_bindings(id,tenant_id,resource_id,owner_type,owner_id) VALUES('binding-unknown',10001,'res-src','unknown','outside-owner')`) + case "foreign-wiki-body": + if _, e := fx.pool.Exec(fx.ctx, `INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,content) VALUES('foreign-wiki',10001,'kb-other','foreign',$1)`, "![external](resource://"+wsHandleSource+")"); e != nil { + t.Fatal(e) + } + case "foreign-knowledge-metadata": + if _, e := fx.pool.Exec(fx.ctx, `UPDATE knowledges SET metadata=jsonb_build_object('image_info',jsonb_build_object('url',$1::text)) WHERE id='doc-other'`, "resource://"+wsHandleSource); e != nil { + t.Fatal(e) + } + } + before := r10State(t, fx) + e := target.Restore(fx.ctx, result.Backup) + if e == nil { + t.Error("restore deleted a resource with an out-of-plan reference") + } else { + r10Save(t, "held", e.Error()) + } + r10Unchanged(t, fx, before) + }) + } +} diff --git a/internal/releaseadapter/v071/data_schema_r11_test.go b/internal/releaseadapter/v071/data_schema_r11_test.go new file mode 100644 index 0000000..fa04403 --- /dev/null +++ b/internal/releaseadapter/v071/data_schema_r11_test.go @@ -0,0 +1,188 @@ +package v071 + +import ( + "encoding/json" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" + "os" + "reflect" + "strings" + "testing" + "time" +) + +func TestR11CatalogBindingIsolated(t *testing.T) { + for _, mode := range []string{"matching", "default", "unique-predicate", "sequence-definition", "sequence-ownership", "incoming-fk", "outgoing-fk", "internal-local-fk", "generated", "trigger"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, embeddingDimension: 1024}) + seedTargetData(t, fx) + r11Mirror(t, fx) + target := fx.target(t) + pg, e := ExportLibrary(fx.ctx, fx.pool, PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}) + if e != nil { + t.Fatal(e) + } + catalog, digest, e := target.migrationCatalog(fx.ctx) + if e != nil { + t.Fatal(e) + } + if !reflect.DeepEqual(catalog, pg.Catalog) { + t.Fatal("captured source and target catalogs differ") + } + expected := r11CatalogData(t) + var cols []r11Column + if e = json.Unmarshal(catalog["columns"], &cols); e != nil { + t.Fatal(e) + } + if !reflect.DeepEqual(cols, expected.Columns) { + t.Fatal("real v071 columns/defaults/types differ from reconstructed target") + } + var indexes []map[string]any + json.Unmarshal(catalog["indexes"], &indexes) + if len(indexes) != len(expected.Indexes) { + t.Fatal("missing actual indexes") + } + expectedRaw, e := os.ReadFile("testdata/catalog-v071-r11.json") + if e != nil { + t.Fatal(e) + } + var original map[string]json.RawMessage + json.Unmarshal(expectedRaw, &original) + for _, kind := range []string{"columns", "constraints", "indexes", "triggers", "relations"} { + var a, b any + json.Unmarshal(original[kind], &a) + json.Unmarshal(catalog[kind], &b) + if !reflect.DeepEqual(a, b) { + t.Fatal("catalog mismatch", kind) + } + } + r10Save(t, "source-catalog", pg.Catalog) + r10Save(t, "schema-digest", digest) + es, e := target.Search().ExportLibrary(fx.ctx, SearchIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}, 100) + if e != nil { + t.Fatal(e) + } + archive, e := librarysnapshot.Open(fx.archiveRoot, 128*1024*1024) + if e != nil { + t.Fatal(e) + } + defer archive.Close() + compatibility := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256} + snapshot, e := ArchiveLibraryCandidate(fx.ctx, archive, "internal", PostgresIdentity{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}, compatibility, pg, es, fx.objects, time.Now().UTC()) + if e != nil { + t.Fatal(e) + } + if mode == "matching" { + before := r10State(t, fx) + manifest, e := archive.Load(snapshot) + if e != nil { + t.Fatal(e) + } + got, e := target.preflightMigrationCatalog(fx.ctx, archive, manifest) + if e != nil || got != digest { + t.Fatal(got, e) + } + r10Unchanged(t, fx, before) + return + } + statements := map[string]string{ + "default": `ALTER TABLE chunks ALTER COLUMN flags SET DEFAULT 7`, + "unique-predicate": `DROP INDEX idx_wiki_pages_kb_slug;CREATE UNIQUE INDEX idx_wiki_pages_kb_slug ON wiki_pages(knowledge_base_id,slug) WHERE deleted_at IS NOT NULL`, + "sequence-definition": `ALTER SEQUENCE chunks_seq_id_seq INCREMENT 2`, + "sequence-ownership": `ALTER SEQUENCE chunks_seq_id_seq OWNED BY chunks.seq_id`, + "incoming-fk": `CREATE TABLE outside_cursor(log_id bigint REFERENCES wiki_log_entries(id))`, + "outgoing-fk": `CREATE TABLE outside_models(id varchar(64) PRIMARY KEY);ALTER TABLE knowledges ADD FOREIGN KEY(embedding_model_id) REFERENCES outside_models(id)`, + "internal-local-fk": `ALTER TABLE wiki_page_issues ADD COLUMN log_id bigint REFERENCES wiki_log_entries(id)`, + "generated": `ALTER TABLE wiki_pages ADD COLUMN lower_slug text GENERATED ALWAYS AS(lower(slug)) STORED`, + "trigger": `CREATE FUNCTION r11_noop() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END';CREATE TRIGGER r11_noop BEFORE INSERT ON wiki_pages FOR EACH ROW EXECUTE FUNCTION r11_noop()`, + } + r10Exec(t, fx, statements[mode]) + r11RejectNatural(t, fx, snapshot) + // An identically extended source/target must not make an unreviewed FK safe. + if strings.Contains(mode, "fk") { + now, _, e := target.migrationCatalog(fx.ctx) + if e != nil { + t.Fatal(e) + } + if e = validateMigrationCatalog(now); e == nil { + t.Fatal("unreviewed FK admitted when both sides match") + } + r10Save(t, "unknown-fk-rejection", e.Error()) + } + }) + } +} +func TestR11ReferenceAndCursorIsolated(t *testing.T) { + for _, mode := range []string{"valid", "linked-valid", "legacy-pages", "historical-log", "chunk-parent", "chunk-pre", "chunk-next", "chunk-tag", "wiki-folder", "folder-parent", "folder-cycle", "wiki-source", "wiki-chunk", "log-object-id", "log-array-number"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + r11Mirror(t, fx) + snapshot := r11Source(t, fx, func(p map[string][]map[string]any) { + switch mode { + case "linked-valid": + p["chunks"] = append(p["chunks"], map[string]any{"id": "chunk-src-2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "knowledge_id": "doc-src", "content": "second", "seq_id": 11, "pre_chunk_id": "chunk-src", "parent_chunk_id": "chunk-src"}) + p["chunks"][0]["next_chunk_id"] = "chunk-src-2" + p["chunks"][0]["tag_id"] = "tag-src" + p["wiki_pages"][0]["source_refs"] = []string{"doc-src|Source title"} + p["wiki_pages"][0]["chunk_refs"] = []string{"chunk-src-2"} + p["wiki_pages"][0]["page_metadata"] = map[string]any{"literal_number": 100, "tags": []string{"literal"}} + case "legacy-pages": + p["wiki_log_entries"][0]["pages_affected"] = []string{"index", "historic-removed-page"} + case "historical-log": + p["wiki_log_entries"][0]["knowledge_id"] = "deleted-knowledge" + p["wiki_log_entries"][0]["pages_affected"] = []any{map[string]any{"slug": "deleted-page", "title": "historic"}} + case "chunk-parent": + p["chunks"][0]["parent_chunk_id"] = "chunk-other" + case "chunk-pre": + p["chunks"][0]["pre_chunk_id"] = "chunk-other" + case "chunk-next": + p["chunks"][0]["next_chunk_id"] = "chunk-other" + case "chunk-tag": + p["chunks"][0]["tag_id"] = "tag-outside" + case "wiki-folder": + p["wiki_pages"][0]["folder_id"] = "foreign-folder" + case "folder-parent": + p["wiki_folders"][0]["parent_id"] = "foreign-folder" + case "folder-cycle": + p["wiki_folders"][0]["parent_id"] = "folder-src" + case "wiki-source": + p["wiki_pages"][0]["source_refs"] = []string{"doc-other"} + case "wiki-chunk": + p["wiki_pages"][0]["chunk_refs"] = []string{"chunk-other"} + case "log-object-id": + p["wiki_log_entries"][0]["pages_affected"] = []any{map[string]any{"slug": "index", "log_id": 100}} + case "log-array-number": + p["wiki_log_entries"][0]["pages_affected"] = []int{100} + } + }) + if mode != "valid" && mode != "linked-valid" && mode != "legacy-pages" && mode != "historical-log" { + r11RejectNatural(t, fx, snapshot) + return + } + target := fx.target(t) + out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if out.State != "succeeded" { + t.Fatal(out) + } + var actual int64 + if e := fx.pool.QueryRow(fx.ctx, `SELECT id FROM wiki_log_entries WHERE knowledge_base_id=$1`, wsTargetKB).Scan(&actual); e != nil { + t.Fatal(e) + } + var sourceCursor, validCursor int + if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM wiki_log_entries WHERE knowledge_base_id=$1 AND id<100`, wsTargetKB).Scan(&sourceCursor); e != nil { + t.Fatal(e) + } + if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM wiki_log_entries WHERE knowledge_base_id=$1 AND id<$2`, wsTargetKB, actual).Scan(&validCursor); e != nil { + t.Fatal(e) + } + if actual == 100 || sourceCursor == validCursor { + t.Fatal("expected evidence of DB-local old cursor not transferable") + } + r10Save(t, "cursor-boundary", map[string]any{"source_cursor": 100, "mapped_id": actual, "source_cursor_count": sourceCursor, "mapped_cursor_count": validCursor, "policy": "fresh target cursor works; cross-source or pre-replace external cursor is not automatically translated"}) + if e := target.Restore(fx.ctx, out.Backup); e != nil { + t.Fatal(e) + } + }) + } +} diff --git a/internal/releaseadapter/v071/data_state_r12_test.go b/internal/releaseadapter/v071/data_state_r12_test.go new file mode 100644 index 0000000..8a995c8 --- /dev/null +++ b/internal/releaseadapter/v071/data_state_r12_test.go @@ -0,0 +1,284 @@ +package v071 + +import ( + "encoding/json" + "fmt" + "net/http" + "reflect" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// r12 covers the acceptance rows that had an implementation but no executed +// scenario: soft-delete before-image completeness (B09), shared-resource +// difference matrix (B11), foreign index document byte identity (B18), +// independent index oracle on content/vector/metadata (B20) and pre-existing +// object versions across a late failure (B15). + +func r12ESDoc(t *testing.T, fx *writeSetFixture, id string) map[string]any { + t.Helper() + return recoveryIndexReadback(t, fx)[id] +} + +func r12PutDoc(t *testing.T, fx *writeSetFixture, id, chunkID string, tenant uint64, kb, knowledge, content string, embedding []float64) { + t.Helper() + body, err := json.Marshal(map[string]any{"tenant_id": tenant, "knowledge_base_id": kb, + "knowledge_id": knowledge, "chunk_id": chunkID, "source_id": chunkID, "content": content, "embedding": embedding}) + if err != nil { + t.Fatal(err) + } + request, err := http.NewRequestWithContext(fx.ctx, "PUT", + fmt.Sprintf("%s/%s/_doc/%s?refresh=true", fx.searchBase, fx.index, id), strings.NewReader(string(body))) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", "application/json") + response, err := fx.client.Do(request) + if err != nil { + t.Fatalf("put doc: %v", err) + } + defer response.Body.Close() + if response.StatusCode != 200 && response.StatusCode != 201 { + t.Fatalf("put doc %s => %d", id, response.StatusCode) + } +} + +// B09:destructive predicate 能碰到的每一张带 deleted_at 的表都必须进入 +// before-image;晚阶段失败后的恢复要把这些行逐列放回去(不是"恢复活跃行")。 +func TestR12DeletedCascadeBeforeImageAndRestoreIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + for _, statement := range []string{ + `UPDATE knowledges SET deleted_at=now() WHERE id='doc-other'`, + `UPDATE chunks SET deleted_at=now() WHERE id='chunk-other'`, + `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,deleted_at) VALUES('deleted-tag',10001,'kb-target',now())`, + `UPDATE resources SET deleted_at=now() WHERE id='res-orphan'`, + `INSERT INTO wiki_folders(id,tenant_id,knowledge_base_id,deleted_at) VALUES('deleted-folder',10001,'kb-target',now())`, + `INSERT INTO wiki_page_issues(id,tenant_id,knowledge_base_id,deleted_at) VALUES('deleted-issue',10001,'kb-target',now())`, + `UPDATE wiki_pages SET deleted_at=now() WHERE id='wiki-target'`, + } { + r10Exec(t, fx, statement) + } + softDeleted := []string{"knowledges", "chunks", "knowledge_tags", "resources", "wiki_folders", "wiki_page_issues", "wiki_pages"} + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatal(err) + } + backup, err := fx.backups(t, target).Prepare(fx.ctx, "", current) + if err != nil { + t.Fatal(err) + } + archive, err := librarysnapshot.Open(fx.archiveRoot, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + manifest, err := archive.Load(backup.SnapshotID) + if err != nil { + t.Fatal(err) + } + archive.Close() + counts := map[string]int64{} + for _, part := range manifest.Parts { + if part.Kind == "database" || part.Kind == "wiki" { + counts[part.Name] = part.Count + } + } + for _, table := range softDeleted { + if counts[table] != current.Counts[table] { + t.Fatalf("before-image 漏掉 %s 的软删除行:备份 %d 行,删除谓词命中 %d 行", table, counts[table], current.Counts[table]) + } + } + r10Save(t, "deleted-before-image-counts", counts) + + // 晚阶段失败 → 恢复:所有行(含软删除行)逐列回到失败前的样子。 + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, fx.backups(t, target), nil) + if outcome.State != "rolled_back" { + t.Fatalf("late failure must roll back: %+v", outcome) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("rollback did not restore soft-deleted rows exactly: %s", diff) + } + var survivors int + if err := fx.pool.QueryRow(fx.ctx, + `SELECT count(*) FROM knowledge_tags WHERE deleted_at IS NOT NULL AND knowledge_base_id=$1`, wsTargetKB).Scan(&survivors); err != nil { + t.Fatal(err) + } + if survivors != 1 { + t.Fatalf("soft-deleted tag row lost after rollback: %d", survivors) + } +} + +// B18:同 _id 已属其它知识库时,写前拒绝并且那份外部文档的 _source、向量和 +// seq_no/term 一个字节都不能变。 +func TestR12ForeignIndexDocumentStaysByteIdenticalIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + fx.indexDoc(t, "chunk-src", wsTargetTenant, wsOtherKB, "doc-other", "protected foreign vector") + before := r10State(t, fx) + foreignBefore := r12ESDoc(t, fx, "chunk-src") + if foreignBefore == nil { + t.Fatal("foreign document fixture missing") + } + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "failed" || outcome.FailedAt != "" { + t.Fatalf("index collision must fail before any write: %+v", outcome) + } + r10Unchanged(t, fx, before) + foreignAfter := r12ESDoc(t, fx, "chunk-src") + if !reflect.DeepEqual(foreignBefore, foreignAfter) { + t.Fatalf("foreign document changed:\n%v\n->\n%v", foreignBefore, foreignAfter) + } + source, _ := foreignAfter["_source"].(map[string]any) + if source["knowledge_base_id"] != wsOtherKB { + t.Fatalf("foreign document changed owner: %v", source["knowledge_base_id"]) + } + r10Save(t, "foreign-document", foreignAfter) +} + +// B20:发布成功后,正文/向量/metadata 任一被改都必须让独立 oracle 变红; +// 未改动时同一 oracle 必须通过(合法本地列映射不因这项收紧被误杀)。 +func TestR12IndexOracleDetectsContentVectorAndMetadataChangesIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, fx.target(t)), nil) + if outcome.State != "succeeded" { + t.Fatalf("baseline publish failed: %+v", outcome) + } + expect := libraryrelease.Expectation{SnapshotID: snapshot} + if err := target.Verify(fx.ctx, expect); err != nil { + t.Fatalf("baseline oracle must pass: %v", err) + } + docID := expectedIndexID("chunk-src") + chunkID := expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-src") + published := r12ESDoc(t, fx, docID) + if published == nil { + t.Fatal("published document missing") + } + source, _ := published["_source"].(map[string]any) + originalContent, _ := source["content"].(string) + originalEmbedding := source["embedding"] + originalKnowledge, _ := source["knowledge_id"].(string) + + // 1) 正文被改。 + r12PutDoc(t, fx, docID, chunkID, wsTargetTenant, wsTargetKB, originalKnowledge, "被篡改的正文", []float64{0.1, 0.2}) + if err := target.Verify(fx.ctx, expect); err == nil { + t.Fatal("正文篡改没有让独立 oracle 变红") + } + r12PutDoc(t, fx, docID, chunkID, wsTargetTenant, wsTargetKB, originalKnowledge, originalContent, []float64{0.1, 0.2}) + if err := target.Verify(fx.ctx, expect); err != nil { + t.Fatalf("恢复正文后 oracle 必须通过:%v", err) + } + // 2) 向量被改(同维不同值)。 + r12PutDoc(t, fx, docID, chunkID, wsTargetTenant, wsTargetKB, originalKnowledge, originalContent, []float64{0.9, 0.8}) + if err := target.Verify(fx.ctx, expect); err == nil { + t.Fatal("向量篡改没有让独立 oracle 变红") + } + r12PutDoc(t, fx, docID, chunkID, wsTargetTenant, wsTargetKB, originalKnowledge, originalContent, []float64{0.1, 0.2}) + if err := target.Verify(fx.ctx, expect); err != nil { + t.Fatalf("恢复向量后 oracle 必须通过:%v", err) + } + // 3) metadata(knowledge_id)被改。 + r12PutDoc(t, fx, docID, chunkID, wsTargetTenant, wsTargetKB, "doc-target", originalContent, []float64{0.1, 0.2}) + if err := target.Verify(fx.ctx, expect); err == nil { + t.Fatal("metadata 篡改没有让独立 oracle 变红") + } + r12PutDoc(t, fx, docID, chunkID, wsTargetTenant, wsTargetKB, originalKnowledge, originalContent, []float64{0.1, 0.2}) + if err := target.Verify(fx.ctx, expect); err != nil { + t.Fatalf("恢复 metadata 后 oracle 必须通过:%v", err) + } + if !reflect.DeepEqual(originalEmbedding, []any{0.1, 0.2}) && !reflect.DeepEqual(originalEmbedding, []any{0.10000000149011612, 0.20000000298023224}) { + t.Logf("published embedding representation = %v", originalEmbedding) + } +} + +// B15:对象已上传、Wiki 阶段失败时,本次新建对象不得残留,且**已有对象的 +// 精确版本**不能因为回滚而变化。 +func TestR12LateWikiFailureKeepsPreExistingObjectVersionsIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + existing := wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-target") + before, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", existing) + if err != nil || !before.Exists { + t.Fatalf("pre-existing object missing: %+v %v", before, err) + } + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, fx.backups(t, target), nil) + if outcome.State != "rolled_back" || outcome.FailedAt != libraryrelease.StageWiki { + t.Fatalf("late wiki failure: %+v", outcome) + } + if fx.objects.puts.Load() == 0 { + t.Fatal("late failure never reached the real object write") + } + after, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", existing) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(before, after) { + t.Fatalf("pre-existing object version changed across rollback: %+v -> %+v", before, after) + } + created, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", + wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-src")) + if err != nil || created.Exists { + t.Fatalf("created object residue after rollback: %+v %v", created, err) + } + r10Save(t, "object-versions", map[string]any{"existing_before": before, "existing_after": after}) +} + +// B11:同 ID 共享资源在 handle / 定位 / 字节 三类差异下都必须写前拒绝, +// 并且其它知识库看到的字节与版本不变。 +func TestR12SharedResourceDifferenceMatrixIsolated(t *testing.T) { + for _, mode := range []string{"handle", "locator", "bytes"} { + t.Run(mode, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + sharedPath := wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-shared") + sharedBefore, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", sharedPath) + if err != nil || !sharedBefore.Exists { + t.Fatalf("shared object missing: %+v %v", sharedBefore, err) + } + row := map[string]any{"id": "res-shared", "handle": wsHandleShared, "tenant_id": wsSourceTenant, + "storage_backend_id": "backend-source", "provider": "oss", + "physical_path": wsLocator("backend-source", "oss", "source-bucket", wsSourceTenant, "res-shared"), + "size": int64(8)} + // 归档里必须有这条资源自己的字节,否则失败原因会变成"归档依赖不全", + // 而不是被测的差异类型。 + extra := map[string]string{"res-shared": "12345678"} + switch mode { + case "handle": + row["handle"] = "hhhhhhhhhhhhhhhhhhhhhh" + case "locator": + row["physical_path"] = wsLocator("backend-source", "oss", "source-bucket", wsSourceTenant, "res-shared-moved") + case "bytes": + extra["res-shared"] = "87654321" + } + snapshot := sealSourceSnapshotScope(t, fx, wsSourceTenant, wsSourceKB, func(parts map[string][]map[string]any) { + parts["resources"] = append(parts["resources"], row) + }, extra) + before := r10State(t, fx) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "failed" || outcome.FailedAt != "" { + t.Fatalf("%s 差异必须写前拒绝:%+v", mode, outcome) + } + r10Unchanged(t, fx, before) + sharedAfter, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", sharedPath) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(sharedBefore, sharedAfter) { + t.Fatalf("%s 差异改动了共享对象的版本:%+v -> %+v", mode, sharedBefore, sharedAfter) + } + }) + } +} diff --git a/internal/releaseadapter/v071/document_export.go b/internal/releaseadapter/v071/document_export.go index b2f2885..a00b385 100644 --- a/internal/releaseadapter/v071/document_export.go +++ b/internal/releaseadapter/v071/document_export.go @@ -3,6 +3,7 @@ package v071 import ( "context" "errors" + "fmt" "strings" "time" @@ -63,8 +64,14 @@ func (exporter *DocumentExporter) Export(ctx context.Context, item releaseworkfl return nil, errors.New("invalid document release plan") } sourceContract, err := exporter.config.Contract.Contract(ctx, item) - if err != nil || sourceContract.WeKnoraVersion != releasebundle.WeKnoraVersionV071 || - sourceContract.MigrationVersion != releasebundle.WeKnoraMigrationV071 || sourceContract.TenantID != exporter.config.TenantID || + if err == nil && (sourceContract.WeKnoraVersion != releasebundle.WeKnoraVersionV071 || + sourceContract.MigrationVersion != releasebundle.WeKnoraMigrationV071) { + // 单文档发布包是 0.7.1 契约:读到的库是别的版本时必须说清楚原因, + // 而不是和"租户/模型不对"共用一句泛化错误。 + return nil, fmt.Errorf("single-document release supports only v0.7.1 (74): source library declares %s (%d), so its rows and index documents must go through the library-level publish path", + sourceContract.WeKnoraVersion, sourceContract.MigrationVersion) + } + if err != nil || sourceContract.TenantID != exporter.config.TenantID || sourceContract.KnowledgeBaseID != item.TestKnowledgeBaseID || sourceContract.RetrieverEngine != "elasticsearch_v8" || sourceContract.EmbeddingModel != exporter.config.EmbeddingModel || sourceContract.EmbeddingDimension != releasebundle.EmbeddingDimensionV071 { return nil, errors.New("source WeKnora release contract mismatch") diff --git a/internal/releaseadapter/v071/document_target.go b/internal/releaseadapter/v071/document_target.go index e390273..d08ad93 100644 --- a/internal/releaseadapter/v071/document_target.go +++ b/internal/releaseadapter/v071/document_target.go @@ -246,7 +246,9 @@ func (target *DocumentTarget) restoreBundle(ctx context.Context, item releasewor // bundle. The bundle's own contract keeps the SOURCE base it was exported from. func targetIdentities(item releaseworkflow.PlanItem, manifest releasebundle.Manifest) (PostgresIdentity, SearchIdentity) { postgresIdentity := PostgresIdentity{TenantID: manifest.Contract.TenantID, KnowledgeBaseID: item.TargetBase(), KnowledgeID: manifest.Contract.KnowledgeID} - return postgresIdentity, SearchIdentity(postgresIdentity) + // 单文档发布路径沿用 0.7.1 契约(索引带 tenant_id)。 + return postgresIdentity, SearchIdentity{TenantID: postgresIdentity.TenantID, + KnowledgeBaseID: postgresIdentity.KnowledgeBaseID, KnowledgeID: postgresIdentity.KnowledgeID} } var _ releaseworkflow.SidecarTarget = (*DocumentTarget)(nil) diff --git a/internal/releaseadapter/v071/ds02_bundle_test.go b/internal/releaseadapter/v071/ds02_bundle_test.go new file mode 100644 index 0000000..8bb31c3 --- /dev/null +++ b/internal/releaseadapter/v071/ds02_bundle_test.go @@ -0,0 +1,319 @@ +package v071 + +// DS-02 冻结输入 bundle:同一份文件同时给旧源码探针(6fe98c9 工作树)与当前源码 +// 使用。bundle 只含业务输入(十表来源行、目标种子行、序列种子、ES 文档、对象字节、 +// 固定时间与完整 DDL);两个隔离目标各自执行同一份 DDL、插入同一批行。 +// +// 唯一的环境替换是对象桶名:bundle 里写 %BUCKET%,两侧各自换成自己的桶。 +// 这不是输入差异,必须在报告里显式列出。 +// +// 导出(不连接任何服务): +// KG_DS02_BUNDLE_OUT=/path/dir go test -run TestDS02ExportFrozenBundle +// 新侧对照: +// KG_DS02_BUNDLE=/path/dir/ds02-frozen-bundle.json go test -run TestDS02FrozenBundleIsolated + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +type ds02BundleSeedRow struct { + Table string `json:"table"` + Row map[string]any `json:"row"` +} + +type ds02BundleSeedDoc struct { + ID string `json:"id"` + Tenant uint64 `json:"tenant"` + KB string `json:"kb"` + Knowledge string `json:"knowledge"` + Content string `json:"content"` +} + +type ds02FrozenBundle struct { + Bundle string `json:"bundle"` + Version int `json:"version"` + CreatedAt string `json:"created_at"` + Scope map[string]any `json:"scope"` + Sequences map[string][]any `json:"sequences"` + SourceRows map[string][]map[string]any `json:"source_rows"` + TargetRows []ds02BundleSeedRow `json:"target_rows"` + // OldAdapterRows 只给旧源码探针用:6fe98c9 在 resources 阶段按目标范围查资源行 + // (它在 database 阶段不重写租户),所以目标必须先有这两行才能走到 wiki。 + // 这是旧入口适配差异,不是业务输入;新侧不读这个字段。 + OldAdapterRows []ds02BundleSeedRow `json:"old_adapter_target_rows"` + SeedDocs []ds02BundleSeedDoc `json:"seed_docs"` + SeedObjects map[string]string `json:"seed_objects"` + Vectors map[string][]float64 `json:"vectors"` + DDL []string `json:"ddl"` +} + +// ds02BundleDDL 从保留的真实 v071 catalog 生成完整 DDL;旧/新隔离目标执行同一份。 +func ds02BundleDDL(t *testing.T) []string { + t.Helper() + catalog := r11CatalogData(t) + ddl := []string{ + `CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`, + `CREATE EXTENSION IF NOT EXISTS pg_trgm`, + // 预备份的 schema 契约从这张台账读版本;bundle 必须自带,不能靠夹具残留。 + `CREATE TABLE schema_migrations(version int,dirty bool)`, + `INSERT INTO schema_migrations VALUES(74,false)`, + // 旧源码的"库已结清"查询要读这两张任务表;同一份 DDL 两侧都建。 + `CREATE TABLE task_pending_ops(tenant_id bigint,task_type text,scope text,scope_id text)`, + `CREATE TABLE task_dead_letters(tenant_id bigint,task_type text,scope text,scope_id text)`, + `CREATE TABLE knowledge_bases(id text,tenant_id bigint,indexing_strategy jsonb,deleted_at timestamptz)`, + `INSERT INTO knowledge_bases VALUES('` + wsTargetKB + `',10001,'{}',NULL),('` + wsOtherKB + `',10001,'{}',NULL),('` + wsSourceKB + `',10002,'{}',NULL)`, + `CREATE TABLE storage_backends(id text PRIMARY KEY, tenant_id bigint, provider text, config jsonb, created_at timestamptz)`, + `INSERT INTO storage_backends VALUES('backend-target',10001,'minio','{"bucket_name":"` + ds02BucketPlaceholder + `"}',now())`, + } + for _, sequence := range catalog.Sequences { + ddl = append(ddl, fmt.Sprintf("CREATE SEQUENCE %s START %d", sequence.Name, sequence.Start)) + } + for _, table := range productionLibraryTables { + defs := []string{} + for _, column := range catalog.Columns { + if column.Table != table { + continue + } + definition := pgxIdentifier(column.Name) + " " + column.Type + if column.Required { + definition += " NOT NULL" + } + if column.Default != "" { + definition += " DEFAULT " + column.Default + } + defs = append(defs, definition) + } + ddl = append(ddl, "CREATE TABLE "+table+"("+strings.Join(defs, ",")+")") + } + ddl = append(ddl, `ALTER SEQUENCE wiki_log_entries_id_seq OWNED BY wiki_log_entries.id`, + `CREATE TABLE resource_access_grants(id text,resource_id varchar(36))`) + constraints := append([]struct { + Table string `json:"table_name"` + Name string `json:"name"` + Definition string `json:"definition"` + }{}, catalog.Constraints...) + sort.SliceStable(constraints, func(i, j int) bool { + return !strings.HasPrefix(constraints[i].Definition, "FOREIGN KEY") && strings.HasPrefix(constraints[j].Definition, "FOREIGN KEY") + }) + names := map[string]bool{} + for _, constraint := range constraints { + ddl = append(ddl, "ALTER TABLE "+constraint.Table+" ADD CONSTRAINT "+constraint.Name+" "+constraint.Definition) + names[constraint.Name] = true + } + for _, index := range catalog.Indexes { + if names[index.Name] { + continue + } + ddl = append(ddl, index.Definition) + } + return ddl +} + +// pgxIdentifier 只处理本 catalog 里的普通小写列名。 +func pgxIdentifier(name string) string { return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` } + +func ds02BundleSequences() map[string][]any { + return map[string][]any{ + "chunks_seq_id_seq": {int64(100000005), false}, + "knowledge_tags_seq_id_seq": {int64(50), false}, + "wiki_log_entries_id_seq": {int64(10), false}, + } +} + +func TestDS02ExportFrozenBundle(t *testing.T) { + root := os.Getenv("KG_DS02_BUNDLE_OUT") + if root == "" { + t.Skip("set KG_DS02_BUNDLE_OUT to write the frozen input bundle") + } + rows := ds02SourceRows() + // 逐表 hash,便于两侧各自核对同一份输入。 + perTable := map[string]string{} + for table, list := range rows { + raw, err := json.Marshal(list) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(raw) + perTable[table] = hex.EncodeToString(sum[:]) + } + bundle := ds02FrozenBundle{ + Bundle: "ds02-frozen-input", + Version: 1, + CreatedAt: "2026-11-02T00:00:00Z", + Scope: map[string]any{"source_tenant": wsSourceTenant, "source_kb": wsSourceKB, "target_tenant": wsTargetTenant, "target_kb": wsTargetKB, "other_kb": wsOtherKB, "foreign_tenant": 20000}, + Sequences: ds02BundleSequences(), + SourceRows: rows, + SeedObjects: func() map[string]string { + out := map[string]string{} + for id, body := range ds02Objects { + out[id] = body + } + for id, body := range ds02SeedObjects() { + out[id] = body + } + return out + }(), + Vectors: ds02Vectors, + DDL: ds02BundleDDL(t), + } + for _, row := range ds02SeedRows() { + bundle.TargetRows = append(bundle.TargetRows, ds02BundleSeedRow{Table: row.table, Row: row.row}) + } + for _, doc := range ds02SeedDocs() { + bundle.SeedDocs = append(bundle.SeedDocs, ds02BundleSeedDoc{ID: doc.id, Tenant: doc.tenant, KB: doc.kb, Knowledge: doc.knowledge, Content: doc.content}) + } + raw, err := json.MarshalIndent(bundle, "", " ") + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(root, 0700); err != nil { + t.Fatal(err) + } + path := filepath.Join(root, "ds02-frozen-bundle.json") + if err := os.WriteFile(path, append(raw, '\n'), 0600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(append(raw, '\n')) + hash := hex.EncodeToString(sum[:]) + if err := os.WriteFile(filepath.Join(root, "ds02-frozen-bundle.sha256"), []byte(hash+" ds02-frozen-bundle.json\n"), 0600); err != nil { + t.Fatal(err) + } + result := map[string]any{"bundle": path, "sha256": hash, "table_hashes": perTable, + "bytes": len(raw) + 1, "ddl_statements": len(bundle.DDL), "created_at": bundle.CreatedAt} + if run := os.Getenv("KG_R10_RUN"); run != "" { + r10Save(t, "bundle", result) + } + encoded, _ := json.MarshalIndent(result, "", " ") + t.Logf("%s", encoded) +} + +func ds02LoadBundle(t *testing.T) (ds02FrozenBundle, string) { + t.Helper() + path := os.Getenv("KG_DS02_BUNDLE") + if path == "" { + t.Skip("set KG_DS02_BUNDLE to run the frozen-bundle comparison") + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read frozen bundle: %v", err) + } + sum := sha256.Sum256(raw) + hash := hex.EncodeToString(sum[:]) + sidecar, err := os.ReadFile(strings.TrimSuffix(path, ".json") + ".sha256") + if err != nil { + t.Fatalf("read bundle sha256 sidecar: %v", err) + } + if !strings.HasPrefix(strings.TrimSpace(string(sidecar)), hash) { + t.Fatalf("bundle sha256 %s does not match sidecar %q", hash, strings.TrimSpace(string(sidecar))) + } + var bundle ds02FrozenBundle + if err := json.Unmarshal(raw, &bundle); err != nil { + t.Fatalf("parse frozen bundle: %v", err) + } + if bundle.Bundle != "ds02-frozen-input" || bundle.Version != 1 || len(bundle.DDL) == 0 { + t.Fatalf("unexpected frozen bundle header: %+v", bundle.Bundle) + } + return bundle, hash +} + +// TestDS02FrozenBundleIsolated 用与旧源码探针同一份 bundle 初始化新目标并发布, +// 再用独立 oracle 检查;bundle hash 写进 raw,供与旧侧结果对齐。 +func TestDS02FrozenBundleIsolated(t *testing.T) { + bundle, hash := ds02LoadBundle(t) + // 桶名在两个隔离目标里不同:fixture 在真正建 schema 时把 %BUCKET% 换成自己的桶。 + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, ddl: bundle.DDL}) + for name, value := range bundle.Sequences { + last := int64(value[0].(float64)) + called := value[1].(bool) + r10Exec(t, fx, fmt.Sprintf("SELECT setval('%s',%d,%t)", name, last, called)) + } + for id, body := range bundle.SeedObjects { + if id != "res-other" { + continue + } + path := wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, id) + if err := fx.objects.s3.Put(fx.ctx, "minio", path, strings.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + } + for _, row := range bundle.TargetRows { + if _, ok := ds02ScopeDecl[row.Table]; !ok { + t.Fatalf("bundle target row for undeclared table %s", row.Table) + } + r11Insert(t, fx, row.Table, ds02SeedRow(row.Row, fx.bucket)) + } + for _, doc := range bundle.SeedDocs { + fx.indexDoc(t, doc.ID, doc.Tenant, doc.KB, doc.Knowledge, doc.Content) + } + spec := ds02Spec{rows: map[string][]map[string]any{}, vectors: bundle.Vectors, objects: map[string]string{}} + for table, rows := range bundle.SourceRows { + for _, row := range rows { + spec.rows[table] = append(spec.rows[table], ds02Canon(t, fx, table, row)) + } + } + // 来源对象只取"来源资源行声明的那几个";res-other 是外围哨兵,不参与来源对象比对。 + for _, row := range bundle.SourceRows["resources"] { + id := fmt.Sprint(row["id"]) + body, ok := bundle.SeedObjects[id] + if !ok { + t.Fatalf("bundle has no bytes for source resource %s", id) + } + spec.objects[id] = body + } + preserved := map[string][]map[string]any{} + for _, table := range ds02TargetTables { + preserved[table] = ds02OtherRows(t, fx, table) + } + expectation := ds02Expected(t, fx, spec) + expected, paths := expectation.Rows, expectation.Paths + for _, table := range []string{"resources", "resource_bindings"} { + expected[table] = append(expected[table], ds02SameTenantRows(t, fx, table)...) + } + expected["knowledge_tag_relations"] = append(expected["knowledge_tag_relations"], + ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM knowledge_tag_relations AS x + WHERE knowledge_id NOT IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)`, + wsTargetTenant, wsTargetKB)...) + snapshot := ds02Seal(t, fx, spec) + recorder, inventory := ds02AttachEgress(t, fx) + target := fx.target(t) + backups := fx.backups(t, target) + recorder.setPhase("publish") + out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, backups, nil) + recorder.setPhase("oracle-read") + r10Save(t, "bundle-identity", map[string]any{"path": os.Getenv("KG_DS02_BUNDLE"), "sha256": hash, + "source_tenant": bundle.Scope["source_tenant"], "target_tenant": bundle.Scope["target_tenant"], + "created_at": bundle.CreatedAt, "adapter_note": "DDL 与行内容相同;对象桶名以 %BUCKET% 占位,两侧各自替换。"}) + r10Save(t, "outcome", out) + if out.State != "succeeded" { + t.Fatalf("new source must publish the frozen bundle: %+v", out) + } + if out.Backup.WriteSet == nil { + t.Fatal("write set missing") + } + ledger, err := LoadWriteSet(fx.archiveRoot, out.Backup.WriteSet.Digest) + if err != nil { + t.Fatalf("load write set: %v", err) + } + columns := ds02LocalColumns(t, fx, spec, expectation) + mappingDiffs := ds02CheckLocalIDMapping(columns, ledger.LocalIDs) + r10Save(t, "mapping-diffs", mappingDiffs) + if len(mappingDiffs) != 0 { + t.Fatalf("frozen-bundle publish fails the independent mapping oracle:\n%s", strings.Join(mappingDiffs, "\n")) + } + diffs := ds02Check(t, fx, spec, expected, paths, preserved, recorder, inventory) + r10Save(t, "green-diffs", diffs) + if len(diffs) != 0 { + t.Fatalf("frozen-bundle independent oracle disagrees:\n%s", strings.Join(diffs, "\n")) + } + r10Save(t, "sequences-after", ds02SequenceSummary(t, fx)) +} diff --git a/internal/releaseadapter/v071/ds02_identical_input_test.go b/internal/releaseadapter/v071/ds02_identical_input_test.go new file mode 100644 index 0000000..efa5c4d --- /dev/null +++ b/internal/releaseadapter/v071/ds02_identical_input_test.go @@ -0,0 +1,735 @@ +package v071 + +// DS-02 十表同输入对照(同租户、不同知识库)。 +// +// 背景:跨租户冻结 bundle 的旧侧 6fe98c9 在 database 阶段不改写租户、resources 阶段 +// 却按目标租户查资源行,跨租户资源必然在 wiki 之前失败。旧侧归档因此省略了 +// resources / resource_bindings 两表 —— 那不是"同一输入",只能算受约束的回归对照。 +// +// 本文件把场景改成"来源与目标同租户、不同知识库": +// * 旧侧的资源查询只按 tenant_id,同租户下能在 resources 阶段找到刚插入的资源行, +// 前置缺陷不再触发; +// * wiki_log_entries 的数字 id 仍在同一租户的其它知识库里占用了 id=1, +// 旧代码按归档原样插入时仍会撞 wiki_log_entries_pkey / 23505。 +// +// 因此两侧都能消费"真正相同的十表输入":来源归档十表逐表内容、目标种子、完整 DDL、 +// 三条序列、ES 文档与对象字节。本文件负责生成新的 bundle 与执行前导出"实际消费输入" +// 证据;旧侧探针(旧 SHA 工作树内未跟踪测试文件)导出同一形状的证据,再由证据根脚本 +// 逐项比较 —— 不是"读同一个文件再各自过滤"。 +// +// 导出(不连接任何服务): +// KG_DS02_IDENTICAL_BUNDLE_OUT=/path/dir go test -run TestDS02ExportIdenticalInputBundle +// 新侧执行: +// KG_DS02_BUNDLE=/path/dir/ds02-identical-input-bundle.json go test -run TestDS02IdenticalInputBundleIsolated + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// 时间固定:bundle 声明、归档 manifest、发布 request 都用这一个时刻。 +const ds02IdenticalTime = "2026-11-02T00:00:00Z" + +func ds02IdenticalScope() map[string]any { + return map[string]any{ + "source_tenant": uint64(wsTargetTenant), + "source_kb": wsSourceKB, + "target_tenant": uint64(wsTargetTenant), + "target_kb": wsTargetKB, + "other_kb": wsOtherKB, + "foreign_tenant": uint64(wsForeignTnt), + } +} + +// ds02IdenticalSourceRows 是十表来源行的纯声明:租户与目标相同,知识库不同。 +// 资源定位符里的租户段随租户一起改写(bucket 段保持固定的来源桶名,不引用两侧 +// 一次性桶,否则归档内容会随环境变化);location_hash 按真实定位符重算。 +func ds02IdenticalSourceRows() map[string][]map[string]any { + rows := ds02SourceRows() + for table, list := range rows { + for _, row := range list { + if _, ok := row["tenant_id"]; ok { + row["tenant_id"] = uint64(wsTargetTenant) + } + if table != "resources" { + continue + } + id := fmt.Sprint(row["id"]) + path := wsLocator("backend-source", "oss", "source-bucket", wsTargetTenant, id) + row["physical_path"] = path + sum := sha256.Sum256([]byte(path)) + row["location_hash"] = hex.EncodeToString(sum[:]) + } + } + return rows +} + +// ds02IdenticalSeedRows 给目标种子补上显式时间戳:种子行是"发布前目标已有数据", +// 两侧都必须逐列相等;让 now()/CURRENT_TIMESTAMP 在两侧落地成不同值会让"实际目标种子 +// 相同"这条断言无法成立。DDL 与 catalog 本身不改。 +func ds02IdenticalSeedRows() []struct { + table string + row map[string]any +} { + timestamps := map[string][]string{ + "knowledges": {"created_at", "updated_at"}, + "chunks": {"created_at", "updated_at"}, + "knowledge_tags": {"created_at", "updated_at"}, + "knowledge_tag_relations": {"created_at"}, + "resources": {"created_at", "updated_at"}, + "resource_bindings": {"created_at"}, + "wiki_folders": {"created_at", "updated_at"}, + "wiki_pages": {"created_at", "updated_at"}, + "wiki_page_issues": {"created_at", "updated_at"}, + "wiki_log_entries": {"created_at"}, + } + fixed := map[string]string{"created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z"} + seeds := ds02SeedRows() + out := make([]struct { + table string + row map[string]any + }, 0, len(seeds)) + for _, seed := range seeds { + row := map[string]any{} + for key, value := range seed.row { + row[key] = value + } + for _, column := range timestamps[seed.table] { + if _, ok := row[column]; ok { + continue + } + row[column] = fixed[column] + } + out = append(out, struct { + table string + row map[string]any + }{table: seed.table, row: row}) + } + return out +} + +// ds02IdenticalDDL 用同一份真实 catalog 生成完整 DDL,只把来源知识库的租户改成与目标 +// 相同的值(bundle 的 scope 声明必须与 DDL 里的行一致)。其他语句逐字节相同。 +func ds02IdenticalDDL(t *testing.T) []string { + t.Helper() + ddl := ds02BundleDDL(t) + old := "('" + wsSourceKB + "'," + strconv.Itoa(wsSourceTenant) + replacement := "('" + wsSourceKB + "'," + strconv.Itoa(wsTargetTenant) + replaced := 0 + out := make([]string, 0, len(ddl)) + for _, statement := range ddl { + if strings.Contains(statement, old) { + statement = strings.Replace(statement, old, replacement, 1) + replaced++ + } + out = append(out, statement) + } + if replaced != 1 { + t.Fatalf("source knowledge base row in DDL: want exactly 1 statement, replaced %d", replaced) + } + return out +} + +func TestDS02ExportIdenticalInputBundle(t *testing.T) { + root := os.Getenv("KG_DS02_IDENTICAL_BUNDLE_OUT") + if root == "" { + t.Skip("set KG_DS02_IDENTICAL_BUNDLE_OUT to write the identical-input bundle") + } + rows := ds02IdenticalSourceRows() + perTable := map[string]string{} + for table, list := range rows { + raw, err := json.Marshal(list) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(raw) + perTable[table] = hex.EncodeToString(sum[:]) + } + objects := map[string]string{} + for id, body := range ds02Objects { + objects[id] = body + } + for id, body := range ds02SeedObjects() { + objects[id] = body + } + bundle := ds02FrozenBundle{ + Bundle: "ds02-identical-input", + Version: 2, + CreatedAt: ds02IdenticalTime, + Scope: ds02IdenticalScope(), + Sequences: ds02BundleSequences(), + SourceRows: rows, + SeedObjects: objects, + Vectors: ds02Vectors, + DDL: ds02IdenticalDDL(t), + } + for _, seed := range ds02IdenticalSeedRows() { + bundle.TargetRows = append(bundle.TargetRows, ds02BundleSeedRow{Table: seed.table, Row: seed.row}) + } + for _, doc := range ds02SeedDocs() { + bundle.SeedDocs = append(bundle.SeedDocs, ds02BundleSeedDoc{ID: doc.id, Tenant: doc.tenant, KB: doc.kb, Knowledge: doc.knowledge, Content: doc.content}) + } + raw, err := json.MarshalIndent(bundle, "", " ") + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(root, 0700); err != nil { + t.Fatal(err) + } + path := filepath.Join(root, "ds02-identical-input-bundle.json") + if err := os.WriteFile(path, append(raw, '\n'), 0600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(append(raw, '\n')) + hash := hex.EncodeToString(sum[:]) + if err := os.WriteFile(filepath.Join(root, "ds02-identical-input-bundle.sha256"), []byte(hash+" ds02-identical-input-bundle.json\n"), 0600); err != nil { + t.Fatal(err) + } + result := map[string]any{"bundle": path, "sha256": hash, "table_hashes": perTable, + "bytes": len(raw) + 1, "ddl_statements": len(bundle.DDL), "created_at": bundle.CreatedAt, + "scope": bundle.Scope} + if run := os.Getenv("KG_R10_RUN"); run != "" { + r10Save(t, "identical-bundle", result) + } + encoded, _ := json.MarshalIndent(result, "", " ") + t.Logf("%s", encoded) +} + +func ds02LoadIdenticalBundle(t *testing.T) (ds02FrozenBundle, string) { + t.Helper() + path := os.Getenv("KG_DS02_BUNDLE") + if path == "" { + t.Skip("set KG_DS02_BUNDLE to run the identical-input comparison") + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read identical bundle: %v", err) + } + sum := sha256.Sum256(raw) + hash := hex.EncodeToString(sum[:]) + sidecar, err := os.ReadFile(strings.TrimSuffix(path, ".json") + ".sha256") + if err != nil { + t.Fatalf("read identical bundle sha256 sidecar: %v", err) + } + if !strings.HasPrefix(strings.TrimSpace(string(sidecar)), hash) { + t.Fatalf("identical bundle sha256 %s does not match sidecar %q", hash, strings.TrimSpace(string(sidecar))) + } + var bundle ds02FrozenBundle + if err := json.Unmarshal(raw, &bundle); err != nil { + t.Fatalf("parse identical bundle: %v", err) + } + if bundle.Bundle != "ds02-identical-input" || bundle.Version != 2 || len(bundle.DDL) == 0 || + bundle.CreatedAt != ds02IdenticalTime { + t.Fatalf("unexpected identical bundle header: %s v%d created=%s ddl=%d", + bundle.Bundle, bundle.Version, bundle.CreatedAt, len(bundle.DDL)) + } + return bundle, hash +} + +func ds02BundleUint(value any) uint64 { + switch typed := value.(type) { + case float64: + return uint64(typed) + case uint64: + return typed + case int: + return uint64(typed) + case json.Number: + parsed, _ := strconv.ParseUint(string(typed), 10, 64) + return parsed + } + return 0 +} + +// ds02InputTable 是一张表/一组对象的"规范化语义输入":逐行规范化 JSON + 计数 + 摘要。 +type ds02InputTable struct { + Count int `json:"count"` + SHA256 string `json:"sha256"` + Rows []string `json:"rows"` +} + +type ds02InputArchive struct { + Manifest map[string]any `json:"manifest"` + Tables map[string]ds02InputTable `json:"tables"` + Resources map[string]ds02InputTable `json:"resources"` +} + +type ds02InputEvidence struct { + Side string `json:"side"` + BundleSHA string `json:"bundle_sha256"` + Scope map[string]any `json:"scope"` + FixedTime string `json:"fixed_time"` + Physical map[string]string `json:"physical"` + DDL ds02InputTable `json:"ddl"` + Sequences map[string][]any `json:"sequences_before"` + Archive ds02InputArchive `json:"archive"` + PartPhys map[string]map[string]any `json:"archive_part_physical"` + TargetSeed map[string]ds02InputTable `json:"target_seed"` + Objects map[string]ds02InputTable `json:"objects"` + ES map[string]ds02InputTable `json:"es"` + Semantic string `json:"semantic_sha256"` +} + +// ds02DigestRows 把行集合规范化成稳定可比较的字符串:用 UseNumber 解码后用 +// encoding/json 重编码(键按字典序),数字原样保留。 +func ds02DigestRows(raw [][]byte) (ds02InputTable, error) { + rows := make([]string, 0, len(raw)) + for _, item := range raw { + dec := json.NewDecoder(bytes.NewReader(item)) + dec.UseNumber() + var value map[string]any + if err := dec.Decode(&value); err != nil { + return ds02InputTable{}, err + } + encoded, err := json.Marshal(value) + if err != nil { + return ds02InputTable{}, err + } + rows = append(rows, string(encoded)) + } + sort.Strings(rows) + sum := sha256.Sum256([]byte(strings.Join(rows, "\n"))) + return ds02InputTable{Count: len(rows), SHA256: hex.EncodeToString(sum[:]), Rows: rows}, nil +} + +func ds02DigestQuery(t *testing.T, fx *writeSetFixture, query string, args ...any) ds02InputTable { + t.Helper() + items := ds02Read(t, fx, query, args...) + raw := make([][]byte, 0, len(items)) + for _, item := range items { + encoded, err := json.Marshal(item) + if err != nil { + t.Fatal(err) + } + raw = append(raw, encoded) + } + table, err := ds02DigestRows(raw) + if err != nil { + t.Fatal(err) + } + return table +} + +// ds02NormalizeBucket 把这一侧的一次性桶名换回 %BUCKET%:桶名是唯一不可避免的 +// namespace 替换,两侧必须用同一规范归一,才谈得上"语义输入相同"。物理桶名单独记。 +// resources.location_hash 是 sha256(physical_path) 的派生值:路径被归一后必须按同一 +// 规则重算(先验证它确实等于物理路径的摘要,避免把无关字段一起改写)。 +func ds02NormalizeBucket(table ds02InputTable, bucket string) ds02InputTable { + if bucket == "" { + return table + } + rows := make([]string, 0, len(table.Rows)) + for _, row := range table.Rows { + normalized := strings.ReplaceAll(row, bucket, ds02BucketPlaceholder) + var parsed map[string]any + if json.Unmarshal([]byte(normalized), &parsed) == nil { + path, hasPath := parsed["physical_path"].(string) + hash, hasHash := parsed["location_hash"].(string) + physicalPath := strings.ReplaceAll(path, ds02BucketPlaceholder, bucket) + if hasPath && hasHash && hash == ds02SHA256Hex(physicalPath) { + parsed["location_hash"] = ds02SHA256Hex(path) + if encoded, err := json.Marshal(parsed); err == nil { + normalized = string(encoded) + } + } + } + rows = append(rows, normalized) + } + sum := sha256.Sum256([]byte(strings.Join(rows, "\n"))) + return ds02InputTable{Count: len(rows), SHA256: hex.EncodeToString(sum[:]), Rows: rows} +} + +func ds02SHA256Hex(value string) string { + sum := sha256.Sum256([]byte(value)) + return hex.EncodeToString(sum[:]) +} + +// ds02DatabaseName 只留库名:证据里不记连接串。 +func ds02DatabaseName(dsn string) string { + name := dsn + if index := strings.LastIndex(name, "/"); index >= 0 { + name = name[index+1:] + } + if index := strings.Index(name, "?"); index >= 0 { + name = name[:index] + } + return name +} + +// ds02ArchiveSnapshot 读回归档里"实际写下的"部件,逐表导出。 +func ds02ArchiveSnapshot(t *testing.T, root, snapshotID string) (ds02InputArchive, map[string]map[string]any) { + t.Helper() + archive, err := librarysnapshot.Open(root, 128*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + manifest, err := archive.Load(snapshotID) + if err != nil { + t.Fatalf("load archive %s: %v", snapshotID, err) + } + out := ds02InputArchive{Tables: map[string]ds02InputTable{}, Resources: map[string]ds02InputTable{}} + parts := make([]map[string]any, 0, len(manifest.Parts)) + physical := map[string]map[string]any{} + for _, part := range manifest.Parts { + // 只记语义字段:部件字节的 sha256 会因 JSON 键序(PG 列序 vs Go 字典序)不同, + // 属于物理身份,单独记录,不混进"同一输入"的语义比较。 + parts = append(parts, map[string]any{"kind": part.Kind, "name": part.Name, "count": part.Count}) + physical[part.Kind+"/"+part.Name] = map[string]any{"bytes": part.Bytes, "sha256": part.SHA256} + reader, err := archive.OpenPart(part) + if err != nil { + t.Fatalf("open archive part %s: %v", part.Name, err) + } + body, err := io.ReadAll(reader) + reader.Close() + if err != nil { + t.Fatal(err) + } + switch part.Kind { + case "resource": + sum := sha256.Sum256(body) + out.Resources[part.Name] = ds02InputTable{Count: 1, SHA256: hex.EncodeToString(sum[:]), + Rows: []string{string(body)}} + case "database", "wiki", "index": + var items []json.RawMessage + if err := json.Unmarshal(body, &items); err != nil { + t.Fatalf("archive part %s: %v", part.Name, err) + } + raw := make([][]byte, 0, len(items)) + for _, item := range items { + raw = append(raw, []byte(item)) + } + table, err := ds02DigestRows(raw) + if err != nil { + t.Fatalf("archive part %s: %v", part.Name, err) + } + out.Tables[part.Kind+"/"+part.Name] = table + } + } + out.Manifest = map[string]any{"tenant": manifest.TenantID, "knowledge_base": manifest.KnowledgeBaseID, + "format": manifest.Format, "policy": manifest.ValidationPolicy, "parts": parts} + sort.Slice(parts, func(i, j int) bool { + left := fmt.Sprint(parts[i]["kind"]) + "/" + fmt.Sprint(parts[i]["name"]) + right := fmt.Sprint(parts[j]["kind"]) + "/" + fmt.Sprint(parts[j]["name"]) + return left < right + }) + return out, physical +} + +// ds02IdenticalSeal 与 ds02SealScope 同形,但使用固定的创建时间与实际来源范围, +// 并把 index 部件的范围写到声明的来源租户/知识库。 +func ds02IdenticalSeal(t *testing.T, fx *writeSetFixture, spec ds02Spec, sourceTenant uint64, sourceKB string) string { + t.Helper() + archive, err := librarysnapshot.Open(fx.archiveRoot, 128*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + encode := func(value any) []byte { + raw, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return raw + } + kinds := map[string]string{"knowledges": "database", "chunks": "database", "knowledge_tags": "database", + "knowledge_tag_relations": "database", "resources": "database", "resource_bindings": "database", + "wiki_folders": "wiki", "wiki_pages": "wiki", "wiki_page_issues": "wiki", "wiki_log_entries": "wiki"} + parts := []librarysnapshot.Part{} + for _, table := range ds02TargetTables { + part, err := archive.Put(bytes.NewReader(encode(spec.rows[table]))) + if err != nil { + t.Fatal(err) + } + part.Kind, part.Name, part.Count = kinds[table], table, int64(len(spec.rows[table])) + parts = append(parts, part) + } + objects := make([]string, 0, len(spec.objects)) + for id := range spec.objects { + objects = append(objects, id) + } + sort.Strings(objects) + for _, id := range objects { + part, err := archive.Put(bytes.NewReader([]byte(spec.objects[id]))) + if err != nil { + t.Fatal(err) + } + part.Kind, part.Name, part.Count = "resource", id, 1 + parts = append(parts, part) + } + indexRows := []map[string]any{} + for _, chunk := range spec.rows["chunks"] { + id := fmt.Sprint(chunk["id"]) + indexRows = append(indexRows, map[string]any{"id": id, "source": map[string]any{ + "tenant_id": sourceTenant, "knowledge_base_id": sourceKB, + "knowledge_id": chunk["knowledge_id"], "chunk_id": id, "source_id": id, + "content": chunk["content"], "embedding": spec.vectors[id]}}) + } + indexPart, err := archive.Put(bytes.NewReader(encode(indexRows))) + if err != nil { + t.Fatal(err) + } + indexPart.Kind, indexPart.Name, indexPart.Count = "index", "chunks", int64(len(indexRows)) + parts = append(parts, indexPart) + created, err := time.Parse(time.RFC3339, ds02IdenticalTime) + if err != nil { + t.Fatal(err) + } + manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, + Format: librarysnapshot.Format, Scope: "internal", TenantID: sourceTenant, KnowledgeBaseID: sourceKB, + CreatedAt: created, Parts: parts, + Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", + EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("a", 64)}} + id, err := archive.Seal(manifest) + if err != nil { + t.Fatalf("seal identical snapshot: %v", err) + } + return id +} + +// ds02ListObjects 读真实对象存储里"执行前实际存在"的对象:key + 字节摘要。 +func ds02ListObjects(t *testing.T, fx *writeSetFixture) map[string]ds02InputTable { + t.Helper() + out := map[string]ds02InputTable{} + paginator := awss3.NewListObjectsV2Paginator(fx.objects.s3.client, &awss3.ListObjectsV2Input{ + Bucket: aws.String(fx.bucket)}) + for paginator.HasMorePages() { + page, err := paginator.NextPage(fx.ctx) + if err != nil { + t.Fatalf("list objects: %v", err) + } + for _, item := range page.Contents { + key := aws.ToString(item.Key) + object, err := fx.objects.s3.client.GetObject(fx.ctx, &awss3.GetObjectInput{ + Bucket: aws.String(fx.bucket), Key: aws.String(key)}) + if err != nil { + t.Fatalf("read object %s: %v", key, err) + } + body, err := io.ReadAll(object.Body) + object.Body.Close() + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(body) + out[key] = ds02InputTable{Count: 1, SHA256: hex.EncodeToString(sum[:]), Rows: []string{string(body)}} + } + } + return out +} + +func ds02IdenticalDDLDigest(t *testing.T, ddl []string, bucket string) ds02InputTable { + t.Helper() + rows := make([]string, 0, len(ddl)) + for _, statement := range ddl { + rows = append(rows, strings.ReplaceAll(statement, bucket, ds02BucketPlaceholder)) + } + sum := sha256.Sum256([]byte(strings.Join(rows, "\n"))) + return ds02InputTable{Count: len(rows), SHA256: hex.EncodeToString(sum[:]), Rows: rows} +} + +// ds02CaptureInputs 在执行前导出"这一侧真正消费的输入"。 +func ds02CaptureInputs(t *testing.T, fx *writeSetFixture, spec ds02Spec, bundle ds02FrozenBundle, + hash, snapshotID string, sourceTenant uint64, sourceKB string, ddl []string) ds02InputEvidence { + t.Helper() + evidence := ds02InputEvidence{ + Side: "new", + BundleSHA: hash, + Scope: bundle.Scope, + FixedTime: ds02IdenticalTime, + Physical: map[string]string{"bucket": fx.bucket, "es_index": fx.index, "database": ds02DatabaseName(os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")), "archive_root": fx.archiveRoot, "snapshot_id": snapshotID, "object_store": "real MinIO via S3ObjectStore"}, + DDL: ds02IdenticalDDLDigest(t, ddl, fx.bucket), + Sequences: map[string][]any{}, + TargetSeed: map[string]ds02InputTable{}, + Objects: ds02ListObjects(t, fx), + ES: map[string]ds02InputTable{}, + } + evidence.Archive, evidence.PartPhys = ds02ArchiveSnapshot(t, fx.archiveRoot, snapshotID) + for name, table := range evidence.Archive.Tables { + evidence.Archive.Tables[name] = ds02NormalizeBucket(table, fx.bucket) + } + for _, name := range []string{"chunks_seq_id_seq", "knowledge_tags_seq_id_seq", "wiki_log_entries_id_seq"} { + var last int64 + var called bool + if err := fx.pool.QueryRow(fx.ctx, "SELECT last_value,is_called FROM "+name).Scan(&last, &called); err != nil { + t.Fatalf("sequence %s: %v", name, err) + } + evidence.Sequences[name] = []any{last, called} + } + for _, table := range ds02TargetTables { + evidence.TargetSeed[table] = ds02NormalizeBucket(ds02DigestQuery(t, fx, + "SELECT to_jsonb(x)::text FROM "+table+" AS x ORDER BY 1"), fx.bucket) + } + docs := ds02Docs(t, fx) + ids := make([]string, 0, len(docs)) + for id := range docs { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + raw, err := json.Marshal(docs[id]) + if err != nil { + t.Fatal(err) + } + table, err := ds02DigestRows([][]byte{raw}) + if err != nil { + t.Fatal(err) + } + evidence.ES[id] = table + } + semantic := map[string]any{"fixed_time": evidence.FixedTime, "scope": evidence.Scope, + "ddl": evidence.DDL, "sequences_before": evidence.Sequences, + "archive": evidence.Archive, "target_seed": evidence.TargetSeed, + "objects_before": evidence.Objects, "es_before": evidence.ES} + rawSemantic, err := json.Marshal(semantic) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(rawSemantic) + evidence.Semantic = hex.EncodeToString(sum[:]) + _ = sourceTenant + _ = sourceKB + return evidence +} + +func TestDS02IdenticalInputBundleIsolated(t *testing.T) { + bundle, hash := ds02LoadIdenticalBundle(t) + sourceTenant := ds02BundleUint(bundle.Scope["source_tenant"]) + sourceKB := fmt.Sprint(bundle.Scope["source_kb"]) + if sourceTenant != wsTargetTenant || sourceKB == wsTargetKB { + t.Fatalf("identical bundle must be same tenant, different knowledge base: source=%d/%s target=%d/%s", + sourceTenant, sourceKB, uint64(wsTargetTenant), wsTargetKB) + } + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, ddl: bundle.DDL}) + ds02VerifyScopeDecl(t, fx) + for name, value := range bundle.Sequences { + last := int64(value[0].(float64)) + called := value[1].(bool) + r10Exec(t, fx, fmt.Sprintf("SELECT setval('%s',%d,%t)", name, last, called)) + } + for id, body := range bundle.SeedObjects { + if id != "res-other" { + continue + } + path := wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, id) + if err := fx.objects.s3.Put(fx.ctx, "minio", path, strings.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + } + for _, row := range bundle.TargetRows { + if _, ok := ds02ScopeDecl[row.Table]; !ok { + t.Fatalf("bundle target row for undeclared table %s", row.Table) + } + r11Insert(t, fx, row.Table, ds02SeedRow(row.Row, fx.bucket)) + } + for _, doc := range bundle.SeedDocs { + fx.indexDoc(t, doc.ID, doc.Tenant, doc.KB, doc.Knowledge, doc.Content) + } + spec := ds02Spec{rows: map[string][]map[string]any{}, vectors: bundle.Vectors, objects: map[string]string{}} + for table, rows := range bundle.SourceRows { + for _, row := range rows { + spec.rows[table] = append(spec.rows[table], ds02Canon(t, fx, table, row)) + } + } + for _, table := range ds02TargetTables { + if len(spec.rows[table]) == 0 { + t.Fatalf("bundle source archive has no rows for %s; ten-table input is required", table) + } + } + for _, row := range bundle.SourceRows["resources"] { + id := fmt.Sprint(row["id"]) + body, ok := bundle.SeedObjects[id] + if !ok { + t.Fatalf("bundle has no bytes for source resource %s", id) + } + spec.objects[id] = body + } + preserved := map[string][]map[string]any{} + for _, table := range ds02TargetTables { + preserved[table] = ds02OtherRows(t, fx, table) + } + expectation := ds02Expected(t, fx, spec) + expected, paths := expectation.Rows, expectation.Paths + // resources / resource_bindings 没有 knowledge_base_id:同租户其它知识库的行也在 + // 目标范围内,必须原样保留。 + for _, table := range []string{"resources", "resource_bindings"} { + expected[table] = append(expected[table], ds02SameTenantRows(t, fx, table)...) + } + expected["knowledge_tag_relations"] = append(expected["knowledge_tag_relations"], + ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM knowledge_tag_relations AS x + WHERE knowledge_id NOT IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)`, + wsTargetTenant, wsTargetKB)...) + snapshot := ds02IdenticalSeal(t, fx, spec, sourceTenant, sourceKB) + evidence := ds02CaptureInputs(t, fx, spec, bundle, hash, snapshot, sourceTenant, sourceKB, bundle.DDL) + r10Save(t, "actual-inputs", evidence) + recorder, inventory := ds02AttachEgress(t, fx) + target := fx.target(t) + backups := fx.backups(t, target) + recorder.setPhase("publish") + out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, backups, nil) + recorder.setPhase("oracle-read") + r10Save(t, "bundle-identity", map[string]any{"path": os.Getenv("KG_DS02_BUNDLE"), "sha256": hash, + "source_tenant": sourceTenant, "source_kb": sourceKB, "target_tenant": wsTargetTenant, + "target_kb": wsTargetKB, "created_at": bundle.CreatedAt}) + r10Save(t, "outcome", out) + if out.State != "succeeded" { + t.Fatalf("new source must publish the identical-input bundle: %+v", out) + } + if out.Backup.WriteSet == nil { + t.Fatal("write set missing") + } + ledger, err := LoadWriteSet(fx.archiveRoot, out.Backup.WriteSet.Digest) + if err != nil { + t.Fatalf("load write set: %v", err) + } + columns := ds02LocalColumns(t, fx, spec, expectation) + mappingDiffs := ds02CheckLocalIDMapping(columns, ledger.LocalIDs) + r10Save(t, "mapping-diffs", mappingDiffs) + if len(mappingDiffs) != 0 { + t.Fatalf("identical-input publish fails the independent mapping oracle:\n%s", strings.Join(mappingDiffs, "\n")) + } + diffs := ds02Check(t, fx, spec, expected, paths, preserved, recorder, inventory) + r10Save(t, "green-diffs", diffs) + if len(diffs) != 0 { + t.Fatalf("identical-input independent oracle disagrees:\n%s", strings.Join(diffs, "\n")) + } + r10Save(t, "sequences-after", ds02SequenceSummary(t, fx)) + r10Save(t, "sentinels-after", map[string]any{ + "sibling_object": ds02CaptureObject(t, fx, wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, "res-other")), + "foreign_doc": ds02Docs(t, fx)["chunk-foreign"], + "other_kb_log": ds02Read(t, fx, "SELECT to_jsonb(x)::text FROM wiki_log_entries AS x WHERE tenant_id=$1 AND knowledge_base_id=$2", wsTargetTenant, wsOtherKB), + }) +} + +func ds02CaptureObject(t *testing.T, fx *writeSetFixture, path string) map[string]any { + t.Helper() + reader, err := fx.objects.s3.Open(fx.ctx, "minio", path) + if err != nil { + t.Fatalf("read object: %v", err) + } + body, err := io.ReadAll(reader) + reader.Close() + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(body) + return map[string]any{"path": strings.ReplaceAll(path, fx.bucket, ds02BucketPlaceholder), + "bytes": len(body), "sha256": hex.EncodeToString(sum[:])} +} diff --git a/internal/releaseadapter/v071/ds02_identity_test.go b/internal/releaseadapter/v071/ds02_identity_test.go new file mode 100644 index 0000000..e6603d7 --- /dev/null +++ b/internal/releaseadapter/v071/ds02_identity_test.go @@ -0,0 +1,78 @@ +package v071 + +// DS-02 测试进程身份:把"runner 记录的那份源码构建的二进制"与"真正执行的进程" +// 绑定起来。runner 用 -ldflags 注入三个只在本测试包存在的值(run nonce、完整 +// commit、源码树摘要),并在启动前后各算一次二进制 sha256;这里在进程内读 +// os.Executable 的哈希,与 runner 通过环境变量声明的期望值逐字符比较。 +// +// 这些值不是产品 metadata:不参与发布、不改 internal/version。 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "testing" +) + +// 由 runner 的 -ldflags -X 注入;未注入时保留显眼的值,绝不伪装成已知身份。 +var ( + ds02ProvenanceNonce = "unlinked" + ds02ProvenanceCommit = "unlinked" + ds02ProvenanceTree = "unlinked" +) + +type ds02ProcessIdentity struct { + Nonce string `json:"nonce"` + Commit string `json:"commit"` + SourceTree string `json:"source_tree"` + Executable string `json:"executable"` + BinarySHA256 string `json:"binary_sha256"` +} + +func TestDS02ProcessIdentity(t *testing.T) { + expectedNonce := os.Getenv("KG_DS02_EXPECT_NONCE") + if expectedNonce == "" { + t.Skip("requires runner-injected expectations (KG_DS02_EXPECT_NONCE)") + } + executable, err := os.Executable() + if err != nil { + t.Fatalf("resolve own executable: %v", err) + } + raw, err := os.ReadFile(executable) + if err != nil { + t.Fatalf("read own executable: %v", err) + } + sum := sha256.Sum256(raw) + identity := ds02ProcessIdentity{ + Nonce: ds02ProvenanceNonce, + Commit: ds02ProvenanceCommit, + SourceTree: ds02ProvenanceTree, + Executable: executable, + BinarySHA256: hex.EncodeToString(sum[:]), + } + encoded, err := json.Marshal(identity) + if err != nil { + t.Fatal(err) + } + // 单行输出给 runner 解析:证明是"这个进程自报",不是 runner 事后补写。 + t.Logf("DS02-IDENTITY %s", encoded) + cases := []struct { + name string + linked string + expected string + }{ + {"nonce", identity.Nonce, expectedNonce}, + {"commit", identity.Commit, os.Getenv("KG_DS02_EXPECT_COMMIT")}, + {"source tree", identity.SourceTree, os.Getenv("KG_DS02_EXPECT_TREE")}, + {"binary sha256", identity.BinarySHA256, os.Getenv("KG_DS02_EXPECT_BINARY_SHA256")}, + } + for _, item := range cases { + if item.expected == "" { + t.Fatalf("%s expectation missing from runner environment", item.name) + } + if item.linked != item.expected { + t.Fatalf("%s mismatch: process has %q, runner expected %q", item.name, item.linked, item.expected) + } + } +} diff --git a/internal/releaseadapter/v071/ds02_legacy_compat_test.go b/internal/releaseadapter/v071/ds02_legacy_compat_test.go new file mode 100644 index 0000000..4a079e5 --- /dev/null +++ b/internal/releaseadapter/v071/ds02_legacy_compat_test.go @@ -0,0 +1,205 @@ +package v071 + +// DS-02 历史兼容矩阵(B31):旧 manifest、V1 台账、空作业/目标身份这些 +// "缺证明"的组合必须在正式入口被拒绝,且目标全部数据(PG 逐行 + 索引文档 + +// 对象版本 + 序列)一个字节都不变。这里不做 V1→V2 迁移。 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +func ds02UniverseHash(t *testing.T, fx *writeSetFixture) string { + t.Helper() + raw, err := json.Marshal(r10State(t, fx)) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]) +} + +func ds02Plan() libraryrelease.WriteSet { + now := time.Now().UTC() + return libraryrelease.WriteSet{ + Version: libraryrelease.MigrationWriteSetVersion, + ContractVersion: 1, + SourceTenantID: wsSourceTenant, + SourceKnowledgeBaseID: wsSourceKB, + JobID: "job-ds02-legacy", + Target: "internal", + TenantID: wsTargetTenant, + KnowledgeBaseID: wsTargetKB, + BackupSnapshotID: strings.Repeat("b", 64), + TargetSnapshotID: strings.Repeat("c", 64), + CreatedAt: now, + SchemaDigest: strings.Repeat("d", 64), + Rows: []libraryrelease.WriteSetRow{}, + Universe: map[string]libraryrelease.TableFingerprint{ + "knowledges": {Count: 0, Digest: strings.Repeat("e", 64)}, + }, + LocalIDs: []libraryrelease.LocalIDMapping{ + {Table: "wiki_log_entries", Column: "id", Source: "1", Target: "10"}, + }, + } +} + +// ds02OldManifest 在归档里写一份"旧格式 manifest":缺 compatibility 契约字段。 +// 它按归档的命名规则带正确摘要,所以能证明拒绝来自结构校验,而不是文件名坏了。 +func ds02OldManifest(t *testing.T, fx *writeSetFixture) (string, string) { + t.Helper() + valid := sealSourceSnapshot(t, fx, nil) + path := filepath.Join(fx.archiveRoot, "versions", valid+".json") + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(raw, &payload); err != nil { + t.Fatal(err) + } + delete(payload, "compatibility") + encoded, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(encoded) + id := hex.EncodeToString(sum[:]) + oldPath := filepath.Join(fx.archiveRoot, "versions", id+".json") + if err := os.WriteFile(oldPath, encoded, 0600); err != nil { + t.Fatal(err) + } + fileSum := sha256.Sum256(encoded) + return id, hex.EncodeToString(fileSum[:]) +} + +// ds02LegacySeed 用与 full-shape 用例同一份真实 v071 catalog(r11Mirror)造目标行: +// 三条本地号序列必须真实存在,否则"序列不变"就是空覆盖。 +func ds02LegacySeed(t *testing.T, fx *writeSetFixture) { + t.Helper() + for _, row := range []struct { + table string + row map[string]any + }{ + {"knowledges", map[string]any{"id": "doc-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "type": "document", "title": "目标旧文档"}}, + {"chunks", map[string]any{"id": "chunk-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "knowledge_id": "doc-target", "content": "目标旧正文", "chunk_index": 0}}, + {"knowledge_tags", map[string]any{"id": "tag-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "name": "目标标签"}}, + {"knowledge_tag_relations", map[string]any{"knowledge_id": "doc-target", "tag_id": "tag-target"}}, + {"resources", map[string]any{"id": "res-target", "handle": wsHandleTarget, "tenant_id": wsTargetTenant, "provider": "minio", "storage_backend_id": "backend-target", "physical_path": wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, "res-target"), "size": int64(8)}}, + {"resource_bindings", map[string]any{"id": "bind-target", "tenant_id": wsTargetTenant, "resource_id": "res-target", "owner_type": "knowledge", "owner_id": "doc-target", "relation": "attachment"}}, + {"wiki_folders", map[string]any{"id": "folder-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "name": "目标目录"}}, + {"wiki_pages", map[string]any{"id": "wiki-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "slug": "index", "content": "目标旧 wiki"}}, + {"wiki_page_issues", map[string]any{"id": "issue-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "slug": "index", "issue_type": "review"}}, + {"wiki_log_entries", map[string]any{"id": int64(5), "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "action": "ingest"}}, + } { + r11Insert(t, fx, row.table, row.row) + } +} + +func TestDS02LegacyCompatibilityMatrixIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + // 同 catalog 初始化:十表真实列/约束/三条序列都在,目标行不是最小 schema 的残影。 + r11Mirror(t, fx) + ds02LegacySeed(t, fx) + sequences := ds02SequenceSummary(t, fx) + r10Save(t, "sequences-before", sequences) + target := fx.target(t) + oldManifest, oldManifestHash := ds02OldManifest(t, fx) + before := ds02UniverseHash(t, fx) + + // 旧 manifest 本身必须读不出来(缺兼容契约),且文件内容不变。 + archive, err := librarysnapshot.Open(fx.archiveRoot, 64*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + if _, err := archive.Load(oldManifest); err == nil || !strings.Contains(err.Error(), "compatibility") { + t.Fatalf("old manifest must be rejected for missing compatibility contract, got %v", err) + } + raw, err := os.ReadFile(filepath.Join(fx.archiveRoot, "versions", oldManifest+".json")) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(raw) + if hex.EncodeToString(sum[:]) != oldManifestHash { + t.Fatal("rejected old manifest was rewritten") + } + + cases := []struct { + name string + build func() libraryrelease.WriteSet + expect string + }{ + {"legacy-v1-plan", func() libraryrelease.WriteSet { + set := ds02Plan() + set.Version = libraryrelease.WriteSetVersion + set.ContractVersion = 0 + set.SourceTenantID = 0 + set.SourceKnowledgeBaseID = "" + set.LocalIDs = nil + set.SchemaDigest = "" + return set + }, "legacy/incomplete plan"}, + {"v1-carrying-new-semantics", func() libraryrelease.WriteSet { + set := ds02Plan() + set.Version = libraryrelease.WriteSetVersion + return set + }, "historical V1"}, + {"empty-operation", func() libraryrelease.WriteSet { + set := ds02Plan() + set.JobID = "" + return set + }, "作业"}, + {"empty-target-scope", func() libraryrelease.WriteSet { + set := ds02Plan() + set.TenantID = 0 + set.KnowledgeBaseID = "" + return set + }, "目标范围"}, + {"local-mapping-without-source", func() libraryrelease.WriteSet { + set := ds02Plan() + set.SourceTenantID = 0 + return set + }, "source contract"}, + {"old-manifest-bound-plan", func() libraryrelease.WriteSet { + set := ds02Plan() + set.TargetSnapshotID = oldManifest + return set + }, "compatibility"}, + } + for _, scenario := range cases { + set := scenario.build() + if err := set.Seal(); err != nil { + // 某些组合在 Seal 阶段就被拒绝(V1 携带迁移语义):同样是拒绝, + // 但必须点名原因,而不是别的错误。 + if !strings.Contains(err.Error(), scenario.expect) { + t.Fatalf("%s: sealed rejected for wrong reason: %v", scenario.name, err) + } + r10Save(t, "reject-"+scenario.name, map[string]string{"stage": "seal", "error": err.Error()}) + } else if err := target.AdoptWriteSet(set); err == nil { + t.Fatalf("%s: incomplete plan was adopted", scenario.name) + } else { + if !strings.Contains(err.Error(), scenario.expect) { + t.Fatalf("%s: rejected for wrong reason: %v", scenario.name, err) + } + r10Save(t, "reject-"+scenario.name, map[string]string{"stage": "adopt", "error": err.Error()}) + } + if after := ds02UniverseHash(t, fx); after != before { + t.Fatalf("%s: rejected plan changed target data (%s -> %s)", scenario.name, before, after) + } + if after := ds02SequenceSummary(t, fx); fmt.Sprint(after) != fmt.Sprint(sequences) { + t.Fatalf("%s: rejected plan changed local sequences (%v -> %v)", scenario.name, sequences, after) + } + } + r10Save(t, "universe-hash", before) +} diff --git a/internal/releaseadapter/v071/ds02_mapping_oracle_test.go b/internal/releaseadapter/v071/ds02_mapping_oracle_test.go new file mode 100644 index 0000000..9173c85 --- /dev/null +++ b/internal/releaseadapter/v071/ds02_mapping_oracle_test.go @@ -0,0 +1,242 @@ +package v071 + +// DS-02 本地号映射 oracle。 +// +// 旧检查只数"每表来源/目标各几个、是否重复",因此三种语义错误能一路绿: +// 目标互换(1→11,2→10)、来源集合被替换(999→10)、目标根本不存在(1→999)。 +// 这里的检查器只接收四样东西: +// * 测试声明的来源行(数字 id 来自夹具声明,不由被测映射器产生); +// * 独立推导的期望目标行(来源 id 经过独立算出的分配顺序得到目标数字 id); +// * 真实目标行(按目标数字 id 从数据库读回); +// * 持久账本(WriteSet.LocalIDs)。 +// +// 它不调用任何产品映射函数,也不读写存储:把 (table,column,source,target) 当 +// 精确集合比较,并用 source 关联声明行、用 target 关联真实目标行。因此 +// "账本里的配对本身正确、真实行也正确" 和 "账本把配对写错" 是两件独立的事: +// 语义副本变异只改账本内存副本,不会碰 digest 校验;反过来,改归档字节让摘要 +// 拒绝也不等于映射语义检查红,两者必须分开报告。 + +import ( + "encoding/json" + "fmt" + "sort" + "strconv" + + "knowledge-governance/internal/libraryrelease" +) + +// ds02LocalColumn 是一张含本地号的表的独立期望与真实读回。 +type ds02LocalColumn struct { + Table string + Column string + // Sources 是夹具声明的来源数字 id(升序,即分配顺序)。 + Sources []int64 + // Expected 是 source→target 的独立期望(来源序列起点 + 声明顺序)。 + Expected map[int64]int64 + // ExpectedRows 是 source→独立推导的完整目标行(逐列,含真实目标数字 id)。 + ExpectedRows map[int64]map[string]any + // Actual 是真实目标行:target 数字 id→整行。 + Actual map[int64]map[string]any +} + +func ds02RowKey(row map[string]any) string { + raw, err := json.Marshal(row) + if err != nil { + return fmt.Sprintf("", err) + } + return string(raw) +} + +// ds02CheckLocalIDMapping 返回差异;空表示账本与独立期望一致,且每个配对都能 +// 落到真实目标行上。 +func ds02CheckLocalIDMapping(columns []ds02LocalColumn, ledger []libraryrelease.LocalIDMapping) []string { + var diffs []string + declared := map[string]*ds02LocalColumn{} + for index := range columns { + column := &columns[index] + if _, ok := declared[column.Table]; ok { + diffs = append(diffs, "duplicate declared local column for "+column.Table) + continue + } + declared[column.Table] = column + } + // 解析账本:逐条严格校验,任何解析失败都是差异,不静默跳过。 + type pair struct { + source int64 + target int64 + } + observed := map[string]map[int64]int64{} + seenSource := map[string]map[int64]bool{} + seenTarget := map[string]map[int64]bool{} + seenColumn := map[string]map[string]bool{} + for _, mapping := range ledger { + column, ok := declared[mapping.Table] + if !ok { + diffs = append(diffs, "unexpected ledger table "+mapping.Table) + continue + } + if mapping.Column != column.Column { + diffs = append(diffs, fmt.Sprintf("%s ledger column %q, want %q", mapping.Table, mapping.Column, column.Column)) + continue + } + source, err := strconv.ParseInt(mapping.Source, 10, 64) + if err != nil || source <= 0 { + diffs = append(diffs, fmt.Sprintf("%s ledger source %q is not a positive integer", mapping.Table, mapping.Source)) + continue + } + target, err := strconv.ParseInt(mapping.Target, 10, 64) + if err != nil || target <= 0 { + diffs = append(diffs, fmt.Sprintf("%s ledger target %q is not a positive integer", mapping.Table, mapping.Target)) + continue + } + if observed[mapping.Table] == nil { + observed[mapping.Table] = map[int64]int64{} + seenSource[mapping.Table] = map[int64]bool{} + seenTarget[mapping.Table] = map[int64]bool{} + seenColumn[mapping.Table] = map[string]bool{} + } + if seenSource[mapping.Table][source] { + diffs = append(diffs, fmt.Sprintf("%s duplicate ledger source %d", mapping.Table, source)) + } + if seenTarget[mapping.Table][target] { + diffs = append(diffs, fmt.Sprintf("%s duplicate ledger target %d", mapping.Table, target)) + } + key := strconv.FormatInt(source, 10) + "->" + strconv.FormatInt(target, 10) + if seenColumn[mapping.Table][key] { + diffs = append(diffs, fmt.Sprintf("%s duplicate ledger pair %s", mapping.Table, key)) + } + seenSource[mapping.Table][source] = true + seenTarget[mapping.Table][target] = true + seenColumn[mapping.Table][key] = true + observed[mapping.Table][source] = target + } + for _, column := range columns { + table := column.Table + got := observed[table] + // 1) 来源集合必须精确等于声明集合。 + var missing []int64 + expectedTargets := map[int64]bool{} + for _, source := range column.Sources { + want, ok := column.Expected[source] + if !ok { + diffs = append(diffs, fmt.Sprintf("%s source %d has no independent expectation", table, source)) + continue + } + expectedTargets[want] = true + actual, ok := got[source] + if !ok { + missing = append(missing, source) + continue + } + if actual != want { + diffs = append(diffs, fmt.Sprintf("%s wrong target pair: source %d mapped to %d, want %d", table, source, actual, want)) + } + // 3) 来源 id 关联声明行、target id 关联真实目标行:必须逐列相等。 + wantRow, ok := column.ExpectedRows[source] + if !ok { + diffs = append(diffs, fmt.Sprintf("%s source %d has no expected target row", table, source)) + continue + } + actualRow, ok := column.Actual[want] + if !ok { + diffs = append(diffs, fmt.Sprintf("%s target %d has no real target row", table, want)) + continue + } + if ds02RowKey(wantRow) != ds02RowKey(actualRow) { + diffs = append(diffs, fmt.Sprintf("%s source %d -> target %d row mismatch: want %s got %s", + table, source, want, ds02RowKey(wantRow), ds02RowKey(actualRow))) + } + } + var extraSources []int64 + for source := range got { + if _, ok := column.Expected[source]; !ok { + extraSources = append(extraSources, source) + } + } + if len(missing) > 0 { + sort.Slice(missing, func(i, j int) bool { return missing[i] < missing[j] }) + diffs = append(diffs, fmt.Sprintf("%s missing ledger source %v", table, missing)) + } + if len(extraSources) > 0 { + sort.Slice(extraSources, func(i, j int) bool { return extraSources[i] < extraSources[j] }) + diffs = append(diffs, fmt.Sprintf("%s unexpected ledger source %v", table, extraSources)) + } + // 2) target 集合必须精确等于独立预测集合,而且确实存在这些目标行。 + for _, target := range got { + if !expectedTargets[target] { + diffs = append(diffs, fmt.Sprintf("%s ledger target %d is not an independently predicted target", table, target)) + } + } + for target := range expectedTargets { + if _, ok := column.Actual[target]; !ok { + diffs = append(diffs, fmt.Sprintf("%s predicted target %d does not exist in target storage", table, target)) + } + } + if len(got) == 0 && len(column.Sources) > 0 { + diffs = append(diffs, fmt.Sprintf("%s has no ledger mapping rows", table)) + } + } + return diffs +} + +// ds02FlipMappingTargets 互换同一张表两条映射的目标,模拟"配对写反"。 +func ds02FlipMappingTargets(ledger []libraryrelease.LocalIDMapping, table string) []libraryrelease.LocalIDMapping { + out := append([]libraryrelease.LocalIDMapping(nil), ledger...) + first := -1 + for index := range out { + if out[index].Table != table { + continue + } + if first < 0 { + first = index + continue + } + out[first].Target, out[index].Target = out[index].Target, out[first].Target + return out + } + return out +} + +// ds02ReplaceMapping 把同一张表第一条映射的某个字段替换成新值。 +func ds02ReplaceMapping(ledger []libraryrelease.LocalIDMapping, table, field, value string) []libraryrelease.LocalIDMapping { + out := append([]libraryrelease.LocalIDMapping(nil), ledger...) + for index := range out { + if out[index].Table != table { + continue + } + switch field { + case "source": + out[index].Source = value + case "target": + out[index].Target = value + case "column": + out[index].Column = value + } + return out + } + return out +} + +// ds02DropMapping 删掉同一张表的最后一条映射(少项)。 +func ds02DropMapping(ledger []libraryrelease.LocalIDMapping, table string) []libraryrelease.LocalIDMapping { + out := append([]libraryrelease.LocalIDMapping(nil), ledger...) + for index := len(out) - 1; index >= 0; index-- { + if out[index].Table != table { + continue + } + return append(out[:index], out[index+1:]...) + } + return out +} + +// ds02DuplicateMapping 复制同一张表的第一条映射(多项/重复来源与目标)。 +func ds02DuplicateMapping(ledger []libraryrelease.LocalIDMapping, table string) []libraryrelease.LocalIDMapping { + out := append([]libraryrelease.LocalIDMapping(nil), ledger...) + for index := range out { + if out[index].Table != table { + continue + } + return append(out, out[index]) + } + return out +} diff --git a/internal/releaseadapter/v071/ds02_mapping_unit_test.go b/internal/releaseadapter/v071/ds02_mapping_unit_test.go new file mode 100644 index 0000000..df54474 --- /dev/null +++ b/internal/releaseadapter/v071/ds02_mapping_unit_test.go @@ -0,0 +1,103 @@ +package v071 + +// 映射 oracle 自身的负例矩阵:这里不连数据库,只用合成行证明检查器对 +// "目标互换 / 不存在目标 / 来源被替换 / 少项 / 多项 / 重复 / 错列" 会红, +// 且对合法账本为绿。真实账本正例与语义副本变异在 full-shape 用例里跑同一个 +// 检查器(那里才连接真实 PG/ES/MinIO)。 + +import ( + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +func ds02UnitColumns() []ds02LocalColumn { + rows := func(target int64, id string) map[string]any { + return map[string]any{"id": id, "seq_id": target, "tenant_id": 10001} + } + return []ds02LocalColumn{{ + Table: "chunks", + Column: "seq_id", + Sources: []int64{41, 42}, + Expected: map[int64]int64{ + 41: 100, + 42: 101, + }, + ExpectedRows: map[int64]map[string]any{ + 41: rows(100, "chunk-src"), + 42: rows(101, "chunk-src2"), + }, + Actual: map[int64]map[string]any{ + 100: rows(100, "chunk-src"), + 101: rows(101, "chunk-src2"), + }, + }} +} + +func ds02UnitLedger() []libraryrelease.LocalIDMapping { + return []libraryrelease.LocalIDMapping{ + {Table: "chunks", Column: "seq_id", Source: "41", Target: "100"}, + {Table: "chunks", Column: "seq_id", Source: "42", Target: "101"}, + } +} + +func TestDS02MappingOracleUnitCases(t *testing.T) { + valid := ds02CheckLocalIDMapping(ds02UnitColumns(), ds02UnitLedger()) + if len(valid) != 0 { + t.Fatalf("valid ledger must be green, got %v", valid) + } + cases := []struct { + name string + build func() []libraryrelease.LocalIDMapping + want string + }{ + {"swapped-targets", func() []libraryrelease.LocalIDMapping { + return ds02FlipMappingTargets(ds02UnitLedger(), "chunks") + }, "wrong target pair"}, + {"nonexistent-target", func() []libraryrelease.LocalIDMapping { + return ds02ReplaceMapping(ds02UnitLedger(), "chunks", "target", "999") + }, "not an independently predicted target"}, + {"replaced-source", func() []libraryrelease.LocalIDMapping { + return ds02ReplaceMapping(ds02UnitLedger(), "chunks", "source", "999") + }, "unexpected ledger source"}, + {"missing-entry", func() []libraryrelease.LocalIDMapping { + return ds02DropMapping(ds02UnitLedger(), "chunks") + }, "missing ledger source"}, + {"duplicate-pair", func() []libraryrelease.LocalIDMapping { + return ds02DuplicateMapping(ds02UnitLedger(), "chunks") + }, "duplicate ledger source"}, + {"wrong-column", func() []libraryrelease.LocalIDMapping { + return ds02ReplaceMapping(ds02UnitLedger(), "chunks", "column", "id") + }, "ledger column"}, + {"garbled-source", func() []libraryrelease.LocalIDMapping { + return ds02ReplaceMapping(ds02UnitLedger(), "chunks", "source", "41x") + }, "not a positive integer"}, + {"unexpected-table", func() []libraryrelease.LocalIDMapping { + ledger := ds02UnitLedger() + return append(ledger, libraryrelease.LocalIDMapping{Table: "knowledges", Column: "seq_id", Source: "1", Target: "2"}) + }, "unexpected ledger table"}, + } + for _, scenario := range cases { + diffs := ds02CheckLocalIDMapping(ds02UnitColumns(), scenario.build()) + joined := strings.Join(diffs, "\n") + if len(diffs) == 0 { + t.Fatalf("%s: checker stayed green", scenario.name) + } + if !strings.Contains(joined, scenario.want) { + t.Fatalf("%s: failed for an unrelated reason:\n%s", scenario.name, joined) + } + } +} + +// 真实目标行被改错一个字也必须红:配对正确但行内容不对不算通过。 +func TestDS02MappingOracleChecksTargetRowContent(t *testing.T) { + columns := ds02UnitColumns() + columns[0].Actual[101] = map[string]any{"id": "chunk-src2", "seq_id": 101, "tenant_id": 10001, "content": "tampered"} + columns[0].ExpectedRows[42] = map[string]any{"id": "chunk-src2", "seq_id": 101, "tenant_id": 10001, "content": "expected"} + diffs := ds02CheckLocalIDMapping(columns, ds02UnitLedger()) + joined := strings.Join(diffs, "\n") + if !strings.Contains(joined, "row mismatch") { + t.Fatalf("row content tamper must be red, got %v", diffs) + } +} diff --git a/internal/releaseadapter/v071/ds02_oracle_test.go b/internal/releaseadapter/v071/ds02_oracle_test.go new file mode 100644 index 0000000..10195fa --- /dev/null +++ b/internal/releaseadapter/v071/ds02_oracle_test.go @@ -0,0 +1,1382 @@ +package v071 + +// DS-02:整库发布的独立 oracle。 +// +// 这里不调用被测的映射/改写函数来生成期望值:期望由夹具自己声明的十张表逐列内容 +// 推导(来源范围 → 目标范围的映射规则、资源定位符、location_hash 都在本文件里 +// 用字面规则重算),本地号(chunks.seq_id / knowledge_tags.seq_id / +// wiki_log_entries.id)由测试**发布前**读到的序列状态加声明顺序算出来。 +// 正文、引用、向量、对象字节、Wiki 日志映射分别有独立断言;断言本身再用 +// "真实改写目标存储 → 必须红 → 改回 → 必须绿" 证明不是空跑。 + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "sort" + "strconv" + "strings" + "sync" + "testing" + "time" + + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// ds02Vectors 是夹具声明的来源向量(逐分块不同)。索引部件由它生成, +// 不是由被测适配器生成。 +var ds02Vectors = map[string][]float64{ + "chunk-src": {0.5, 1.5}, + "chunk-src2": {-2.25, 3.75}, + "chunk-src3": {1.0, -1.0}, +} + +// ds02Objects 是夹具声明的资源字节(长度与 resources.size 一致)。 +var ds02Objects = map[string]string{ + "res-src": "abc12345", + "res-src2": "wxyz6789", +} + +var ds02TargetTables = []string{"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", + "resources", "resource_bindings", "wiki_folders", "wiki_pages", "wiki_page_issues", "wiki_log_entries"} + +func ds02Canon(t *testing.T, fx *writeSetFixture, table string, row map[string]any) map[string]any { + t.Helper() + raw, err := json.Marshal(row) + if err != nil { + t.Fatal(err) + } + var canonical []byte + if err := fx.pool.QueryRow(fx.ctx, + "SELECT to_jsonb(jsonb_populate_record(NULL::"+table+",$1::jsonb))", raw).Scan(&canonical); err != nil { + t.Fatalf("canonicalize %s: %v", table, err) + } + dec := json.NewDecoder(bytes.NewReader(canonical)) + dec.UseNumber() + var out map[string]any + if err := dec.Decode(&out); err != nil { + t.Fatal(err) + } + return out +} + +func ds02Read(t *testing.T, fx *writeSetFixture, query string, args ...any) []map[string]any { + t.Helper() + rows, err := fx.pool.Query(fx.ctx, query, args...) + if err != nil { + t.Fatalf("oracle query: %v", err) + } + defer rows.Close() + var out []map[string]any + for rows.Next() { + var text string + if err := rows.Scan(&text); err != nil { + t.Fatal(err) + } + dec := json.NewDecoder(strings.NewReader(text)) + dec.UseNumber() + var row map[string]any + if err := dec.Decode(&row); err != nil { + t.Fatal(err) + } + out = append(out, row) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + return out +} + +func ds02Normalize(rows []map[string]any) []string { + out := make([]string, 0, len(rows)) + for _, row := range rows { + raw, _ := json.Marshal(row) + out = append(out, string(raw)) + } + sort.Strings(out) + return out +} + +// ds02Compare 返回人可读的差异;空串表示逐列内容完全一致(含行数)。 +func ds02Compare(table string, want, got []map[string]any) string { + w, g := ds02Normalize(want), ds02Normalize(got) + if len(w) == len(g) { + same := true + for i := range w { + if w[i] != g[i] { + same = false + break + } + } + if same { + return "" + } + } + seen := map[string]bool{} + for _, row := range g { + seen[row] = true + } + var missing, extra []string + for _, row := range w { + if !seen[row] { + missing = append(missing, row) + } + } + present := map[string]bool{} + for _, row := range w { + present[row] = true + } + for _, row := range g { + if !present[row] { + extra = append(extra, row) + } + } + if len(missing) > 6 { + missing = missing[:6] + } + if len(extra) > 6 { + extra = extra[:6] + } + return fmt.Sprintf("%s: want %d rows, got %d; missing=%v extra=%v", table, len(w), len(g), missing, extra) +} + +// ds02SequenceNext 是本地号分配的独立期望:发布前序列状态 + 是否已调用。 +func ds02SequenceNext(t *testing.T, fx *writeSetFixture, sequence string) int64 { + t.Helper() + var last int64 + var called bool + if err := fx.pool.QueryRow(fx.ctx, "SELECT last_value,is_called FROM "+sequence).Scan(&last, &called); err != nil { + t.Fatal(err) + } + if called { + return last + 1 + } + return last +} + +// ds02Spec 是夹具声明的来源内容(十表逐列 + 向量 + 对象字节)。 +type ds02Spec struct { + rows map[string][]map[string]any + vectors map[string][]float64 + objects map[string]string +} + +// ds02SourceRows 是来源十表的纯声明(未按目标 schema 规范化);bundle 导出与 +// 真跑夹具共用,保证"同一输入"来自同一份声明。 +func ds02SourceRows() map[string][]map[string]any { + tag := func(id string, seq int64) map[string]any { + return map[string]any{"id": id, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "name": "name-" + id, "color": "#112233", "sort_order": 3, "seq_id": seq, + "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z"} + } + sourcePath := func(id string) string { + return wsLocator("backend-source", "oss", "source-bucket", wsSourceTenant, id) + } + sourceHash := func(id string) string { + sum := sha256.Sum256([]byte(sourcePath(id))) + return hex.EncodeToString(sum[:]) + } + rows := map[string][]map[string]any{ + "knowledges": { + {"id": "doc-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "type": "document", + "title": "来源文档一", "description": "desc-1", "source": "resource://" + wsHandleSource, + "parse_status": "completed", "enable_status": "enabled", "embedding_model_id": "source-model", + "file_name": "one.md", "file_type": "md", "file_size": int64(8), "file_path": "source/one.md", + "file_hash": strings.Repeat("1", 64), "storage_size": int64(8), "metadata": map[string]any{"k": "v1"}, + "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z", + "processed_at": "2026-01-03T00:00:00Z", "summary_status": "none", "channel": "web", + "pending_subtasks_count": 0}, + {"id": "doc-src2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "type": "document", + "title": "来源文档二", "description": "desc-2", "source": "upload", + "parse_status": "completed", "enable_status": "enabled", "embedding_model_id": "source-model", + "file_name": "two.md", "file_type": "md", "file_size": int64(4), "file_path": "source/two.md", + "file_hash": strings.Repeat("2", 64), "storage_size": int64(4), "metadata": map[string]any{"k": "v2"}, + "created_at": "2026-01-04T00:00:00Z", "updated_at": "2026-01-05T00:00:00Z", + "summary_status": "none", "channel": "web", "pending_subtasks_count": 1}, + }, + "chunks": { + {"id": "chunk-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "knowledge_id": "doc-src", "content": "来源正文一 resource://" + wsHandleSource, + "chunk_index": 0, "is_enabled": true, "start_at": 0, "end_at": 12, + "next_chunk_id": "chunk-src2", "chunk_type": "text", "status": 1, "flags": 1, + "seq_id": int64(41), "content_hash": strings.Repeat("3", 64), + "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z"}, + {"id": "chunk-src2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "knowledge_id": "doc-src", "content": "来源正文二", "chunk_index": 1, "is_enabled": true, + "start_at": 12, "end_at": 20, "pre_chunk_id": "chunk-src", "chunk_type": "text", + "status": 1, "flags": 1, "seq_id": int64(42), "content_hash": strings.Repeat("4", 64), + "created_at": "2026-01-03T00:00:00Z", "updated_at": "2026-01-04T00:00:00Z"}, + // 第三块专门给 parent_chunk_id 分支一个非空命中(旧夹具全为 null)。 + {"id": "chunk-src3", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "knowledge_id": "doc-src", "content": "来源正文三", "chunk_index": 2, "is_enabled": true, + "start_at": 20, "end_at": 28, "parent_chunk_id": "chunk-src", "chunk_type": "text", + "status": 1, "flags": 1, "seq_id": int64(43), "content_hash": strings.Repeat("7", 64), + "created_at": "2026-01-05T00:00:00Z", "updated_at": "2026-01-06T00:00:00Z"}, + }, + "knowledge_tags": {tag("tag-src", 11), tag("tag-src2", 12)}, + "knowledge_tag_relations": { + {"knowledge_id": "doc-src", "tag_id": "tag-src", "created_at": "2026-01-01T00:00:00Z"}, + {"knowledge_id": "doc-src2", "tag_id": "tag-src2", "created_at": "2026-01-03T00:00:00Z"}, + }, + "resources": { + {"id": "res-src", "handle": wsHandleSource, "tenant_id": wsSourceTenant, + "storage_backend_id": "backend-source", "provider": "oss", "physical_path": sourcePath("res-src"), + "location_hash": sourceHash("res-src"), "kind": "file", "mime_type": "image/png", + "original_name": "a.png", "size": int64(8), "content_hash": strings.Repeat("5", 64), + "lifecycle": "persistent", "state": "active", + "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z"}, + {"id": "res-src2", "handle": strings.Repeat("g", 22), "tenant_id": wsSourceTenant, + "storage_backend_id": "backend-source", "provider": "oss", "physical_path": sourcePath("res-src2"), + "location_hash": sourceHash("res-src2"), "kind": "file", "mime_type": "image/png", + "original_name": "b.png", "size": int64(8), "content_hash": strings.Repeat("6", 64), + "lifecycle": "persistent", "state": "active", + "created_at": "2026-01-03T00:00:00Z", "updated_at": "2026-01-04T00:00:00Z"}, + }, + "resource_bindings": { + {"id": "bind-src", "resource_id": "res-src", "tenant_id": wsSourceTenant, + "owner_type": "knowledge", "owner_id": "doc-src", "relation": "attachment", + "created_at": "2026-01-01T00:00:00Z"}, + {"id": "bind-src2", "resource_id": "res-src2", "tenant_id": wsSourceTenant, + "owner_type": "knowledge", "owner_id": "doc-src2", "relation": "attachment", + "created_at": "2026-01-03T00:00:00Z"}, + }, + "wiki_folders": { + {"id": "folder-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "parent_id": "", "name": "根目录", "path": "root", "depth": 0, "sort_order": 1, + "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z"}, + {"id": "folder-src2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "parent_id": "folder-src", "name": "子目录", "path": "root/sub", "depth": 1, "sort_order": 2, + "created_at": "2026-01-03T00:00:00Z", "updated_at": "2026-01-04T00:00:00Z"}, + }, + "wiki_pages": { + {"id": "wiki-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "slug": "index", + "title": "首页", "page_type": "summary", "status": "published", "content": "来源 wiki 首页", + "summary": "摘要一", "parent_slug": "", "folder_id": "folder-src", "category_path": []any{"root"}, + "wiki_path": "index", "depth": 0, "sort_order": 1, + "source_refs": []any{"doc-src|来源文档一"}, + "chunk_refs": []any{"chunk-src"}, "in_links": []any{}, "out_links": []any{"guide"}, + "page_metadata": map[string]any{"lang": "zh"}, "aliases": []any{"home"}, "version": 1, + "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z"}, + {"id": "wiki-src2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "slug": "guide", + "title": "指南", "page_type": "summary", "status": "published", "content": "来源 wiki 指南", + "summary": "摘要二", "parent_slug": "", "folder_id": "folder-src2", "category_path": []any{"root", "sub"}, + "wiki_path": "root/sub/guide", "depth": 1, "sort_order": 2, + "source_refs": []any{"doc-src2|来源文档二"}, + "chunk_refs": []any{"chunk-src2"}, "in_links": []any{"guide"}, "out_links": []any{}, + "page_metadata": map[string]any{"lang": "zh"}, "aliases": []any{}, "version": 1, + "created_at": "2026-01-03T00:00:00Z", "updated_at": "2026-01-04T00:00:00Z"}, + }, + "wiki_page_issues": { + {"id": "issue-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "slug": "index", + "issue_type": "review", "description": "需要复核", "suspected_knowledge_ids": []any{"doc-src"}, + "status": "pending", "reported_by": "fixture", + "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-02T00:00:00Z"}, + }, + "wiki_log_entries": { + {"id": int64(1), "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "action": "ingest", + "knowledge_id": "doc-src", "doc_title": "来源文档一", "summary": "首次入库", + "pages_affected": []any{map[string]any{"slug": "index", "title": "首页"}}, + "created_at": "2026-01-01T00:00:00Z"}, + {"id": int64(2), "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "action": "update", + "knowledge_id": "doc-src2", "doc_title": "来源文档二", "summary": "更新", + "pages_affected": []any{map[string]any{"slug": "guide", "title": "指南"}}, + "created_at": "2026-01-03T00:00:00Z"}, + }, + } + return rows +} + +func ds02SourceSpec(t *testing.T, fx *writeSetFixture) ds02Spec { + t.Helper() + rows := ds02SourceRows() + for table, list := range rows { + for i, row := range list { + rows[table][i] = ds02Canon(t, fx, table, row) + } + } + return ds02Spec{rows: rows, vectors: ds02Vectors, objects: ds02Objects} +} + +// ds02Expectation 是独立推导的期望:逐表逐列的行、资源定位符、本地号分配, +// 以及"来源数字 id → 期望目标行"的对应(mapping oracle 用它把配对落到真实行)。 +type ds02Expectation struct { + Rows map[string][]map[string]any + Paths map[string]string + Local map[string]map[int64]int64 + RowsBySource map[string]map[int64]map[string]any +} + +// ds02Expected 从声明内容独立推导目标范围应有的十表逐列内容。 +func ds02Expected(t *testing.T, fx *writeSetFixture, spec ds02Spec) ds02Expectation { + t.Helper() + targetBackend, targetProvider := "backend-target", "minio" + locator := func(id string) string { + // 独立重算定位符:storage:///://// + return fmt.Sprintf("storage://%s/%s://%s/%d/%s/a.png", targetBackend, targetProvider, fx.bucket, wsTargetTenant, id) + } + next := map[string]int64{ + "chunks": ds02SequenceNext(t, fx, "chunks_seq_id_seq"), + "knowledge_tags": ds02SequenceNext(t, fx, "knowledge_tags_seq_id_seq"), + "wiki_log_entries": ds02SequenceNext(t, fx, "wiki_log_entries_id_seq"), + } + local := map[string]map[int64]int64{"chunks": {}, "knowledge_tags": {}, "wiki_log_entries": {}} + for _, table := range []string{"chunks", "knowledge_tags", "wiki_log_entries"} { + sources := []int64{} + for _, row := range spec.rows[table] { + raw := row["seq_id"] + if table == "wiki_log_entries" { + raw = row["id"] + } + value, err := strconv.ParseInt(fmt.Sprint(raw), 10, 64) + if err != nil { + t.Fatalf("%s local id: %v", table, err) + } + sources = append(sources, value) + } + sort.Slice(sources, func(i, j int) bool { return sources[i] < sources[j] }) + value := next[table] + for _, source := range sources { + local[table][source] = value + value++ + } + } + expected := map[string][]map[string]any{} + paths := map[string]string{} + rowsBySource := map[string]map[int64]map[string]any{} + for table, rows := range spec.rows { + for _, declared := range rows { + row := map[string]any{} + for key, value := range declared { + row[key] = value + } + rule := ds02ScopeDecl[table] + if rule.Tenant { + row["tenant_id"] = json.Number(strconv.FormatUint(wsTargetTenant, 10)) + } + if rule.KnowledgeBase { + row["knowledge_base_id"] = wsTargetKB + } + var sourceKey int64 + switch table { + case "chunks", "knowledge_tags": + sourceKey, _ = strconv.ParseInt(fmt.Sprint(row["seq_id"]), 10, 64) + row["seq_id"] = json.Number(strconv.FormatInt(local[table][sourceKey], 10)) + case "wiki_log_entries": + sourceKey, _ = strconv.ParseInt(fmt.Sprint(row["id"]), 10, 64) + row["id"] = json.Number(strconv.FormatInt(local[table][sourceKey], 10)) + case "resources": + id := fmt.Sprint(row["id"]) + expectedPath := locator(id) + paths[id] = expectedPath + row["physical_path"] = expectedPath + sum := sha256.Sum256([]byte(expectedPath)) + row["location_hash"] = hex.EncodeToString(sum[:]) + row["storage_backend_id"] = targetBackend + row["provider"] = targetProvider + } + canonical := ds02Canon(t, fx, table, row) + expected[table] = append(expected[table], canonical) + if _, ok := local[table]; ok { + if rowsBySource[table] == nil { + rowsBySource[table] = map[int64]map[string]any{} + } + rowsBySource[table][sourceKey] = canonical + } + } + } + return ds02Expectation{Rows: expected, Paths: paths, Local: local, RowsBySource: rowsBySource} +} + +// ds02BucketPlaceholder 让冻结 bundle 不绑定某个一次性桶名:两个隔离目标各自把 +// 环境桶替换进来,输入内容(行、id、字节)本身逐字节相同。 +const ds02BucketPlaceholder = "%BUCKET%" + +// ds02SeedRows 是"发布前目标实例本来就有的数据"的声明。bundle 导出与夹具插入共用 +// 这一份,避免两份行内容漂移。 +func ds02SeedRows() []struct { + table string + row map[string]any +} { + return []struct { + table string + row map[string]any + }{ + {"knowledges", map[string]any{"id": "doc-other", "tenant_id": 10001, "knowledge_base_id": wsOtherKB, "type": "document", "title": "别的知识库文档", "source": "x"}}, + {"knowledges", map[string]any{"id": "doc-foreign", "tenant_id": 20000, "knowledge_base_id": "kb-foreign", "type": "document", "title": "外部租户文档", "source": "x"}}, + {"chunks", map[string]any{"id": "chunk-other", "tenant_id": 10001, "knowledge_base_id": wsOtherKB, "knowledge_id": "doc-other", "content": "别的知识库正文", "chunk_index": 0, "start_at": 0, "end_at": 1, "seq_id": int64(7)}}, + {"knowledge_tags", map[string]any{"id": "tag-other", "tenant_id": 10001, "knowledge_base_id": wsOtherKB, "name": "别的知识库标签", "seq_id": int64(9)}}, + {"knowledge_tag_relations", map[string]any{"knowledge_id": "doc-other", "tag_id": "tag-other"}}, + {"resources", map[string]any{"id": "res-other", "handle": wsHandleOther, "tenant_id": 10001, "provider": "minio", "physical_path": wsLocator("backend-target", "minio", ds02BucketPlaceholder, 10001, "res-other"), "storage_backend_id": "backend-target", "size": int64(8)}}, + {"resource_bindings", map[string]any{"id": "bind-other", "resource_id": "res-other", "tenant_id": 10001, "owner_type": "knowledge", "owner_id": "doc-other", "relation": "attachment"}}, + {"wiki_folders", map[string]any{"id": "folder-other", "tenant_id": 10001, "knowledge_base_id": wsOtherKB, "name": "别的知识库目录"}}, + {"wiki_pages", map[string]any{"id": "wiki-other", "tenant_id": 10001, "knowledge_base_id": wsOtherKB, "slug": "index", "content": "别的知识库 wiki"}}, + {"wiki_page_issues", map[string]any{"id": "issue-other", "tenant_id": 10001, "knowledge_base_id": wsOtherKB, "slug": "index", "issue_type": "review", "reported_by": "fixture", "description": "x"}}, + // 这条是 B03 的碰撞输入:来源日志数字 id=1 与其它知识库已有的 id=1 同值。 + {"wiki_log_entries", map[string]any{"id": int64(1), "tenant_id": 10001, "knowledge_base_id": wsOtherKB, "action": "ingest"}}, + // 目标范围自己的数据:整库发布必须把它们替换成来源内容。 + {"knowledges", map[string]any{"id": "doc-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "type": "document", "title": "目标旧文档", "source": "x", "parse_status": "completed", "pending_subtasks_count": 0}}, + {"chunks", map[string]any{"id": "chunk-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "knowledge_id": "doc-target", "content": "目标旧正文", "chunk_index": 0, "start_at": 0, "end_at": 1, "seq_id": int64(8)}}, + {"wiki_pages", map[string]any{"id": "wiki-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, "slug": "index", "content": "目标旧 wiki"}}, + } +} + +// ds02SeedDocs 是发布前就存在的索引文档(目标旧文档 + 外围租户文档)。 +func ds02SeedDocs() []struct { + id string + tenant uint64 + kb string + knowledge string + content string +} { + return []struct { + id string + tenant uint64 + kb string + knowledge string + content string + }{ + {"chunk-target", wsTargetTenant, wsTargetKB, "doc-target", "目标旧正文"}, + {"chunk-foreign", 20000, "kb-foreign", "doc-foreign", "外部正文"}, + } +} + +// ds02SeedObjects 是发布前就存在的对象字节(外围对象 res-other 用于哨兵)。 +func ds02SeedObjects() map[string]string { + return map[string]string{"res-other": strings.Repeat("z", 8)} +} + +func ds02SubstituteBucket(value string, bucket string) string { + return strings.ReplaceAll(value, ds02BucketPlaceholder, bucket) +} + +func ds02Seed(t *testing.T, fx *writeSetFixture) { + t.Helper() + for id, body := range ds02SeedObjects() { + path := wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, id) + if err := fx.objects.s3.Put(fx.ctx, "minio", path, strings.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + } + for _, row := range ds02SeedRows() { + r11Insert(t, fx, row.table, ds02SeedRow(row.row, fx.bucket)) + } + for _, doc := range ds02SeedDocs() { + fx.indexDoc(t, doc.id, doc.tenant, doc.kb, doc.knowledge, doc.content) + } +} + +// ds02SeedRow 返回替换了环境桶的副本,不改共享声明。 +func ds02SeedRow(row map[string]any, bucket string) map[string]any { + out := map[string]any{} + for key, value := range row { + if text, ok := value.(string); ok { + out[key] = ds02SubstituteBucket(text, bucket) + } else { + out[key] = value + } + } + return out +} + +// ds02Seal 用声明内容封一份十表全非空快照(索引向量来自夹具声明)。 +func ds02Seal(t *testing.T, fx *writeSetFixture, spec ds02Spec) string { + t.Helper() + return ds02SealScope(t, fx, spec, wsSourceTenant, wsSourceKB) +} + +// ds02SealScope 允许指定来源范围:冻结 bundle 用"同租户不同知识库"的对照场景。 +func ds02SealScope(t *testing.T, fx *writeSetFixture, spec ds02Spec, sourceTenant uint64, sourceKB string) string { + t.Helper() + archive, err := librarysnapshot.Open(fx.archiveRoot, 128*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + encode := func(value any) []byte { + raw, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return raw + } + kinds := map[string]string{"knowledges": "database", "chunks": "database", "knowledge_tags": "database", + "knowledge_tag_relations": "database", "resources": "database", "resource_bindings": "database", + "wiki_folders": "wiki", "wiki_pages": "wiki", "wiki_page_issues": "wiki", "wiki_log_entries": "wiki"} + parts := []librarysnapshot.Part{} + for _, table := range ds02TargetTables { + part, err := archive.Put(bytes.NewReader(encode(spec.rows[table]))) + if err != nil { + t.Fatal(err) + } + part.Kind, part.Name, part.Count = kinds[table], table, int64(len(spec.rows[table])) + parts = append(parts, part) + } + for _, id := range []string{"res-src", "res-src2"} { + part, err := archive.Put(bytes.NewReader([]byte(spec.objects[id]))) + if err != nil { + t.Fatal(err) + } + part.Kind, part.Name, part.Count = "resource", id, 1 + parts = append(parts, part) + } + indexRows := []map[string]any{} + for _, chunk := range spec.rows["chunks"] { + id := fmt.Sprint(chunk["id"]) + indexRows = append(indexRows, map[string]any{"id": id, "source": map[string]any{ + "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "knowledge_id": chunk["knowledge_id"], "chunk_id": id, "source_id": id, + "content": chunk["content"], "embedding": spec.vectors[id]}}) + } + indexPart, err := archive.Put(bytes.NewReader(encode(indexRows))) + if err != nil { + t.Fatal(err) + } + indexPart.Kind, indexPart.Name, indexPart.Count = "index", "chunks", int64(len(indexRows)) + parts = append(parts, indexPart) + manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, + Format: librarysnapshot.Format, Scope: "internal", TenantID: sourceTenant, KnowledgeBaseID: sourceKB, + CreatedAt: time.Now().UTC(), Parts: parts, + Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", + EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("a", 64)}} + id, err := archive.Seal(manifest) + if err != nil { + t.Fatalf("seal ds02 snapshot: %v", err) + } + return id +} + +// ds02Docs 读回索引里的全部文档(独立查询,不经过被测 SearchExporter)。 +func ds02Docs(t *testing.T, fx *writeSetFixture) map[string]map[string]any { + t.Helper() + body := `{"size":1000,"query":{"match_all":{}}}` + request, err := http.NewRequestWithContext(fx.ctx, "POST", fx.searchBase+"/"+fx.index+"/_search", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", "application/json") + response, err := fx.client.Do(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != 200 { + raw, _ := io.ReadAll(response.Body) + t.Fatalf("search %d: %s", response.StatusCode, raw) + } + var payload struct { + Hits struct { + Hits []struct { + ID string `json:"_id"` + Source map[string]any `json:"_source"` + } `json:"hits"` + } `json:"hits"` + } + if err := json.NewDecoder(response.Body).Decode(&payload); err != nil { + t.Fatal(err) + } + out := map[string]map[string]any{} + for _, hit := range payload.Hits.Hits { + out[hit.ID] = hit.Source + } + return out +} + +// ds02ScopeRule 是本测试自己声明的表范围规则,用来独立推导目标行该按什么范围读。 +// 刻意不读产品的 tableHasTenant/tablesWithKB:期望与查询共用产品的范围分类时, +// "两边一起错" 会被判绿。声明本身还要与真实 schema 的列集合对拍(ds02VerifyScopeDecl)。 +type ds02ScopeRule struct { + Tenant bool + KnowledgeBase bool +} + +var ds02ScopeDecl = map[string]ds02ScopeRule{ + "knowledges": {Tenant: true, KnowledgeBase: true}, + "chunks": {Tenant: true, KnowledgeBase: true}, + "knowledge_tags": {Tenant: true, KnowledgeBase: true}, + "knowledge_tag_relations": {Tenant: false, KnowledgeBase: false}, + "resources": {Tenant: true, KnowledgeBase: false}, + "resource_bindings": {Tenant: true, KnowledgeBase: false}, + "wiki_folders": {Tenant: true, KnowledgeBase: true}, + "wiki_pages": {Tenant: true, KnowledgeBase: true}, + "wiki_page_issues": {Tenant: true, KnowledgeBase: true}, + "wiki_log_entries": {Tenant: true, KnowledgeBase: true}, +} + +// ds02VerifyScopeDecl 把声明的表/列集合与真实 schema 对拍:表集合必须恰好是这十张, +// 每张表是否存在 tenant_id / knowledge_base_id 列必须与声明一致。 +func ds02VerifyScopeDecl(t *testing.T, fx *writeSetFixture) { + t.Helper() + declared := map[string]bool{} + for table := range ds02ScopeDecl { + declared[table] = true + } + actual := map[string]bool{} + for _, table := range ds02TargetTables { + actual[table] = true + } + if fmt.Sprint(declared) != fmt.Sprint(actual) { + t.Fatalf("scope declaration tables %v do not match target table set %v", declared, actual) + } + for _, table := range ds02TargetTables { + rule := ds02ScopeDecl[table] + rows := ds02Read(t, fx, `SELECT jsonb_build_object('c', column_name)::text AS row FROM information_schema.columns + WHERE table_schema='public' AND table_name=$1`, table) + hasTenant, hasKB := false, false + for _, row := range rows { + switch fmt.Sprint(row["c"]) { + case "tenant_id": + hasTenant = true + case "knowledge_base_id": + hasKB = true + } + } + if hasTenant != rule.Tenant || hasKB != rule.KnowledgeBase { + t.Fatalf("%s scope declaration (tenant=%v kb=%v) disagrees with schema (tenant=%v kb=%v)", + table, rule.Tenant, rule.KnowledgeBase, hasTenant, hasKB) + } + } + r10Save(t, "scope-declaration", ds02ScopeDecl) +} + +// ds02Egress 是一条被观测到的出站请求。phase 把"发布段"与"oracle 读段/夹具" +// 分开记账:只有发布段的 embedding 计数才能支撑零调用声明。 +type ds02Egress struct { + Phase string `json:"phase"` + Client string `json:"client"` + Method string `json:"method"` + URL string `json:"url"` +} + +type ds02EgressRecorder struct { + mu sync.Mutex + phase string + entries []ds02Egress +} + +func (r *ds02EgressRecorder) setPhase(phase string) { + r.mu.Lock() + r.phase = phase + r.mu.Unlock() +} + +func (r *ds02EgressRecorder) wrap(client string, base http.RoundTripper) http.RoundTripper { + if base == nil { + base = http.DefaultTransport + } + return roundTripFunc(func(request *http.Request) (*http.Response, error) { + r.mu.Lock() + r.entries = append(r.entries, ds02Egress{Phase: r.phase, Client: client, Method: request.Method, URL: request.URL.String()}) + r.mu.Unlock() + return base.RoundTrip(request) + }) +} + +func (r *ds02EgressRecorder) entriesFor(phase string) []ds02Egress { + r.mu.Lock() + defer r.mu.Unlock() + var out []ds02Egress + for _, entry := range r.entries { + if entry.Phase == phase { + out = append(out, entry) + } + } + return out +} + +// ds02IsEmbeddingTarget 按目的地址识别向量化调用,而不是只看品牌字符串: +// 任何路径里的 embed/embeddings/encode 段都算;已知模型服务域名也算。 +func ds02IsEmbeddingTarget(raw string) bool { + parsed, err := url.Parse(raw) + if err != nil { + return false + } + path := strings.ToLower(parsed.Path) + for _, marker := range []string{"embedding", "embeddings", "/embed", "/encode", "embeddings/create"} { + if strings.Contains(path, marker) { + return true + } + } + host := strings.ToLower(parsed.Hostname()) + for _, brand := range []string{"dashscope", "openai", "minimax", "siliconflow", "deepseek", "volces", "aliyuncs"} { + if strings.Contains(host, brand) { + return true + } + } + return false +} + +// ds02EgressDiffs 是纯函数:给定某一段的请求与声明的 client 清单,返回差异。 +func ds02EgressDiffs(see []ds02Egress, inventory []string) []string { + var diffs []string + seenClients := map[string]bool{} + for _, entry := range see { + seenClients[entry.Client] = true + if ds02IsEmbeddingTarget(entry.URL) { + diffs = append(diffs, fmt.Sprintf("embedding calls: want 0 got %s %s (%s)", entry.Method, entry.URL, entry.Client)) + } + } + for _, client := range inventory { + if !seenClients[client] { + diffs = append(diffs, "declared egress client never observed in publish: "+client) + } + } + for client := range seenClients { + known := false + for _, declared := range inventory { + if client == declared { + known = true + } + } + if !known { + diffs = append(diffs, "undeclared egress client observed in publish: "+client) + } + } + return diffs +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) } + +// ds02RecordingHTTPClient 适配 AWS SDK 的 HTTPClient 接口(只有 Do)。 +type ds02RecordingHTTPClient struct { + recorder *ds02EgressRecorder + name string + next awss3.HTTPClient +} + +func (c *ds02RecordingHTTPClient) Do(request *http.Request) (*http.Response, error) { + c.recorder.mu.Lock() + c.recorder.entries = append(c.recorder.entries, ds02Egress{Phase: c.recorder.phase, Client: c.name, Method: request.Method, URL: request.URL.String()}) + c.recorder.mu.Unlock() + return c.next.Do(request) +} + +// ds02AttachEgress 把本测试全部可达 HTTP 构造器接到同一个记录器上,并返回可观测的 +// client 清单:ES(产品搜索/备份/独立读回共用 fx.client)与对象存储 SDK 客户端。 +// 正式装配里的 object gateway client 不在本测试路径上(本测试直接注入 S3 存储)。 +func ds02AttachEgress(t *testing.T, fx *writeSetFixture) (*ds02EgressRecorder, []string) { + t.Helper() + recorder := &ds02EgressRecorder{phase: "fixture"} + fx.client.Transport = recorder.wrap("elastic", http.DefaultTransport) + t.Cleanup(func() { + fx.client.Transport = nil + }) + options := fx.objects.s3.client.Options() + next := options.HTTPClient + if next == nil { + next = http.DefaultClient + } + options.HTTPClient = &ds02RecordingHTTPClient{recorder: recorder, name: "object-store", next: next} + fx.objects.s3.client = awss3.New(options) + return recorder, []string{"elastic", "object-store"} +} + +// ds02Check 是 oracle 本体:返回逐项差异;空 = 全绿。 +func ds02Check(t *testing.T, fx *writeSetFixture, spec ds02Spec, expected map[string][]map[string]any, + paths map[string]string, preserved map[string][]map[string]any, + recorder *ds02EgressRecorder, inventory []string) []string { + t.Helper() + var diffs []string + scope := func(table string) (string, []any) { + rule, ok := ds02ScopeDecl[table] + if !ok { + t.Fatalf("table %s missing from independent scope declaration", table) + } + if !rule.Tenant { + return "SELECT to_jsonb(x)::text FROM " + table + " AS x ORDER BY 1", nil + } + if rule.KnowledgeBase { + return "SELECT to_jsonb(x)::text FROM " + table + " AS x WHERE tenant_id=$1 AND knowledge_base_id=$2 ORDER BY 1", + []any{wsTargetTenant, wsTargetKB} + } + return "SELECT to_jsonb(x)::text FROM " + table + " AS x WHERE tenant_id=$1 ORDER BY 1", []any{wsTargetTenant} + } + for _, table := range ds02TargetTables { + query, args := scope(table) + if diff := ds02Compare(table, expected[table], ds02Read(t, fx, query, args...)); diff != "" { + diffs = append(diffs, diff) + } + // 目标范围之外的行必须一字不动(含其它知识库/租户以及它们的历史资源)。 + if !ds02ScopeDecl[table].Tenant { + continue + } + other := "SELECT to_jsonb(x)::text FROM " + table + " AS x WHERE tenant_id<>$1" + if ds02ScopeDecl[table].KnowledgeBase { + other = "SELECT to_jsonb(x)::text FROM " + table + " AS x WHERE NOT (tenant_id=$1 AND knowledge_base_id=$2)" + } + if diff := ds02Compare(table+"(non-target)", preserved[table], ds02Read(t, fx, other, args...)); diff != "" { + diffs = append(diffs, diff) + } + } + // 引用清单:逐种关系分别断言 violations=0 **且** matched>0。范围外关系显式列出, + // 不把"七组 OR 查询"叫"全部引用"。 + type relation struct { + name string + sql string + matched string + covered bool + reason string + } + relations := []relation{ + {"chunk→knowledge", `SELECT count(*) FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND NOT EXISTS(SELECT 1 FROM knowledges k WHERE k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id)`, + `SELECT count(*) FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND EXISTS(SELECT 1 FROM knowledges k WHERE k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id)`, true, ""}, + {"chunk.pre_chunk_id→chunk", `SELECT count(*) FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.pre_chunk_id<>'' AND NOT EXISTS(SELECT 1 FROM chunks p WHERE p.id=c.pre_chunk_id AND p.tenant_id=c.tenant_id AND p.knowledge_base_id=c.knowledge_base_id)`, + `SELECT count(*) FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.pre_chunk_id<>'' AND EXISTS(SELECT 1 FROM chunks p WHERE p.id=c.pre_chunk_id AND p.tenant_id=c.tenant_id AND p.knowledge_base_id=c.knowledge_base_id)`, true, ""}, + {"chunk.next_chunk_id→chunk", `SELECT count(*) FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.next_chunk_id<>'' AND NOT EXISTS(SELECT 1 FROM chunks n WHERE n.id=c.next_chunk_id AND n.tenant_id=c.tenant_id AND n.knowledge_base_id=c.knowledge_base_id)`, + `SELECT count(*) FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.next_chunk_id<>'' AND EXISTS(SELECT 1 FROM chunks n WHERE n.id=c.next_chunk_id AND n.tenant_id=c.tenant_id AND n.knowledge_base_id=c.knowledge_base_id)`, true, ""}, + {"chunk.parent_chunk_id→chunk", `SELECT count(*) FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND coalesce(c.parent_chunk_id,'')<>'' AND NOT EXISTS(SELECT 1 FROM chunks q WHERE q.id=c.parent_chunk_id AND q.tenant_id=c.tenant_id AND q.knowledge_base_id=c.knowledge_base_id)`, + `SELECT count(*) FROM chunks c WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND coalesce(c.parent_chunk_id,'')<>'' AND EXISTS(SELECT 1 FROM chunks q WHERE q.id=c.parent_chunk_id AND q.tenant_id=c.tenant_id AND q.knowledge_base_id=c.knowledge_base_id)`, true, ""}, + {"relation→tag", `SELECT count(*) FROM knowledge_tag_relations r WHERE NOT EXISTS(SELECT 1 FROM knowledge_tags t WHERE t.id=r.tag_id)`, + `SELECT count(*) FROM knowledge_tag_relations r WHERE EXISTS(SELECT 1 FROM knowledge_tags t WHERE t.id=r.tag_id)`, true, ""}, + {"relation→knowledge", `SELECT count(*) FROM knowledge_tag_relations r WHERE NOT EXISTS(SELECT 1 FROM knowledges k WHERE k.id=r.knowledge_id)`, + `SELECT count(*) FROM knowledge_tag_relations r WHERE EXISTS(SELECT 1 FROM knowledges k WHERE k.id=r.knowledge_id)`, true, ""}, + {"binding→resource", `SELECT count(*) FROM resource_bindings b WHERE b.tenant_id=$1 AND NOT EXISTS(SELECT 1 FROM resources r WHERE r.id=b.resource_id)`, + `SELECT count(*) FROM resource_bindings b WHERE b.tenant_id=$1 AND EXISTS(SELECT 1 FROM resources r WHERE r.id=b.resource_id)`, true, ""}, + {"binding→knowledge", `SELECT count(*) FROM resource_bindings b WHERE b.tenant_id=$1 AND b.owner_type='knowledge' AND NOT EXISTS(SELECT 1 FROM knowledges k WHERE k.id=b.owner_id)`, + `SELECT count(*) FROM resource_bindings b WHERE b.tenant_id=$1 AND b.owner_type='knowledge' AND EXISTS(SELECT 1 FROM knowledges k WHERE k.id=b.owner_id)`, true, ""}, + {"wiki page→folder", `SELECT count(*) FROM wiki_pages p WHERE p.tenant_id=$1 AND p.knowledge_base_id=$2 AND p.folder_id<>'' AND NOT EXISTS(SELECT 1 FROM wiki_folders f WHERE f.id=p.folder_id)`, + `SELECT count(*) FROM wiki_pages p WHERE p.tenant_id=$1 AND p.knowledge_base_id=$2 AND p.folder_id<>''`, true, ""}, + {"wiki folder→parent folder", `SELECT count(*) FROM wiki_folders f WHERE f.tenant_id=$1 AND f.knowledge_base_id=$2 AND f.parent_id<>'' AND NOT EXISTS(SELECT 1 FROM wiki_folders p WHERE p.id=f.parent_id AND p.tenant_id=f.tenant_id AND p.knowledge_base_id=f.knowledge_base_id)`, + `SELECT count(*) FROM wiki_folders f WHERE f.tenant_id=$1 AND f.knowledge_base_id=$2 AND f.parent_id<>''`, true, ""}, + {"wiki page.source_refs→knowledge", `SELECT count(*) FROM wiki_pages p, jsonb_array_elements_text(coalesce(p.source_refs,'[]'::jsonb)) ref WHERE p.tenant_id=$1 AND p.knowledge_base_id=$2 AND NOT EXISTS(SELECT 1 FROM knowledges k WHERE k.id=split_part(ref,'|',1) AND k.tenant_id=p.tenant_id AND k.knowledge_base_id=p.knowledge_base_id)`, + `SELECT count(*) FROM wiki_pages p, jsonb_array_elements_text(coalesce(p.source_refs,'[]'::jsonb)) ref WHERE p.tenant_id=$1 AND p.knowledge_base_id=$2 AND EXISTS(SELECT 1 FROM knowledges k WHERE k.id=split_part(ref,'|',1) AND k.tenant_id=p.tenant_id AND k.knowledge_base_id=p.knowledge_base_id)`, true, ""}, + {"wiki page.chunk_refs→chunk", `SELECT count(*) FROM wiki_pages p, jsonb_array_elements_text(coalesce(p.chunk_refs,'[]'::jsonb)) ref WHERE p.tenant_id=$1 AND p.knowledge_base_id=$2 AND NOT EXISTS(SELECT 1 FROM chunks c WHERE c.id=ref AND c.tenant_id=p.tenant_id AND c.knowledge_base_id=p.knowledge_base_id)`, + `SELECT count(*) FROM wiki_pages p, jsonb_array_elements_text(coalesce(p.chunk_refs,'[]'::jsonb)) ref WHERE p.tenant_id=$1 AND p.knowledge_base_id=$2 AND EXISTS(SELECT 1 FROM chunks c WHERE c.id=ref AND c.tenant_id=p.tenant_id AND c.knowledge_base_id=p.knowledge_base_id)`, true, ""}, + {"wiki issue.suspected_knowledge_ids→knowledge", `SELECT count(*) FROM wiki_page_issues i, jsonb_array_elements_text(coalesce(i.suspected_knowledge_ids,'[]'::jsonb)) ref WHERE i.tenant_id=$1 AND i.knowledge_base_id=$2 AND NOT EXISTS(SELECT 1 FROM knowledges k WHERE k.id=ref AND k.tenant_id=i.tenant_id AND k.knowledge_base_id=i.knowledge_base_id)`, + `SELECT count(*) FROM wiki_page_issues i, jsonb_array_elements_text(coalesce(i.suspected_knowledge_ids,'[]'::jsonb)) ref WHERE i.tenant_id=$1 AND i.knowledge_base_id=$2 AND EXISTS(SELECT 1 FROM knowledges k WHERE k.id=ref AND k.tenant_id=i.tenant_id AND k.knowledge_base_id=i.knowledge_base_id)`, true, ""}, + {"wiki issue→page", `SELECT count(*) FROM wiki_page_issues i WHERE i.tenant_id=$1 AND i.knowledge_base_id=$2 AND NOT EXISTS(SELECT 1 FROM wiki_pages p WHERE p.slug=i.slug AND p.tenant_id=i.tenant_id AND p.knowledge_base_id=i.knowledge_base_id)`, + `SELECT count(*) FROM wiki_page_issues i WHERE i.tenant_id=$1 AND i.knowledge_base_id=$2`, true, ""}, + {"wiki log→knowledge", `SELECT count(*) FROM wiki_log_entries l WHERE l.tenant_id=$1 AND l.knowledge_base_id=$2 AND NOT EXISTS(SELECT 1 FROM knowledges k WHERE k.id=l.knowledge_id)`, + `SELECT count(*) FROM wiki_log_entries l WHERE l.tenant_id=$1 AND l.knowledge_base_id=$2`, true, ""}, + {"wiki log.pages_affected→page", `SELECT count(*) FROM wiki_log_entries l, jsonb_array_elements(coalesce(l.pages_affected,'[]'::jsonb)) e WHERE l.tenant_id=$1 AND l.knowledge_base_id=$2 AND NOT EXISTS(SELECT 1 FROM wiki_pages p WHERE p.slug=e->>'slug' AND p.tenant_id=l.tenant_id AND p.knowledge_base_id=l.knowledge_base_id)`, + `SELECT count(*) FROM wiki_log_entries l, jsonb_array_elements(coalesce(l.pages_affected,'[]'::jsonb)) e WHERE l.tenant_id=$1 AND l.knowledge_base_id=$2 AND EXISTS(SELECT 1 FROM wiki_pages p WHERE p.slug=e->>'slug' AND p.tenant_id=l.tenant_id AND p.knowledge_base_id=l.knowledge_base_id)`, true, ""}, + // 范围外(显式声明,不静默跳过):软导航字段没有外键契约,允许悬空。 + {"wiki page.parent_slug", "", "", false, "soft slug navigation, no FK; fixture keeps it empty"}, + {"wiki page.in_links/out_links", "", "", false, "soft slug navigation, no FK; dangling by design"}, + {"chunk.relation_chunks/indirect_relation_chunks", "", "", false, "jsonb relation hints, no FK contract"}, + } + for _, relation := range relations { + if !relation.covered { + continue + } + var violations, matched int64 + var args []any + if strings.Contains(relation.sql, "$2") { + args = []any{wsTargetTenant, wsTargetKB} + } else if strings.Contains(relation.sql, "$1") { + args = []any{wsTargetTenant} + } + if err := fx.pool.QueryRow(fx.ctx, relation.sql, args...).Scan(&violations); err != nil { + t.Fatalf("reference %s: %v", relation.name, err) + } + if err := fx.pool.QueryRow(fx.ctx, relation.matched, args...).Scan(&matched); err != nil { + t.Fatalf("reference coverage %s: %v", relation.name, err) + } + if violations != 0 { + diffs = append(diffs, fmt.Sprintf("reference %s: %d violations", relation.name, violations)) + } + if matched == 0 { + diffs = append(diffs, fmt.Sprintf("reference %s: oracle matched no rows", relation.name)) + } + } + inventoryRaw := make([]map[string]any, 0, len(relations)) + for _, item := range relations { + inventoryRaw = append(inventoryRaw, map[string]any{"name": item.name, "covered": item.covered, + "out_of_scope_reason": item.reason}) + } + r10Save(t, "reference-inventory", inventoryRaw) + // 向量/正文:索引文档逐条与声明完全一致(多一条少一条都算差异)。 + docs := ds02Docs(t, fx) + if len(docs) != len(spec.rows["chunks"])+1 { // +1:目标范围之外的 chunk-foreign + diffs = append(diffs, fmt.Sprintf("index docs: want %d got %d", len(spec.rows["chunks"])+1, len(docs))) + } + for _, chunk := range spec.rows["chunks"] { + sourceID := fmt.Sprint(chunk["id"]) + id := expectedIndexID(sourceID) + doc, ok := docs[id] + if !ok { + diffs = append(diffs, "index doc missing: "+id) + continue + } + source := doc + want := map[string]any{"tenant_id": json.Number(strconv.FormatUint(wsTargetTenant, 10)), + "knowledge_base_id": wsTargetKB, + "knowledge_id": expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", fmt.Sprint(chunk["knowledge_id"])), + "chunk_id": expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", sourceID), + "source_id": expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", sourceID), + "content": chunk["content"], "embedding": spec.vectors[sourceID]} + for key, value := range want { + if fmt.Sprint(source[key]) != fmt.Sprint(value) { + diffs = append(diffs, fmt.Sprintf("index doc %s.%s: want %v got %v", id, key, value, source[key])) + } + } + } + // 外围索引文档:完整 _source 逐字段比,不只比 content。 + foreignWant := map[string]any{"tenant_id": json.Number("20000"), "knowledge_base_id": "kb-foreign", + "knowledge_id": "doc-foreign", "chunk_id": "chunk-foreign", "source_id": "chunk-foreign", + "content": "外部正文", "embedding": []any{0.1, 0.2}} + if foreign, ok := docs["chunk-foreign"]; !ok { + diffs = append(diffs, "foreign index doc disappeared") + } else if !ds02SameJSON(foreign, foreignWant) { + diffs = append(diffs, fmt.Sprintf("foreign index doc _source changed: want %s got %s", ds02RowKey(foreignWant), ds02RowKey(foreign))) + } + // 对象字节:按独立重算的定位符读回,逐字节比。 + for id, want := range spec.objects { + reader, err := fx.objects.s3.Open(fx.ctx, "minio", paths[id]) + if err != nil { + diffs = append(diffs, fmt.Sprintf("object %s: %v", id, err)) + continue + } + got, err := io.ReadAll(reader) + reader.Close() + if err != nil { + diffs = append(diffs, fmt.Sprintf("object %s read: %v", id, err)) + continue + } + if string(got) != want { + diffs = append(diffs, fmt.Sprintf("object %s bytes: want %q got %q", id, want, got)) + } + } + // 外围对象:res-other 的字节也必须逐字节比(旧 oracle 只读 spec.objects)。 + otherPath := wsLocator("backend-target", "minio", fx.bucket, 10001, "res-other") + reader, err := fx.objects.s3.Open(fx.ctx, "minio", otherPath) + if err != nil { + diffs = append(diffs, "sibling object res-other unreadable: "+err.Error()) + } else { + got, readErr := io.ReadAll(reader) + reader.Close() + if readErr != nil { + diffs = append(diffs, "sibling object res-other read: "+readErr.Error()) + } else if string(got) != strings.Repeat("z", 8) { + diffs = append(diffs, fmt.Sprintf("sibling object res-other bytes: want %q got %q", strings.Repeat("z", 8), got)) + } + } + // Wiki 日志映射:内容元组多重集双射(本地号不参与身份,来源 id 只用于覆盖检查)。 + wantTuples := []string{} + for _, row := range spec.rows["wiki_log_entries"] { + copied := map[string]any{} + for key, value := range row { + if key == "id" { + continue + } + copied[key] = value + } + copied["tenant_id"] = json.Number(strconv.FormatUint(wsTargetTenant, 10)) + copied["knowledge_base_id"] = wsTargetKB + if knowledge, ok := copied["knowledge_id"].(string); ok && knowledge != "" { + copied["knowledge_id"] = expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", knowledge) + } + raw, _ := json.Marshal(copied) + wantTuples = append(wantTuples, string(raw)) + } + gotTuples := []string{} + actualLogs := ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM wiki_log_entries AS x WHERE tenant_id=$1 AND knowledge_base_id=$2`, wsTargetTenant, wsTargetKB) + for _, row := range actualLogs { + copied := map[string]any{} + for key, value := range row { + if key == "id" { + continue + } + copied[key] = value + } + raw, _ := json.Marshal(copied) + gotTuples = append(gotTuples, string(raw)) + } + sort.Strings(wantTuples) + sort.Strings(gotTuples) + if fmt.Sprint(wantTuples) != fmt.Sprint(gotTuples) { + diffs = append(diffs, fmt.Sprintf("wiki log tuple bijection broken: want %v got %v", wantTuples, gotTuples)) + } + // Embedding:只对"发布段"记账;oracle 读段的请求不混进来。发布段必须有请求 + // (不是空绿),且 client 集合必须正是本测试声明的可达集合。 + publishEgress := recorder.entriesFor("publish") + diffs = append(diffs, ds02EgressDiffs(publishEgress, inventory)...) + if len(publishEgress) == 0 { + diffs = append(diffs, "no HTTP requests observed in publish phase; zero-embedding oracle would be vacuous") + } + return diffs +} + +func ds02SameJSON(left, right map[string]any) bool { + return ds02RowKey(left) == ds02RowKey(right) +} + +// ds02OtherRows 读目标范围之外的行(发布前抓一次,发布后要求一字不差)。 +func ds02OtherRows(t *testing.T, fx *writeSetFixture, table string) []map[string]any { + t.Helper() + rule := ds02ScopeDecl[table] + if !rule.Tenant { + return nil + } + if rule.KnowledgeBase { + return ds02Read(t, fx, "SELECT to_jsonb(x)::text FROM "+table+" AS x WHERE NOT (tenant_id=$1 AND knowledge_base_id=$2)", wsTargetTenant, wsTargetKB) + } + return ds02Read(t, fx, "SELECT to_jsonb(x)::text FROM "+table+" AS x WHERE tenant_id<>$1", wsTargetTenant) +} + +func ds02SameTenantRows(t *testing.T, fx *writeSetFixture, table string) []map[string]any { + t.Helper() + return ds02Read(t, fx, "SELECT to_jsonb(x)::text FROM "+table+" AS x WHERE tenant_id=$1", wsTargetTenant) +} + +// ds02SequenceSummary 记三条本地号序列的 (last_value,is_called):序列不存在直接失败, +// 不允许"空集合被当成不变"。 +func ds02SequenceSummary(t *testing.T, fx *writeSetFixture) map[string][]any { + t.Helper() + summary := map[string][]any{} + for _, name := range []string{"chunks_seq_id_seq", "knowledge_tags_seq_id_seq", "wiki_log_entries_id_seq"} { + var exists bool + if err := fx.pool.QueryRow(fx.ctx, "SELECT to_regclass($1) IS NOT NULL", name).Scan(&exists); err != nil { + t.Fatal(err) + } + if !exists { + t.Fatalf("local sequence %s does not exist; sequence coverage would be empty", name) + } + var last int64 + var called bool + if err := fx.pool.QueryRow(fx.ctx, "SELECT last_value,is_called FROM "+name).Scan(&last, &called); err != nil { + t.Fatal(err) + } + summary[name] = []any{last, called} + } + return summary +} + +// ds02LocalColumns 把"声明来源 + 独立期望目标行 + 真实目标行"组成映射 oracle 的输入。 +func ds02LocalColumns(t *testing.T, fx *writeSetFixture, spec ds02Spec, expectation ds02Expectation) []ds02LocalColumn { + t.Helper() + var columns []ds02LocalColumn + for _, contract := range []struct{ table, column string }{ + {"chunks", "seq_id"}, {"knowledge_tags", "seq_id"}, {"wiki_log_entries", "id"}, + } { + sources := []int64{} + for _, row := range spec.rows[contract.table] { + raw := row["seq_id"] + if contract.table == "wiki_log_entries" { + raw = row["id"] + } + value, err := strconv.ParseInt(fmt.Sprint(raw), 10, 64) + if err != nil { + t.Fatalf("%s declared local id: %v", contract.table, err) + } + sources = append(sources, value) + } + sort.Slice(sources, func(i, j int) bool { return sources[i] < sources[j] }) + actual := map[int64]map[string]any{} + for _, row := range ds02Read(t, fx, "SELECT to_jsonb(x)::text FROM "+contract.table+ + " AS x WHERE tenant_id=$1 AND knowledge_base_id=$2", wsTargetTenant, wsTargetKB) { + value, err := strconv.ParseInt(fmt.Sprint(row[contract.column]), 10, 64) + if err != nil { + t.Fatalf("%s actual local id: %v", contract.table, err) + } + actual[value] = row + } + columns = append(columns, ds02LocalColumn{Table: contract.table, Column: contract.column, + Sources: sources, Expected: expectation.Local[contract.table], + ExpectedRows: expectation.RowsBySource[contract.table], Actual: actual}) + } + return columns +} + +func TestDS02FullShapeOracleIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + // 用保留下来的真实 v071 catalog 重建十张表:逐列、外键、序列都是真实形状。 + r11Mirror(t, fx) + for _, sql := range []string{ + `SELECT setval('chunks_seq_id_seq',100000005,false)`, + `SELECT setval('knowledge_tags_seq_id_seq',50,false)`, + `SELECT setval('wiki_log_entries_id_seq',10,false)`, + } { + r10Exec(t, fx, sql) + } + ds02VerifyScopeDecl(t, fx) + ds02Seed(t, fx) + preserved := map[string][]map[string]any{} + for _, table := range ds02TargetTables { + preserved[table] = ds02OtherRows(t, fx, table) + } + spec := ds02SourceSpec(t, fx) + expectation := ds02Expected(t, fx, spec) + expected, paths := expectation.Rows, expectation.Paths + // 独立 oracle:只对"来源快照将写进目标范围"的期望行按 scoped-sha256-v1 + // 推导目标身份;随后追加的同租户/外库保留行仍是原身份,不能映射。 + for table := range expected { + for i, row := range expected[table] { + expected[table][i] = expectedTargetRow(table, row) + } + } + for table, bySeq := range expectation.RowsBySource { + for seq, row := range bySeq { + bySeq[seq] = expectedTargetRow(table, row) + } + } + for _, table := range []string{"resources", "resource_bindings"} { + expected[table] = append(expected[table], ds02SameTenantRows(t, fx, table)...) + } + // knowledge_tag_relations 没有 tenant/kb:产品按父文档归属删除,非目标范围的 + // 关系行必须原样保留,所以它们也在期望里。 + expected["knowledge_tag_relations"] = append(expected["knowledge_tag_relations"], + ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM knowledge_tag_relations AS x + WHERE knowledge_id NOT IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)`, + wsTargetTenant, wsTargetKB)...) + + sequencesBefore := ds02SequenceSummary(t, fx) + snapshot := ds02Seal(t, fx, spec) + recorder, inventory := ds02AttachEgress(t, fx) + target := fx.target(t) + backups := fx.backups(t, target) + recorder.setPhase("publish") + out := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, backups, nil) + recorder.setPhase("oracle-read") + r10Save(t, "outcome", out) + if out.State != "succeeded" { + t.Fatalf("full-shape publish must succeed: %+v", out) + } + sequencesAfter := ds02SequenceSummary(t, fx) + r10Save(t, "sequences", map[string]any{"before": sequencesBefore, "after": sequencesAfter}) + // 写集合里的本地号映射:独立语义 checker(不是"数个数/看双射"的循环)。 + if out.Backup.WriteSet == nil { + t.Fatal("write set missing") + } + ledger, err := LoadWriteSet(fx.archiveRoot, out.Backup.WriteSet.Digest) + if err != nil { + t.Fatalf("load write set: %v", err) + } + columns := ds02LocalColumns(t, fx, spec, expectation) + mappingDiffs := ds02CheckLocalIDMapping(columns, ledger.LocalIDs) + r10Save(t, "mapping-diffs", mappingDiffs) + if len(mappingDiffs) != 0 { + t.Fatalf("persisted ledger fails the independent mapping oracle:\n%s", strings.Join(mappingDiffs, "\n")) + } + // 语义副本变异:只改内存里的账本副本,目标存储与归档字节都不动。这个 RED + // 才是 mapping RED;改日志 action/正文只能证明内容 oracle 会红。 + for _, scenario := range []struct { + name string + build func([]libraryrelease.LocalIDMapping) []libraryrelease.LocalIDMapping + want string + }{ + {"swapped-targets", func(ledger []libraryrelease.LocalIDMapping) []libraryrelease.LocalIDMapping { + return ds02FlipMappingTargets(ledger, "wiki_log_entries") + }, "wrong target pair"}, + {"nonexistent-target", func(ledger []libraryrelease.LocalIDMapping) []libraryrelease.LocalIDMapping { + return ds02ReplaceMapping(ledger, "wiki_log_entries", "target", "999") + }, "not an independently predicted target"}, + {"replaced-source", func(ledger []libraryrelease.LocalIDMapping) []libraryrelease.LocalIDMapping { + return ds02ReplaceMapping(ledger, "wiki_log_entries", "source", "999") + }, "unexpected ledger source"}, + {"missing-entry", func(ledger []libraryrelease.LocalIDMapping) []libraryrelease.LocalIDMapping { + return ds02DropMapping(ledger, "chunks") + }, "missing ledger source"}, + {"duplicate-entry", func(ledger []libraryrelease.LocalIDMapping) []libraryrelease.LocalIDMapping { + return ds02DuplicateMapping(ledger, "knowledge_tags") + }, "duplicate ledger source"}, + {"wrong-column", func(ledger []libraryrelease.LocalIDMapping) []libraryrelease.LocalIDMapping { + return ds02ReplaceMapping(ledger, "chunks", "column", "id") + }, "ledger column"}, + } { + red := ds02CheckLocalIDMapping(columns, scenario.build(ledger.LocalIDs)) + r10Save(t, "mapping-red-"+scenario.name, red) + joined := strings.Join(red, "\n") + if len(red) == 0 { + t.Fatalf("%s: semantic mapping mutation stayed green", scenario.name) + } + if !strings.Contains(joined, scenario.want) { + t.Fatalf("%s: mapping oracle failed for an unrelated reason:\n%s", scenario.name, joined) + } + } + // 归档字节变异 = checksum gate,不是 mapping RED:它只能证明摘要拒收, + // 不能替代上面那组语义 RED。 + ledgerPath := writeSetPath(fx.archiveRoot, out.Backup.WriteSet.Digest) + info, err := os.Stat(ledgerPath) + if err != nil { + t.Fatalf("stat persisted ledger: %v", err) + } + original, err := os.ReadFile(ledgerPath) + if err != nil { + t.Fatalf("read persisted ledger: %v", err) + } + // 台账落盘是只读的,变异前显式放开权限,结束后恢复原权限与原始字节。 + if err := os.Chmod(ledgerPath, 0600); err != nil { + t.Fatalf("unlock persisted ledger: %v", err) + } + // 只追加空白不会改变解析后的内容摘要(实现按内容摘要校验,不按字节); + // 这里改一个真实字段值,让内容摘要必然不符。 + var tampered map[string]any + if err := json.Unmarshal(original, &tampered); err != nil { + t.Fatalf("parse persisted ledger: %v", err) + } + if mappings, ok := tampered["local_ids"].([]any); ok && len(mappings) > 0 { + if first, ok := mappings[0].(map[string]any); ok { + first["target"] = "999999999" + } + } + reencoded, err := json.Marshal(tampered) + if err != nil { + t.Fatalf("encode tampered ledger: %v", err) + } + if err := os.WriteFile(ledgerPath, reencoded, 0600); err != nil { + t.Fatalf("tamper persisted ledger: %v", err) + } + _, digestErr := LoadWriteSet(fx.archiveRoot, out.Backup.WriteSet.Digest) + r10Save(t, "digest-gate", map[string]any{"error": fmt.Sprint(digestErr)}) + if digestErr == nil { + t.Fatal("tampered ledger bytes were accepted; digest gate is missing") + } + if err := os.WriteFile(ledgerPath, original, 0600); err != nil { + t.Fatalf("restore persisted ledger: %v", err) + } + if err := os.Chmod(ledgerPath, info.Mode().Perm()); err != nil { + t.Fatalf("restore ledger mode: %v", err) + } + if _, err := LoadWriteSet(fx.archiveRoot, out.Backup.WriteSet.Digest); err != nil { + t.Fatalf("restored ledger must load again: %v", err) + } + diffs := ds02Check(t, fx, spec, expected, paths, preserved, recorder, inventory) + r10Save(t, "green-diffs", diffs) + if len(diffs) != 0 { + t.Fatalf("independent oracle disagrees on a correct publish:\n%s", strings.Join(diffs, "\n")) + } + r10Save(t, "green-egress", map[string]any{"publish": recorder.entriesFor("publish"), + "oracle": recorder.entriesFor("oracle-read"), "inventory": inventory}) + + // 负控制:另一个 client 打到自定义 /v1/encode 路径必须被识别为 embedding, + // 而真正的发布段仍是 0。这证明分类器不靠品牌字符串。 + encoder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + })) + defer encoder.Close() + custom := &http.Client{Transport: recorder.wrap("custom-encoder", http.DefaultTransport)} + recorder.setPhase("negative-control") + request, err := http.NewRequestWithContext(fx.ctx, "POST", encoder.URL+"/v1/encode", strings.NewReader(`{}`)) + if err != nil { + t.Fatal(err) + } + response, err := custom.Do(request) + if err != nil { + t.Fatalf("negative control request: %v", err) + } + response.Body.Close() + negative := recorder.entriesFor("negative-control") + negativeDiffs := ds02EgressDiffs(append(append([]ds02Egress{}, recorder.entriesFor("publish")...), negative...), inventory) + r10Save(t, "negative-control", map[string]any{"entries": negative, "diffs_if_in_publish": negativeDiffs}) + if len(negativeDiffs) == 0 { + t.Fatal("custom /v1/encode path was not classified as an embedding call") + } + if len(ds02EgressDiffs(recorder.entriesFor("publish"), inventory)) != 0 { + t.Fatalf("publish phase embedding expectation broken: %v", ds02EgressDiffs(recorder.entriesFor("publish"), inventory)) + } + recorder.setPhase("oracle-read") + + // 变异自检:对真实目标改正文 / 向量 / 引用 / 日志内容 / 外围 ES 文档 / 外围对象, + // oracle 必须红;改回后必须绿。 + content := fmt.Sprint(expected["chunks"][0]["content"]) + putDoc := func(id, body string) { + request, _ := http.NewRequestWithContext(fx.ctx, "PUT", fx.searchBase+"/"+fx.index+"/_doc/"+id+"?refresh=true", strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + response, err := fx.client.Do(request) + if err != nil { + t.Fatal(err) + } + response.Body.Close() + if response.StatusCode >= 300 { + t.Fatalf("mutate doc %s: %d", id, response.StatusCode) + } + } + putObject := func(path, body string) { + if err := fx.objects.s3.Put(fx.ctx, "minio", path, strings.NewReader(body), int64(len(body))); err != nil { + t.Fatal(err) + } + } + foreignPath := wsLocator("backend-target", "minio", fx.bucket, 10001, "res-other") + foreignDoc := `{"tenant_id":20000,"knowledge_base_id":"kb-foreign","knowledge_id":"doc-foreign","chunk_id":"chunk-foreign","source_id":"chunk-foreign","content":"外部正文","embedding":[0.1,0.2]}` + foreignDocTampered := `{"tenant_id":20000,"knowledge_base_id":"kb-foreign","knowledge_id":"doc-foreign","chunk_id":"chunk-foreign","source_id":"chunk-foreign","content":"外部正文篡改","embedding":[0.1,0.2]}` + mappedDoc := expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", "doc-src") + mappedTag := expectedTargetID(wsTargetTenant, wsTargetKB, "knowledge_tags", "tag-src") + mappedChunk := expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-src") + mappedIndex := expectedIndexID("chunk-src") + chunkJSON := func(embedding string) string { + return fmt.Sprintf(`{"tenant_id":%d,"knowledge_base_id":%q,"knowledge_id":%q,"chunk_id":%q,"source_id":%q,"content":%q,"embedding":%s}`, + wsTargetTenant, wsTargetKB, mappedDoc, mappedChunk, mappedChunk, content, embedding) + } + chunkDoc, chunkDocTampered := chunkJSON("[0.5,1.5]"), chunkJSON("[9.5,9.5]") + var originalChunk string + if err := fx.pool.QueryRow(fx.ctx, `SELECT content FROM chunks WHERE id=$1`, mappedChunk).Scan(&originalChunk); err != nil { + t.Fatalf("read published chunk content: %v", err) + } + execOne := func(sql string, args ...any) { + tag, err := fx.pool.Exec(fx.ctx, sql, args...) + if err != nil { + t.Fatalf("mutation sql: %v", err) + } + if tag.RowsAffected() != 1 { + t.Fatalf("mutation sql affected %d rows, want 1", tag.RowsAffected()) + } + } + mutations := []struct { + name string + marker string + mutate func() + restore func() + }{ + {"content", "chunks:", func() { + execOne(`UPDATE chunks SET content=content||'!MUT' WHERE id=$1`, mappedChunk) + }, func() { + execOne(`UPDATE chunks SET content=$1 WHERE id=$2`, originalChunk, mappedChunk) + }}, + {"vector", "index doc " + expectedIndexID("chunk-src") + ".embedding", func() { + putDoc(mappedIndex, chunkDocTampered) + }, func() { + putDoc(mappedIndex, chunkDoc) + }}, + {"reference", "reference relation", func() { + execOne(`UPDATE knowledge_tag_relations SET tag_id='missing-tag' WHERE knowledge_id=$1 AND tag_id=$2`, mappedDoc, mappedTag) + }, func() { + execOne(`UPDATE knowledge_tag_relations SET tag_id=$1 WHERE knowledge_id=$2 AND tag_id='missing-tag'`, mappedTag, mappedDoc) + }}, + // 这是日志内容变异,不是本地号映射变异:映射 RED 只在账本语义副本上做。 + {"log-content", "wiki log", func() { + execOne(`UPDATE wiki_log_entries SET action='tampered' WHERE tenant_id=10001 AND knowledge_base_id='kb-target' AND knowledge_id=$1`, mappedDoc) + }, func() { + execOne(`UPDATE wiki_log_entries SET action='ingest' WHERE tenant_id=10001 AND knowledge_base_id='kb-target' AND knowledge_id=$1`, mappedDoc) + }}, + {"foreign-index-source", "foreign index doc _source changed", func() { + putDoc("chunk-foreign", foreignDocTampered) + }, func() { + putDoc("chunk-foreign", foreignDoc) + }}, + {"foreign-object-bytes", "res-other bytes", func() { + putObject(foreignPath, strings.Repeat("z", 7)+"!") + }, func() { + putObject(foreignPath, strings.Repeat("z", 8)) + }}, + } + for _, mutation := range mutations { + mutation.mutate() + red := ds02Check(t, fx, spec, expected, paths, preserved, recorder, inventory) + r10Save(t, "red-"+mutation.name, red) + if len(red) == 0 { + t.Fatalf("%s mutation: oracle stayed green", mutation.name) + } + joined := strings.Join(red, "\n") + if !strings.Contains(joined, mutation.marker) { + t.Fatalf("%s mutation: oracle failed for an unrelated reason:\n%s", mutation.name, joined) + } + mutation.restore() + green := ds02Check(t, fx, spec, expected, paths, preserved, recorder, inventory) + if len(green) != 0 { + t.Fatalf("%s mutation not restored cleanly:\n%s", mutation.name, strings.Join(green, "\n")) + } + } +} diff --git a/internal/releaseadapter/v071/formal_ds01_negative_r38_test.go b/internal/releaseadapter/v071/formal_ds01_negative_r38_test.go new file mode 100644 index 0000000..dd02d5e --- /dev/null +++ b/internal/releaseadapter/v071/formal_ds01_negative_r38_test.go @@ -0,0 +1,567 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// argvOf 读回真实进程的 argv:报告里的"新 PID"必须能对上真正被执行的那条命令, +// 不能只凭 cmd.Process 的内存句柄。 +func argvOf(t *testing.T, pid int) []string { + t.Helper() + raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) + if err != nil { + t.Fatalf("read /proc/%d/cmdline: %v", pid, err) + } + fields := strings.Split(strings.TrimRight(string(raw), "\x00"), "\x00") + if len(fields) == 0 || fields[0] == "" { + t.Fatalf("/proc/%d/cmdline is empty", pid) + } + return fields +} + +// processIdentityOf 把"这次真实重启后的执行者"的身份留档:PID、argv、可执行文件摘要。 +// 场景与构建标签由调用方补,因为 drill 构建会缩短租约,不能冒充生产默认参数。 +func processIdentityOf(t *testing.T, pid int) map[string]any { + t.Helper() + exe, err := os.Readlink(fmt.Sprintf("/proc/%d/exe", pid)) + if err != nil { + t.Fatalf("read /proc/%d/exe: %v", pid, err) + } + raw, err := os.ReadFile(exe) + if err != nil { + t.Fatalf("read executable %s: %v", exe, err) + } + sum := sha256.Sum256(raw) + return map[string]any{"pid": pid, "argv": argvOf(t, pid), "executable": exe, + "executable_sha256": hex.EncodeToString(sum[:]), "scenario": os.Getenv("KG_R38_SCENARIO"), + "build_tags": os.Getenv("KG_R38_BUILD_TAGS")} +} + +func errText(err error) string { + if err == nil { + return "" + } + return err.Error() +} + +// d06Snapshot 是"接管前后不得变化"的一整组现场事实:目标 PG 逐行、ES 命中代次与内容、 +// 对象版本与逐字节摘要、恢复 effect 文件(键+值)、marker 转发计数、派发台账整行、 +// journal 状态。两次真实接管都必须与同一份基线完全一致。 +type d06Snapshot struct { + PG map[string][]string `json:"pg"` + Index map[string]map[string]any `json:"index"` + Objects map[string]string `json:"objects"` + ObjectBytes map[string]string `json:"object_bytes"` + Effects map[string]map[string]any `json:"effects"` + MarkerCreates int `json:"marker_creates"` + WireForwarded int `json:"wire_forwarded"` + Ledger map[string]string `json:"ledger"` + JournalSHA string `json:"journal_sha256"` + JournalState string `json:"journal_state"` + JournalBackup string `json:"journal_backup_snapshot_id"` + JournalAttempt int `json:"journal_attempt"` + JournalRecover string `json:"journal_recovered_backup"` +} + +// d06LedgerIdentity 是"派发许可属于谁"的那几列:它们一旦变了就是重置/回填台账。 +var d06LedgerIdentity = []string{"state", "owner", "epoch", "nonce", "request_digest", "plan_digest", + "binding_digest", "marker_receipt", "dispatch_committed_at", "prepared_at"} + +// DS01 D16 负例:新的正式 worker 在 recover 路径上必须零新写、保持 held。 +// - N1:合法 Acquire 已提交 dispatching、真实发送前进程被终止;新 worker 看到 +// dispatching+missing,不得再发 create,也不得先写 PG/resources。 +// - N2:旧协议 mark-intent + missing、没有 DS01 台账;新 worker(协议开启)同样 +// held,且不得回填台账。 +// - secondRestart(D06):N1 的边界不变,但第一个接管者也要被真实终止并换成第二个 +// 新 PID,再走同一 recover API 仍 held;两次接管共用同一份基线做完整对拍。 +func r38RunDS01Negative(t *testing.T, ctx context.Context, root string, api r38API, gov *pgxpool.Pool, + store *postgresstore.Store, fx *writeSetFixture, job governance.LibraryJob, backupID string, + n1, missing, secondRestart bool, worker *exec.Cmd, workerEnv map[string]string, proxy *r38RefusalProxy, + start func(string, string, map[string]string) *exec.Cmd) { + t.Helper() + save := func(name string, value any) { + t.Helper() + raw, err := json.MarshalIndent(value, "", " ") + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, name), raw, 0o600); err != nil { + t.Fatal(err) + } + } + ledger := func() (string, string, string, int) { + t.Helper() + var state, owner, nonce string + var count int + if err := gov.QueryRow(ctx, `SELECT count(*) FROM library_index_restore_dispatch`).Scan(&count); err != nil { + t.Fatal(err) + } + if count == 0 { + return "", "", "", 0 + } + if err := gov.QueryRow(ctx, `SELECT state, dispatch_owner, dispatch_nonce FROM library_index_restore_dispatch +WHERE index_name=$1 AND document_id='chunk-target'`, fx.index).Scan(&state, &owner, &nonce); err != nil { + t.Fatal(err) + } + return state, owner, nonce, count + } + // 老执行者被杀后,租约必须真的过期才允许新 attempt 接管;等权威时钟而不是睡固定值。 + waitLease := func(label string) { + t.Helper() + deadline := time.Now().Add(40 * time.Second) + for { + var expired bool + if err := gov.QueryRow(ctx, `SELECT COALESCE(lease_until < clock_timestamp(), true) +FROM library_jobs WHERE id=$1`, job.ID).Scan(&expired); err != nil { + t.Fatal(err) + } + if expired { + return + } + if time.Now().After(deadline) { + t.Fatalf("%s: window lease never expired", label) + } + time.Sleep(300 * time.Millisecond) + } + } + wireForwarded := func() int { + events, _ := proxy.snapshot() + forwarded := 0 + for _, event := range events { + if event["refused"] == true && event["dispatched"] == false { + continue + } + path, _ := event["path"].(string) + if event["method"] == http.MethodPut && strings.Contains(path, "/_doc/chunk-target") { + forwarded++ + } + } + return forwarded + } + capture := func(name string) d06Snapshot { + t.Helper() + var snap d06Snapshot + snap.PG = universeDump(t, fx.pool) + snap.Index = recoveryIndexReadback(t, fx) + snap.Objects = objectVersionSet(t, fx) + snap.ObjectBytes = r38ObjectVersionDigests(t, ctx, fx, objectInventoryR38(t, ctx, fx)) + if len(snap.ObjectBytes) != len(snap.Objects) { + t.Fatalf("object byte digest coverage %d/%d", len(snap.ObjectBytes), len(snap.Objects)) + } + snap.Effects = r38IndexEffects(t, filepath.Join(root, "archive"), "chunk-target") + snap.MarkerCreates = proxy.markerCreates() + snap.WireForwarded = wireForwarded() + var row string + if err := gov.QueryRow(ctx, `SELECT to_jsonb(x)::text FROM library_index_restore_dispatch AS x +WHERE index_name=$1 AND document_id='chunk-target'`, fx.index).Scan(&row); err != nil { + t.Fatal(err) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal([]byte(row), &raw); err != nil { + t.Fatalf("parse dispatch ledger row: %v", err) + } + // 台账列里有数字/bool/NULL;按列名保存 JSON 原文,比较的是每一列的精确值。 + snap.Ledger = map[string]string{} + for key, value := range raw { + snap.Ledger[key] = string(value) + } + journalRaw, err := os.ReadFile(filepath.Join(root, "maintenance", job.ID+".json")) + if err != nil { + t.Fatalf("read maintenance journal: %v", err) + } + sum := sha256.Sum256(journalRaw) + snap.JournalSHA = hex.EncodeToString(sum[:]) + var journal map[string]any + if err := json.Unmarshal(journalRaw, &journal); err != nil { + t.Fatalf("parse maintenance journal: %v", err) + } + snap.JournalState, _ = journal["state"].(string) + snap.JournalBackup, _ = journal["backup_snapshot_id"].(string) + snap.JournalRecover, _ = journal["recovered_backup"].(string) + if attempt, ok := journal["attempt"].(float64); ok { + snap.JournalAttempt = int(attempt) + } + save(name, snap) + return snap + } + // compare 返回可留档的判定结果和必须让用例失败的问题清单。 + compare := func(before, after d06Snapshot) (map[string]any, []string) { + t.Helper() + problems := []string{} + pgDiff := diffUniverse(before.PG, after.PG) + indexEqual := reflect.DeepEqual(before.Index, after.Index) + objectsEqual := reflect.DeepEqual(before.Objects, after.Objects) + bytesEqual := reflect.DeepEqual(before.ObjectBytes, after.ObjectBytes) + effectsEqual := reflect.DeepEqual(before.Effects, after.Effects) + changed := []string{} + for _, key := range d06LedgerIdentity { + if before.Ledger[key] != after.Ledger[key] { + changed = append(changed, key) + } + } + ledgerRowsEqual := true + if len(before.Ledger) != len(after.Ledger) { + ledgerRowsEqual = false + } else { + for key, value := range before.Ledger { + if after.Ledger[key] != value { + ledgerRowsEqual = false + break + } + } + } + out := map[string]any{ + "pg_diff": pgDiff, "index_equal": indexEqual, "objects_equal": objectsEqual, + "object_bytes_equal": bytesEqual, "effects_equal": effectsEqual, + "effects_keys": effectPhases(before.Effects), + "marker_creates_before": before.MarkerCreates, "marker_creates_after": after.MarkerCreates, + "marker_create_delta": after.MarkerCreates - before.MarkerCreates, + "wire_forwarded_before": before.WireForwarded, "wire_forwarded_after": after.WireForwarded, + "ledger_identity_changed": changed, "ledger_row_text_equal": ledgerRowsEqual, + "journal_state": after.JournalState, "journal_attempt": after.JournalAttempt, + "journal_backup_equal": before.JournalBackup == after.JournalBackup, + "journal_sha256_before": before.JournalSHA, "journal_sha256_after": after.JournalSHA, + } + if pgDiff != "" { + problems = append(problems, "target PG changed: "+pgDiff) + } + if !indexEqual { + problems = append(problems, "target index generation/content changed") + } + if !objectsEqual { + problems = append(problems, "object version set changed") + } + if !bytesEqual { + problems = append(problems, "object bytes changed") + } + if !effectsEqual { + problems = append(problems, "persisted index effect files (key or value) changed") + } + if after.MarkerCreates != before.MarkerCreates { + problems = append(problems, fmt.Sprintf("marker creates %d -> %d", before.MarkerCreates, after.MarkerCreates)) + } + if after.WireForwarded != before.WireForwarded { + problems = append(problems, fmt.Sprintf("forwarded marker writes %d -> %d", before.WireForwarded, after.WireForwarded)) + } + if len(changed) != 0 { + problems = append(problems, "dispatch ledger identity changed: "+strings.Join(changed, ",")) + } + if after.JournalState != "held" { + problems = append(problems, fmt.Sprintf("journal state %q is not held", after.JournalState)) + } + if before.JournalBackup != after.JournalBackup || after.JournalBackup == "" { + problems = append(problems, "journal backup identity changed") + } + if after.JournalRecover != "" { + problems = append(problems, "journal claims a recovered backup while the window must stay held") + } + return out, problems + } + + if n1 { + deadline := time.Now().Add(45 * time.Second) + for { + state, owner, nonce, _ := ledger() + if state == "dispatching" && owner != "" && nonce != "" { + save("17n1-dispatching-ledger.json", map[string]any{"state": state, "owner": owner, "nonce": nonce, + "marker_creates": proxy.markerCreates()}) + break + } + if time.Now().After(deadline) { + t.Fatalf("acquire never reached durable dispatching (state=%q)", state) + } + time.Sleep(200 * time.Millisecond) + } + if creates := proxy.markerCreates(); creates != 0 { + t.Fatalf("dispatching boundary already forwarded %d marker creates", creates) + } + } else if missing { + // N2-missing 边界必须是"真实 legacy mark-intent 已落盘、目标确实缺失、零 DS01 + // 台账"。三个事实都由现场独立读回,不从旧 run 推断。 + effects := r38IndexEffects(t, filepath.Join(root, "archive"), "chunk-target") + intent, hasIntent := effects["restore-mark-intent"] + index := recoveryIndexReadback(t, fx) + _, present := index["chunk-target"] + state, owner, nonce, count := ledger() + facts := map[string]any{"mark_intent_phases": effectPhases(effects), "has_mark_intent": hasIntent, + "target_document_present": present, "dispatch_rows": count, "dispatch_state": state, + "dispatch_owner": owner, "dispatch_nonce": nonce, "marker_creates": proxy.markerCreates(), + "refused_before_dispatch": proxy.refused} + save("17n2-legacy-missing-boundary.json", facts) + if !hasIntent || intent == nil { + t.Fatalf("legacy boundary has no real mark-intent: %v", facts) + } + if present { + t.Fatalf("legacy boundary target document is not missing: %v", facts) + } + if count != 0 || state != "" { + t.Fatalf("legacy boundary unexpectedly has %d dispatch rows (state=%q)", count, state) + } + } else { + if state, _, _, count := ledger(); count != 0 || state != "" { + t.Fatalf("legacy boundary unexpectedly has %d dispatch rows (state=%q)", count, state) + } + } + + // 终止旧执行者并读回它确实退出。 + oldPID := worker.Process.Pid + oldKillErr := worker.Process.Kill() + oldWaitErr := worker.Wait() + if _, err := os.Stat(fmt.Sprintf("/proc/%d", oldPID)); err == nil { + t.Fatalf("old worker %d still alive", oldPID) + } + if n1 { + waitLease("first takeover") + } + save("17n2-original-worker-exit.json", map[string]any{"pid": oldPID, "kill_error": errText(oldKillErr), + "wait_error": errText(oldWaitErr), "proc_present_after_wait": false}) + beforeDispatching := proxy.markerCreates() + beforePG := universeDump(t, fx.pool) + beforeIndex := recoveryIndexReadback(t, fx) + beforeObjects := objectVersionSet(t, fx) + beforeObjectBytes := r38ObjectVersionDigests(t, ctx, fx, objectInventoryR38(t, ctx, fx)) + beforeEffects := r38IndexEffects(t, filepath.Join(root, "archive"), "chunk-target") + save("17n-held-snapshot.json", map[string]any{"old_pid": oldPID, "marker_creates": beforeDispatching}) + // D06 的两次接管都必须与"第一次 recover 之前"的同一份基线一致,这里先把基线冻结。 + var baseline d06Snapshot + if secondRestart { + baseline = capture("17n2-baseline-before-first-recover.json") + } + + // 同一冻结二进制的新正式 worker;不携带一次性接缝。 + newEnv := map[string]string{} + for k, v := range workerEnv { + newEnv[k] = v + } + delete(newEnv, "KG_DS01_TEST_HOLD_AFTER_CAS") + delete(newEnv, "KG_DS01_TEST_REFUSE_MARKER") + if !n1 { + newEnv["LIBRARY_RESTORE_DISPATCH_V2"] = "1" + } + fresh := start("worker", "worker-negative", newEnv) + firstIdentity := processIdentityOf(t, fresh.Process.Pid) + firstIdentity["binary"] = "worker" + firstIdentity["worker_env_lease_duration"] = newEnv["WORKER_LEASE_DURATION"] + firstIdentity["dispatch_protocol_v2"] = newEnv["LIBRARY_RESTORE_DISPATCH_V2"] + firstIdentity["replaces_pid"] = oldPID + save("17n-new-worker.json", firstIdentity) + + code, accepted := api.do(t, http.MethodPost, "/api/v1/library/maintenance/recover", + map[string]any{"scope": "internal", "window_job_id": job.ID}) + if code != http.StatusAccepted { + t.Fatalf("recover with a held dispatch boundary => %d %v", code, accepted) + } + save("17n-recover-accepted.json", map[string]any{"http": code, "body": accepted, "window_job_id": job.ID}) + queueID, _ := accepted["job"].(map[string]any)["id"].(string) + if queueID == "" { + t.Fatalf("recover response has no queue job: %v", accepted) + } + deadline := time.Now().Add(120 * time.Second) + var queueState, lastError string + var attempts int + for { + if err := gov.QueryRow(ctx, `SELECT state, attempt, COALESCE(last_error,'') FROM jobs WHERE id=$1`, queueID). + Scan(&queueState, &attempts, &lastError); err != nil { + t.Fatal(err) + } + if queueState != "running" && queueState != "pending" { + break + } + if time.Now().After(deadline) { + t.Fatalf("negative recovery never reached a terminal/retry state (state=%s err=%s)", queueState, lastError) + } + time.Sleep(300 * time.Millisecond) + } + firstKillErr := fresh.Process.Kill() + firstWaitErr := fresh.Wait() + if _, err := os.Stat(fmt.Sprintf("/proc/%d", fresh.Process.Pid)); err == nil { + t.Fatalf("first restart worker %d still alive after kill", fresh.Process.Pid) + } + save("17n-recovery-failed.json", map[string]any{"queue": queueID, "state": queueState, + "attempt": attempts, "last_error": lastError}) + if !strings.Contains(lastError, "held") && !strings.Contains(lastError, "dispatch") && + !strings.Contains(lastError, "旧协议") && !strings.Contains(lastError, "legacy") { + t.Fatalf("negative recovery did not fail on the dispatch boundary: %s", lastError) + } + + afterPG := universeDump(t, fx.pool) + afterIndex := recoveryIndexReadback(t, fx) + afterObjects := objectVersionSet(t, fx) + afterObjectBytes := r38ObjectVersionDigests(t, ctx, fx, objectInventoryR38(t, ctx, fx)) + afterEffects := r38IndexEffects(t, filepath.Join(root, "archive"), "chunk-target") + state, owner, nonce, count := ledger() + creates := proxy.markerCreates() + save("17n-oracle.json", map[string]any{"ledger_state": state, "ledger_owner": owner, "ledger_nonce": nonce, + "ledger_rows": count, "marker_creates_after": creates, + "pg_diff": diffUniverse(beforePG, afterPG), + "index_equal": reflect.DeepEqual(beforeIndex, afterIndex), + "objects_equal": reflect.DeepEqual(beforeObjects, afterObjects), + "object_bytes_equal": reflect.DeepEqual(beforeObjectBytes, afterObjectBytes), + "effects_equal": reflect.DeepEqual(beforeEffects, afterEffects)}) + if diff := diffUniverse(beforePG, afterPG); diff != "" { + t.Fatalf("negative recovery wrote PG: %s", diff) + } + if !reflect.DeepEqual(beforeIndex, afterIndex) { + t.Fatal("negative recovery changed the index") + } + if !reflect.DeepEqual(beforeObjects, afterObjects) { + t.Fatal("negative recovery changed objects") + } + if !reflect.DeepEqual(beforeObjectBytes, afterObjectBytes) { + t.Fatal("negative recovery changed object bytes") + } + if !reflect.DeepEqual(beforeEffects, afterEffects) { + t.Fatal("negative recovery changed the persisted index effect files") + } + if creates != beforeDispatching { + t.Fatalf("negative recovery forwarded %d new marker creates", creates-beforeDispatching) + } + if n1 { + if state != "dispatching" || owner == "" { + t.Fatalf("dispatching record was rewritten: state=%q owner=%q", state, owner) + } + } else if count != 0 { + t.Fatalf("legacy negative back-filled %d dispatch rows", count) + } + code, blocked := api.do(t, http.MethodPost, "/api/v1/library/restores", + map[string]any{"scope": "internal", "snapshot_id": backupID}) + if code != http.StatusConflict || blocked["code"] != "library_target_in_maintenance" { + t.Fatalf("negative recovery opened the write entry: %d %v", code, blocked) + } + save("17n-entry-409.json", map[string]any{"http": code, "body": blocked}) + + if !secondRestart { + return + } + + // ---------- D06:第二次真实重启仍 held ---------- + // 第一个接管者已在上面被真实终止(Kill + Wait);先读回它确实退出,再等权威时钟 + // 判定窗口租约过期,才允许第二个新 PID 接管。两次接管之间不允许写任何状态。 + save("17n2-first-restart-exit.json", map[string]any{"pid": fresh.Process.Pid, + "kill_error": errText(firstKillErr), "wait_error": errText(firstWaitErr), + "proc_present_after_wait": false}) + firstAfter := capture("17n2-after-first-recover.json") + firstVerdict, firstProblems := compare(baseline, firstAfter) + firstVerdict["restart"] = "first takeover (old worker killed, new PID #1 recovered)" + firstVerdict["problems"] = firstProblems + save("17n2-first-takeover-oracle.json", firstVerdict) + if len(firstProblems) != 0 { + t.Fatalf("first takeover changed the held baseline: %v", firstProblems) + } + + waitLease("second takeover") + beforeSecond := capture("17n2-before-second-recover.json") + secondEnv := map[string]string{} + for k, v := range newEnv { + secondEnv[k] = v + } + delete(secondEnv, "KG_DS01_TEST_HOLD_AFTER_CAS") + delete(secondEnv, "KG_DS01_TEST_REFUSE_MARKER") + second := start("worker", "worker-second", secondEnv) + secondIdentity := processIdentityOf(t, second.Process.Pid) + secondIdentity["binary"] = "worker" + secondIdentity["worker_env_lease_duration"] = secondEnv["WORKER_LEASE_DURATION"] + secondIdentity["dispatch_protocol_v2"] = secondEnv["LIBRARY_RESTORE_DISPATCH_V2"] + secondIdentity["replaces_pid"] = fresh.Process.Pid + secondIdentity["distinct_pids"] = []int{oldPID, fresh.Process.Pid, second.Process.Pid} + save("17n2-second-worker.json", secondIdentity) + if second.Process.Pid == oldPID || second.Process.Pid == fresh.Process.Pid { + t.Fatalf("second takeover reused a PID: %v", secondIdentity["distinct_pids"]) + } + + secondCode, secondAccepted := api.do(t, http.MethodPost, "/api/v1/library/maintenance/recover", + map[string]any{"scope": "internal", "window_job_id": job.ID}) + if secondCode != http.StatusAccepted { + t.Fatalf("second recover via the normal API => %d %v", secondCode, secondAccepted) + } + save("17n2-second-recover-accepted.json", map[string]any{"http": secondCode, "body": secondAccepted, + "window_job_id": job.ID}) + secondQueue, _ := secondAccepted["job"].(map[string]any)["id"].(string) + if secondQueue != governance.LibraryRecoveryQueueID(job.ID) { + t.Fatalf("second recover queue id = %q, want the window's own %q", secondQueue, + governance.LibraryRecoveryQueueID(job.ID)) + } + if secondAccepted["window_job_id"] != job.ID || secondAccepted["scope"] != "internal" { + t.Fatalf("second recover response window binding = %v", secondAccepted) + } + secondDeadline := time.Now().Add(120 * time.Second) + var secondState, secondError string + var secondAttempt int + for { + if err := gov.QueryRow(ctx, `SELECT state, attempt, COALESCE(last_error,'') FROM jobs WHERE id=$1`, secondQueue). + Scan(&secondState, &secondAttempt, &secondError); err != nil { + t.Fatal(err) + } + if secondState != "running" && secondState != "pending" { + break + } + if time.Now().After(secondDeadline) { + t.Fatalf("second recovery never reached a terminal/retry state (state=%s err=%s)", secondState, secondError) + } + time.Sleep(300 * time.Millisecond) + } + secondKillErr := second.Process.Kill() + secondWaitErr := second.Wait() + if _, err := os.Stat(fmt.Sprintf("/proc/%d", second.Process.Pid)); err == nil { + t.Fatalf("second restart worker %d still alive after kill", second.Process.Pid) + } + save("17n2-second-restart-exit.json", map[string]any{"pid": second.Process.Pid, + "kill_error": errText(secondKillErr), "wait_error": errText(secondWaitErr), + "proc_present_after_wait": false}) + save("17n2-second-recovery-failed.json", map[string]any{"http": secondCode, "queue": secondQueue, + "state": secondState, "attempt": secondAttempt, "last_error": secondError, + "window_job_id": job.ID}) + if !strings.Contains(secondError, "held") && !strings.Contains(secondError, "dispatch") && + !strings.Contains(secondError, "旧协议") && !strings.Contains(secondError, "legacy") { + t.Fatalf("second recovery did not fail on the dispatch boundary: %s", secondError) + } + + afterSecond := capture("17n2-after-second-recover.json") + stepVerdict, stepProblems := compare(beforeSecond, afterSecond) + cumulativeVerdict, cumulativeProblems := compare(baseline, afterSecond) + state, owner, nonce, count = ledger() + problems := append(append([]string{}, stepProblems...), cumulativeProblems...) + if count != 1 || state != "dispatching" || owner == "" || nonce == "" { + problems = append(problems, fmt.Sprintf("dispatch ledger after second takeover: rows=%d state=%q owner=%q nonce=%q", + count, state, owner, nonce)) + } + secondBlockedCode, secondBlocked := api.do(t, http.MethodPost, "/api/v1/library/restores", + map[string]any{"scope": "internal", "snapshot_id": backupID}) + if secondBlockedCode != http.StatusConflict || secondBlocked["code"] != "library_target_in_maintenance" { + problems = append(problems, fmt.Sprintf("write entry after second takeover => %d %v", secondBlockedCode, secondBlocked)) + } + save("17n2-entry-409.json", map[string]any{"http": secondBlockedCode, "body": secondBlocked}) + maintenanceCode, maintenanceBody := api.do(t, http.MethodGet, "/api/v1/library/maintenance?scope=internal", nil) + instanceView, _ := maintenanceBody["instance_maintenance"].(map[string]any) + if maintenanceCode != http.StatusOK || maintenanceBody["held"] != true || instanceView == nil || + instanceView["state"] != "needs_restore" || instanceView["owner_job_id"] != job.ID { + problems = append(problems, fmt.Sprintf("maintenance after second takeover => %d %v", maintenanceCode, maintenanceBody)) + } + save("17n2-maintenance-held.json", map[string]any{"http": maintenanceCode, "body": maintenanceBody}) + save("17n2-oracle.json", map[string]any{ + "step": map[string]any{"verdict": stepVerdict, "problems": stepProblems}, + "cumulative_since_first_recover": map[string]any{"verdict": cumulativeVerdict, "problems": cumulativeProblems}, + "ledger_state": state, "ledger_owner": owner, "ledger_nonce": nonce, "ledger_rows": count, + "entry_http": secondBlockedCode, "entry_code": secondBlocked["code"], + "maintenance_held": maintenanceBody["held"], "problems": problems}) + if len(problems) != 0 { + t.Fatalf("second takeover changed the held baseline: %v", problems) + } +} diff --git a/internal/releaseadapter/v071/formal_es_fault_test.go b/internal/releaseadapter/v071/formal_es_fault_test.go new file mode 100644 index 0000000..32cf44c --- /dev/null +++ b/internal/releaseadapter/v071/formal_es_fault_test.go @@ -0,0 +1,81 @@ +package v071 + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" +) + +// This is only a faulting wire: every response, commit and CAS originates in +// the real isolated ES. Successful bodies are recorded, then one is withheld. +func formalElasticFaultProxy(t *testing.T, root, upstream, fault string) string { + t.Helper() + var mu sync.Mutex + dropped := false + events := []map[string]any{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, e := io.ReadAll(r.Body) + if e != nil { + http.Error(w, "read failed", 500) + return + } + request, e := http.NewRequestWithContext(r.Context(), r.Method, upstream+r.URL.RequestURI(), bytes.NewReader(raw)) + if e != nil { + http.Error(w, "request failed", 500) + return + } + request.Header = r.Header.Clone() + response, e := http.DefaultClient.Do(request) + if e != nil { + http.Error(w, "upstream failed", 502) + return + } + body, e := io.ReadAll(response.Body) + response.Body.Close() + if e != nil { + http.Error(w, "upstream body failed", 502) + return + } + mutating := r.Method == "PUT" || r.Method == "DELETE" || strings.Contains(r.URL.Path, "_bulk") + mu.Lock() + selected := fault == "apply-clean" && strings.HasSuffix(r.URL.Path, "/_doc/chunk-src") && !bytes.Contains(raw, []byte(indexClaimPrefix)) + selected = selected || (fault == "restore-write" && strings.HasSuffix(r.URL.Path, "/_create/chunk-target")) + selected = selected || (fault == "restore-clean" && r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/_doc/chunk-target") && !bytes.Contains(raw, []byte(indexRestoreClaimPrefix))) + drop := !dropped && selected && response.StatusCode >= 200 && response.StatusCode < 300 + if mutating { + events = append(events, map[string]any{"method": r.Method, "path": r.URL.RequestURI(), "request": string(raw), "response": string(body), "status": response.StatusCode, "dropped": drop}) + encoded, _ := json.MarshalIndent(events, "", " ") + _ = os.WriteFile(filepath.Join(root, "es-wire.json"), encoded, 0600) + } + if drop { + dropped = true + _ = os.WriteFile(filepath.Join(root, "es-response-dropped"), []byte(fault), 0600) + } + mu.Unlock() + if drop { + if hijacker, ok := w.(http.Hijacker); ok { + connection, _, err := hijacker.Hijack() + if err == nil { + connection.Close() + } + } + return + } + for k, values := range response.Header { + for _, v := range values { + w.Header().Add(k, v) + } + } + w.WriteHeader(response.StatusCode) + _, _ = w.Write(body) + })) + t.Cleanup(server.Close) + return server.URL +} diff --git a/internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go new file mode 100644 index 0000000..6606c3b --- /dev/null +++ b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_early_test.go @@ -0,0 +1,339 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" +) + +// 本轮唯一新增的夹具输入:来源文档二改为"已解析完成、无未结算子任务"。 +// +// 旧矩阵的 ds02SourceRows 一行不改:原 pending=1 输入仍然由正式来源契约拒绝(见负控)。 +// 这里只复制一份本轮 R38 early 场景专用声明,证明早段数据库故障不是靠不合法的来源夹具制造。 +func r38LegalSourceRows(t *testing.T) map[string][]map[string]any { + t.Helper() + rows := ds02SourceRows() + shared := ds02SourceRows() + index := -1 + for i, row := range rows["knowledges"] { + if row["id"] == "doc-src2" { + index = i + } + } + if index < 0 { + t.Fatal("source declaration lost doc-src2") + } + if shared["knowledges"][index]["pending_subtasks_count"] != 1 { + t.Fatalf("shared ds02 source declaration must stay pending=1, got %v", + shared["knowledges"][index]["pending_subtasks_count"]) + } + rows["knowledges"][index]["pending_subtasks_count"] = 0 + rows["knowledges"][index]["parse_status"] = "completed" + return rows +} + +func r38LegalSourceSpec(t *testing.T, fx *writeSetFixture) ds02Spec { + t.Helper() + rows := r38LegalSourceRows(t) + for table, list := range rows { + for i, row := range list { + rows[table][i] = ds02Canon(t, fx, table, row) + } + } + return ds02Spec{rows: rows, vectors: ds02Vectors, objects: ds02Objects} +} + +// r38SearchPathDB 让正式的结算检查跑在一张只装本轮声明的真实 PostgreSQL 表上。 +// 为什么不是直接插进业务表:来源行与发布写入共用主键 id,插进同一命名空间会让发布 +// 自己撞主键,故障就不再是"恢复阶段 database"。隔离 schema 只改变解析目标,不改产品代码。 +type r38SearchPathDB struct { + pool *pgxpool.Pool + schema string +} + +func (d r38SearchPathDB) BeginTx(ctx context.Context, opts pgx.TxOptions) (pgx.Tx, error) { + tx, err := d.pool.BeginTx(ctx, opts) + if err != nil { + return nil, err + } + if _, err := tx.Exec(ctx, `SET LOCAL search_path TO "`+d.schema+`", public`); err != nil { + _ = tx.Rollback(context.WithoutCancel(ctx)) + return nil, err + } + return tx, nil +} + +// r38ProveLegalSourceContract 用产品自己的 checkLibrarySourceSettlement 对 +// "本轮专用来源声明"做真实 PostgreSQL 结算,并保留 pending=1 被拒绝的负控。 +// 返回原始证据;调用方负责落盘。 +func r38ProveLegalSourceContract(t *testing.T, fx *writeSetFixture, spec ds02Spec) map[string]any { + t.Helper() + const schema = "r38_legal_source" + ctx := fx.ctx + if _, err := fx.pool.Exec(ctx, `DROP SCHEMA IF EXISTS `+schema+` CASCADE; +CREATE SCHEMA `+schema+`; +CREATE TABLE `+schema+`.knowledges (LIKE public.knowledges INCLUDING ALL)`); err != nil { + t.Fatalf("create the isolated settlement schema: %v", err) + } + drop := func() int { + if _, err := fx.pool.Exec(ctx, `DROP SCHEMA IF EXISTS `+schema+` CASCADE`); err != nil { + t.Fatalf("drop the isolated settlement schema: %v", err) + } + var left int + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.schemata WHERE schema_name=$1`, schema).Scan(&left); err != nil { + t.Fatalf("read back the isolated settlement schema: %v", err) + } + return left + } + t.Cleanup(func() { _ = drop }) + insert := `INSERT INTO ` + schema + `.knowledges SELECT * FROM jsonb_populate_record(NULL::` + schema + `.knowledges,$1::jsonb)` + for _, row := range spec.rows["knowledges"] { + raw, err := json.Marshal(row) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(ctx, insert, raw); err != nil { + t.Fatalf("insert the declared source row %v: %v", row["id"], err) + } + } + var declared int + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM `+schema+`.knowledges`).Scan(&declared); err != nil { + t.Fatal(err) + } + // 负控:同一条正式结算必须拒绝 pending=1。控制行是本夹具自己插入的,解除只按 id+租户+库删除。 + // 行形状取自本轮声明(canonical 行包含 NOT NULL 默认值),只改 id/范围/pending。 + controlID := "doc-src-pending-control" + controlKB := "kb-source-pending-control" + control := map[string]any{} + for key, value := range spec.rows["knowledges"][0] { + control[key] = value + } + control["id"] = controlID + control["tenant_id"] = wsSourceTenant + control["knowledge_base_id"] = controlKB + control["title"] = "待处理来源(负控)" + control["parse_status"] = "completed" + control["pending_subtasks_count"] = 1 + rawControl, err := json.Marshal(control) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(ctx, insert, rawControl); err != nil { + t.Fatalf("insert the pending=1 negative control: %v", err) + } + db := r38SearchPathDB{pool: fx.pool, schema: schema} + pendingErr := checkLibrarySourceSettlement(ctx, db) + if pendingErr == nil { + t.Fatal("the formal settlement accepted a pending=1 source row: the negative control was lost") + } + controlDelete := `DELETE FROM ` + schema + `.knowledges WHERE id=$1 AND tenant_id=$2 AND knowledge_base_id=$3` + tag, err := fx.pool.Exec(ctx, controlDelete, controlID, wsSourceTenant, controlKB) + if err != nil { + t.Fatalf("remove the pending=1 negative control: %v", err) + } + if tag.RowsAffected() != 1 { + t.Fatalf("pending control removal affected %d rows", tag.RowsAffected()) + } + var controlLeft int + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM `+schema+`.knowledges WHERE id=$1`, controlID).Scan(&controlLeft); err != nil { + t.Fatal(err) + } + if controlLeft != 0 { + t.Fatalf("pending control row left %d rows", controlLeft) + } + settlementErr := checkLibrarySourceSettlement(ctx, db) + if settlementErr != nil { + t.Fatalf("the declared legal source rows were rejected by the formal settlement: %v", settlementErr) + } + // 校准作用域:同一条 SQL 在隔离 schema 里看到的就是本轮声明,而不是业务表里的旧行。 + tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}) + if err != nil { + t.Fatal(err) + } + var searchPath string + var visible int + if err := tx.QueryRow(ctx, `SHOW search_path`).Scan(&searchPath); err != nil { + t.Fatal(err) + } + if err := tx.QueryRow(ctx, `SELECT count(*) FROM knowledges`).Scan(&visible); err != nil { + t.Fatal(err) + } + _ = tx.Rollback(context.WithoutCancel(ctx)) + var businessCopies int + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM public.knowledges WHERE tenant_id=$1`, wsSourceTenant).Scan(&businessCopies); err != nil { + t.Fatal(err) + } + if businessCopies != 0 { + t.Fatalf("source rows leaked into the business knowledges table: %d", businessCopies) + } + if visible != declared { + t.Fatalf("settlement scope saw %d rows, want the %d declared rows", visible, declared) + } + left := drop() + return map[string]any{ + "shared_declaration_kept_pending": 1, + "declared_source_rows": declared, + "declared_knowledge_pending": []int{0, 0}, + "declared_knowledge_parse_status": []string{"completed", "completed"}, + "settlement_sql": librarySourceSettlementSQL, + "pending_control": map[string]any{"id": controlID, "pending_subtasks_count": 1, + "rejected": true, "error": pendingErr.Error(), + "delete_statement": controlDelete, "deleted": tag.RowsAffected(), "rows_left": controlLeft}, + "legal_settlement": "passed", "legal_error": nil, + "search_path": searchPath, "settlement_visible_rows": visible, + "business_table_source_rows": businessCopies, + "schema": schema, "schema_dropped": left == 0, + "scope_note": "same formal settlement SQL, executed on a real PostgreSQL table holding exactly the declared rows; the business tables were never given these ids because publish writes the same ids", + } +} + +const r38PGEarlyFaultInsert = `INSERT INTO knowledges SELECT * FROM jsonb_populate_record(NULL::knowledges, $1::jsonb)` + +// r38ArmPGEarlyFault 是早段唯一新增的故障:发布已经把目标范围的 before-image 文档删掉, +// 恢复的 database 阶段会按原 id 把该文档插回;先用一行"外部范围、同主键"的 knowledges +// 占住这个 id,那条真实 INSERT 就得到 SQLSTATE 23505。不改 schema/ACL,也不停共享 PG。 +func r38ArmPGEarlyFault(t *testing.T, fx *writeSetFixture, knowledgeID string) map[string]any { + t.Helper() + if knowledgeID == "" { + t.Fatal("pg early fault armed without a knowledges identity") + } + var inTarget int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE id=$1 AND tenant_id=$2 AND knowledge_base_id=$3`, + knowledgeID, wsTargetTenant, wsTargetKB).Scan(&inTarget); err != nil { + t.Fatal(err) + } + if inTarget != 0 { + t.Fatalf("before-image knowledges id %s is still in the target scope: publish did not free the primary key", knowledgeID) + } + var raw []byte + if err := fx.pool.QueryRow(fx.ctx, `SELECT to_jsonb(x) FROM knowledges x ORDER BY id LIMIT 1`).Scan(&raw); err != nil { + t.Fatalf("pg early fault needs one existing knowledges row as a shape template: %v", err) + } + var row map[string]any + if err := json.Unmarshal(raw, &row); err != nil { + t.Fatal(err) + } + row["id"] = knowledgeID + row["tenant_id"] = 20000 + row["knowledge_base_id"] = "kb-r38-foreign" + row["title"] = "外部范围占位文档" + encoded, err := json.Marshal(row) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(fx.ctx, r38PGEarlyFaultInsert, encoded); err != nil { + t.Fatalf("arm pg early fault (foreign row holding knowledge %s): %v", knowledgeID, err) + } + var tenant int64 + var kb string + if err := fx.pool.QueryRow(fx.ctx, `SELECT tenant_id,knowledge_base_id FROM knowledges WHERE id=$1`, knowledgeID).Scan(&tenant, &kb); err != nil { + t.Fatal(err) + } + if tenant != 20000 || kb != "kb-r38-foreign" { + t.Fatalf("pg early fault row readback = %d/%s, want 20000/kb-r38-foreign", tenant, kb) + } + return map[string]any{"stage": "database", "table": "knowledges", "conflict_id": knowledgeID, + "conflict_tenant": tenant, "conflict_kb": kb, "insert_statement": r38PGEarlyFaultInsert, + "expected_sqlstate": r38PGSQLState, + "mechanism": "foreign-scope row holds the primary key the recovery database stage restores", + "target_row_absent_at_arm": true, "schema_changed": false, + "scope": "one disposable business database; shared PG, ACL and sessions untouched"} +} + +// r38PGEarlyFaultHeld 证明:故障行仍在;同一 INSERT 仍被服务器以 23505 拒绝且没有多出行; +// database 阶段整段回滚,所以十张表都还是发布写入后的内容(不是 before-image)。 +func r38PGEarlyFaultHeld(t *testing.T, fx *writeSetFixture, before, applied map[string][]map[string]any, + failureText, knowledgeID string) map[string]any { + t.Helper() + if len(before) == 0 || len(applied) == 0 { + t.Fatal("held early-pg evidence needs both the before-image and the applied readback") + } + var rows int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE id=$1 AND tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'`, + knowledgeID).Scan(&rows); err != nil { + t.Fatal(err) + } + if rows != 1 { + t.Fatalf("pg early fault row was not preserved at held: %d rows for knowledge %s", rows, knowledgeID) + } + var raw []byte + if err := fx.pool.QueryRow(fx.ctx, `SELECT to_jsonb(x) FROM knowledges x WHERE id=$1`, knowledgeID).Scan(&raw); err != nil { + t.Fatal(err) + } + _, probeErr := fx.pool.Exec(fx.ctx, r38PGEarlyFaultInsert, raw) + var pgErr *pgconn.PgError + if probeErr == nil || !errors.As(probeErr, &pgErr) { + t.Fatalf("fault probe did not raise a PG error: %v", probeErr) + } + if pgErr.Code != r38PGSQLState { + t.Fatalf("fault probe SQLSTATE = %q, want %s", pgErr.Code, r38PGSQLState) + } + var probeRows int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE id=$1`, knowledgeID).Scan(&probeRows); err != nil { + t.Fatal(err) + } + if probeRows != 1 { + t.Fatalf("failed probe left %d rows for knowledge %s: the statement did not roll back", probeRows, knowledgeID) + } + held := r38TargetRows(t, fx) + stillApplied := []string{} + for _, table := range ds02TargetTables { + if diff := r38CompareRows("held "+table, applied[table], held[table]); diff != "" { + t.Fatalf("held %s does not match the applied publish (the database stage must roll back as a whole): %s", table, diff) + } + stillApplied = append(stillApplied, table) + } + rolledBack := 0 + for _, table := range ds02TargetTables { + if r38CompareRows("held-vs-before "+table, before[table], held[table]) != "" { + rolledBack++ + } + } + if rolledBack == 0 { + t.Fatal("held state equals the before-image: the early database stage cannot have failed") + } + encoded, err := json.Marshal(held) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(encoded) + counts := map[string]int{} + for table, values := range held { + counts[table] = len(values) + } + return map[string]any{"conflict_id": knowledgeID, "conflict_rows": rows, + "probe_statement": r38PGEarlyFaultInsert, "sqlstate": pgErr.Code, "probe_error": pgErr.Error(), + "probe_rows_after_error": probeRows, + "transaction": "database stage INSERT failed; that stage transaction rolled back; no later stage ran", + "still_applied_tables": stillApplied, "tables_differing_from_before": rolledBack, + "held_row_counts": counts, "held_pg_sha256": hex.EncodeToString(sum[:]), + "matches_applied_publish": true, + "failure_text_has_sqlstate": strings.Contains(failureText, "SQLSTATE "+r38PGSQLState), + "failure_text_has_stage": strings.Contains(failureText, "恢复阶段 database 失败")} +} + +func r38DisarmPGEarlyFault(t *testing.T, fx *writeSetFixture, knowledgeID string) map[string]any { + t.Helper() + statement := `DELETE FROM knowledges WHERE id=$1 AND tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'` + tag, err := fx.pool.Exec(fx.ctx, statement, knowledgeID) + if err != nil { + t.Fatal(err) + } + var left int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'`).Scan(&left); err != nil { + t.Fatal(err) + } + if tag.RowsAffected() != 1 || left != 0 { + t.Fatalf("pg early fault not removed: deleted=%d left=%d", tag.RowsAffected(), left) + } + return map[string]any{"statement": statement, "deleted": tag.RowsAffected(), "foreign_rows_left": left, + "readback_absent": true} +} diff --git a/internal/releaseadapter/v071/formal_maintenance_recovery_r38_fullshape_test.go b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_fullshape_test.go new file mode 100644 index 0000000..82cbd54 --- /dev/null +++ b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_fullshape_test.go @@ -0,0 +1,641 @@ +package v071 + +// DS03 全形状补齐:把 DS02 已验的十表声明、独立期望与 LocalIDs oracle 真正复用到 +// 对象恢复的正式 worker 分支,而不是继续用"五张空表"充当全形状。 +// +// 这里只放夹具声明与独立观察,不放产品逻辑: +// - 目标 before-image 十表都非空(含旧目标行、同租户邻库行、外部租户哨兵); +// - 来源快照十表都非空(直接用 DS02 的 ds02SourceRows/ds02Objects 声明); +// - 引用承诺逐种计数(父子分块、标签关系、资源绑定、目录父子、wiki 引用、 +// 页面问题、日志),来源与恢复后都要求 matched>0,而不是只看"没有违反"; +// - 对象受保护版本按 versionId 逐个 GET 算 SHA256(不拿 ETag/size 当字节指纹)。 + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// r38Row 是一行声明:表名 + 未按目标 schema 规范化的列值。 +type r38Row struct { + Table string + Row map[string]any +} + +// 本地号必须低于序列起点(产品的预检会拒绝排在已用值之后的序列)。 +const ( + r38ChunkSeqTarget2 = int64(11) + r38ChunkSeqTarget3 = int64(12) + r38TagSeqTarget = int64(10) + r38WikiLogTarget = int64(2) +) + +// r38SeedObjectBytes 是目标 before-image 的对象字节(每个资源各自不同)。 +func r38SeedObjectBytes() map[string]string { + return map[string]string{ + "res-target": "12345678", + "res-shared": "87654321", + "res-orphan": "abcdefgh", + "res-other": "zzzzzzzz", + "res-foreign": "ffffffff", + } +} + +// r38BeforeImageRows 是发布前目标的完整声明:DS02 已验的邻库/外部租户行, +// 加上目标范围自己十表都非空的行(旧内容,恢复必须回到这里)。 +func r38BeforeImageRows() []r38Row { + rows := []r38Row{} + for _, declared := range ds02SeedRows() { + row := map[string]any{} + for key, value := range declared.row { + row[key] = value + } + // 目标旧文档本来就用目标知识库绑定的模型入库:恢复回放会把 + // embedding_model_id 重定向到该模型,预置成同一个值才是真实的写前状态。 + if declared.table == "knowledges" && row["id"] == "doc-target" { + row["embedding_model_id"] = "r38-model" + } + rows = append(rows, r38Row{Table: declared.table, Row: row}) + } + locator := func(id string) string { + return wsLocator("backend-target", "minio", ds02BucketPlaceholder, wsTargetTenant, id) + } + rows = append(rows, + r38Row{"chunks", map[string]any{"id": "chunk-target2", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, + "knowledge_id": "doc-target", "content": "目标旧正文二 图:resource://" + wsHandleTarget, "chunk_index": 1, + "start_at": int64(8), "end_at": int64(16), "pre_chunk_id": "chunk-target", "parent_chunk_id": "chunk-target", + "seq_id": r38ChunkSeqTarget2}}, + r38Row{"chunks", map[string]any{"id": "chunk-target3", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, + "knowledge_id": "doc-target", "content": "目标旧正文三", "chunk_index": 2, + "start_at": int64(16), "end_at": int64(24), "next_chunk_id": "chunk-target", + "seq_id": r38ChunkSeqTarget3}}, + r38Row{"knowledge_tags", map[string]any{"id": "tag-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, + "name": "目标旧标签", "sort_order": 1, "seq_id": r38TagSeqTarget}}, + r38Row{"knowledge_tag_relations", map[string]any{"knowledge_id": "doc-target", "tag_id": "tag-target"}}, + r38Row{"wiki_folders", map[string]any{"id": "folder-target", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, + "parent_id": "", "name": "目标根目录", "path": "root", "depth": 0, "sort_order": 1}}, + r38Row{"wiki_folders", map[string]any{"id": "folder-target2", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, + "parent_id": "folder-target", "name": "目标子目录", "path": "root/sub", "depth": 1, "sort_order": 2}}, + r38Row{"wiki_pages", map[string]any{"id": "wiki-target2", "tenant_id": wsTargetTenant, "knowledge_base_id": wsTargetKB, + "slug": "guide", "title": "目标指南", "page_type": "summary", "status": "published", + "content": "目标旧指南", "summary": "目标摘要", "parent_slug": "index", "folder_id": "folder-target2", + "category_path": []any{"root", "sub"}, "wiki_path": "root/sub/guide", "depth": 1, "sort_order": 2, + "source_refs": []any{"doc-target|目标旧文档"}, "chunk_refs": []any{"chunk-target2"}, + "in_links": []any{}, "out_links": []any{}, "page_metadata": map[string]any{"lang": "zh"}, + "aliases": []any{}, "version": 1}}, + r38Row{"wiki_page_issues", map[string]any{"id": "issue-target", "tenant_id": wsTargetTenant, + "knowledge_base_id": wsTargetKB, "slug": "guide", "issue_type": "review", "description": "目标旧问题", + "suspected_knowledge_ids": []any{"doc-target"}, "status": "pending", "reported_by": "fixture"}}, + r38Row{"wiki_log_entries", map[string]any{"id": r38WikiLogTarget, "tenant_id": wsTargetTenant, + "knowledge_base_id": wsTargetKB, "action": "ingest", "knowledge_id": "doc-target", + "doc_title": "目标旧文档", "summary": "目标旧日志", + "pages_affected": []any{map[string]any{"slug": "guide", "title": "目标指南"}}}}, + r38Row{"resources", map[string]any{"id": "res-target", "handle": wsHandleTarget, "tenant_id": wsTargetTenant, + "storage_backend_id": "backend-target", "provider": "minio", "physical_path": locator("res-target"), + "kind": "file", "mime_type": "image/png", "original_name": "a.png", "size": int64(8)}}, + r38Row{"resources", map[string]any{"id": "res-shared", "handle": wsHandleShared, "tenant_id": wsTargetTenant, + "storage_backend_id": "backend-target", "provider": "minio", "physical_path": locator("res-shared"), + "kind": "file", "mime_type": "image/png", "original_name": "a.png", "size": int64(8)}}, + r38Row{"resources", map[string]any{"id": "res-orphan", "handle": wsHandleOrphan, "tenant_id": wsTargetTenant, + "storage_backend_id": "backend-target", "provider": "minio", "physical_path": locator("res-orphan"), + "kind": "file", "mime_type": "image/png", "original_name": "a.png", "size": int64(8)}}, + r38Row{"resources", map[string]any{"id": "res-foreign", "handle": wsHandleForeign, "tenant_id": wsForeignTnt, + "storage_backend_id": "backend-target", "provider": "minio", "physical_path": locator("res-foreign"), + "kind": "file", "mime_type": "image/png", "original_name": "a.png", "size": int64(8)}}, + r38Row{"resource_bindings", map[string]any{"id": "bind-target", "resource_id": "res-target", + "tenant_id": wsTargetTenant, "owner_type": "knowledge", "owner_id": "doc-target", "relation": "attachment"}}, + r38Row{"resource_bindings", map[string]any{"id": "bind-target2", "resource_id": "res-target", + "tenant_id": wsTargetTenant, "owner_type": "chunk", "owner_id": "chunk-target2", "relation": "attachment"}}, + r38Row{"resource_bindings", map[string]any{"id": "bind-shared-target", "resource_id": "res-shared", + "tenant_id": wsTargetTenant, "owner_type": "knowledge", "owner_id": "doc-target", "relation": "attachment"}}, + r38Row{"resource_bindings", map[string]any{"id": "bind-foreign", "resource_id": "res-foreign", + "tenant_id": wsForeignTnt, "owner_type": "knowledge", "owner_id": "doc-foreign", "relation": "attachment"}}, + r38Row{"resource_bindings", map[string]any{"id": "bind-shared-other", "resource_id": "res-shared", + "tenant_id": wsTargetTenant, "owner_type": "knowledge", "owner_id": "doc-other", "relation": "attachment"}}, + ) + return rows +} + +// r38BeforeImageDocs 是目标 before-image 的索引文档:目标范围内每个分块都要有, +// 外部租户文档是"恢复不得动"的哨兵。 +func r38BeforeImageDocs() []struct { + id string + tenant uint64 + kb string + knowledge string + content string +} { + return []struct { + id string + tenant uint64 + kb string + knowledge string + content string + }{ + {"chunk-target", wsTargetTenant, wsTargetKB, "doc-target", "目标旧正文"}, + {"chunk-target2", wsTargetTenant, wsTargetKB, "doc-target", "目标旧正文二 图:resource://" + wsHandleTarget}, + {"chunk-target3", wsTargetTenant, wsTargetKB, "doc-target", "目标旧正文三"}, + {"chunk-foreign", wsForeignTnt, "kb-foreign", "doc-foreign", "外部正文"}, + } +} + +// r38SeedFullShape 重建真实 v071 十表结构,并种入非空的 before-image。 +// 返回的是"声明 → schema 规范化"后的独立期望行(不是从数据库读回来的)。 +func r38SeedFullShape(t *testing.T, fx *writeSetFixture) map[string][]map[string]any { + t.Helper() + r11Mirror(t, fx) + for _, statement := range []string{ + `SELECT setval('chunks_seq_id_seq',100000005,false)`, + `SELECT setval('knowledge_tags_seq_id_seq',50,false)`, + `SELECT setval('wiki_log_entries_id_seq',10,false)`, + } { + r10Exec(t, fx, statement) + } + for id, body := range r38SeedObjectBytes() { + path := wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, id) + if err := fx.objects.s3.Put(fx.ctx, "minio", path, strings.NewReader(body), int64(len(body))); err != nil { + t.Fatalf("seed object %s: %v", id, err) + } + } + expected := map[string][]map[string]any{} + for _, item := range r38BeforeImageRows() { + row := ds02SeedRow(item.Row, fx.bucket) + r11Insert(t, fx, item.Table, row) + expected[item.Table] = append(expected[item.Table], ds02Canon(t, fx, item.Table, row)) + } + for _, doc := range r38BeforeImageDocs() { + fx.indexDoc(t, doc.id, doc.tenant, doc.kb, doc.knowledge, doc.content) + } + return expected +} + +// r38SourceVectors 是夹具声明的来源向量(1024 维,符合目标真实模型维度), +// 逐分块不同;索引内容由它生成,不由被测适配器生成。 +func r38SourceVectors() map[string][]float64 { + build := func(seed float64) []float64 { + vector := make([]float64, 1024) + vector[0] = seed + vector[1] = 1 - seed + vector[2] = seed / 2 + return vector + } + return map[string][]float64{ + "chunk-src": build(0.5), + "chunk-src2": build(0.25), + "chunk-src3": build(0.75), + } +} + +// r38SealFullShape 用 DS02 的十表声明封一份十表全非空快照,索引向量与映射摘要 +// 由本夹具显式给出(不从被测适配器取)。 +func r38SealFullShape(t *testing.T, fx *writeSetFixture, spec ds02Spec, mapping string) string { + t.Helper() + vectors := r38SourceVectors() + archive, err := librarysnapshot.Open(fx.archiveRoot, 256<<20) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + encode := func(value any) []byte { + raw, e := json.Marshal(value) + if e != nil { + t.Fatal(e) + } + return raw + } + kinds := map[string]string{"knowledges": "database", "chunks": "database", "knowledge_tags": "database", + "knowledge_tag_relations": "database", "resources": "database", "resource_bindings": "database", + "wiki_folders": "wiki", "wiki_pages": "wiki", "wiki_page_issues": "wiki", "wiki_log_entries": "wiki"} + parts := []librarysnapshot.Part{} + for _, table := range ds02TargetTables { + if len(spec.rows[table]) == 0 { + t.Fatalf("source part %s must be non-empty: a vacuous full-shape claim is not evidence", table) + } + part, err := archive.Put(bytes.NewReader(encode(spec.rows[table]))) + if err != nil { + t.Fatal(err) + } + part.Kind, part.Name, part.Count = kinds[table], table, int64(len(spec.rows[table])) + parts = append(parts, part) + } + objectIDs := make([]string, 0, len(spec.objects)) + for id := range spec.objects { + objectIDs = append(objectIDs, id) + } + sort.Strings(objectIDs) + for _, id := range objectIDs { + part, e := archive.Put(strings.NewReader(spec.objects[id])) + if e != nil { + t.Fatal(e) + } + part.Kind, part.Name, part.Count = "resource", id, 1 + parts = append(parts, part) + } + indexRows := []map[string]any{} + for _, chunk := range spec.rows["chunks"] { + id := fmt.Sprint(chunk["id"]) + vector, ok := vectors[id] + if !ok || len(vector) != 1024 { + t.Fatalf("source chunk %s has no declared 1024-dim vector", id) + } + indexRows = append(indexRows, map[string]any{"id": id, "source": map[string]any{ + "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "knowledge_id": chunk["knowledge_id"], "chunk_id": id, "source_id": id, + "content": chunk["content"], "embedding": vector}}) + } + indexPart, e := archive.Put(bytes.NewReader(encode(indexRows))) + if e != nil { + t.Fatal(e) + } + indexPart.Kind, indexPart.Name, indexPart.Count = "index", "chunks", int64(len(indexRows)) + parts = append(parts, indexPart) + manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, + Format: librarysnapshot.Format, Scope: "internal", TenantID: wsSourceTenant, KnowledgeBaseID: wsSourceKB, + CreatedAt: time.Now().UTC(), Parts: parts, + Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", + EmbeddingDimension: 1024, IndexMappingSHA256: mapping}} + id, err := archive.Seal(manifest) + if err != nil { + t.Fatalf("seal full-shape snapshot: %v", err) + } + return id +} + +// r38SourcePartCounts 读回来源快照每个部件的行数:十表必须全部非空。 +func r38SourcePartCounts(t *testing.T, fx *writeSetFixture, source string) map[string]int64 { + t.Helper() + archive, err := librarysnapshot.Open(fx.archiveRoot, 256<<20) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + manifest, err := archive.Load(source) + if err != nil { + t.Fatal(err) + } + counts := map[string]int64{} + for _, part := range manifest.Parts { + if part.Kind == "database" || part.Kind == "wiki" { + counts[part.Name] = part.Count + } + } + for _, table := range ds02TargetTables { + if counts[table] <= 0 { + t.Fatalf("source snapshot part %s is empty (%d): full-shape claim would be vacuous", table, counts[table]) + } + } + return counts +} + +// r38TargetRows 独立读出目标范围的行(按本测试声明的表范围规则,不读产品的分类)。 +func r38TargetRows(t *testing.T, fx *writeSetFixture) map[string][]map[string]any { + t.Helper() + return r38RowsForScope(t, fx, true) +} + +// r38SentinelRows 读目标范围之外的行:发布/恢复都不得改动它们。 +func r38SentinelRows(t *testing.T, fx *writeSetFixture) map[string][]map[string]any { + t.Helper() + return r38RowsForScope(t, fx, false) +} + +func r38RowsForScope(t *testing.T, fx *writeSetFixture, inside bool) map[string][]map[string]any { + t.Helper() + out := map[string][]map[string]any{} + for _, table := range ds02TargetTables { + rule := ds02ScopeDecl[table] + switch { + case table == "knowledge_tag_relations": + query := `SELECT to_jsonb(x)::text FROM knowledge_tag_relations AS x + WHERE knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)` + if !inside { + query = `SELECT to_jsonb(x)::text FROM knowledge_tag_relations AS x + WHERE knowledge_id NOT IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)` + } + out[table] = ds02Read(t, fx, query, wsTargetTenant, wsTargetKB) + case rule.Tenant && rule.KnowledgeBase: + query := "SELECT to_jsonb(x)::text FROM " + table + " AS x WHERE tenant_id=$1 AND knowledge_base_id=$2" + if !inside { + query = "SELECT to_jsonb(x)::text FROM " + table + " AS x WHERE NOT (tenant_id=$1 AND knowledge_base_id=$2)" + } + out[table] = ds02Read(t, fx, query, wsTargetTenant, wsTargetKB) + case rule.Tenant: + query := "SELECT to_jsonb(x)::text FROM " + table + " AS x WHERE tenant_id=$1" + if !inside { + query = "SELECT to_jsonb(x)::text FROM " + table + " AS x WHERE tenant_id<>$1" + } + out[table] = ds02Read(t, fx, query, wsTargetTenant) + default: + t.Fatalf("table %s has no declared independent scope rule", table) + } + } + return out +} + +// r38CompareRows 比较两份行集合(逐列、多重集),返回人可读差异或空串。 +func r38CompareRows(label string, want, got []map[string]any) string { + if diff := ds02Compare(label, want, got); diff != "" { + return diff + } + return "" +} + +var r38ResourceToken = regexp.MustCompile(`resource://([A-Za-z0-9_-]{22})`) + +// r38ReferenceKinds 是"发布内容必须真的兑现的引用承诺"清单。 +var r38ReferenceKinds = []string{ + "chunks.next_chunk_id", "chunks.pre_chunk_id", "chunks.parent_chunk_id", "chunks.resource_handle", + "knowledge_tag_relations.knowledge_id", "knowledge_tag_relations.tag_id", + "resource_bindings.resource_id", "resource_bindings.owner_id", + "wiki_folders.parent_id", "wiki_pages.folder_id", "wiki_pages.source_refs", + "wiki_pages.chunk_refs", "wiki_page_issues.slug", "wiki_page_issues.suspected_knowledge_ids", + "wiki_log_entries.knowledge_id", "wiki_log_entries.pages_affected_slug", +} + +// r38ReferenceCounts 独立计算每种引用承诺在给定行集合里匹配到多少条。 +// 只数"真的指向存在的行"的引用,未知引用不计——空匹配会被调用方判失败。 +func r38ReferenceCounts(rows map[string][]map[string]any) map[string]int { + counts := map[string]int{} + ids := func(table string) map[string]bool { + out := map[string]bool{} + for _, row := range rows[table] { + out[r38Text(row["id"])] = true + } + return out + } + handles := map[string]bool{} + for _, row := range rows["resources"] { + handles[r38Text(row["handle"])] = true + } + chunks := ids("chunks") + knowledges := ids("knowledges") + tags := ids("knowledge_tags") + resources := ids("resources") + folders := ids("wiki_folders") + slugs := map[string]bool{} + for _, page := range rows["wiki_pages"] { + slugs[r38Text(page["slug"])] = true + } + for _, chunk := range rows["chunks"] { + for _, field := range []string{"next_chunk_id", "pre_chunk_id", "parent_chunk_id"} { + if ref := r38Text(chunk[field]); ref != "" && chunks[ref] { + counts["chunks."+field]++ + } + } + for _, match := range r38ResourceToken.FindAllStringSubmatch(r38Text(chunk["content"]), -1) { + if handles[match[1]] { + counts["chunks.resource_handle"]++ + } + } + } + for _, relation := range rows["knowledge_tag_relations"] { + if knowledges[r38Text(relation["knowledge_id"])] { + counts["knowledge_tag_relations.knowledge_id"]++ + } + if tags[r38Text(relation["tag_id"])] { + counts["knowledge_tag_relations.tag_id"]++ + } + } + for _, binding := range rows["resource_bindings"] { + if resources[r38Text(binding["resource_id"])] { + counts["resource_bindings.resource_id"]++ + } + owner := r38Text(binding["owner_id"]) + if chunks[owner] || knowledges[owner] { + counts["resource_bindings.owner_id"]++ + } + } + for _, folder := range rows["wiki_folders"] { + if parent := r38Text(folder["parent_id"]); parent != "" && folders[parent] { + counts["wiki_folders.parent_id"]++ + } + } + for _, page := range rows["wiki_pages"] { + if folder := r38Text(page["folder_id"]); folder != "" && folders[folder] { + counts["wiki_pages.folder_id"]++ + } + for _, ref := range r38List(page["source_refs"]) { + knowledge := strings.SplitN(r38Text(ref), "|", 2)[0] + if knowledges[knowledge] { + counts["wiki_pages.source_refs"]++ + } + } + for _, ref := range r38List(page["chunk_refs"]) { + if chunks[r38Text(ref)] { + counts["wiki_pages.chunk_refs"]++ + } + } + } + for _, issue := range rows["wiki_page_issues"] { + if slugs[r38Text(issue["slug"])] { + counts["wiki_page_issues.slug"]++ + } + for _, ref := range r38List(issue["suspected_knowledge_ids"]) { + if knowledges[r38Text(ref)] { + counts["wiki_page_issues.suspected_knowledge_ids"]++ + } + } + } + for _, entry := range rows["wiki_log_entries"] { + if knowledges[r38Text(entry["knowledge_id"])] { + counts["wiki_log_entries.knowledge_id"]++ + } + for _, page := range r38List(entry["pages_affected"]) { + reference, _ := page.(map[string]any) + if reference != nil && slugs[r38Text(reference["slug"])] { + counts["wiki_log_entries.pages_affected_slug"]++ + } + } + } + return counts +} + +// r38RequireReferences 要求每种承诺都 matched>0;返回按种类排序的计数。 +func r38RequireReferences(t *testing.T, label string, rows map[string][]map[string]any) map[string]int { + t.Helper() + counts := r38ReferenceCounts(rows) + var missing []string + for _, kind := range r38ReferenceKinds { + if counts[kind] <= 0 { + missing = append(missing, kind) + } + } + if len(missing) > 0 { + t.Fatalf("%s: reference promises with zero matches: %v (counts=%v)", label, missing, counts) + } + return counts +} + +// r38DeclaredTargetScope 按本测试声明的范围规则,从独立声明里取目标范围应有的行。 +// 期望来自声明,不来自任何一次数据库读回。 +func r38DeclaredTargetScope(t *testing.T, declared map[string][]map[string]any, table string) []map[string]any { + t.Helper() + rule := ds02ScopeDecl[table] + if table == "knowledge_tag_relations" { + knowledge := map[string]bool{} + for _, row := range declared["knowledges"] { + if r38Text(row["tenant_id"]) == fmt.Sprint(wsTargetTenant) && r38Text(row["knowledge_base_id"]) == wsTargetKB { + knowledge[r38Text(row["id"])] = true + } + } + out := []map[string]any{} + for _, row := range declared[table] { + if knowledge[r38Text(row["knowledge_id"])] { + out = append(out, row) + } + } + return out + } + out := []map[string]any{} + for _, row := range declared[table] { + if r38Text(row["tenant_id"]) != fmt.Sprint(wsTargetTenant) { + continue + } + if rule.KnowledgeBase && r38Text(row["knowledge_base_id"]) != wsTargetKB { + continue + } + out = append(out, row) + } + return out +} + +// r38FindWriteSet 按作业身份取回这次发布真正落盘的写集合(文件名即摘要,取回时 +// 逐项校验字节/内容摘要)。同一作业出现两份台账说明现场不唯一,直接失败。 +func r38FindWriteSet(t *testing.T, archiveRoot, jobID string) *libraryrelease.WriteSet { + t.Helper() + dir := filepath.Join(archiveRoot, writeSetDirName) + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("read write-set ledger dir %s: %v", dir, err) + } + var found *libraryrelease.WriteSet + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") { + continue + } + digest := strings.TrimSuffix(entry.Name(), ".json") + set, loadErr := LoadWriteSet(archiveRoot, digest) + if loadErr != nil { + t.Fatalf("persisted write set %s does not verify: %v", digest, loadErr) + } + if set.JobID != jobID { + continue + } + if found != nil { + t.Fatalf("two persisted write sets for job %s: %s and %s", jobID, found.Digest, set.Digest) + } + found = set + } + if found == nil { + t.Fatalf("no persisted write set for job %s", jobID) + } + return found +} + +// r38ObjectVersionDigests 对给定清单里的每个 versionId 单独 GET 并计算 SHA256。 +// 这是字节指纹;ETag/size 只作为旁证,绝不参与"字节相同"的判定。 +func r38ObjectVersionDigests(t *testing.T, ctx context.Context, fx *writeSetFixture, + inventory *s3.ListObjectVersionsOutput) map[string]string { + t.Helper() + digests := map[string]string{} + for _, version := range inventory.Versions { + key, id := aws.ToString(version.Key), aws.ToString(version.VersionId) + if key == "" || id == "" { + t.Fatalf("version listing row without key/version-id: %+v", version) + } + response, err := fx.objects.s3.client.GetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(fx.bucket), Key: aws.String(key), VersionId: aws.String(id)}) + if err != nil { + t.Fatalf("GET %s@%s: %v", key, id, err) + } + body, readErr := io.ReadAll(response.Body) + response.Body.Close() + if readErr != nil { + t.Fatalf("read %s@%s: %v", key, id, readErr) + } + if int64(len(body)) != aws.ToInt64(version.Size) { + t.Fatalf("%s@%s bytes=%d but version metadata size=%d", key, id, len(body), aws.ToInt64(version.Size)) + } + sum := sha256.Sum256(body) + digests[key+"@"+id] = hex.EncodeToString(sum[:]) + } + if len(digests) != len(inventory.Versions) { + t.Fatalf("version digest coverage %d/%d", len(digests), len(inventory.Versions)) + } + return digests +} + +// r38Text 把声明/读回里的标量统一成字符串比较键。 +func r38Text(value any) string { + switch typed := value.(type) { + case nil: + return "" + case string: + return typed + case fmt.Stringer: + return typed.String() + } + return fmt.Sprint(value) +} + +func r38List(value any) []any { + if list, ok := value.([]any); ok { + return list + } + return nil +} + +// r38LocalColumns 复用 DS02 的映射 oracle 输入:声明来源 + 独立期望目标行 + 真实目标行。 +func r38LocalColumns(t *testing.T, fx *writeSetFixture, spec ds02Spec, expectation ds02Expectation) []ds02LocalColumn { + t.Helper() + var columns []ds02LocalColumn + for _, contract := range []struct{ table, column string }{ + {"chunks", "seq_id"}, {"knowledge_tags", "seq_id"}, {"wiki_log_entries", "id"}, + } { + sources := []int64{} + for _, row := range spec.rows[contract.table] { + raw := row["seq_id"] + if contract.table == "wiki_log_entries" { + raw = row["id"] + } + value, err := strconv.ParseInt(fmt.Sprint(raw), 10, 64) + if err != nil { + t.Fatalf("%s declared local id: %v", contract.table, err) + } + sources = append(sources, value) + } + sort.Slice(sources, func(i, j int) bool { return sources[i] < sources[j] }) + actual := map[int64]map[string]any{} + for _, row := range ds02Read(t, fx, "SELECT to_jsonb(x)::text FROM "+contract.table+ + " AS x WHERE tenant_id=$1 AND knowledge_base_id=$2", wsTargetTenant, wsTargetKB) { + value, err := strconv.ParseInt(fmt.Sprint(row[contract.column]), 10, 64) + if err != nil { + t.Fatalf("%s actual local id: %v", contract.table, err) + } + actual[value] = row + } + columns = append(columns, ds02LocalColumn{Table: contract.table, Column: contract.column, + Sources: sources, Expected: expectation.Local[contract.table], + ExpectedRows: expectation.RowsBySource[contract.table], Actual: actual}) + } + return columns +} diff --git a/internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go new file mode 100644 index 0000000..2c93b77 --- /dev/null +++ b/internal/releaseadapter/v071/formal_maintenance_recovery_r38_test.go @@ -0,0 +1,2303 @@ +package v071 + +// r38:正式 worker / maintenance / recover API 的"有证据可恢复"闭环。 +// +// 场景(全部由真实进程与真实存储产生,测试只播种/观察): +// 1. 真实 publish:worker 执行 apply(database/resources/index 真实写入,对象经对象网关 +// 生成 receipt);快照缺 wiki 部件 → wiki 阶段真实失败(与 r37 contractFailWikiTarget 同一定点)。 +// 2. 失败后的自动回滚在 restore-finalize-intent 已落盘、marker 仍停在自己世代时被 +// 传输层拒绝"clean 派发"(拒绝 = 不转发、不丢响应;ES 里 marker 原样保留)。 +// → 回滚失败 → 维护窗口 held + needs_restore(不是 adapter 返回值当结论)。 +// 3. HTTP:GET /library/maintenance 看到 held/needs_restore;写入口 POST /library/restores 返回 409。 +// 4. 撤一次性故障 → POST /library/maintenance/recover(同一 window/job/backup)→ worker 续作 +// 一次 clean 写入 → 校验通过、入口 open、维护释放;PG 逐行/对象版本/ES _source 全量恢复。 +// +// 该测试只在 KG_R38_RUN 指定的隔离部署里运行;故障只存在于本进程的 ES 传输层。 + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + "golang.org/x/crypto/bcrypt" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" + "knowledge-governance/internal/objectgateway" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/version" +) + +// r38RefusalProxy 是"只在传输层拒绝,不转发"的故障注入: +// 选中的写请求被直接 503,绝不落到真实 ES;其余请求原样转发并记录变更请求现场。 +type r38RefusalProxy struct { + url string + mu sync.Mutex + refuseClean bool + refuseMarker bool + corruptVerify bool + events []map[string]any + refused int + corrupted int + root string +} + +func newR38RefusalProxy(t *testing.T, root, upstream string) *r38RefusalProxy { + t.Helper() + p := &r38RefusalProxy{root: root, refuseClean: true} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, e := io.ReadAll(r.Body) + if e != nil { + http.Error(w, "read failed", 500) + return + } + p.mu.Lock() + refuseClean := p.refuseClean + refuseMarker := p.refuseMarker + p.mu.Unlock() + selected := refuseClean && r.Method == http.MethodPut && + strings.Contains(r.URL.Path, "/_doc/chunk-target") && + !bytes.Contains(raw, []byte(indexRestoreClaimPrefix)) + // N2-missing:拒绝**恢复标记 create 本身**,让旧协议回滚停在"意图已落盘、目标 + // 确实缺失"的边界上;这不是 clean 拒绝,也不写任何目标字节。 + markerRefused := refuseMarker && (r.Method == http.MethodPut || r.Method == http.MethodPost) && + strings.Contains(r.URL.Path, "/_create/") && bytes.Contains(raw, []byte(indexRestoreClaimPrefix)) + if selected || markerRefused { + p.mu.Lock() + p.refused++ + p.events = append(p.events, map[string]any{ + "method": r.Method, "path": r.URL.RequestURI(), "request": string(raw), + "marker_refused": markerRefused, "dispatched": false, "refused": true, + "at": time.Now().UTC().Format(time.RFC3339Nano)}) + p.flush() + p.mu.Unlock() + // 拒绝发生在派发之前:真实 ES 一次都没有收到这份写入。 + http.Error(w, "r38 injected refusal before dispatch", http.StatusServiceUnavailable) + return + } + request, e := http.NewRequestWithContext(r.Context(), r.Method, upstream+r.URL.RequestURI(), bytes.NewReader(raw)) + if e != nil { + http.Error(w, "request failed", 500) + return + } + request.Header = r.Header.Clone() + // 读回内容必须是明文 JSON:否则注入的"内容不一致"只会变成无法解析的压缩字节, + // 校验侧会把它当成传输错误而不是真实内容差异。 + request.Header.Del("Accept-Encoding") + response, e := http.DefaultClient.Do(request) + if e != nil { + http.Error(w, "upstream failed", 502) + return + } + body, e := io.ReadAll(response.Body) + response.Body.Close() + if e != nil { + http.Error(w, "upstream body failed", 502) + return + } + p.mu.Lock() + corrupt := p.corruptVerify && response.StatusCode == 200 && strings.Contains(r.URL.Path, "_search") + if corrupt { + // 只改这一份读回内容并立刻解除:校验阶段读到"与快照不一致"的真实不一致, + // 后续回滚/恢复的 _mget 与 _doc 请求仍然读到真实 ES。 + p.corruptVerify = false + p.corrupted++ + body = corruptSearchBody(body) + } + p.mu.Unlock() + if r.Method == http.MethodPut || r.Method == http.MethodPost || r.Method == http.MethodDelete { + p.mu.Lock() + p.events = append(p.events, map[string]any{ + "method": r.Method, "path": r.URL.RequestURI(), "request": string(raw), + "status": response.StatusCode, "dispatched": true, "refused": false, "corrupted": corrupt, + "at": time.Now().UTC().Format(time.RFC3339Nano)}) + if len(p.events)%8 == 0 { + p.flush() + } + p.mu.Unlock() + } + for k, values := range response.Header { + for _, v := range values { + w.Header().Add(k, v) + } + } + w.WriteHeader(response.StatusCode) + _, _ = w.Write(body) + })) + t.Cleanup(server.Close) + p.url = server.URL + p.mu.Lock() + p.flush() + p.mu.Unlock() + return p +} + +func (p *r38RefusalProxy) flush() { + encoded, _ := json.MarshalIndent(p.events, "", " ") + _ = os.WriteFile(filepath.Join(p.root, "es-wire.json"), encoded, 0600) +} + +func (p *r38RefusalProxy) setRefuseClean(refuse bool) { + p.mu.Lock() + defer p.mu.Unlock() + p.refuseClean = refuse + p.flush() +} + +func (p *r38RefusalProxy) setRefuseMarker(refuse bool) { + p.mu.Lock() + defer p.mu.Unlock() + p.refuseMarker = refuse + p.flush() +} + +// markerCreates 只数**真实转发**到 ES 的恢复标记 create(路径 _create + claim 前缀)。 +func (p *r38RefusalProxy) markerCreates() int { + p.mu.Lock() + defer p.mu.Unlock() + count := 0 + for _, event := range p.events { + path, _ := event["path"].(string) + request, _ := event["request"].(string) + dispatched, _ := event["dispatched"].(bool) + if dispatched && strings.Contains(path, "/_create/") && strings.Contains(request, indexRestoreClaimPrefix) { + count++ + } + } + return count +} + +func (p *r38RefusalProxy) armVerifyCorruption() { + p.mu.Lock() + defer p.mu.Unlock() + p.corruptVerify = true + p.flush() +} + +func (p *r38RefusalProxy) corruptionCount() int { + p.mu.Lock() + defer p.mu.Unlock() + return p.corrupted +} + +// corruptSearchBody 让校验阶段的读回与快照内容不一致(真实内容差异,不是错误响应)。 +func corruptSearchBody(body []byte) []byte { + var payload map[string]any + if json.Unmarshal(body, &payload) != nil { + return body + } + hits, _ := payload["hits"].(map[string]any)["hits"].([]any) + if len(hits) == 0 { + return body + } + hit, _ := hits[0].(map[string]any) + source, _ := hit["_source"].(map[string]any) + if source == nil { + return body + } + content, _ := source["content"].(string) + source["content"] = content + "-r38-verify-mismatch" + encoded, e := json.Marshal(payload) + if e != nil { + return body + } + return encoded +} + +func (p *r38RefusalProxy) snapshot() ([]map[string]any, int) { + p.mu.Lock() + defer p.mu.Unlock() + out := append([]map[string]any(nil), p.events...) + return out, p.refused +} + +// r38ObjectRefusalProxy 是对象网关前的传输层拒绝:被选中的恢复型对象操作在派发前 +// 直接 503,网关一次都没收到;其余请求原样转发并记录现场。拒绝发生在 reserve 之前, +// 因此不会产生"已落盘但结果未知"的 intent,撤障后同一 operation 仍可安全重试。 +type r38ObjectRefusalProxy struct { + url string + upstream string + root string + mu sync.Mutex + armed bool + events []map[string]any + refused int + forwarded int +} + +func newR38ObjectRefusalProxy(t *testing.T, root, upstream string) *r38ObjectRefusalProxy { + t.Helper() + p := &r38ObjectRefusalProxy{root: root, upstream: upstream} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, e := io.ReadAll(r.Body) + if e != nil { + http.Error(w, "read failed", 500) + return + } + var envelope struct { + Authorization map[string]any `json:"authorization"` + Request map[string]any `json:"request"` + } + _ = json.Unmarshal(raw, &envelope) + p.mu.Lock() + armed := p.armed + p.mu.Unlock() + action, _ := envelope.Request["action"].(string) + selected := armed && r.Method == http.MethodPost && r.URL.Path == "/v1/execute" && action == "delete" + if selected { + p.mu.Lock() + p.refused++ + p.events = append(p.events, map[string]any{ + "method": r.Method, "path": r.URL.RequestURI(), "request": envelope.Request, + "authorization": envelope.Authorization, "body": string(raw), + "receiver": p.upstream, "gateway_scope": r.Header.Get("X-KG-Gateway-Scope"), + "response_status": http.StatusServiceUnavailable, + "response_body": "r38 injected object restore refusal before dispatch\n", + "dispatched": false, "forwarded": false, "refused": true, + "at": time.Now().UTC().Format(time.RFC3339Nano)}) + p.flush() + p.mu.Unlock() + http.Error(w, "r38 injected object restore refusal before dispatch", http.StatusServiceUnavailable) + return + } + request, e := http.NewRequestWithContext(r.Context(), r.Method, p.upstream+r.URL.RequestURI(), bytes.NewReader(raw)) + if e != nil { + http.Error(w, "request failed", 500) + return + } + request.Header = r.Header.Clone() + request.Header.Del("Accept-Encoding") + response, e := http.DefaultClient.Do(request) + if e != nil { + http.Error(w, "upstream failed", 502) + return + } + body, e := io.ReadAll(response.Body) + response.Body.Close() + if e != nil { + http.Error(w, "upstream body failed", 502) + return + } + if r.Method == http.MethodPost { + p.mu.Lock() + p.events = append(p.events, map[string]any{ + "method": r.Method, "path": r.URL.RequestURI(), "request": envelope.Request, + "status": response.StatusCode, "receiver": p.upstream, + "dispatched": true, "forwarded": true, "refused": false, + "at": time.Now().UTC().Format(time.RFC3339Nano)}) + if !selected { + p.forwarded++ + } + p.mu.Unlock() + } + for k, values := range response.Header { + for _, v := range values { + w.Header().Add(k, v) + } + } + w.WriteHeader(response.StatusCode) + _, _ = w.Write(body) + })) + t.Cleanup(server.Close) + p.url = server.URL + p.flush() + return p +} + +func (p *r38ObjectRefusalProxy) flush() { + encoded, _ := json.MarshalIndent(p.events, "", " ") + _ = os.WriteFile(filepath.Join(p.root, "object-wire.json"), encoded, 0600) +} + +func (p *r38ObjectRefusalProxy) setArmed(armed bool) { + p.mu.Lock() + defer p.mu.Unlock() + p.armed = armed + p.flush() +} + +func (p *r38ObjectRefusalProxy) snapshot() ([]map[string]any, int, int) { + p.mu.Lock() + defer p.mu.Unlock() + out := append([]map[string]any(nil), p.events...) + return out, p.refused, p.forwarded +} + +type r38API struct { + base string + client *http.Client +} + +func (a r38API) do(t *testing.T, method, path string, payload any) (int, map[string]any) { + t.Helper() + var body []byte + if payload != nil { + encoded, e := json.Marshal(payload) + if e != nil { + t.Fatal(e) + } + body = encoded + } + request, e := http.NewRequest(method, a.base+path, bytes.NewReader(body)) + if e != nil { + t.Fatal(e) + } + if body != nil { + request.Header.Set("Content-Type", "application/json") + } + response, e := a.client.Do(request) + if e != nil { + t.Fatalf("%s %s: %v", method, path, e) + } + defer response.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20)) + out := map[string]any{} + if len(raw) > 0 { + _ = json.Unmarshal(raw, &out) + } + return response.StatusCode, out +} + +// r38ActivateDS01 在维护窗口 held 的当下登记恢复派发激活。 +// +// 证据只声明身份/作业/journal 摘要/writer 集合;事实全部来自 worker 进程写下的 +// journal 字节、治理库实例维护行与本进程对目标的一次只读观察。它不在窗口开始前 +// "先激活再证明":没有 held 的真实停写/排空证据时,激活门必须失败关闭。 +func r38ActivateDS01(t *testing.T, ctx context.Context, root string, gov *pgxpool.Pool, + cfg appconfig.Config, fx *writeSetFixture, job governance.LibraryJob) (string, map[string]any, error) { + journalPath := filepath.Join(root, "maintenance", job.ID+".json") + rawJournal, err := os.ReadFile(journalPath) + if err != nil { + return "", nil, fmt.Errorf("read held journal: %w", err) + } + var journal map[string]any + if err := json.Unmarshal(rawJournal, &journal); err != nil { + return "", nil, fmt.Errorf("parse held journal: %w", err) + } + if state, _ := journal["state"].(string); state != "held" { + return "", nil, fmt.Errorf("activation requires a held journal, got %v", journal["state"]) + } + var ownerJob, servicesRaw, rowState string + var released *time.Time + err = gov.QueryRow(ctx, `SELECT owner_job_id, services::text, state, released_at +FROM library_instance_maintenance WHERE instance=$1`, cfg.LibraryTargetInstance).Scan( + &ownerJob, &servicesRaw, &rowState, &released) + if err != nil { + return "", nil, fmt.Errorf("read maintenance window: %w", err) + } + if ownerJob != job.ID || released != nil { + return "", nil, fmt.Errorf("maintenance window %s/%s released=%v does not match job %s", ownerJob, rowState, released, job.ID) + } + var names []string + if err := json.Unmarshal([]byte(servicesRaw), &names); err != nil { + return "", nil, fmt.Errorf("parse maintenance writer set: %w", err) + } + services, _ := journal["services"].([]any) + if len(names) == 0 || len(names) != len(services) { + return "", nil, fmt.Errorf("writer sets differ: governance %v, journal %d", names, len(services)) + } + writers := make([]libraryrelease.RestoreDispatchWriterDrain, 0, len(names)) + for i, name := range names { + entry, ok := services[i].(map[string]any) + if !ok { + return "", nil, fmt.Errorf("journal service %d is not an object", i) + } + instanceID, _ := entry["id"].(string) + if instanceID == "" { + return "", nil, fmt.Errorf("journal service %d has no immutable id", i) + } + writers = append(writers, libraryrelease.RestoreDispatchWriterDrain{Name: name, Kind: "worker", InstanceID: instanceID}) + } + // 现场只读观察:目标指纹必须与维护窗口记录的一致(发现"配置换了目标")。 + probe := fx.target(t) + fingerprint, _, observeErr := probe.observeRestoreTarget(ctx) + if observeErr != nil { + return "", nil, fmt.Errorf("observe live target: %w", observeErr) + } + windowFingerprint, _ := journal["target_fingerprint"].(string) + if windowFingerprint == "" { + return "", nil, errors.New("maintenance journal has no target fingerprint") + } + build := version.DisplayVersion() + if expected := os.Getenv("KG_R38_VERSION"); expected != "" && build != expected { + return "", nil, fmt.Errorf("test binary build %q != runner identity %q", build, expected) + } + var database, systemIdentifier, databaseOID string + if err := gov.QueryRow(ctx, ` +SELECT current_database(), + (SELECT system_identifier::text FROM pg_control_system()), + (SELECT oid::text FROM pg_database WHERE datname = current_database())`).Scan( + &database, &systemIdentifier, &databaseOID); err != nil { + return "", nil, fmt.Errorf("read governance authority: %w", err) + } + if expected := os.Getenv("KG_R38_COMMIT"); expected != "" && version.CommitSHA != expected { + return "", nil, fmt.Errorf("test binary commit %q != runner identity %q", version.CommitSHA, expected) + } + journalSum := sha256.Sum256(rawJournal) + // 激活后同一窗口还会继续写 journal(recovered 等);把激活那一刻的字节原样留档, + // 否则事后无法从最终目录重算 activation 里登记的摘要。 + journalSnapshot := filepath.Join(root, "05b-journal-snapshot.json") + if err := os.WriteFile(journalSnapshot, rawJournal, 0600); err != nil { + return "", nil, err + } + now := time.Now().UTC() + evidence := libraryrelease.RestoreDispatchActivationEvidence{ + ProtocolVersion: libraryrelease.RestoreDispatchActivationProtocolVersion, + ProtocolEpoch: libraryrelease.RestoreDispatchProtocolEpoch, + TargetIdentity: cfg.LibraryTargetIdentity(), TargetFingerprint: windowFingerprint, + RestoreTargetFingerprint: fingerprint, TargetInstance: cfg.LibraryTargetInstance, GovernanceDatabase: database, + GovernanceAuthority: libraryrelease.RestoreDispatchGovernanceAuthority{SystemIdentifier: systemIdentifier, DatabaseOID: databaseOID}, + ProtocolBuild: build, ProtocolBuildSHA: version.CommitSHA, + AttestedBy: "r38-runner", AttestedAt: now, + MaintenanceJob: job.ID, MaintenanceJournal: job.ID + ".json", + MaintenanceJournalSHA256: hex.EncodeToString(journalSum[:]), Writers: writers, + } + rawEvidence, err := json.Marshal(evidence) + if err != nil { + return "", nil, err + } + evidencePath := filepath.Join(root, "ds01-activation-request.json") + if err := os.WriteFile(evidencePath, rawEvidence, 0600); err != nil { + return "", nil, err + } + evidenceSum := sha256.Sum256(rawEvidence) + activationStore := postgresstore.NewStore(gov).WithRestoreDispatchEvidence(filepath.Join(root, "maintenance")) + if err := activationStore.ActivateRestoreDispatch(ctx, evidencePath, hex.EncodeToString(evidenceSum[:]), + cfg.LibraryTargetIdentity(), fingerprint, time.Now().UTC()); err != nil { + return "", nil, fmt.Errorf("activate restore dispatch: %w", err) + } + // 读回登记行与写进台账的已核事实:报告必须能指出"代码核了什么"。 + var target, drainDigest, stored string + var activatedAt time.Time + if err := gov.QueryRow(ctx, `SELECT target_identity, drain_evidence_digest, evidence::text, activated_at +FROM library_index_restore_dispatch_activation WHERE target_identity=$1`, cfg.LibraryTargetIdentity()).Scan( + &target, &drainDigest, &stored, &activatedAt); err != nil { + return "", nil, fmt.Errorf("read activation row: %w", err) + } + gate, _ := journal["gate"].(map[string]any) + quiesce, _ := journal["quiesce"].(map[string]any) + facts := map[string]any{ + "target": target, "fingerprint": fingerprint, "window_fingerprint": windowFingerprint, + "governance_database": database, + "governance_authority": map[string]string{"system_identifier": systemIdentifier, "database_oid": databaseOID, + "primary": "true"}, + "protocol_build_sha": version.CommitSHA, + "maintenance_job": job.ID, "protocol_build": build, + "journal_sha256": drainDigest, "journal_snapshot": filepath.Base(journalSnapshot), + "activation_evidence_sha256": hex.EncodeToString(evidenceSum[:]), + "journal_state": journal["state"], "gate": gate, "quiesce": quiesce, + "writers": writers, "activated_at": activatedAt, "stored_evidence_bytes": len(stored), + "post_activation_observation": "journal read on disk + governance row + live target fingerprint"} + return fingerprint, facts, nil +} + +// TestFormalMaintenanceRecoveryObjectRestoreHeldThenRecovered 是本轮对象恢复分支的 +// 显式入口:隔离部署里必须由 runner 传入 KG_R38_SCENARIO=object-restore; +// 在隔离部署中未设置直接失败,不把旧 ES 分支的运行冒名成对象分支。 +func TestFormalMaintenanceRecoveryObjectRestoreHeldThenRecovered(t *testing.T) { + if os.Getenv("KG_R38_RUN") == "" { + t.Skip("requires the dedicated r38 isolated deployment (KG_R38_RUN)") + } + if os.Getenv("KG_R38_SCENARIO") != "object-restore" { + t.Fatalf("object recovery branch requires KG_R38_SCENARIO=object-restore, got %q", os.Getenv("KG_R38_SCENARIO")) + } + TestFormalMaintenanceRecoveryHeldThenRecovered(t) +} + +// TestFormalMaintenanceRecoveryPGRestoreHeldThenRecovered 是 PG 恢复失败分支的显式入口: +// 隔离部署里必须由 runner 传入 KG_R38_SCENARIO=pg-restore。发布失败入口复用已证明的 +// after:wiki 定点;唯一新增故障来自这次专用恢复事务里的真实主键冲突(SQLSTATE 23505), +// 不靠停共享 PG、扩大 ACL 或改产品返回值制造。 +func TestFormalMaintenanceRecoveryPGRestoreHeldThenRecovered(t *testing.T) { + if os.Getenv("KG_R38_RUN") == "" { + t.Skip("requires the dedicated r38 isolated deployment (KG_R38_RUN)") + } + if os.Getenv("KG_R38_SCENARIO") != "pg-restore" { + t.Fatalf("pg recovery branch requires KG_R38_SCENARIO=pg-restore, got %q", os.Getenv("KG_R38_SCENARIO")) + } + TestFormalMaintenanceRecoveryHeldThenRecovered(t) +} + +// TestFormalMaintenanceRecoveryPGEarlyRestoreHeldThenRecovered 是早段 database 恢复失败的显式入口: +// 发布失败入口仍是已证明的 after:wiki 定点;唯一新增故障是恢复第一段(database)里的真实 +// 主键冲突。来源输入改用本轮专用副本:未删除文档 parse_status=completed 且 +// pending_subtasks_count=0,并在封版前用产品自己的正式结算检查证明它可被接受; +// 旧的 pending=1 输入仍保留为"被正式契约拒绝"的负控,不放宽 quiesce。 +func TestFormalMaintenanceRecoveryPGEarlyRestoreHeldThenRecovered(t *testing.T) { + if os.Getenv("KG_R38_RUN") == "" { + t.Skip("requires the dedicated r38 isolated deployment (KG_R38_RUN)") + } + if os.Getenv("KG_R38_SCENARIO") != "pg-early" { + t.Fatalf("pg early recovery branch requires KG_R38_SCENARIO=pg-early, got %q", os.Getenv("KG_R38_SCENARIO")) + } + TestFormalMaintenanceRecoveryHeldThenRecovered(t) +} + +func TestFormalMaintenanceRecoveryHeldThenRecovered(t *testing.T) { + root := os.Getenv("KG_R38_RUN") + if root == "" { + t.Skip("requires the dedicated r38 isolated deployment (KG_R38_RUN)") + } + scenario := os.Getenv("KG_R38_SCENARIO") + objectBranch := scenario == "object-restore" + pgBranch := scenario == "pg-restore" + earlyBranch := scenario == "pg-early" + ds01Positive := scenario == "ds01" + ds01N1 := scenario == "ds01-n1" + // D06:在 N1 的 dispatching+missing 边界上再真实重启一次——第一次接管 held 之后, + // 真实终止那个新执行者并启动第二个新 PID,再次走同一 recover API 仍 held。 + ds01Second := scenario == "ds01-n1-second" + ds01N2 := scenario == "ds01-n2" + ds01N2Missing := scenario == "ds01-n2-missing" + ds01Branch := ds01Positive || ds01N1 || ds01Second || ds01N2 || ds01N2Missing + // 三条分支共用同一套 fullshape/真实入库装配;对象分支与两种 PG 分支都让 ES 恢复不成为 + // 第一个失败点:ES 分支拒绝 clean 派发,PG 分支在恢复自己的事务里拿到真实 SQLSTATE。 + fullShape := objectBranch || pgBranch || earlyBranch + ctx := context.Background() + save := func(name string, value any) { + t.Helper() + raw, e := json.MarshalIndent(value, "", " ") + if e != nil { + t.Fatal(e) + } + if e = os.WriteFile(filepath.Join(root, name), raw, 0600); e != nil { + t.Fatal(e) + } + } + must := func(e error) { + t.Helper() + if e != nil { + t.Fatal(e) + } + } + archiveRoot := filepath.Join(root, "archive") + must(os.MkdirAll(archiveRoot, 0700)) + must(os.MkdirAll(filepath.Join(root, "maintenance"), 0700)) + + // ---------- 1) 隔离目标现场 ---------- + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, archiveRoot: archiveRoot, embeddingDimension: 1024}) + // 对象分支复用 DS02 已验的十表全形状声明与独立 oracle:真实 v071 catalog + + // 目标 before-image 十表全非空。旧 ES 分支保持原最小夹具语义,不在本轮扩围。 + var declaredBefore map[string][]map[string]any + var beforeSentinels map[string][]map[string]any + if fullShape { + declaredBefore = r38SeedFullShape(t, fx) + } else { + seedTargetData(t, fx) + } + // 早段分支的来源输入是专用副本(pending=0/completed)。封版前先用产品自己的正式结算 + // 检查证明这份输入可被接受,并保留原 pending=1 被拒绝的负控。共享声明一行不改。 + var earlySourceSpec ds02Spec + if earlyBranch { + earlySourceSpec = r38LegalSourceSpec(t, fx) + save("01c-legal-source-proof.json", r38ProveLegalSourceContract(t, fx, earlySourceSpec)) + } + _, e := fx.pool.Exec(ctx, `ALTER TABLE knowledge_bases ADD COLUMN embedding_model_id text, ADD COLUMN vector_store_id text; +CREATE TABLE models(id text PRIMARY KEY,name text,parameters jsonb,deleted_at timestamptz); +CREATE TABLE vector_stores(id text PRIMARY KEY,engine_type text,index_config jsonb,deleted_at timestamptz); +INSERT INTO models VALUES('r38-model','text-embedding-v4','{"embedding_parameters":{"dimension":1024}}',NULL); +INSERT INTO vector_stores VALUES('r38-vector','elasticsearch_v8','{}',NULL); +UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-vector';`) + must(e) + beforePG := universeDump(t, fx.pool) + save("01-pg-before.json", beforePG) + // PG 分支的故障锚点:恢复的最后一段 PG 写入(wiki 阶段)会把 before-image 的 + // 日志行按原 id 插回目标范围,所以一个同主键、不同范围的"外来行"会让那条真实 + // INSERT 报 23505;发布/恢复都不改 schema,也不动共享 PG。 + var conflictLog int64 + var conflictKnowledge string + var beforeTarget map[string][]map[string]any + if pgBranch { + must(fx.pool.QueryRow(ctx, `SELECT id FROM wiki_log_entries WHERE tenant_id=$1 AND knowledge_base_id=$2 ORDER BY id DESC LIMIT 1`, + wsTargetTenant, wsTargetKB).Scan(&conflictLog)) + if conflictLog == 0 { + t.Fatal("pg branch needs a before-image wiki log identity to collide with") + } + beforeTarget = r38TargetRows(t, fx) + } + if earlyBranch { + // 早段的冲突锚点:before-image 目标文档。发布整库替换时它会被删掉,恢复的 database + // 阶段必须按原 id 插回;外部范围同主键行会让那条真实 INSERT 报 23505。 + must(fx.pool.QueryRow(ctx, `SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 ORDER BY id LIMIT 1`, + wsTargetTenant, wsTargetKB).Scan(&conflictKnowledge)) + if conflictKnowledge == "" { + t.Fatal("pg early branch needs a before-image knowledge identity to collide with") + } + beforeTarget = r38TargetRows(t, fx) + } + if fullShape { + for _, table := range ds02TargetTables { + if len(beforePG[table]) == 0 { + t.Fatalf("before-image table %s is empty: the ten-table claim would be vacuous", table) + } + } + beforeSentinels = r38SentinelRows(t, fx) + for _, table := range ds02TargetTables { + if len(beforeSentinels[table]) == 0 { + t.Fatalf("sentinel rows for %s are empty: a neighbour-scope claim needs real rows", table) + } + } + save("01a-pg-sentinel-before.json", beforeSentinels) + save("01b-pg-before-reference-promises.json", r38RequireReferences(t, "declared before-image", declaredBefore)) + } + beforeIndex := recoveryIndexReadback(t, fx) + save("02-index-before.json", beforeIndex) + beforeObjects := objectInventoryR38(t, ctx, fx) + save("03-objects-before.json", beforeObjects) + var beforeDigests map[string]string + if fullShape { + beforeDigests = r38ObjectVersionDigests(t, ctx, fx, beforeObjects) + if len(beforeDigests) == 0 { + t.Fatal("before-image has no object versions to fingerprint") + } + save("03a-object-byte-digests-before.json", beforeDigests) + } + + target := fx.target(t) + mapping, e := target.Search().MappingSHA256(ctx) + must(e) + // 对象分支:来源十表全非空(DS02 声明)、索引向量与映射摘要由夹具显式给出; + // 快照完整可封存,发布在写完后由"读回与快照不一致"进入回滚(同 r37 定点)。 + var spec ds02Spec + var expectation ds02Expectation + var source string + var sourceParts map[string]int64 + if fullShape { + if earlyBranch { + // 早段专用来源副本:doc-src2 pending=0/completed,已通过上面的正式结算检查。 + spec = earlySourceSpec + } else { + spec = ds02SourceSpec(t, fx) + } + expectation = ds02Expected(t, fx, spec) + source = r38SealFullShape(t, fx, spec, mapping) + save("04-snapshot.json", map[string]any{"snapshot": source, "index_mapping_sha256": mapping, "full_shape": true}) + sourceParts = r38SourcePartCounts(t, fx, source) + save("04a-source-parts.json", sourceParts) + save("04b-source-reference-promises.json", r38RequireReferences(t, "source declaration", spec.rows)) + } else { + source = sealSourceSnapshot(t, fx, nil) + archive, e := librarysnapshot.Open(archiveRoot, 256<<20) + must(e) + manifest, e := archive.Load(source) + must(e) + manifest.Compatibility.EmbeddingDimension = 1024 + manifest.Compatibility.IndexMappingSHA256 = mapping + source, e = archive.Seal(manifest) + must(e) + archive.Close() + save("04-snapshot.json", map[string]any{"snapshot": source, "index_mapping_sha256": mapping}) + } + + // ---------- 2) 治理库 / 网关 / API / worker ---------- + govDSN := os.Getenv("KG_R38_GOVERNANCE_DSN") + gov, e := pgxpool.New(ctx, govDSN) + must(e) + t.Cleanup(gov.Close) + must(postgresstore.ApplyMigrations(ctx, gov)) + _, e = gov.Exec(ctx, objectgateway.Schema) + must(e) + reader := gatewayReadOnlyGovernance(t, ctx, gov, govDSN) + project := os.Getenv("KG_R38_PROJECT") + proxy := newR38RefusalProxy(t, root, fx.searchBase) + if ds01N2Missing { + // N2-missing:只拒绝旧协议的恢复标记 create,回滚因此停在"意图已落盘、 + // 目标确实缺失"的边界;clean 放行以免把失败误归因到 clean 拒绝。 + proxy.setRefuseClean(false) + proxy.setRefuseMarker(true) + } + if fullShape || ds01Positive || ds01N1 || ds01Second { + // 对象分支要证明的是"对象恢复传输失败",ES 的回滚写入必须放行, + // 否则失败会被误报成旧的 ES clean-dispatch 分支。DS01 分支要让恢复在 + // 派发 CAS 之前被产品接缝拒绝,ES 传输层不能先拒绝别的写。 + proxy.setRefuseClean(false) + } + objectProxy := newR38ObjectRefusalProxy(t, root, "http://"+os.Getenv("KG_R38_GATEWAY_ADDR")) + save("00-scenario.json", map[string]any{"scenario": scenario, "object_restore_branch": objectBranch, + "label": os.Getenv("KG_R38_LABEL"), "commit": os.Getenv("KG_R38_COMMIT"), + "version": os.Getenv("KG_R38_VERSION"), "release_version": os.Getenv("KG_R38_RELEASE_VERSION"), + "publish_entry": "store.CreateLibraryDispatch (publish API entry not proven)"}) + // 四类进程身份:测试进程自证 executable hash 与 runner 期望一致;产品三类在 start() + // 里按 /proc//exe 读回真实 executable 并逐字节比对构建产物。 + testExecutable, e := os.Executable() + must(e) + testHash := sha256.Sum256(func() []byte { raw, _ := os.ReadFile(testExecutable); return raw }()) + testIdentity := map[string]any{"label": "test", "pid": os.Getpid(), "executable": testExecutable, + "executable_sha256": hex.EncodeToString(testHash[:]), "expected_sha256": os.Getenv("KG_R38_TEST_BINARY_SHA"), + "commit": os.Getenv("KG_R38_COMMIT"), "source_tree": os.Getenv("KG_R38_SOURCE_TREE")} + if testIdentity["expected_sha256"] == "" || testIdentity["executable_sha256"] != testIdentity["expected_sha256"] { + t.Fatalf("test process identity mismatch: %v", testIdentity) + } + save("00-test-process-identity.json", testIdentity) + + env := map[string]string{ + "KG_LIBRARY_TEST_ISOLATED": "1", "DATABASE_URL": govDSN, "LIBRARY_WORKER_ROLE": "release-executor", + "WORKER_POLL_INTERVAL": "200ms", "WORKER_LEASE_DURATION": "30s", + "PRODUCTION_RELEASE_REQUESTS_ENABLED": "true", "PRODUCTION_BACKUP_RESTORE_VERIFIED": "true", + "LIBRARY_ARCHIVE_ROOT": archiveRoot, "LIBRARY_CAPACITY_BUDGET_BYTES": "1073741824", + "LIBRARY_PRODUCTION_DATABASE_URL": os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), + "LIBRARY_PRODUCTION_ELASTIC_URL": proxy.url, "LIBRARY_PRODUCTION_INDEX": fx.index, + "LIBRARY_PRODUCTION_TENANT_ID": "10001", "LIBRARY_PRODUCTION_KB_INTERNAL": wsTargetKB, + "LIBRARY_PRODUCTION_S3_PROVIDER": "minio", "LIBRARY_PRODUCTION_S3_ENDPOINT": os.Getenv("KG_LIBRARY_TEST_S3_ENDPOINT"), + "LIBRARY_PRODUCTION_S3_BUCKET": fx.bucket, + "LIBRARY_PRODUCTION_S3_ACCESS_KEY": os.Getenv("KG_R38_READER_KEY"), + "LIBRARY_PRODUCTION_S3_SECRET_KEY": os.Getenv("KG_R38_READER_SECRET"), + "LIBRARY_TARGET_INSTANCE": project, "LIBRARY_TARGET_PROJECT": project, "LIBRARY_TARGET_WRITERS": "writer", + "LIBRARY_TARGET_NON_WRITERS": "ingress=entry gate,redis=queue,minio=object backend", + "LIBRARY_TARGET_INGRESS_URL": os.Getenv("KG_R38_INGRESS"), "LIBRARY_TARGET_INGRESS_SERVICE": "ingress", + "LIBRARY_TARGET_INGRESS_DRAIN_FILE": filepath.Join(root, "gate/drain.json"), + "LIBRARY_TARGET_REDIS_ADDR": os.Getenv("KG_R38_REDIS_ADDR"), "LIBRARY_TARGET_REDIS_PASSWORD": os.Getenv("KG_R38_REDIS_PASSWORD"), + "LIBRARY_TARGET_REDIS_DB": "0", "LIBRARY_TARGET_JOURNAL_ROOT": filepath.Join(root, "maintenance"), + "LIBRARY_TARGET_DOCKER_SOCKET": "/var/run/docker.sock", "LIBRARY_EMBEDDING_DIMENSION": "1024", + "KG_TEST_BARRIER_DIR": filepath.Join(root, "barriers"), "KG_TEST_BARRIER_POINTS": "after:wiki", + "KG_TEST_BARRIER_TIMEOUT": "300s", + } + if ds01Branch && os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + t.Fatal("ds01 branch requires KG_LIBRARY_TEST_ISOLATED=1") + } + if ds01Positive || ds01N1 || ds01Second { + env["LIBRARY_RESTORE_DISPATCH_V2"] = "1" + } + if ds01Positive { + env["KG_DS01_TEST_REFUSE_MARKER"] = fx.index + "/chunk-target" + } + if ds01N1 || ds01Second { + env["KG_DS01_TEST_HOLD_AFTER_CAS"] = fx.index + "/chunk-target" + env["WORKER_LEASE_DURATION"] = "8s" + } + env["PRODUCTION_RELEASE_AUTHORIZER_REF"] = project + env["PRODUCTION_RELEASE_AUTH_TOKEN_FILE"] = filepath.Join(root, "authorization-token") + must(os.WriteFile(env["PRODUCTION_RELEASE_AUTH_TOKEN_FILE"], []byte(objectgateway.Digest([]byte(root+"approval"))), 0600)) + cfg, e := appconfig.Load(func(k string) string { return env[k] }) + must(e) + var ds01Fingerprint string + + dataToken := objectgateway.Digest([]byte(root + "data")) + controlToken := objectgateway.Digest([]byte(root + "control")) + env["LIBRARY_OBJECT_GATEWAY_URL"] = objectProxy.url + env["LIBRARY_OBJECT_GATEWAY_TOKEN"] = dataToken + + // worker 的对象身份是只读的:任何对象写入只能经网关,receipt 因此必然来自真实生产写。 + readStore, e := NewS3ObjectStore(S3ObjectStoreConfig{Provider: "minio", Endpoint: env["LIBRARY_PRODUCTION_S3_ENDPOINT"], + Bucket: fx.bucket, AccessKeyID: env["LIBRARY_PRODUCTION_S3_ACCESS_KEY"], SecretAccessKey: env["LIBRARY_PRODUCTION_S3_SECRET_KEY"], + Region: "us-east-1", ForcePathStyle: true}) + must(e) + allowedRead, e := readStore.Open(ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, 10001, "res-target")) + must(e) + allowedBody, e := io.ReadAll(allowedRead) + allowedRead.Close() + must(e) + if !bytes.Equal(allowedBody, []byte("12345678")) { + t.Fatal("readonly identity could not read original bytes") + } + if denied := readStore.Put(ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, 10001, "r38-denied"), bytes.NewReader([]byte("denied")), 6); denied == nil { + t.Fatal("worker readonly identity unexpectedly wrote an object") + } + save("05-identity.json", map[string]any{"worker_object_identity": "readonly", "gateway_only_writer": true, + "bucket": fx.bucket, "index": fx.index, "target": cfg.LibraryTargetIdentity(), "project": project, + "readonly_read_bytes": string(allowedBody), "readonly_put_denied": true}) + + scope := objectgateway.Digest([]byte("minio\x00" + env["LIBRARY_PRODUCTION_S3_ENDPOINT"] + "\x00" + fx.bucket)) + pub, priv, e := ed25519.GenerateKey(rand.Reader) + must(e) + digestFile := func(name string) string { + raw, e := os.ReadFile(filepath.Join(root, name)) + must(e) + return objectgateway.Digest(raw) + } + initialDrain := filepath.Join(root, "initial-drain.json") + if _, e := os.Stat(initialDrain); e != nil { + t.Fatalf("runner must provide real initial drain evidence: %v", e) + } + payload, e := json.Marshal(objectgateway.Attestation{Protocol: objectgateway.Protocol, Scope: scope, GatewayID: project, + IssuedAt: time.Now().Add(-time.Second), ExpiresAt: time.Now().Add(50 * time.Minute), + WriterInventory: digestFile("05-identity.json"), PolicyEvidence: digestFile("05-identity.json"), + DenialEvidence: digestFile("05-identity.json"), DrainEvidence: digestFile("initial-drain.json")}) + must(e) + signedRaw, e := json.Marshal(objectgateway.SignedAttestation{Payload: payload, Signature: ed25519.Sign(priv, payload)}) + must(e) + // 审计有效期按真实时钟记录(网关要求不超过 1 小时;这里自己证明没有改系统时间)。 + var attestationView objectgateway.Attestation + must(json.Unmarshal(payload, &attestationView)) + nowProbe := time.Now() + if attestationView.ExpiresAt.Sub(attestationView.IssuedAt) > time.Hour || nowProbe.After(attestationView.ExpiresAt) { + t.Fatalf("gateway audit validity invalid: issued=%s expires=%s now=%s", + attestationView.IssuedAt, attestationView.ExpiresAt, nowProbe) + } + save("05a-gateway-audit.json", map[string]any{"issued_at": attestationView.IssuedAt, "expires_at": attestationView.ExpiresAt, + "now": nowProbe, "validity": attestationView.ExpiresAt.Sub(attestationView.IssuedAt).String(), + "clock_source": "system-clock-unmodified"}) + must(os.WriteFile(filepath.Join(root, "audit.json"), signedRaw, 0600)) + + processes := []map[string]any{} + expectedBinaries := map[string]string{} + must(json.Unmarshal([]byte(os.Getenv("KG_R38_BINARY_SHA")), &expectedBinaries)) + start := func(binary, label string, values map[string]string) *exec.Cmd { + t.Helper() + cmd := exec.Command(filepath.Join(os.Getenv("KG_R38_BIN"), binary)) + cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} + for k, v := range values { + cmd.Env = append(cmd.Env, k+"="+v) + } + f, e := os.OpenFile(filepath.Join(root, label+".log"), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600) + must(e) + cmd.Stdout = f + cmd.Stderr = f + must(cmd.Start()) + executable, e := os.Readlink(fmt.Sprintf("/proc/%d/exe", cmd.Process.Pid)) + must(e) + raw, e := os.ReadFile(executable) + must(e) + sum := sha256.Sum256(raw) + digest := hex.EncodeToString(sum[:]) + expected := expectedBinaries[binary] + record := map[string]any{"label": label, "pid": cmd.Process.Pid, "binary": binary, + "argv": argvOf(t, cmd.Process.Pid), "scenario": os.Getenv("KG_R38_SCENARIO"), + "executable": executable, "executable_sha256": digest, "expected_sha256": expected, + "match": expected != "" && digest == expected, + "commit": os.Getenv("KG_R38_COMMIT"), "source_tree": os.Getenv("KG_R38_SOURCE_TREE")} + if !record["match"].(bool) { + t.Fatalf("%s process identity mismatch: %v", label, record) + } + processes = append(processes, record) + save("06-processes.json", processes) + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); f.Close() }) + return cmd + } + genv := map[string]string{"OBJECT_GATEWAY_LISTEN": os.Getenv("KG_R38_GATEWAY_ADDR"), "OBJECT_GATEWAY_DATABASE_URL": govDSN, + "OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL": reader.Config().ConnString(), "OBJECT_GATEWAY_ARCHIVE_ROOT": archiveRoot, + "OBJECT_GATEWAY_TARGET_ID": cfg.LibraryTargetIdentity(), "OBJECT_GATEWAY_PROVIDER": "minio", + "OBJECT_GATEWAY_ENDPOINT": env["LIBRARY_PRODUCTION_S3_ENDPOINT"], "OBJECT_GATEWAY_BUCKET": fx.bucket, + "OBJECT_GATEWAY_REGION": "us-east-1", "OBJECT_GATEWAY_ACCESS_KEY": os.Getenv("KG_LIBRARY_TEST_S3_ACCESS_KEY"), + "OBJECT_GATEWAY_SECRET_KEY": os.Getenv("KG_LIBRARY_TEST_S3_SECRET_KEY"), "OBJECT_GATEWAY_DATA_TOKEN": dataToken, + "OBJECT_GATEWAY_CONTROL_TOKEN": controlToken, "OBJECT_GATEWAY_ID": project, + "OBJECT_GATEWAY_AUDIT_FILE": filepath.Join(root, "audit.json"), + "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY": base64.StdEncoding.EncodeToString(pub)} + start("object-gateway", "gateway", genv) + client, e := objectgateway.NewClient(env["LIBRARY_OBJECT_GATEWAY_URL"], dataToken, scope) + must(e) + ready := false + for i := 0; i < 100; i++ { + if client.ReadyForAcquisition(ctx) == nil { + ready = true + break + } + time.Sleep(100 * time.Millisecond) + } + if !ready { + t.Fatal("object gateway not ready; inspect gateway.log") + } + + apiAddr := os.Getenv("KG_R38_API_ADDR") + apiEnv := map[string]string{} + for k, v := range env { + apiEnv[k] = v + } + apiEnv["APP_ADDR"] = apiAddr + apiEnv["GOVERNANCE_SPOOL_ROOT"] = filepath.Join(root, "spool") + apiEnv["RELEASE_WORKER_ENABLED"] = "false" + must(os.MkdirAll(apiEnv["GOVERNANCE_SPOOL_ROOT"], 0700)) + start("api", "api", apiEnv) + apiURL := "http://" + apiAddr + for i := 0; i < 120; i++ { + if response, err := http.Get(apiURL + "/health"); err == nil { + response.Body.Close() + if response.StatusCode == 200 { + break + } + } + if i == 119 { + t.Fatal("api /health never became 200") + } + time.Sleep(200 * time.Millisecond) + } + + // 管理员会话(只改这一次性治理库里的 admin 口令;口令只存在内存里)。 + password := hex.EncodeToString(func() []byte { b := make([]byte, 18); _, _ = rand.Read(b); return b }()) + hash, e := bcrypt.GenerateFromPassword([]byte(password), 10) + must(e) + _, e = gov.Exec(ctx, `UPDATE users SET password_hash=$1, must_change_password=false, failed_attempts=0, + locked_until=NULL, state='active' WHERE username='admin'`, string(hash)) + must(e) + jar, e := cookiejar.New(nil) + must(e) + api := r38API{base: apiURL, client: &http.Client{Jar: jar, Timeout: 30 * time.Second}} + code, body := api.do(t, http.MethodPost, "/api/v1/auth/login", map[string]string{"username": "admin", "password": password}) + if code != http.StatusOK { + t.Fatalf("admin login => %d %v", code, body) + } + if user, _ := body["data"].(map[string]any); user["role"] != "admin" { + t.Fatalf("admin session role = %v", body) + } + save("07-session.json", map[string]any{"login_http": code, "role": "admin"}) + + // ---------- 3) 播种真实发布作业(worker 执行,测试不写目标) ---------- + store := postgresstore.NewStore(gov).WithLibraryTarget(cfg.LibraryTargetIdentity()) + now := time.Now().UTC() + digest, e := governance.LibraryRequestDigest("internal", governance.LibraryJobSync, map[string]any{"target_snapshot_id": source}) + must(e) + must(store.CreateLibraryAuthorization(ctx, governance.LibraryReleaseAuthorization{ID: project + "-auth", Scope: "internal", + SnapshotID: source, ParamsDigest: digest, ExpiresAt: now.Add(time.Hour), CreatedAt: now})) + op, _, e := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: project + "-operation", Scope: "internal", + Kind: governance.LibraryJobSync, TargetSnapshotID: source, RequestDigest: digest, OperationKey: project, CreatedAt: now}) + must(e) + job, _, e := store.CreateLibraryDispatch(ctx, governance.LibraryJob{ID: project + "-job", OperationID: op.ID, Scope: "internal", + Kind: governance.LibraryJobSync, TargetSnapshotID: source, IdempotencyKey: project, RequestDigest: digest}, + governance.SyncStages(), false, now) + must(e) + queueID := job.QueueJobID + if queueID == "" { + must(gov.QueryRow(ctx, "SELECT queue_job_id FROM library_jobs WHERE id=$1", job.ID).Scan(&queueID)) + } + save("08-job.json", map[string]any{"job": job.ID, "operation": job.OperationID, "queue": queueID, + "snapshot": source, "index": fx.index, "bucket": fx.bucket, "target": cfg.LibraryTargetIdentity()}) + + workerEnv := map[string]string{} + for k, v := range env { + workerEnv[k] = v + } + workerEnv["WORKER_ID"] = project + "-worker" + worker := start("worker", "worker", workerEnv) + + waitJob := func(id string, want func(string) bool, seconds int, label string) string { + t.Helper() + deadline := time.Now().Add(time.Duration(seconds) * time.Second) + var state, message string + for time.Now().Before(deadline) { + if e := gov.QueryRow(ctx, "SELECT state,COALESCE(last_error,'') FROM jobs WHERE id=$1", id).Scan(&state, &message); e != nil { + t.Fatalf("read queue %s: %v", id, e) + } + if want(state) { + return state + } + if state == "failed" || state == "completed" || state == "cancelled" || state == "dead" { + if !want(state) { + t.Fatalf("%s terminal state=%s error=%s", label, state, message) + } + } + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("%s timeout (state=%s error=%s)", label, state, message) + return state + } + // 真实发布在四个阶段写完后停在 wiki 之后的屏障上;此时才注入一次性"校验读回不一致", + // 放行后由生产自己的校验判定失败并进入回滚。 + hitPath := filepath.Join(root, "barriers", "after-wiki.hit") + released := false + var appliedRows map[string][]map[string]any + var appliedIndex map[string]map[string]any + var pgFault map[string]any + for i := 0; i < 900; i++ { + if _, e := os.Stat(hitPath); e == nil { + if fullShape { + // 屏障停在发布已写完、校验尚未开始时:此时目标里是"这次发布真正写进去的 + // 内容"。在这里独立读回十表并核 LocalIDs,而不是等回滚后拿结果反推。 + applied := r38TargetRows(t, fx) + appliedRows = applied + save("08b-applied-pg.json", applied) + appliedIndex = recoveryIndexReadback(t, fx) + save("08f-index-applied.json", appliedIndex) + save("08c-applied-reference-promises.json", r38RequireReferences(t, "applied publish rows", applied)) + ledger := r38FindWriteSet(t, archiveRoot, job.ID) + mappingDiffs := ds02CheckLocalIDMapping(r38LocalColumns(t, fx, spec, expectation), ledger.LocalIDs) + save("08d-publish-mapping.json", map[string]any{"writeset_digest": ledger.Digest, + "job": ledger.JobID, "target_snapshot": ledger.TargetSnapshotID, + "backup_snapshot": ledger.BackupSnapshotID, "local_ids": ledger.LocalIDs, + "mapping_diffs": mappingDiffs}) + if len(ledger.LocalIDs) == 0 { + t.Fatal("publish ledger carries no LocalIDs: a mapping claim would be vacuous") + } + if len(mappingDiffs) != 0 { + t.Fatalf("publish ledger fails the independent mapping oracle:\n%s", strings.Join(mappingDiffs, "\n")) + } + } + proxy.armVerifyCorruption() + if objectBranch { + objectProxy.setArmed(true) + } + if pgBranch { + pgFault = r38ArmPGFault(t, fx, conflictLog) + save("08e-pg-fault-armed.json", pgFault) + } + if earlyBranch { + pgFault = r38ArmPGEarlyFault(t, fx, conflictKnowledge) + save("08e-pg-early-fault-armed.json", pgFault) + } + if ds01Positive || ds01N1 || ds01Second { + // 激活必须发生在真实维护窗口 held 的当下:旧 writer 已被停、入口已排空, + // 而 publish 还没进入恢复派发。这里只读观察 journal/治理库/目标,再登记。 + var activationFacts map[string]any + ds01Fingerprint, activationFacts, e = r38ActivateDS01(t, ctx, root, gov, cfg, fx, job) + must(e) + save("05b-ds01-activation.json", activationFacts) + } + must(os.WriteFile(filepath.Join(root, "barriers", "after-wiki.go"), []byte("release"), 0600)) + save("08a-barrier.json", map[string]any{"point": "after:wiki", "hit": true, "released": true, + "verify_corruption_armed": true, "refuse_clean_dispatch": !fullShape, + "refuse_object_restore_dispatch": objectBranch, "refuse_pg_restore": pgBranch, + "refuse_pg_early_restore": earlyBranch, "scenario": scenario}) + released = true + break + } + var state string + must(gov.QueryRow(ctx, "SELECT state FROM jobs WHERE id=$1", queueID).Scan(&state)) + if state == "failed" || state == "completed" || state == "cancelled" || state == "dead" { + t.Fatalf("publish reached %s before the after:wiki barrier", state) + } + time.Sleep(100 * time.Millisecond) + } + if !released { + t.Fatal("publish never reached the after:wiki barrier") + } + if ds01N1 || ds01Second { + // N1 的边界是 CAS 已提交、真实发送前挂起:此时 publish 作业仍在运行,不能等它 + // 失败。由负例助手等待 durable dispatching、终止执行者,再由新 worker 消费 recover。 + journal := readR38JSON(t, filepath.Join(root, "maintenance", job.ID+".json")) + backupID, _ := journal["backup_snapshot_id"].(string) + if backupID == "" { + if err := gov.QueryRow(ctx, `SELECT snapshot_id FROM library_jobs WHERE id=$1`, job.ID).Scan(&backupID); err != nil { + t.Fatal(err) + } + } + if backupID == "" { + t.Fatal("N1 needs the window backup identity") + } + r38RunDS01Negative(t, ctx, root, api, gov, store, fx, job, backupID, true, false, ds01Second, worker, workerEnv, proxy, start) + return + } + if got := waitJob(queueID, func(s string) bool { return s == "failed" }, 180, "publish rollback must fail at the restore boundary"); got != "failed" { + t.Fatalf("publish state = %s", got) + } + libraryAfterPublish, e := store.LibraryJob(ctx, job.ID) + must(e) + save("09-publish-failed.json", libraryAfterPublish) + if libraryAfterPublish.State != governance.LibraryJobFailed { + t.Fatalf("publish library state = %s (%s)", libraryAfterPublish.State, libraryAfterPublish.Error) + } + failureText := libraryAfterPublish.Error + "\n" + libraryAfterPublish.Recovery + switch { + case ds01Positive, ds01N1: + if !strings.Contains(failureText, "恢复失败") || !strings.Contains(failureText, "injected DS01 marker refusal before dispatch CAS") { + t.Fatalf("publish failure does not name the DS01 pre-CAS refusal: %q", failureText) + } + if strings.Contains(failureText, "index effect outcome unknown") || strings.Contains(failureText, "SQLSTATE") || + strings.Contains(failureText, "conditional object cleanup not confirmed") { + t.Fatalf("ds01 branch was mislabelled as another failure: %q", failureText) + } + case objectBranch: + // 失败必须来自对象恢复边界:回滚已通过 ES clean 写入,随后在对象删除派发前被拒。 + if !strings.Contains(failureText, "恢复失败") || !strings.Contains(failureText, "conditional object cleanup not confirmed") { + t.Fatalf("publish failure does not name the refused object restore: %q", failureText) + } + if strings.Contains(failureText, "index effect outcome unknown") { + t.Fatalf("object branch was mislabelled as the old ES failure: %q", failureText) + } + case pgBranch: + // 失败必须来自 PG 恢复步骤本身:恢复阶段 database + 真实 SQLSTATE,而不是 ES/对象文案。 + if !strings.Contains(failureText, "恢复失败") || !strings.Contains(failureText, "恢复阶段 wiki 失败") { + t.Fatalf("publish failure does not name the failed PG restore stage: %q", failureText) + } + if !strings.Contains(failureText, "SQLSTATE "+r38PGSQLState) { + t.Fatalf("publish failure carries no SQLSTATE %s: %q", r38PGSQLState, failureText) + } + if strings.Contains(failureText, "index effect outcome unknown") || strings.Contains(failureText, "conditional object cleanup not confirmed") { + t.Fatalf("pg branch was mislabelled as an ES or object failure: %q", failureText) + } + save("09a-pg-failure.json", map[string]any{"job": job.ID, "error": libraryAfterPublish.Error, + "recovery": libraryAfterPublish.Recovery, "failed_stage": libraryAfterPublish.Stage, + "expected_sqlstate": r38PGSQLState, "fault_armed": pgFault, "matched_sqlstate": true}) + case earlyBranch: + // 失败必须来自恢复的第一段 database,且是同一条真实主键冲突;不能拿后段 wiki 的 + // 成功/失败冒充早段结论。 + if !strings.Contains(failureText, "恢复失败") || !strings.Contains(failureText, "恢复阶段 database 失败") { + t.Fatalf("publish failure does not name the failed early PG database stage: %q", failureText) + } + if strings.Contains(failureText, "恢复阶段 wiki 失败") { + t.Fatalf("early branch was mislabelled as a wiki-stage failure: %q", failureText) + } + if !strings.Contains(failureText, "SQLSTATE "+r38PGSQLState) { + t.Fatalf("publish failure carries no SQLSTATE %s: %q", r38PGSQLState, failureText) + } + if strings.Contains(failureText, "index effect outcome unknown") || strings.Contains(failureText, "conditional object cleanup not confirmed") { + t.Fatalf("early branch was mislabelled as an ES or object failure: %q", failureText) + } + save("09a-pg-early-failure.json", map[string]any{"job": job.ID, "error": libraryAfterPublish.Error, + "recovery": libraryAfterPublish.Recovery, "failed_stage": libraryAfterPublish.Stage, + "expected_sqlstate": r38PGSQLState, "fault_armed": pgFault, "matched_sqlstate": true}) + default: + if !strings.Contains(failureText, "恢复失败") || !strings.Contains(failureText, "index effect outcome unknown") { + t.Fatalf("publish failure does not name the refused rollback write: %q", failureText) + } + } + if string(libraryAfterPublish.Stage) != "rollback" { + t.Fatalf("publish failed at stage %q, want rollback", libraryAfterPublish.Stage) + } + if proxy.corruptionCount() != 1 { + t.Fatalf("verify corruption applied %d times, want exactly 1", proxy.corruptionCount()) + } + + // 回滚失败必须体现为"窗口 held + 两个维护记录 needs_restore",而不是只在作业文案里。 + heldJournal := readR38JSON(t, filepath.Join(root, "maintenance", job.ID+".json")) + save("10-journal-held.json", heldJournal) + if heldJournal["state"] != "held" { + t.Fatalf("freeze journal state = %v, want held", heldJournal["state"]) + } + heldCode, _ := heldJournal["code"].(string) + // 回滚路径的恢复失败由窗口自己记为 restore_blocked(RecoverWindow 的同类失败是 + // restore_failed):两者都表示"目标不可用、内容风险未解除",不是成功收尾。 + if heldCode != "restore_blocked" { + t.Fatalf("freeze journal code = %q, want restore_blocked", heldCode) + } + if heldJournal["restore_blocked"] != true { + t.Fatalf("freeze journal restore_blocked = %v", heldJournal["restore_blocked"]) + } + backupID, _ := heldJournal["backup_snapshot_id"].(string) + if backupID == "" { + t.Fatal("held journal lost the prebackup identity") + } + instance, e := store.InstanceMaintenanceOf(ctx, cfg.LibraryTargetInstance) + must(e) + scopeRow, e := store.LibraryMaintenanceOf(ctx, "internal") + must(e) + if instance == nil || instance.ReleasedAt != nil || instance.State != "needs_restore" || instance.OwnerJobID != job.ID { + t.Fatalf("instance maintenance = %+v", instance) + } + if scopeRow == nil || scopeRow.ReleasedAt != nil || scopeRow.State != "needs_restore" || scopeRow.OwnerJobID != job.ID { + t.Fatalf("scope maintenance = %+v", scopeRow) + } + save("11-maintenance-held.json", map[string]any{"instance": instance, "scope": scopeRow}) + if pgBranch { + // 失败现场必须保留:故障未自行解除,失败事务没有提交,目标仍是发布写入后的内容。 + save("11a-pg-failed-restore.json", r38PGFaultHeld(t, fx, beforeTarget, appliedRows, failureText, conflictLog)) + } + if earlyBranch { + // 早段失败:database 阶段整个事务回滚,十张表都还是发布写入后的内容。 + save("11a-pg-early-failed-restore.json", r38PGEarlyFaultHeld(t, fx, beforeTarget, appliedRows, failureText, conflictKnowledge)) + } + + // 精确边界:restore-finalize-intent 已落盘、marker 原样停在自己世代上、clean 未派发。 + effects := r38IndexEffects(t, archiveRoot, "chunk-target") + save("12-index-effects-held.json", effects) + switch { + case ds01Positive, ds01N1: + // 派发 CAS 之前被拒:意图已落盘、台账仍是 prepared、没有 claimed/finalize。 + for _, phase := range []string{"apply-intent", "applied", "restore-intent", "restore-mark-intent"} { + if _, ok := effects[phase]; !ok { + t.Fatalf("ds01 held boundary missing %s evidence (have %v)", phase, effectPhases(effects)) + } + } + for _, phase := range []string{"restore-claimed", "restore-finalize-intent", "restored"} { + if _, ok := effects[phase]; ok { + t.Fatalf("ds01 held boundary must not carry %s evidence", phase) + } + } + case ds01N2Missing: + // 旧协议在恢复标记 create 之前被传输层拒绝:意图已落盘、没有 claimed/ + // finalize/restored,也没有任何派发台账。 + for _, phase := range []string{"apply-intent", "applied", "restore-intent", "restore-mark-intent"} { + if _, ok := effects[phase]; !ok { + t.Fatalf("legacy-missing boundary missing %s evidence (have %v)", phase, effectPhases(effects)) + } + } + for _, phase := range []string{"restore-claimed", "restore-finalize-intent", "restored"} { + if _, ok := effects[phase]; ok { + t.Fatalf("legacy-missing boundary must not carry %s evidence", phase) + } + } + case objectBranch, pgBranch: + // 对象分支的 ES clean 写入已成功;PG wiki 分支的 index 阶段先于 wiki 提交。 + // 两者都必须有恢复回执,这不是被拒的边界。 + if _, ok := effects["restored"]; !ok { + t.Fatalf("branch expected a completed index restore receipt (have %v)", effectPhases(effects)) + } + case earlyBranch: + // 早段在 database 就失败:index 阶段根本没跑,索引仍是发布写入后的那一代。 + for _, phase := range []string{"apply-intent", "applied"} { + if _, ok := effects[phase]; !ok { + t.Fatalf("early held boundary missing publish %s evidence (have %v)", phase, effectPhases(effects)) + } + } + if _, ok := effects["restored"]; ok { + t.Fatalf("early held boundary must not carry a restored receipt (have %v)", effectPhases(effects)) + } + default: + for _, phase := range []string{"apply-intent", "applied", "restore-intent", "restore-claimed", "restore-finalize-intent"} { + if _, ok := effects[phase]; !ok { + t.Fatalf("held boundary missing %s evidence (have %v)", phase, effectPhases(effects)) + } + } + if _, ok := effects["restored"]; ok { + t.Fatal("held boundary must not carry a restored receipt") + } + } + heldIndex := recoveryIndexReadback(t, fx) + save("13-index-held.json", heldIndex) + if earlyBranch { + // database 阶段失败时索引还没被恢复:整份读回必须仍是发布写入后的那一代, + // before-image 的 chunk-target 不能提前出现。 + if !reflect.DeepEqual(appliedIndex, heldIndex) { + t.Fatalf("early held index must be exactly the applied publish generation (applied=%d docs, held=%d docs)", + len(appliedIndex), len(heldIndex)) + } + if _, ok := heldIndex["chunk-target"]; ok { + t.Fatal("before-image chunk-target reappeared before the index stage ran") + } + } else if ds01N2Missing { + // 旧协议标记 create 未转发:目标上不能出现任何恢复标记,chunk-target 必须缺失。 + if _, ok := heldIndex["chunk-target"]; ok { + t.Fatal("legacy-missing boundary wrote a restore marker to the index") + } + if creates := proxy.markerCreates(); creates != 0 { + t.Fatalf("legacy-missing boundary forwarded %d marker creates", creates) + } + } else if ds01Positive || ds01N1 { + // 派发 CAS 之前被拒:目标上不能出现恢复标记(恢复写是独占 create)。 + if _, ok := heldIndex["chunk-target"]; ok { + t.Fatal("DS01 pre-CAS refusal wrote the restore marker to the index") + } + if creates := proxy.markerCreates(); creates != 0 { + t.Fatalf("DS01 pre-CAS refusal forwarded %d marker creates", creates) + } + } else { + heldDoc, ok := heldIndex["chunk-target"] + if !ok { + t.Fatal("chunk-target missing at held boundary") + } + heldSource := heldDoc["_source"].(map[string]any) + heldContent, _ := heldSource["content"].(string) + if fullShape { + // 对象/PG wiki 分支里索引已恢复,marker 不能还在:否则说明失败的其实是 ES 分支。 + if strings.HasPrefix(heldContent, indexRestoreClaimPrefix) { + t.Fatalf("restored index left the ES restore marker in place: %q", heldContent) + } + oldSource := beforeIndex["chunk-target"]["_source"] + if !reflect.DeepEqual(oldSource, heldSource) { + t.Fatalf("index was not restored to its before-image") + } + } else if !strings.HasPrefix(heldContent, indexRestoreClaimPrefix) { + t.Fatalf("held index must still carry the restore marker, got %q", heldContent) + } + } + events, refused := proxy.snapshot() + save("14-wire-held.json", map[string]any{"events": events, "refused": refused}) + var heldObjects *s3.ListObjectVersionsOutput + if fullShape { + heldObjects = objectInventoryR38(t, ctx, fx) + save("13a-objects-held.json", heldObjects) + if refused != 0 { + t.Fatalf("object branch must not refuse ES clean dispatch, got %d refusals", refused) + } + } else if ds01Positive || ds01N1 { + if refused != 0 { + t.Fatalf("DS01 branch must not refuse ES transport writes, got %d", refused) + } + } else if refused != 1 { + t.Fatalf("clean dispatch refusals = %d, want exactly 1", refused) + } + forwarded := 0 + for _, event := range events { + if event["refused"] == true && event["dispatched"] == false { + continue + } + if event["method"] == http.MethodPut && strings.Contains(event["path"].(string), "/_doc/chunk-target") { + forwarded++ + } + } + if !fullShape && !ds01Positive && !ds01N1 && forwarded != 0 { + t.Fatalf("refused clean write was forwarded %d times", forwarded) + } + if objectBranch { + objectEvents, objectRefused, objectForwarded := objectProxy.snapshot() + save("14-object-wire-held.json", map[string]any{"events": objectEvents, "refused": objectRefused, + "forwarded_mutations": objectForwarded}) + if objectRefused != 1 { + t.Fatalf("object restore dispatch refusals = %d, want exactly 1", objectRefused) + } + var refusedRequest map[string]any + refusedForwarded := 0 + for _, event := range objectEvents { + request, _ := event["request"].(map[string]any) + if event["refused"] == true { + refusedRequest = request + } + if request != nil && request["action"] == "delete" && event["dispatched"] == true { + refusedForwarded++ + } + } + if refusedRequest == nil || refusedRequest["action"] != "delete" || refusedRequest["key"] == "" { + t.Fatalf("refused object request not captured: %v", refusedRequest) + } + if refusedForwarded != 0 { + t.Fatalf("refused object delete was forwarded %d times", refusedForwarded) + } + operation, _ := refusedRequest["operation"].(string) + createdBy, _ := refusedRequest["created_by"].(string) + key, _ := refusedRequest["key"].(string) + var refusedIntent, refusedReceipt, createReceipt int + must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_intents WHERE operation=$1", operation).Scan(&refusedIntent)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE operation=$1", operation).Scan(&refusedReceipt)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE operation=$1", createdBy).Scan(&createReceipt)) + if refusedIntent != 0 || refusedReceipt != 0 { + t.Fatalf("pre-dispatch refusal must leave no gateway intent/receipt, got intent=%d receipt=%d", refusedIntent, refusedReceipt) + } + if createReceipt != 1 { + t.Fatalf("refused delete does not reference a durable create receipt (created_by=%s rows=%d)", createdBy, createReceipt) + } + var createState string + var createRaw []byte + must(gov.QueryRow(ctx, "SELECT receipt FROM kg_object_gateway_receipts WHERE operation=$1", createdBy).Scan(&createRaw)) + var createView struct { + State string `json:"state"` + } + must(json.Unmarshal(createRaw, &createView)) + createState = createView.State + if createState != "committed" { + t.Fatalf("referenced create receipt state = %q", createState) + } + deleteIntent := r38ObjectEffectPhases(t, archiveRoot, key) + if _, ok := deleteIntent["delete-intent"]; !ok { + t.Fatalf("object restore lacked a durable delete-intent effect (have %v)", effectPhases(deleteIntent)) + } + heldKeys := map[string]bool{} + for _, version := range heldObjects.Versions { + heldKeys[aws.ToString(version.Key)] = true + } + if !heldKeys[key] { + t.Fatalf("created object %s disappeared despite the rollback refusal", key) + } + save("14a-object-refusal.json", map[string]any{"refused_request": refusedRequest, + "receiver": objectProxy.upstream, "forwarded_delete_count": refusedForwarded, + "gateway_intent_rows": refusedIntent, "gateway_receipt_rows": refusedReceipt, + "referenced_create_receipt": map[string]any{"operation": createdBy, "state": createState}, + "durable_effect_phases": effectPhases(deleteIntent), "created_key": key, + "held_object_present": heldKeys[key]}) + } + + // HTTP 入口:窗口 held ⇒ 读写入口 409;恢复入口仍是唯一出口。 + code, maintenance := api.do(t, http.MethodGet, "/api/v1/library/maintenance?scope=internal", nil) + if code != http.StatusOK { + t.Fatalf("GET maintenance => %d %v", code, maintenance) + } + save("15-maintenance-http-held.json", map[string]any{"http": code, "body": maintenance}) + if maintenance["held"] != true { + t.Fatalf("maintenance HTTP held = %v", maintenance["held"]) + } + instanceView, _ := maintenance["instance_maintenance"].(map[string]any) + if instanceView == nil || instanceView["state"] != "needs_restore" || instanceView["owner_job_id"] != job.ID { + t.Fatalf("maintenance HTTP instance view = %v", maintenance["instance_maintenance"]) + } + // held 期间入口必须真的关着:连不上,而不是"还有人返回错误页"。 + closedClient := &http.Client{Timeout: 3 * time.Second} + entryOpen := false + entryDetail := "" + if response, err := closedClient.Get(os.Getenv("KG_R38_INGRESS")); err == nil { + entryOpen = response.StatusCode == http.StatusOK + entryDetail = fmt.Sprintf("HTTP %d", response.StatusCode) + response.Body.Close() + } else { + entryDetail = err.Error() + } + save("15a-ingress-held.json", map[string]any{"ingress": os.Getenv("KG_R38_INGRESS"), "open": entryOpen, "detail": entryDetail}) + if entryOpen { + t.Fatalf("target ingress still serves 200 while the window is held: %s", entryDetail) + } + code, blocked := api.do(t, http.MethodPost, "/api/v1/library/restores", map[string]any{"scope": "internal", "snapshot_id": backupID}) + if code != http.StatusConflict || blocked["code"] != "library_target_in_maintenance" { + t.Fatalf("entry while held => %d %v, want 409 library_target_in_maintenance", code, blocked) + } + save("16-entry-409.json", map[string]any{"http": code, "body": blocked}) + // POST /library/restores 是"新建恢复作业"的入口:恢复后再 POST 会创建新作业, + // 不能为凑 409→200 而制造第二次恢复。同一业务准入改用零写副作用的 + // GET /library/restore-availability(页面判断"这份快照现在能不能恢复"的投影)。 + availabilityPath := "/api/v1/library/restore-availability?scope=internal&snapshot_id=" + backupID + code, availabilityHeld := api.do(t, http.MethodGet, availabilityPath, nil) + if code != http.StatusOK { + t.Fatalf("restore availability while held => %d %v", code, availabilityHeld) + } + heldReasons, _ := availabilityHeld["reasons"].([]any) + heldMaintenanceReason := r38HasReason(heldReasons, "维护") + if availabilityHeld["allowed"] != false || !heldMaintenanceReason { + t.Fatalf("availability while held = %v", availabilityHeld) + } + save("16a-availability-held.json", map[string]any{"http": code, "body": availabilityHeld, + "maintenance_reason": heldMaintenanceReason}) + code, mismatch := api.do(t, http.MethodPost, "/api/v1/library/maintenance/recover", + map[string]any{"scope": "internal", "window_job_id": "some-other-window"}) + if code != http.StatusConflict || mismatch["code"] != "library_window_mismatch" { + t.Fatalf("recover with another window => %d %v", code, mismatch) + } + save("17-window-binding-409.json", map[string]any{"http": code, "body": mismatch}) + if ds01N1 || ds01N2 || ds01N2Missing { + r38RunDS01Negative(t, ctx, root, api, gov, store, fx, job, backupID, ds01N1, ds01N2Missing, false, worker, workerEnv, proxy, start) + return + } + if ds01Positive { + var state, owner, receipt, binding string + must(gov.QueryRow(ctx, `SELECT state, dispatch_owner, COALESCE(marker_receipt::text,''), binding_digest +FROM library_index_restore_dispatch WHERE index_name=$1 AND document_id='chunk-target'`, fx.index). + Scan(&state, &owner, &receipt, &binding)) + creates := proxy.markerCreates() + save("17c-ds01-held-ledger.json", map[string]any{"state": state, "owner": owner, + "receipt": receipt, "binding": binding, "marker_creates_forwarded": creates, + "target_fingerprint": ds01Fingerprint}) + if state != libraryrelease.RestoreDispatchPrepared || owner != "" || receipt != "" || creates != 0 { + t.Fatalf("DS01 held boundary is not a clean prepared record: state=%s owner=%q creates=%d", state, owner, creates) + } + } + + // ---------- 4) 撤故障 → 正常 POST /library/maintenance/recover ---------- + proxy.setRefuseClean(false) + proxy.setRefuseMarker(false) + if objectBranch { + objectProxy.setArmed(false) + } + if pgBranch { + // 只解除本轮注入的 PG 故障(drop trigger/function/switch table),不动共享 PG 本身。 + save("17b-pg-fault-disarmed.json", r38DisarmPGFault(t, fx, conflictLog)) + } + if earlyBranch { + // 精确解除:只删那一行外部范围的 knowledges 占位行;不换成删除 held 记录或重拍备份。 + save("17b-pg-early-fault-disarmed.json", r38DisarmPGEarlyFault(t, fx, conflictKnowledge)) + } + if ds01Positive { + // 正式 worker 必须真的换进程:旧执行者退出后由同一冻结二进制的新 worker 消费恢复。 + oldPID := worker.Process.Pid + _ = worker.Process.Kill() + _ = worker.Wait() // 主动终止的进程返回 signal: killed,这是预期退出 + if _, err := os.Stat(fmt.Sprintf("/proc/%d", oldPID)); err == nil { + t.Fatalf("old worker %d is still alive after kill", oldPID) + } + delete(workerEnv, "KG_DS01_TEST_REFUSE_MARKER") + worker = start("worker", "worker-recover", workerEnv) + save("17c2-ds01-worker-restart.json", map[string]any{"old_pid": oldPID, "new_pid": worker.Process.Pid, + "refusal_env_removed": true, "binary": "worker", "sha256": expectedBinaries["worker"]}) + } + save("17a-recover-request.json", map[string]any{"window_job_id": job.ID, "scope": "internal", + "backup_snapshot_id": backupID, "original_job": job.ID, "object_fault_removed": objectBranch, + "pg_fault_removed": pgBranch, "pg_early_fault_removed": earlyBranch, + "publish_entry": "store.CreateLibraryDispatch (publish API entry not proven)"}) + code, accepted := api.do(t, http.MethodPost, "/api/v1/library/maintenance/recover", + map[string]any{"scope": "internal", "window_job_id": job.ID}) + if code != http.StatusAccepted { + t.Fatalf("POST recover => %d %v", code, accepted) + } + recoveryJob, _ := accepted["job"].(map[string]any) + recoveryQueueID, _ := recoveryJob["id"].(string) + save("18-recover-accepted.json", accepted) + if accepted["window_job_id"] != job.ID || accepted["scope"] != "internal" { + t.Fatalf("recover response window binding = %v", accepted) + } + if recoveryQueueID != governance.LibraryRecoveryQueueID(job.ID) { + t.Fatalf("recovery queue id = %q", recoveryQueueID) + } + if got := waitJob(recoveryQueueID, func(s string) bool { return s == "completed" }, 300, "recovery must complete"); got != "completed" { + t.Fatalf("recovery state = %s", got) + } + if ds01Positive { + var state, owner, receipt string + must(gov.QueryRow(ctx, `SELECT state, dispatch_owner, COALESCE(marker_receipt::text,'') +FROM library_index_restore_dispatch WHERE index_name=$1 AND document_id='chunk-target'`, fx.index). + Scan(&state, &owner, &receipt)) + creates := proxy.markerCreates() + save("18b-ds01-recovered-ledger.json", map[string]any{"state": state, "owner": owner, + "receipt": receipt, "marker_creates_forwarded": creates, "recovery_queue": recoveryQueueID}) + if state != libraryrelease.RestoreDispatchMarkerConfirmed || owner == "" || receipt == "" || creates != 1 { + t.Fatalf("DS01 recovery ledger = state=%s owner=%q creates=%d", state, owner, creates) + } + } + + recoveredJournal := readR38JSON(t, filepath.Join(root, "maintenance", job.ID+".json")) + save("19-journal-recovered.json", recoveredJournal) + if recoveredJournal["state"] != "recovered" { + t.Fatalf("journal after recovery = %v", recoveredJournal["state"]) + } + if recoveredJournal["recovered_backup"] != backupID || recoveredJournal["backup_snapshot_id"] != backupID { + t.Fatalf("recovery bound another backup: %v", recoveredJournal) + } + if digest, _ := recoveredJournal["recovery_digest"].(string); digest == "" { + t.Fatal("recovery finished without a verification digest") + } + instanceAfter, e := store.InstanceMaintenanceOf(ctx, cfg.LibraryTargetInstance) + must(e) + scopeAfter, e := store.LibraryMaintenanceOf(ctx, "internal") + must(e) + if instanceAfter == nil || instanceAfter.ReleasedAt == nil { + t.Fatalf("instance maintenance not released: %+v", instanceAfter) + } + if scopeAfter == nil || scopeAfter.ReleasedAt == nil { + t.Fatalf("scope maintenance not released: %+v", scopeAfter) + } + save("20-maintenance-released.json", map[string]any{"instance": instanceAfter, "scope": scopeAfter}) + code, openMaintenance := api.do(t, http.MethodGet, "/api/v1/library/maintenance?scope=internal", nil) + if code != http.StatusOK || openMaintenance["held"] != false { + t.Fatalf("maintenance after recovery => %d %v", code, openMaintenance) + } + // 入口真的回来了:实际 HTTP 200,而不是"容器起来了"。 + probe := false + for i := 0; i < 100; i++ { + response, err := http.Get(os.Getenv("KG_R38_INGRESS")) + if err == nil { + response.Body.Close() + if response.StatusCode == http.StatusOK { + probe = true + break + } + } + time.Sleep(200 * time.Millisecond) + } + if !probe { + t.Fatal("target ingress did not return HTTP 200 after recovery") + } + save("21-ingress.json", map[string]any{"ingress": os.Getenv("KG_R38_INGRESS"), "http": 200, "open": true, + "maintenance_http": openMaintenance}) + code, availabilityRecovered := api.do(t, http.MethodGet, availabilityPath, nil) + if code != http.StatusOK { + t.Fatalf("restore availability after recovery => %d %v", code, availabilityRecovered) + } + recoveredReasons, _ := availabilityRecovered["reasons"].([]any) + recoveredMaintenanceReason := r38HasReason(recoveredReasons, "维护") + if recoveredMaintenanceReason { + t.Fatalf("availability still reports maintenance after recovery: %v", availabilityRecovered) + } + save("21a-availability-recovered.json", map[string]any{"http": code, "body": availabilityRecovered, + "maintenance_reason": recoveredMaintenanceReason, "post_entry": "not repeated: POST /restores creates a new job"}) + + // ---------- 5) 三个真实存储的全量恢复 ---------- + afterPG := universeDump(t, fx.pool) + save("22-pg-after.json", afterPG) + if diff := diffUniverse(beforePG, afterPG); diff != "" { + t.Fatalf("PG not restored row-by-row: %s", diff) + } + if fullShape { + // 独立 oracle:目标范围十表必须逐列等于声明 before-image(不是"和上一份读回相同"), + // 邻库/外部租户哨兵必须原样保留,恢复后的引用承诺逐种 matched>0。 + restored := r38TargetRows(t, fx) + save("22a-restored-pg-scope.json", restored) + for _, table := range ds02TargetTables { + want := r38DeclaredTargetScope(t, declaredBefore, table) + if len(want) == 0 || len(restored[table]) == 0 { + t.Fatalf("%s: independent expectation %d rows / restored %d rows (both must be non-empty)", + table, len(want), len(restored[table])) + } + if diff := r38CompareRows(table, want, restored[table]); diff != "" { + t.Fatalf("%s not restored to the declared before-image: %s", table, diff) + } + } + afterSentinels := r38SentinelRows(t, fx) + for _, table := range ds02TargetTables { + if diff := r38CompareRows("sentinel "+table, beforeSentinels[table], afterSentinels[table]); diff != "" { + t.Fatalf("neighbour/foreign sentinel %s changed: %s", table, diff) + } + } + save("22b-restored-reference-promises.json", r38RequireReferences(t, "restored before-image", restored)) + } + afterObjects := objectInventoryR38(t, ctx, fx) + save("23-objects-after.json", afterObjects) + if !reflect.DeepEqual(objectVersionIDs(beforeObjects), objectVersionIDs(afterObjects)) { + t.Fatalf("object versions differ from before-image:\n before=%v\n after=%v", + objectVersionIDs(beforeObjects), objectVersionIDs(afterObjects)) + } + if !reflect.DeepEqual(objectDeleteMarkers(beforeObjects), objectDeleteMarkers(afterObjects)) { + t.Fatalf("object delete markers differ from before-image:\n before=%v\n after=%v", + objectDeleteMarkers(beforeObjects), objectDeleteMarkers(afterObjects)) + } + if fullShape { + // 字节指纹:对 before-image 里每个受保护 versionId 单独 GET 算 SHA256,恢复后 + // 同 version 再独立算一次;ETag/size 只当旁证,绝不拿元数据当"逐字节相同"。 + afterDigests := r38ObjectVersionDigests(t, ctx, fx, afterObjects) + save("23b-object-byte-digests-after.json", afterDigests) + for version, digest := range beforeDigests { + got, ok := afterDigests[version] + if !ok { + t.Fatalf("protected object version %s disappeared after recovery", version) + } + if got != digest { + t.Fatalf("protected object version %s bytes changed: before=%s after=%s", version, digest, got) + } + } + if len(beforeDigests) != len(afterDigests) { + t.Fatalf("object byte fingerprint coverage changed: %d -> %d", len(beforeDigests), len(afterDigests)) + } + // 发布期间真的新写过对象:这些版本必须已经从桶里消失,并且有网关 removed 回执。 + beforeVersions := map[string]bool{} + for _, version := range beforeObjects.Versions { + beforeVersions[aws.ToString(version.Key)+"@"+aws.ToString(version.VersionId)] = true + } + createdVersions := []string{} + for _, version := range heldObjects.Versions { + id := aws.ToString(version.Key) + "@" + aws.ToString(version.VersionId) + if !beforeVersions[id] { + createdVersions = append(createdVersions, id) + } + } + if len(createdVersions) == 0 { + t.Fatal("publish created no new object version: the create→remove boundary was never exercised") + } + for _, id := range createdVersions { + if _, ok := afterDigests[id]; ok { + t.Fatalf("version created by the failed publish is still present after recovery: %s", id) + } + } + save("23c-object-created-versions.json", createdVersions) + // 恢复后的对象写入必须来自真实网关:被拒的 delete operation 现在有 removed 回执, + // 版本与计划都对应同一冻结身份,而不是测试手工造的回执。 + objectEvents, _, _ := objectProxy.snapshot() + var operation string + for _, event := range objectEvents { + request, _ := event["request"].(map[string]any) + if event["refused"] == true && request != nil { + operation, _ = request["operation"].(string) + } + } + if operation == "" { + // PG 分支在 held 时还没走到对象删除,没有"被拒请求"可以回溯;按发布新增的 + // key@version 精确匹配 removed 回执,拿到的仍是真实网关写入的操作身份。 + wanted := map[string]bool{} + for _, id := range createdVersions { + wanted[id] = true + } + rows, e := gov.Query(ctx, `SELECT receipt FROM kg_object_gateway_receipts`) + must(e) + for rows.Next() { + var raw []byte + must(rows.Scan(&raw)) + var receipt objectgateway.Receipt + must(json.Unmarshal(raw, &receipt)) + if receipt.State == "removed" && wanted[receipt.Request.Key+"@"+receipt.Version.ID] { + operation = receipt.Request.Operation + } + } + must(rows.Err()) + rows.Close() + if objectBranch { + t.Fatal("object branch lost the refused operation identity") + } + if operation == "" { + t.Fatal("pg branch found no removed receipt bound to a version created by the failed publish") + } + save("23d-removal-bound-by-receipt.json", map[string]any{"operation": operation, + "created_versions": createdVersions}) + } + var removedRaw []byte + must(gov.QueryRow(ctx, "SELECT receipt FROM kg_object_gateway_receipts WHERE operation=$1", operation).Scan(&removedRaw)) + var removed struct { + Request objectgateway.Request `json:"request"` + State string `json:"state"` + Version objectgateway.Version `json:"version"` + } + must(json.Unmarshal(removedRaw, &removed)) + if removed.State != "removed" { + t.Fatalf("recovered object delete receipt state = %q", removed.State) + } + save("23a-object-recovered-receipt.json", map[string]any{"operation": operation, + "state": removed.State, "request": removed.Request, "version": removed.Version}) + found := false + for _, inventory := range beforeObjects.Versions { + if aws.ToString(inventory.Key) == removed.Request.Key && aws.ToString(inventory.VersionId) == removed.Version.ID { + found = true + } + } + if found { + t.Fatal("removed object version still present in the before-image") + } + } + afterIndex := recoveryIndexReadback(t, fx) + save("24-index-after.json", afterIndex) + if len(afterIndex) != len(beforeIndex) { + t.Fatalf("index document set changed: %d -> %d", len(beforeIndex), len(afterIndex)) + } + for id, old := range beforeIndex { + got, ok := afterIndex[id] + if !ok || !reflect.DeepEqual(old["_source"], got["_source"]) { + t.Fatalf("index document %s not restored to its before-image", id) + } + if id == "chunk-target" && reflect.DeepEqual(old["_seq_no"], got["_seq_no"]) { + t.Fatal("restoration reused the applied generation instead of writing a new one") + } + } + if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: backupID}); err != nil { + t.Fatalf("independent verification after recovery: %v", err) + } + recoveredEffects := r38IndexEffects(t, archiveRoot, "chunk-target") + save("25-index-effects-recovered.json", recoveredEffects) + if _, ok := recoveredEffects["restored"]; !ok { + t.Fatalf("recovery did not persist a restored receipt (have %v)", effectPhases(recoveredEffects)) + } + + // 恢复事实与 receipt 都由真实写入产生,没有人工造 receipt。 + var recoverOps, recoveryVersions int + must(gov.QueryRow(ctx, "SELECT count(*) FROM library_operations WHERE kind='recover'").Scan(&recoverOps)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM library_versions WHERE kind='recovery_verified' AND source_job_id=$1", job.ID).Scan(&recoveryVersions)) + var prebackups int + must(gov.QueryRow(ctx, "SELECT count(*) FROM library_versions WHERE kind='production_prebackup' AND source_job_id=$1 AND snapshot_id=$2", + job.ID, backupID).Scan(&prebackups)) + if recoverOps != 1 || recoveryVersions != 1 || prebackups != 1 { + t.Fatalf("durable recovery identities ops=%d events=%d prebackups=%d", recoverOps, recoveryVersions, prebackups) + } + receipts, deliveries := r38Receipts(t, ctx, gov, fx) + save("26-receipts.json", map[string]any{"receipts": receipts, "deliveries": deliveries}) + if len(receipts) == 0 || len(deliveries) == 0 { + t.Fatal("no gateway receipt/delivery evidence for real object writes") + } + if fullShape { + // 发布期与恢复期两条独立记录必须指向同一套 mapping:发布时落盘的写集合摘要, + // 必须同时出现在作业锚点、预备份版本证据、网关回执/投递计划里;恢复意图的 + // request_digest 由窗口/作业/目标/来源/备份/该计划独立重算并与持久记录逐字符比较。 + var publishAnchor, publishRequest string + must(gov.QueryRow(ctx, "SELECT coalesce(writeset_digest,''), request_digest FROM library_operations WHERE id=$1", + job.OperationID).Scan(&publishAnchor, &publishRequest)) + ledger := r38FindWriteSet(t, archiveRoot, job.ID) + // 发布失败在 finalize 之前,锚点列可能还没写;预backup版本证据才是网关 + // 真正核验的那条发布期记录,必须存在并与落盘台账一致。 + var evidenceDigest string + must(gov.QueryRow(ctx, "SELECT coalesce(evidence->>'writeset_digest','') FROM library_versions WHERE kind='production_prebackup' AND source_job_id=$1", job.ID).Scan(&evidenceDigest)) + if evidenceDigest == "" { + t.Fatal("publish-side prebackup version carries no writeset digest") + } + if evidenceDigest != ledger.Digest { + t.Fatalf("prebackup version evidence writeset digest %q != ledger %q", evidenceDigest, ledger.Digest) + } + if publishAnchor != "" && publishAnchor != ledger.Digest { + t.Fatalf("publish operation anchor %q != persisted ledger %q", publishAnchor, ledger.Digest) + } + var recoveryOperation, recoveryTarget, recoveryRequest, recoveryPlan string + must(gov.QueryRow(ctx, `SELECT id, coalesce(target_snapshot_id,''), request_digest, coalesce(writeset_digest,'') + FROM library_operations WHERE kind='recover' AND scope='internal' AND target_id=$1`, cfg.LibraryTargetIdentity()).Scan( + &recoveryOperation, &recoveryTarget, &recoveryRequest, &recoveryPlan)) + wantOperation := governance.LibraryOperationID("internal", governance.LibraryJobRecover, governance.LibraryRecoveryQueueID(job.ID)) + if recoveryOperation != wantOperation { + t.Fatalf("recovery operation id %q, want %q", recoveryOperation, wantOperation) + } + if recoveryTarget != backupID { + t.Fatalf("recovery operation targets snapshot %q, want the frozen backup %q", recoveryTarget, backupID) + } + recomputed, err := governance.LibraryRecoveryDigest("internal", governance.LibraryRecoveryQueueID(job.ID), job.ID, + job.OperationID, cfg.LibraryTargetIdentity(), source, backupID, ledger.Digest) + must(err) + if recomputed != recoveryRequest { + t.Fatalf("recovery request digest %q != independently recomputed %q", recoveryRequest, recomputed) + } + if recoveryPlan != "" && recoveryPlan != ledger.Digest { + t.Fatalf("recovery operation writeset %q != publish ledger %q", recoveryPlan, ledger.Digest) + } + // 发布真实新增的版本必须逐条绑定 removed 回执(同 key + 同 versionId), + // 不是只看"桶里没有这个 key"。 + beforeVersions := map[string]bool{} + for _, version := range beforeObjects.Versions { + beforeVersions[aws.ToString(version.Key)+"@"+aws.ToString(version.VersionId)] = true + } + removedPairs := map[string]bool{} + for _, other := range receipts { + if other.State == "removed" { + removedPairs[other.Request.Key+"@"+other.Version.ID] = true + } + } + boundCreations := 0 + for _, version := range heldObjects.Versions { + id := aws.ToString(version.Key) + "@" + aws.ToString(version.VersionId) + if beforeVersions[id] { + continue + } + if !removedPairs[id] { + t.Fatalf("version %s created by the failed publish has no gateway removal receipt", id) + } + boundCreations++ + } + if boundCreations == 0 { + t.Fatal("no created version was bound to a removal receipt") + } + plans := map[string]bool{} + for _, receipt := range receipts { + if receipt.Request.Grant.Plan != ledger.Digest { + t.Fatalf("gateway receipt plan %q != publish ledger %q", receipt.Request.Grant.Plan, ledger.Digest) + } + plans[receipt.Request.Grant.Plan] = true + } + for _, delivery := range deliveries { + if delivery.PlanDigest != ledger.Digest { + t.Fatalf("gateway delivery plan %q != publish ledger %q", delivery.PlanDigest, ledger.Digest) + } + } + save("27a-mapping-correspondence.json", map[string]any{ + "publish_operation": job.OperationID, "publish_operation_anchor": publishAnchor, + "publish_writeset_digest": evidenceDigest, + "publish_request_digest": publishRequest, + "persisted_ledger_digest": ledger.Digest, "ledger_job": ledger.JobID, + "ledger_target_snapshot": ledger.TargetSnapshotID, "ledger_backup_snapshot": ledger.BackupSnapshotID, + "ledger_source_snapshot": source, "ledger_local_ids": len(ledger.LocalIDs), + "prebackup_evidence_digest": evidenceDigest, + "recovery_operation": recoveryOperation, "recovery_target_snapshot": recoveryTarget, + "recovery_request_digest": recoveryRequest, "recovery_digest_recomputed": recomputed, + "recovery_writeset_digest": recoveryPlan, "receipt_plans": plans, + "created_versions_bound_to_removal": boundCreations, + "receipts": len(receipts), "deliveries": len(deliveries)}) + } + // receipt 必须来自真实网关写入:每条都有对应的 delivery(同计划摘要、同代次), + // 键落在本目标桶的命名空间里;被回滚删掉的那个版本必须有同一网关的 removed 回执。 + committed := 0 + for _, receipt := range receipts { + if receipt.Request.Key == "" || receipt.Version.ID == "" || receipt.Request.Grant.Plan == "" { + t.Fatalf("incomplete receipt %+v", receipt.Request) + } + matched := false + for _, delivery := range deliveries { + if delivery.PlanDigest == receipt.Request.Grant.Plan && delivery.JobID != "" && delivery.AttemptEpoch == receipt.Request.Grant.Epoch { + matched = true + } + } + if !matched { + t.Fatalf("receipt without a durable delivery (plan=%s epoch=%d)", receipt.Request.Grant.Plan, receipt.Request.Grant.Epoch) + } + // 键必须落在本目标桶的对象命名空间里(10001/ 是目标租户前缀)。 + if !strings.HasPrefix(receipt.Request.Key, "10001/") { + t.Fatalf("receipt key %q is outside the isolated target namespace", receipt.Request.Key) + } + if receipt.State != "committed" { + continue + } + committed++ + present := false + for _, version := range afterObjects.Versions { + if aws.ToString(version.Key) == receipt.Request.Key && aws.ToString(version.VersionId) == receipt.Version.ID { + present = true + } + } + if present { + continue + } + removed := false + for _, other := range receipts { + if other.State == "removed" && other.Request.Key == receipt.Request.Key && other.Version.ID == receipt.Version.ID { + removed = true + } + } + if !removed { + t.Fatalf("committed receipt %s@%s vanished without a gateway removal receipt", + receipt.Request.Key, receipt.Version.ID) + } + } + if committed == 0 { + t.Fatal("no committed gateway receipt: object writes cannot be tied to receipt evidence") + } + // Recovery 请求重放:幂等,不得再派发任何写入。 + code, replay := api.do(t, http.MethodPost, "/api/v1/library/maintenance/recover", + map[string]any{"scope": "internal", "window_job_id": job.ID}) + if code != http.StatusConflict || replay["code"] != "library_no_held_window" { + t.Fatalf("recover replay on a released window => %d %v", code, replay) + } + save("27-recover-replay.json", map[string]any{"http": code, "body": replay}) + // 重放后的原始读回全部落盘:父可拿着这些快照独立比对,而不是只看一句 PASS。 + replayPG := universeDump(t, fx.pool) + save("29-pg-after-replay.json", replayPG) + if !reflect.DeepEqual(afterPG, replayPG) { + t.Fatal("replay mutated PG") + } + replayIndex := recoveryIndexReadback(t, fx) + save("30-index-after-replay.json", replayIndex) + if !reflect.DeepEqual(afterIndex, replayIndex) { + t.Fatal("replay rewrote index generations") + } + replayObjects := objectInventoryR38(t, ctx, fx) + save("31-objects-after-replay.json", replayObjects) + if !reflect.DeepEqual(objectVersionIDs(afterObjects), objectVersionIDs(replayObjects)) || + !reflect.DeepEqual(objectDeleteMarkers(afterObjects), objectDeleteMarkers(replayObjects)) { + t.Fatal("replay rewrote object versions or delete markers") + } + if fullShape { + replayDigests := r38ObjectVersionDigests(t, ctx, fx, replayObjects) + save("31a-object-byte-digests-after-replay.json", replayDigests) + if !reflect.DeepEqual(beforeDigests, replayDigests) { + t.Fatal("replay changed protected object bytes") + } + } + replayReceipts, replayDeliveries := r38Receipts(t, ctx, gov, fx) + save("32-receipts-after-replay.json", map[string]any{"receipts": replayReceipts, "deliveries": replayDeliveries}) + if !reflect.DeepEqual(receipts, replayReceipts) || !reflect.DeepEqual(deliveries, replayDeliveries) { + t.Fatal("replay changed gateway receipts or deliveries") + } + + must(worker.Process.Signal(os.Interrupt)) + _ = worker.Wait() + objectEventsAfter, objectRefused, objectForwarded := objectProxy.snapshot() + save("28-result.json", map[string]any{"scenario": scenario, "object_restore_branch": objectBranch, + "pg_restore_branch": pgBranch, "pg_early_restore_branch": earlyBranch, + "window_job": job.ID, "publish_queue": queueID, + "recovery_queue": recoveryQueueID, "backup": backupID, "scope": "internal", "instance": cfg.LibraryTargetInstance, + "held": map[string]any{"journal": "held/restore_blocked", "maintenance": "needs_restore", "entry_http": 409, + "availability_maintenance_reason": true}, + "recovered": map[string]any{"journal": "recovered", "maintenance_released": true, "entry_http": 200, + "pg_rows_restored": true, "object_versions_restored": true, "es_source_restored": true, + "receipts": len(receipts), "deliveries": len(deliveries), "recover_operations": recoverOps, + "object_delete_markers_equal": true, "availability_maintenance_reason": recoveredMaintenanceReason, + "availability_allowed": availabilityRecovered["allowed"], "availability_reasons": recoveredReasons}, + "es_refusals": refused, "object_refusals": objectRefused, "object_forwarded_mutations": objectForwarded, + "publish_entry": "store.CreateLibraryDispatch (publish API entry not proven)", + "object_wire_events_after": len(objectEventsAfter), + "run": map[string]any{"label": os.Getenv("KG_R38_LABEL"), "commit": os.Getenv("KG_R38_COMMIT"), + "source_tree": os.Getenv("KG_R38_SOURCE_TREE"), "version": os.Getenv("KG_R38_VERSION"), + "release_version": os.Getenv("KG_R38_RELEASE_VERSION")}, + "full_shape": map[string]any{"ten_table_before_nonempty": fullShape, + "ten_table_source_nonempty": fullShape, "before_tables": len(beforePG), + "source_parts": sourceParts, "reference_promises": "all matched>0", + "local_id_mapping": "publish ledger vs independent oracle + recovery digest", + "object_byte_sha256_versions": len(beforeDigests)}}) + t.Logf("r38 closed loop: window=%s backup=%s recovery=%s receipts=%d deliveries=%d", + job.ID, backupID, recoveryQueueID, len(receipts), len(deliveries)) +} + +// ---------- 观察辅助 ---------- + +func r38HasReason(reasons []any, needle string) bool { + for _, reason := range reasons { + if text, ok := reason.(string); ok && strings.Contains(text, needle) { + return true + } + } + return false +} + +func objectInventoryR38(t *testing.T, ctx context.Context, fx *writeSetFixture) *s3.ListObjectVersionsOutput { + t.Helper() + out := &s3.ListObjectVersionsOutput{} + var keyMarker, versionMarker *string + for page := 0; ; page++ { + if page > 1000 { + t.Fatal("object inventory pagination did not terminate") + } + result, e := fx.objects.s3.client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{ + Bucket: aws.String(fx.bucket), KeyMarker: keyMarker, VersionIdMarker: versionMarker}) + if e != nil { + t.Fatalf("object inventory: %v", e) + } + out.Versions = append(out.Versions, result.Versions...) + out.DeleteMarkers = append(out.DeleteMarkers, result.DeleteMarkers...) + out.CommonPrefixes = append(out.CommonPrefixes, result.CommonPrefixes...) + if !aws.ToBool(result.IsTruncated) { + break + } + if result.NextKeyMarker == nil && result.NextVersionIdMarker == nil { + t.Fatal("truncated object inventory has no continuation markers") + } + keyMarker, versionMarker = result.NextKeyMarker, result.NextVersionIdMarker + } + return out +} + +func objectVersionIDs(inventory *s3.ListObjectVersionsOutput) []string { + ids := make([]string, 0, len(inventory.Versions)) + for _, version := range inventory.Versions { + ids = append(ids, fmt.Sprintf("%s@%s#%s#%d", aws.ToString(version.Key), aws.ToString(version.VersionId), + aws.ToString(version.ETag), aws.ToInt64(version.Size))) + } + sort.Strings(ids) + return ids +} + +func objectDeleteMarkers(inventory *s3.ListObjectVersionsOutput) []string { + ids := make([]string, 0, len(inventory.DeleteMarkers)) + for _, marker := range inventory.DeleteMarkers { + ids = append(ids, aws.ToString(marker.Key)+"@"+aws.ToString(marker.VersionId)) + } + sort.Strings(ids) + return ids +} + +func readR38JSON(t *testing.T, path string) map[string]any { + t.Helper() + raw, e := os.ReadFile(path) + if e != nil { + t.Fatalf("read %s: %v", path, e) + } + out := map[string]any{} + if e = json.Unmarshal(raw, &out); e != nil { + t.Fatalf("parse %s: %v", path, e) + } + return out +} + +// r38IndexEffects 汇总某个文档在冻结计划下已落盘的阶段证据(phase -> 证据内容)。 +func r38IndexEffects(t *testing.T, archiveRoot, id string) map[string]map[string]any { + t.Helper() + out := map[string]map[string]any{} + dir := filepath.Join(archiveRoot, "effects") + _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if err != nil || info == nil || info.IsDir() || !strings.HasSuffix(path, ".json") { + return nil + } + raw, e := os.ReadFile(path) + if e != nil { + return nil + } + var effect struct { + Change map[string]any `json:"change"` + Receipt map[string]any `json:"receipt"` + } + if json.Unmarshal(raw, &effect) != nil || effect.Change == nil { + return nil + } + if got, _ := effect.Change["id"].(string); got != id { + return nil + } + phase := strings.TrimSuffix(filepath.Base(path), ".json") + out[phase] = map[string]any{"change": effect.Change, "receipt": effect.Receipt} + return nil + }) + return out +} + +func effectPhases(effects map[string]map[string]any) []string { + phases := make([]string, 0, len(effects)) + for phase := range effects { + phases = append(phases, phase) + } + sort.Strings(phases) + return phases +} + +// r38ObjectEffectPhases 汇总对象恢复在冻结计划下已落盘的阶段证据(phase -> 内容)。 +func r38ObjectEffectPhases(t *testing.T, archiveRoot, key string) map[string]map[string]any { + t.Helper() + out := map[string]map[string]any{} + _ = filepath.Walk(filepath.Join(archiveRoot, "effects"), func(path string, info os.FileInfo, err error) error { + if err != nil || info == nil || info.IsDir() || !strings.HasSuffix(path, ".json") || + !strings.Contains(path, string(filepath.Separator)+"objects"+string(filepath.Separator)) { + return nil + } + raw, e := os.ReadFile(path) + if e != nil { + return nil + } + var effect struct { + Plan string `json:"plan"` + Object map[string]any `json:"object"` + Observation map[string]any `json:"observation"` + } + if json.Unmarshal(raw, &effect) != nil || effect.Object == nil { + return nil + } + if got, _ := effect.Object["key"].(string); got != key { + return nil + } + out[strings.TrimSuffix(filepath.Base(path), ".json")] = map[string]any{ + "plan": effect.Plan, "object": effect.Object, "observation": effect.Observation} + return nil + }) + return out +} + +func r38Receipts(t *testing.T, ctx context.Context, gov *pgxpool.Pool, fx *writeSetFixture) ([]objectgateway.Receipt, []objectgateway.Claim) { + t.Helper() + rows, e := gov.Query(ctx, "SELECT receipt FROM kg_object_gateway_receipts ORDER BY 1") + if e != nil { + t.Fatalf("receipts: %v", e) + } + receipts := []objectgateway.Receipt{} + for rows.Next() { + var raw []byte + if e := rows.Scan(&raw); e != nil { + rows.Close() + t.Fatalf("scan receipt: %v", e) + } + var receipt objectgateway.Receipt + if e := json.Unmarshal(raw, &receipt); e != nil { + rows.Close() + t.Fatalf("parse receipt: %v", e) + } + receipts = append(receipts, receipt) + } + rows.Close() + deliveryRows, e := gov.Query(ctx, "SELECT claim FROM kg_object_gateway_deliveries ORDER BY attempt_epoch") + if e != nil { + t.Fatalf("deliveries: %v", e) + } + deliveries := []objectgateway.Claim{} + for deliveryRows.Next() { + var raw []byte + if e := deliveryRows.Scan(&raw); e != nil { + deliveryRows.Close() + t.Fatalf("scan delivery: %v", e) + } + var claim objectgateway.Claim + if e := json.Unmarshal(raw, &claim); e != nil { + deliveryRows.Close() + t.Fatalf("parse delivery: %v", e) + } + deliveries = append(deliveries, claim) + } + deliveryRows.Close() + return receipts, deliveries +} + +// ---------- PG 恢复故障注入(只在本轮一次性业务库) ---------- + +const r38PGSQLState = "23505" + +// r38PGFaultInsert 是恢复自己的 wiki 阶段写法(jsonb_populate_record + SELECT *), +// 这里用同一条语句做"故障探针",证明报错来自恢复会执行的那类 SQL。 +const r38PGFaultInsert = `INSERT INTO wiki_log_entries SELECT * FROM jsonb_populate_record(NULL::wiki_log_entries, $1::jsonb)` + +// r38ArmPGFault 是唯一新增的故障:before-image 的一条 wiki 日志在恢复的最后一段 PG 写入里 +// 会按原 id 插回目标范围;先用一行"外部范围、同主键"的日志占住这个 id,恢复的真实 INSERT +// 就会得到 23505。它不改 schema(不加触发器/约束/索引)、不停共享 PG、不动 ACL;解除就是删这一行。 +func r38ArmPGFault(t *testing.T, fx *writeSetFixture, logID int64) map[string]any { + t.Helper() + if logID == 0 { + t.Fatal("pg fault armed without a wiki log identity") + } + var raw []byte + if e := fx.pool.QueryRow(fx.ctx, `SELECT to_jsonb(x) FROM wiki_log_entries x ORDER BY id LIMIT 1`).Scan(&raw); e != nil { + t.Fatalf("pg fault needs one existing wiki log row as a shape template: %v", e) + } + var row map[string]any + if e := json.Unmarshal(raw, &row); e != nil { + t.Fatal(e) + } + row["id"] = logID + row["tenant_id"] = 20000 + row["knowledge_base_id"] = "kb-r38-foreign" + encoded, e := json.Marshal(row) + if e != nil { + t.Fatal(e) + } + if _, e := fx.pool.Exec(fx.ctx, r38PGFaultInsert, encoded); e != nil { + t.Fatalf("arm pg fault (foreign row holding wiki log %d): %v", logID, e) + } + var tenant int64 + var kb string + if e := fx.pool.QueryRow(fx.ctx, `SELECT tenant_id,knowledge_base_id FROM wiki_log_entries WHERE id=$1`, logID).Scan(&tenant, &kb); e != nil { + t.Fatal(e) + } + if tenant != 20000 || kb != "kb-r38-foreign" { + t.Fatalf("pg fault row readback = %d/%s, want 20000/kb-r38-foreign", tenant, kb) + } + return map[string]any{"stage": "wiki", "table": "wiki_log_entries", "conflict_id": logID, + "conflict_tenant": tenant, "conflict_kb": kb, "insert_statement": r38PGFaultInsert, + "expected_sqlstate": r38PGSQLState, + "mechanism": "foreign-scope row holds the primary key the recovery wiki stage restores", + "schema_changed": false, + "scope": "one disposable business database; shared PG, ACL and sessions untouched"} +} + +// r38HeldAppliedTables 是"wiki 阶段失败时仍保持发布写入内容"的表:wiki_* 属于失败并回滚的 +// 那一阶段;resources 是多知识库共享表,恢复把它的精确清理推迟到四阶段全部成功之后, +// 所以此刻仍带着发布新增的资源行。其余表都属于已提交的 database 阶段。 +func r38HeldAppliedTables() map[string]bool { + return map[string]bool{"wiki_folders": true, "wiki_pages": true, + "wiki_page_issues": true, "wiki_log_entries": true, "resources": true} +} + +// r38PGFaultHeld 证明三件事:故障行还在现场;同一 INSERT 再执行一次仍拿到服务器 SQLSTATE +// 且没有多出行;失败后目标是一个真实的"部分恢复"状态——database 阶段已提交(非 wiki 表 +// 回到 before-image),wiki 阶段失败并整体回滚(wiki 表仍是发布写入后的内容)。 +func r38PGFaultHeld(t *testing.T, fx *writeSetFixture, before, applied map[string][]map[string]any, failureText string, logID int64) map[string]any { + t.Helper() + if len(before) == 0 || len(applied) == 0 { + t.Fatal("held pg evidence needs both the before-image and the applied readback") + } + var rows int + if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM wiki_log_entries WHERE id=$1 AND tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'`, + logID).Scan(&rows); e != nil { + t.Fatal(e) + } + if rows != 1 { + t.Fatalf("pg fault row was not preserved at held: %d rows for wiki log %d", rows, logID) + } + var raw []byte + if e := fx.pool.QueryRow(fx.ctx, `SELECT to_jsonb(x) FROM wiki_log_entries x WHERE id=$1`, logID).Scan(&raw); e != nil { + t.Fatal(e) + } + _, probeErr := fx.pool.Exec(fx.ctx, r38PGFaultInsert, raw) + var pgErr *pgconn.PgError + if probeErr == nil || !errors.As(probeErr, &pgErr) { + t.Fatalf("fault probe did not raise a PG error: %v", probeErr) + } + if pgErr.Code != r38PGSQLState { + t.Fatalf("fault probe SQLSTATE = %q, want %s", pgErr.Code, r38PGSQLState) + } + var probeRows int + if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM wiki_log_entries WHERE id=$1`, logID).Scan(&probeRows); e != nil { + t.Fatal(e) + } + if probeRows != 1 { + t.Fatalf("failed probe left %d rows for wiki log %d: the statement transaction did not roll back", probeRows, logID) + } + held := r38TargetRows(t, fx) + stillApplied := r38HeldAppliedTables() + committed, rolledBack := []string{}, []string{} + for _, table := range ds02TargetTables { + want, label := before[table], "before-image" + if stillApplied[table] { + want, label = applied[table], "applied publish" + } + if diff := r38CompareRows("held "+table, want, held[table]); diff != "" { + t.Fatalf("held %s does not match the %s (earlier stages commit per stage, the failed stage rolls back): %s", table, label, diff) + } + if stillApplied[table] { + rolledBack = append(rolledBack, table) + } else { + committed = append(committed, table) + } + } + encoded, e := json.Marshal(held) + if e != nil { + t.Fatal(e) + } + sum := sha256.Sum256(encoded) + counts := map[string]int{} + for table, values := range held { + counts[table] = len(values) + } + return map[string]any{"conflict_id": logID, "conflict_rows": rows, + "probe_statement": r38PGFaultInsert, "sqlstate": pgErr.Code, "probe_error": pgErr.Error(), + "probe_rows_after_error": probeRows, + "transaction": "wiki stage INSERT failed; that stage transaction rolled back; earlier database stage stayed committed", + "before_image_tables": committed, "still_applied_tables": rolledBack, + "held_row_counts": counts, "held_pg_sha256": hex.EncodeToString(sum[:]), + "matches_before_and_applied": true, + "failure_text_has_sqlstate": strings.Contains(failureText, "SQLSTATE "+r38PGSQLState), + "failure_text_has_stage": strings.Contains(failureText, "恢复阶段 wiki 失败")} +} + +func r38DisarmPGFault(t *testing.T, fx *writeSetFixture, logID int64) map[string]any { + t.Helper() + statement := `DELETE FROM wiki_log_entries WHERE id=$1 AND tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'` + of, e := fx.pool.Exec(fx.ctx, statement, logID) + if e != nil { + t.Fatal(e) + } + var left int + if e := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM wiki_log_entries WHERE tenant_id=20000 AND knowledge_base_id='kb-r38-foreign'`).Scan(&left); e != nil { + t.Fatal(e) + } + if of.RowsAffected() != 1 || left != 0 { + t.Fatalf("pg fault not removed: deleted=%d left=%d", of.RowsAffected(), left) + } + return map[string]any{"statement": statement, "deleted": of.RowsAffected(), "foreign_rows_left": left, + "readback_absent": true} +} diff --git a/internal/releaseadapter/v071/formal_publish_http_r39_helpers_test.go b/internal/releaseadapter/v071/formal_publish_http_r39_helpers_test.go new file mode 100644 index 0000000..bf6fac0 --- /dev/null +++ b/internal/releaseadapter/v071/formal_publish_http_r39_helpers_test.go @@ -0,0 +1,649 @@ +package v071 + +// r39 辅助函数:只服务 publish-http 单场景,复用旧分支已审的 fixture/读回/oracle 规则。 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// r39BaseEnv 是 API / capture / release 三份进程共用的产品配置。 +// 唯一差异(归档根、角色、worker id)在调用点显式覆盖,避免"两套 env 慢慢分叉"。 +func r39BaseEnv(t *testing.T, fx *writeSetFixture) map[string]string { + t.Helper() + sourceArchive := os.Getenv("KG_R38_SOURCE_ARCHIVE") + return map[string]string{ + "KG_LIBRARY_TEST_ISOLATED": "1", + "DATABASE_URL": os.Getenv("KG_R38_GOVERNANCE_DSN"), + "LIBRARY_WORKER_ROLE": "release-executor", + "WORKER_POLL_INTERVAL": "200ms", "WORKER_LEASE_DURATION": "30s", + "PRODUCTION_RELEASE_REQUESTS_ENABLED": "true", "PRODUCTION_BACKUP_RESTORE_VERIFIED": "true", + "LIBRARY_ARCHIVE_ROOT": sourceArchive, + "LIBRARY_CAPACITY_BUDGET_BYTES": "1073741824", + "LIBRARY_PRODUCTION_DATABASE_URL": os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), + "LIBRARY_PRODUCTION_ELASTIC_URL": "", + "LIBRARY_PRODUCTION_INDEX": fx.index, + "LIBRARY_PRODUCTION_TENANT_ID": "10001", + "LIBRARY_PRODUCTION_KB_INTERNAL": wsTargetKB, + "LIBRARY_PRODUCTION_S3_PROVIDER": "minio", + "LIBRARY_PRODUCTION_S3_ENDPOINT": os.Getenv("KG_LIBRARY_TEST_S3_ENDPOINT"), + "LIBRARY_PRODUCTION_S3_BUCKET": fx.bucket, + "LIBRARY_PRODUCTION_S3_ACCESS_KEY": os.Getenv("KG_R38_READER_KEY"), + "LIBRARY_PRODUCTION_S3_SECRET_KEY": os.Getenv("KG_R38_READER_SECRET"), + "LIBRARY_TARGET_INSTANCE": os.Getenv("KG_R38_PROJECT"), + "LIBRARY_TARGET_PROJECT": os.Getenv("KG_R38_PROJECT"), + "LIBRARY_TARGET_WRITERS": "writer", + "LIBRARY_TARGET_NON_WRITERS": "ingress=entry gate,redis=queue,minio=object backend", + "LIBRARY_TARGET_INGRESS_URL": os.Getenv("KG_R38_INGRESS"), + "LIBRARY_TARGET_INGRESS_SERVICE": "ingress", + "LIBRARY_TARGET_INGRESS_DRAIN_FILE": filepath.Join(os.Getenv("KG_R38_RUN"), "gate/drain.json"), + "LIBRARY_TARGET_REDIS_ADDR": os.Getenv("KG_R38_REDIS_ADDR"), + "LIBRARY_TARGET_REDIS_PASSWORD": os.Getenv("KG_R38_REDIS_PASSWORD"), + "LIBRARY_TARGET_REDIS_DB": "0", + "LIBRARY_TARGET_JOURNAL_ROOT": filepath.Join(os.Getenv("KG_R38_RUN"), "maintenance"), + "LIBRARY_TARGET_DOCKER_SOCKET": "/var/run/docker.sock", + "LIBRARY_EMBEDDING_DIMENSION": "1024", + "LIBRARY_SOURCE_INSTANCE": os.Getenv("KG_R38_SOURCE_INSTANCE"), + "LIBRARY_SOURCE_PROJECT": os.Getenv("KG_R38_SOURCE_PROJECT"), + "LIBRARY_SOURCE_APP": os.Getenv("KG_R38_SOURCE_APP"), + "LIBRARY_SOURCE_TENANT_ID": "10002", + "LIBRARY_SOURCE_KB_INTERNAL": wsSourceKB, + } +} + +func r39ReadJSON(t *testing.T, path string) map[string]any { + t.Helper() + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + var out map[string]any + if err := json.Unmarshal(raw, &out); err != nil { + t.Fatalf("decode %s: %v", path, err) + } + return out +} + +func r39DatabaseName(t *testing.T, dsn string) string { + t.Helper() + parsed, err := pgxpool.ParseConfig(dsn) + if err != nil { + t.Fatalf("parse production dsn: %v", err) + } + return parsed.ConnConfig.Database +} + +func r39RegisteredDatabase(t *testing.T, state map[string]any, name string) map[string]any { + t.Helper() + resources, _ := state["resources"].([]any) + for _, item := range resources { + entry, _ := item.(map[string]any) + if entry["kind"] == "database" && entry["name"] == name { + return entry + } + } + t.Fatalf("database %s was never registered before creation", name) + return nil +} + +func r39DatabaseOID(t *testing.T, state map[string]any, name string) string { + t.Helper() + oid, _ := r39RegisteredDatabase(t, state, name)["id"].(string) + return oid +} + +func r39DatabaseOwner(t *testing.T, state map[string]any, name string) string { + t.Helper() + owner, _ := r39RegisteredDatabase(t, state, name)["owner"].(string) + return owner +} + +// r39ArchiveListing 枚举归档本体(清单 + 被引用字节),用于证明 executor 起始为空。 +func r39ArchiveListing(t *testing.T, root string) map[string]any { + t.Helper() + versions := []string{} + blobs := []string{} + if entries, err := os.ReadDir(filepath.Join(root, "versions")); err == nil { + for _, entry := range entries { + versions = append(versions, entry.Name()) + } + } + if entries, err := os.ReadDir(filepath.Join(root, "blobs")); err == nil { + for _, entry := range entries { + blobs = append(blobs, entry.Name()) + } + } + sort.Strings(versions) + sort.Strings(blobs) + return map[string]any{"root": root, "versions": versions, "blobs": blobs, + "versions_present": len(versions) > 0, "blob_count": len(blobs)} +} + +func r39ArchiveHas(t *testing.T, root, id string) bool { + t.Helper() + _, err := os.Stat(filepath.Join(root, "versions", id+".json")) + return err == nil +} + +func r39Manifest(t *testing.T, root, id string) (librarysnapshot.Manifest, []byte) { + t.Helper() + archive, err := librarysnapshot.Open(root, 256<<20) + if err != nil { + t.Fatalf("open archive %s: %v", root, err) + } + defer archive.Close() + manifest, err := archive.Load(id) + if err != nil { + t.Fatalf("load snapshot %s from %s: %v", id, root, err) + } + raw, err := os.ReadFile(filepath.Join(root, "versions", id+".json")) + if err != nil { + t.Fatalf("read manifest %s: %v", id, err) + } + return manifest, raw +} + +// r39WaitLibraryJob 等到业务作业进入期望终态;中途的失败/取消立即报错,不吞。 +func r39WaitLibraryJob(t *testing.T, store *postgresstore.Store, id string, want governance.LibraryJobState, seconds int) governance.LibraryJob { + t.Helper() + deadline := time.Now().Add(time.Duration(seconds) * time.Second) + var last governance.LibraryJob + for time.Now().Before(deadline) { + job, err := store.LibraryJob(context.Background(), id) + if err != nil { + t.Fatalf("read library job %s: %v", id, err) + } + last = job + if job.State == want { + return job + } + if job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled { + t.Fatalf("library job %s reached %s stage=%s error=%s recovery=%s", id, job.State, job.Stage, job.Error, job.Recovery) + } + time.Sleep(250 * time.Millisecond) + } + t.Fatalf("library job %s timeout in state %s stage=%s error=%s", id, last.State, last.Stage, last.Error) + return last +} + +func r39WaitQueue(t *testing.T, pool *pgxpool.Pool, id, want string, seconds int) string { + t.Helper() + deadline := time.Now().Add(time.Duration(seconds) * time.Second) + var state, message string + for time.Now().Before(deadline) { + if err := pool.QueryRow(context.Background(), + `SELECT state,COALESCE(last_error,'') FROM jobs WHERE id=$1`, id).Scan(&state, &message); err != nil { + t.Fatalf("read queue %s: %v", id, err) + } + if state == want { + return state + } + if state == "failed" || state == "completed" || state == "dead" { + t.Fatalf("queue %s terminal state=%s error=%s (want %s)", id, state, message, want) + } + time.Sleep(200 * time.Millisecond) + } + t.Fatalf("queue %s timeout (state=%s error=%s)", id, state, message) + return state +} + +// r39FirstQueueObservation 记录队列作业第一次被看到的形态:用来证明它入的是 handoff 队列, +// 而不是"直接进 release 也行"。 +func r39FirstQueueObservation(t *testing.T, pool *pgxpool.Pool, id string, seconds int) map[string]any { + t.Helper() + deadline := time.Now().Add(time.Duration(seconds) * time.Second) + for time.Now().Before(deadline) { + var raw string + err := pool.QueryRow(context.Background(), `SELECT to_jsonb(x)::text FROM jobs AS x WHERE id=$1`, id).Scan(&raw) + if err == nil { + var row map[string]any + if err := json.Unmarshal([]byte(raw), &row); err != nil { + t.Fatalf("decode queue row: %v", err) + } + return row + } + time.Sleep(100 * time.Millisecond) + } + t.Fatalf("queue job %s never appeared", id) + return nil +} + +func r39EntryOpen(t *testing.T, url string) map[string]any { + t.Helper() + client := &http.Client{Timeout: 10 * time.Second} + code, detail := 0, "" + for i := 0; i < 30; i++ { + response, err := client.Get(url) + if err == nil { + raw, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) + response.Body.Close() + code = response.StatusCode + detail = strings.TrimSpace(string(raw)) + if code == 200 { + return map[string]any{"url": url, "http": code, "open": true, "body_prefix": truncateR39(detail, 200)} + } + } else { + detail = err.Error() + } + time.Sleep(200 * time.Millisecond) + } + return map[string]any{"url": url, "http": code, "open": false, "detail": truncateR39(detail, 300)} +} + +func truncateR39(value string, limit int) string { + if len(value) <= limit { + return value + } + return value[:limit] +} + +// r39RunCLI 执行真实的 libraryctl 并把原始输出(stdout/stderr/rc/字节数)留在证据里。 +func r39RunCLI(t *testing.T, binary string, args ...string) map[string]any { + t.Helper() + command := exec.Command(binary, args...) + command.Env = append(os.Environ(), "LIBRARY_HANDOFF_FIXTURE=1") + var stdout, stderr strings.Builder + command.Stdout = &stdout + command.Stderr = &stderr + err := command.Run() + code := 0 + if err != nil { + if exit, ok := err.(*exec.ExitError); ok { + code = exit.ExitCode() + } else { + code = -1 + } + } + return map[string]any{"binary": binary, "argv": append([]string{binary}, args...), "exit_code": code, + "stdout": truncateR39(stdout.String(), 4000), "stderr": truncateR39(stderr.String(), 2000)} +} + +func r39BlobDigests(t *testing.T, root string, manifest librarysnapshot.Manifest) map[string]map[string]any { + t.Helper() + out := map[string]map[string]any{} + for _, part := range manifest.Parts { + path := filepath.Join(root, "blobs", part.SHA256) + info, err := os.Stat(path) + if err != nil { + t.Fatalf("blob %s missing in %s: %v", part.SHA256, root, err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read blob %s: %v", part.SHA256, err) + } + sum := sha256.Sum256(raw) + out[part.SHA256] = map[string]any{"name": part.Name, "kind": part.Kind, "bytes": info.Size(), + "sha256": hex.EncodeToString(sum[:]), "size_matches_manifest": info.Size() == part.Bytes} + } + return out +} + +// r39HandoffEvidence 证明 handoff 真的经由 libraryctl 落到独立 executor archive, +// 并用真实 pack/unpack/verify 复核两端字节(不是"复制目录后声称成功")。 +func r39HandoffEvidence(t *testing.T, gov *pgxpool.Pool, store *postgresstore.Store, jobID, snapshot, + sourceArchive, executorArchive, libraryctl, repackRoot string) map[string]any { + t.Helper() + ctx := context.Background() + sourceManifest, sourceRaw := r39Manifest(t, sourceArchive, snapshot) + executorManifest, executorRaw := r39Manifest(t, executorArchive, snapshot) + sourceSum, executorSum := sha256.Sum256(sourceRaw), sha256.Sum256(executorRaw) + sourceBlobs := r39BlobDigests(t, sourceArchive, sourceManifest) + executorBlobs := r39BlobDigests(t, executorArchive, executorManifest) + matches := hex.EncodeToString(sourceSum[:]) == snapshot && hex.EncodeToString(executorSum[:]) == snapshot + matches = matches && reflectDeepEqualR39(sourceBlobs, executorBlobs) && len(sourceBlobs) == len(sourceManifest.Parts) + + // 真实 libraryctl:verify(源) → pack(源) → unpack(全新归档) → verify(全新归档)。 + verifySource := r39RunCLI(t, libraryctl, "snapshot-verify", "-archive", sourceArchive, "-snapshot", snapshot) + if err := os.MkdirAll(repackRoot, 0o700); err != nil { + t.Fatalf("prepare repack archive: %v", err) + } + bundleDir := filepath.Join(repackRoot, "bundle") + if err := os.MkdirAll(bundleDir, 0o700); err != nil { + t.Fatalf("prepare bundle dir: %v", err) + } + bundlePath := filepath.Join(bundleDir, snapshot+".tar") + freshArchive := filepath.Join(repackRoot, "archive") + if err := os.MkdirAll(freshArchive, 0o700); err != nil { + t.Fatalf("prepare fresh archive: %v", err) + } + pack := r39RunCLI(t, libraryctl, "snapshot-pack", "-archive", sourceArchive, "-snapshot", snapshot, "-bundle", bundlePath) + var bundleBytes int64 + if info, err := os.Stat(bundlePath); err == nil { + bundleBytes = info.Size() + } + unpack := r39RunCLI(t, libraryctl, "snapshot-unpack", "-archive", freshArchive, "-bundle", bundlePath, "-snapshot", snapshot) + verifyFresh := r39RunCLI(t, libraryctl, "snapshot-verify", "-archive", freshArchive, "-snapshot", snapshot) + verifyExecutor := r39RunCLI(t, libraryctl, "snapshot-verify", "-archive", executorArchive, "-snapshot", snapshot) + freshManifest, freshRaw := r39Manifest(t, freshArchive, snapshot) + freshSum := sha256.Sum256(freshRaw) + freshBlobs := r39BlobDigests(t, freshArchive, freshManifest) + allZero := true + for _, item := range []map[string]any{verifySource, pack, unpack, verifyFresh, verifyExecutor} { + if item["exit_code"] != 0 { + allZero = false + } + } + bundleLeft, err := os.ReadDir(filepath.Join(os.Getenv("KG_R38_EXECUTOR_BUNDLE"))) + bundleAbsent := err == nil && len(bundleLeft) == 0 + + var detail string + stage, err := store.LibraryJob(ctx, jobID) + if err == nil { + detail = stage.Stage + } + stages := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM library_job_stages AS x WHERE job_id='`+jobID+`' AND stage='handoff'`) + return map[string]any{ + "snapshot": snapshot, "job": jobID, "job_stage": detail, + "source_archive": sourceArchive, "executor_archive": executorArchive, + "source_manifest_sha256": hex.EncodeToString(sourceSum[:]), "executor_manifest_sha256": hex.EncodeToString(executorSum[:]), + "fresh_manifest_sha256": hex.EncodeToString(freshSum[:]), + "source_parts": sourceManifest.Parts, "executor_parts": executorManifest.Parts, + "source_blobs": sourceBlobs, "executor_blobs": executorBlobs, + "executor_matches_source": matches, + "fresh_matches_source": hex.EncodeToString(freshSum[:]) == snapshot && reflectDeepEqualR39(freshBlobs, sourceBlobs), + "libraryctl_all_zero": allZero, + "libraryctl": map[string]any{"verify_source": verifySource, "pack": pack, "unpack": unpack, + "verify_fresh": verifyFresh, "verify_executor": verifyExecutor}, + "bundle_bytes": bundleBytes, "bundle_absent_after": bundleAbsent, + "handoff_stage_rows": stages, + "libraryctl_identity": func() map[string]any { + raw, err := os.ReadFile(libraryctl) + if err != nil { + t.Fatalf("read libraryctl: %v", err) + } + sum := sha256.Sum256(raw) + return map[string]any{"path": libraryctl, "sha256": hex.EncodeToString(sum[:])} + }(), + } +} + +func reflectDeepEqualR39(a, b any) bool { + left, err := json.Marshal(a) + if err != nil { + return false + } + right, err := json.Marshal(b) + if err != nil { + return false + } + return string(left) == string(right) +} + +// r39CheckPublishedIndex 用声明内容独立推导"发布后索引应有的文档": +// 目标 tenant/KB、来源 chunk 内容、来源声明的 1024 维向量,逐项核对 _source。 +func r39CheckPublishedIndex(t *testing.T, spec ds02Spec, before, after map[string]map[string]any) map[string]any { + t.Helper() + vectors := r38SourceVectors() + expected := map[string]map[string]any{} + for _, chunk := range spec.rows["chunks"] { + id := fmt.Sprint(chunk["id"]) + vector, ok := vectors[id] + if !ok { + t.Fatalf("source chunk %s has no declared vector", id) + } + expected[id] = map[string]any{"tenant_id": float64(wsTargetTenant), "knowledge_base_id": wsTargetKB, + "knowledge_id": chunk["knowledge_id"], "chunk_id": id, "source_id": id, + "content": chunk["content"], "embedding": vector} + } + problems := []string{} + for id, want := range expected { + doc, ok := after[id] + if !ok { + problems = append(problems, "published document missing: "+id) + continue + } + source, _ := doc["_source"].(map[string]any) + if source == nil { + problems = append(problems, "published document has no _source: "+id) + continue + } + for field, wantValue := range want { + got, exists := source[field] + if !exists { + problems = append(problems, id+"."+field+" missing") + continue + } + if field == "embedding" { + if !r39VectorEqual(wantValue.([]float64), got) { + problems = append(problems, id+".embedding differs from the declared 1024-dim vector") + } + continue + } + if fmt.Sprint(got) != fmt.Sprint(wantValue) { + problems = append(problems, fmt.Sprintf("%s.%s = %v, want %v", id, field, got, wantValue)) + } + } + } + // 目标范围之外的文档必须原样保留;目标范围的旧一代文档必须被替换掉。 + // 判定用独立读到的 _source(tenant/KB),不按 id 名单。 + sentinels, replaced := 0, 0 + for id, doc := range before { + source, _ := doc["_source"].(map[string]any) + if source != nil && fmt.Sprint(source["tenant_id"]) == fmt.Sprint(wsTargetTenant) && + fmt.Sprint(source["knowledge_base_id"]) == wsTargetKB { + replaced++ + if _, stillThere := after[id]; stillThere { + problems = append(problems, "replaced target-generation document survived: "+id) + } + continue + } + sentinels++ + got, ok := after[id] + if !ok { + problems = append(problems, "sentinel document disappeared: "+id) + continue + } + if !reflectDeepEqualR39(doc["_source"], got["_source"]) { + problems = append(problems, "sentinel document changed: "+id) + } + } + if len(after) != len(expected)+sentinels { + problems = append(problems, fmt.Sprintf("index document count = %d, want %d published + %d sentinel", + len(after), len(expected), sentinels)) + } + return map[string]any{"match": len(problems) == 0, "problems": problems, "published_documents": len(expected), + "sentinel_documents": sentinels, "replaced_documents": replaced, "after_documents": len(after)} +} + +func r39VectorEqual(want []float64, got any) bool { + values, ok := got.([]any) + if !ok || len(values) != len(want) { + return false + } + for i, value := range values { + number, ok := value.(float64) + if !ok { + return false + } + delta := number - want[i] + if delta < 0 { + delta = -delta + } + if delta > 1e-9 { + return false + } + } + return true +} + +// r39CheckPublishedObjects 逐资源按真实版本 GET 校验字节:发布后的对象必须就是来源字节。 +func r39CheckPublishedObjects(t *testing.T, ctx context.Context, fx *writeSetFixture, spec ds02Spec, + expectation ds02Expectation) map[string]any { + t.Helper() + problems := []string{} + observed := map[string]any{} + ids := make([]string, 0, len(spec.objects)) + for id := range spec.objects { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + path, ok := expectation.Paths[id] + if !ok { + problems = append(problems, "no expected locator for resource "+id) + continue + } + reader, err := fx.objects.s3.Open(ctx, "minio", path) + if err != nil { + problems = append(problems, fmt.Sprintf("open published object %s: %v", id, err)) + continue + } + body, readErr := io.ReadAll(reader) + reader.Close() + if readErr != nil { + problems = append(problems, fmt.Sprintf("read published object %s: %v", id, readErr)) + continue + } + want := sha256.Sum256([]byte(spec.objects[id])) + got := sha256.Sum256(body) + if hex.EncodeToString(want[:]) != hex.EncodeToString(got[:]) { + problems = append(problems, fmt.Sprintf("object %s bytes differ from the source", id)) + } + observed[id] = map[string]any{"locator": path, "bytes": len(body), "sha256": hex.EncodeToString(got[:]), + "matches_source": hex.EncodeToString(want[:]) == hex.EncodeToString(got[:])} + } + inventory := objectInventoryR38(t, ctx, fx) + digests := r38ObjectVersionDigests(t, ctx, fx, inventory) + return map[string]any{"match": len(problems) == 0, "problems": problems, "objects": observed, + "versions_after": len(digests), "version_digests": digests} +} + +// r39ObjectVersionReadback 逐 key+versionId 实取 GET 并本地算 SHA256, +// 返回完整版本清单(含 key/versionId/ETag/size/SHA256)与同一键的摘要映射。 +// GET 失败、字节数与清单不符、清单里有条目没取到摘要都直接失败(非零): +// ETag/size 只是旁证,不能代替字节。 +func r39ObjectVersionReadback(t *testing.T, ctx context.Context, fx *writeSetFixture, + inventory *s3.ListObjectVersionsOutput) ([]map[string]any, map[string]string) { + t.Helper() + digests := r38ObjectVersionDigests(t, ctx, fx, inventory) + manifest := make([]map[string]any, 0, len(inventory.Versions)) + for _, version := range inventory.Versions { + key, id := aws.ToString(version.Key), aws.ToString(version.VersionId) + digest, ok := digests[key+"@"+id] + if !ok || digest == "" { + t.Fatalf("version %s@%s has no measured SHA256", key, id) + } + manifest = append(manifest, map[string]any{"key": key, "version_id": id, + "etag": aws.ToString(version.ETag), "size": aws.ToInt64(version.Size), "sha256": digest}) + } + sort.Slice(manifest, func(i, j int) bool { + return fmt.Sprint(manifest[i]["key"], "@", manifest[i]["version_id"]) < + fmt.Sprint(manifest[j]["key"], "@", manifest[j]["version_id"]) + }) + return manifest, digests +} + +// r39CompareObjectVersionBytes 逐 key+versionId 比较重放前后的完整清单和实取 SHA256。 +// 版本增减/消失、摘要缺失、字节不同都返回问题;空清单也算问题—— +// 否则"一个对象都没读到"会被当成"完全相同"。 +func r39CompareObjectVersionBytes(label string, before, after []map[string]any, + beforeDigests, afterDigests map[string]string) []string { + problems := []string{} + if len(before) == 0 || len(after) == 0 { + return []string{fmt.Sprintf("%s object version manifest is empty: %d -> %d", label, len(before), len(after))} + } + if len(before) != len(after) { + problems = append(problems, fmt.Sprintf("%s object versions %d -> %d", label, len(before), len(after))) + } + ids := func(manifest []map[string]any) []string { + out := make([]string, 0, len(manifest)) + for _, row := range manifest { + out = append(out, fmt.Sprint(row["key"], "@", row["version_id"])) + } + sort.Strings(out) + return out + } + beforeIDs, afterIDs := ids(before), ids(after) + beforeSet := make(map[string]bool, len(beforeIDs)) + afterSet := make(map[string]bool, len(afterIDs)) + for _, id := range beforeIDs { + beforeSet[id] = true + } + for _, id := range afterIDs { + afterSet[id] = true + } + for _, id := range beforeIDs { + if !afterSet[id] { + problems = append(problems, fmt.Sprintf("%s object version disappeared: %s", label, id)) + continue + } + if beforeDigests[id] == "" || afterDigests[id] == "" { + problems = append(problems, fmt.Sprintf("%s object version %s has no measured SHA256", label, id)) + continue + } + if beforeDigests[id] != afterDigests[id] { + problems = append(problems, fmt.Sprintf("%s object version %s bytes changed: %s -> %s", + label, id, beforeDigests[id], afterDigests[id])) + } + } + for _, id := range afterIDs { + if !beforeSet[id] { + problems = append(problems, fmt.Sprintf("%s object version appeared: %s", label, id)) + } + } + return problems +} + +func r39Flatten(values map[string][]string) []string { + tables := make([]string, 0, len(values)) + for table := range values { + tables = append(tables, table) + } + sort.Strings(tables) + out := make([]string, 0, 64) + for _, table := range tables { + for _, row := range values[table] { + out = append(out, table+"\x00"+row) + } + } + return out +} + +func r39DiffStrings(label string, before, after []string) []string { + if len(before) != len(after) { + return []string{fmt.Sprintf("%s rows %d -> %d", label, len(before), len(after))} + } + for i := range before { + if before[i] != after[i] { + return []string{fmt.Sprintf("%s row %d changed: %s", label, i, after[i])} + } + } + return nil +} + +var _ = aws.ToString + +// r39PublishedScope 返回与期望同口径的实际行集合:resources/resource_bindings 按 +// 目标租户取(产品按内容寻址复用同租户行),knowledge_tag_relations 没有租户列、 +// 期望里已含目标范围外的关系,所以取整表;其余表按目标知识库范围。 +func r39PublishedScope(t *testing.T, fx *writeSetFixture, table string, targetRows []map[string]any) []map[string]any { + t.Helper() + switch table { + case "resources", "resource_bindings": + return ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM `+table+` AS x WHERE tenant_id=$1 ORDER BY 1`, wsTargetTenant) + case "knowledge_tag_relations": + return ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM knowledge_tag_relations AS x ORDER BY 1`) + } + return targetRows +} diff --git a/internal/releaseadapter/v071/formal_publish_http_r39_replay_bytes_control_test.go b/internal/releaseadapter/v071/formal_publish_http_r39_replay_bytes_control_test.go new file mode 100644 index 0000000..7fe2049 --- /dev/null +++ b/internal/releaseadapter/v071/formal_publish_http_r39_replay_bytes_control_test.go @@ -0,0 +1,75 @@ +package v071 + +// r39 重放字节判据的离线负控:原判据只比 Listing 里的 key@versionId#etag#size, +// 同一个 versionId 的字节被改写它完全看不见。这里先把那个盲区固定下来, +// 再要求新判据逐 key+versionId 比较实取 SHA256,缺失/空清单也必须报问题。 + +import ( + "crypto/sha256" + "encoding/hex" + "reflect" + "strings" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" +) + +func r39ControlVersion() types.ObjectVersion { + return types.ObjectVersion{ + Key: aws.String("kb-source/docs/1"), VersionId: aws.String("v-before"), + ETag: aws.String("\"etag-same\""), Size: aws.Int64(4)} +} + +func r39ControlDigest(body string) string { + sum := sha256.Sum256([]byte(body)) + return hex.EncodeToString(sum[:]) +} + +func r39ControlManifest(digest string) ([]map[string]any, map[string]string) { + manifest := []map[string]any{{"key": "kb-source/docs/1", "version_id": "v-before", + "etag": "\"etag-same\"", "size": int64(4), "sha256": digest}} + return manifest, map[string]string{"kb-source/docs/1@v-before": digest} +} + +func TestR39ReplayObjectByteControl(t *testing.T) { + // 1) 旧判据的盲区:Listing 只有 key/versionId/etag/size,没有字节。 + // 同一 versionId 的字节被改写,旧判据仍然报"完全相同"。 + beforeListing := &s3.ListObjectVersionsOutput{Versions: []types.ObjectVersion{r39ControlVersion()}} + afterListing := &s3.ListObjectVersionsOutput{Versions: []types.ObjectVersion{r39ControlVersion()}} + if !reflect.DeepEqual(objectVersionIDs(beforeListing), objectVersionIDs(afterListing)) { + t.Fatalf("control setup is wrong: the legacy version-ID predicate is expected to see identical metadata") + } + beforeManifest, beforeDigests := r39ControlManifest(r39ControlDigest("abcd")) + afterManifest, afterDigests := r39ControlManifest(r39ControlDigest("abce")) + if beforeDigests["kb-source/docs/1@v-before"] == afterDigests["kb-source/docs/1@v-before"] { + t.Fatalf("control setup is wrong: the two bodies must hash differently") + } + + // 2) 新判据必须在"版本元数据完全相同 + 字节不同"的输入上报出差异。 + problems := r39CompareObjectVersionBytes("replay", beforeManifest, afterManifest, beforeDigests, afterDigests) + if len(problems) == 0 { + t.Fatalf("replay byte comparison missed a body change that kept key/versionId/etag/size identical") + } + if !strings.Contains(strings.Join(problems, "\n"), "bytes changed") { + t.Fatalf("byte change must be reported as bytes changed, got: %v", problems) + } + + // 3) 正例对照:字节相同不得报问题。 + if same := r39CompareObjectVersionBytes("replay", beforeManifest, beforeManifest, beforeDigests, beforeDigests); len(same) != 0 { + t.Fatalf("identical manifests must not report problems: %v", same) + } + + // 4) 版本消失、空清单、摘要缺失都必须非零。 + if got := r39CompareObjectVersionBytes("replay", beforeManifest, nil, beforeDigests, map[string]string{}); len(got) == 0 { + t.Fatalf("a disappeared/empty version manifest must be reported") + } + if got := r39CompareObjectVersionBytes("replay", nil, nil, nil, nil); len(got) == 0 { + t.Fatalf("an empty version manifest must be reported") + } + noDigest := map[string]string{} + if got := r39CompareObjectVersionBytes("replay", beforeManifest, beforeManifest, beforeDigests, noDigest); len(got) == 0 { + t.Fatalf("a version without a measured SHA256 must be reported") + } +} diff --git a/internal/releaseadapter/v071/formal_publish_http_r39_test.go b/internal/releaseadapter/v071/formal_publish_http_r39_test.go new file mode 100644 index 0000000..ce8ac92 --- /dev/null +++ b/internal/releaseadapter/v071/formal_publish_http_r39_test.go @@ -0,0 +1,1030 @@ +package v071 + +// r39:单一本地专用场景 —— 真实 HTTP 发布成功闭环 + 同一请求原样重放。 +// +// 链路(全部由真实进程/真实存储产生,测试只声明来源、播种 before-image、观察读回): +// +// POST /api/v1/library/syncs(真实监听、管理员会话) +// → library.snapshot.handoff 队列(capture 角色 worker 消费) +// → 真实 libraryctl pack/unpack/verify → 独立 executor archive +// → library.sync 队列(release-executor 角色 worker 消费) +// → 业务 succeeded / 两队列 completed / production_effective / 维护释放 / 入口恢复 +// → 同一 body 原样重放:复用同 operation+job,目标内容与执行次数不增加 +// +// 与旧 r38 分支的边界: +// - 旧分支用 store.CreateLibraryDispatch 直建作业证明"故障恢复";本场景的发布必须来自 +// 真实 HTTP handler,测试不得直接建 publish 作业; +// - 旧分支的隔离装配/鉴权/读回/provenance 规则沿用,但目标基线走正式 HTTP +// POST /api/v1/library/baselines(真实整库捕获 + 校验 + 登记),不手写生效版本; +// - 本地 handoff 使用已实现的 local transport + 真实 libraryctl,明确不证明 SSH/云传输。 + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/cookiejar" + "os" + "os/exec" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + "golang.org/x/crypto/bcrypt" + + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" + "knowledge-governance/internal/objectgateway" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// r39SourceSchema 是本轮"真实本地来源实例"的落地位置:业务库里一张独立 schema, +// 装的就是本轮声明的合法来源行。产品不读它;它只负责证明"manifest 的内容来自真实 +// PostgreSQL 行",而不是凭空构造。 +const r39SourceSchema = "r39_source" + +// r39Result 是本场景的逐项断言结果;失败项必须留在文件里,不能只体现在日志。 +type r39Result struct { + Run string `json:"run"` + Scenario string `json:"scenario"` + Checks []map[string]any `json:"checks"` + Failed []string `json:"failed"` + Status string `json:"status"` + Finished string `json:"finished"` + Assertion int `json:"assertion_count"` +} + +func r39Write(t *testing.T, path string, value any) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatalf("prepare evidence dir: %v", err) + } + raw, err := json.MarshalIndent(value, "", " ") + if err != nil { + t.Fatalf("encode %s: %v", path, err) + } + if err := os.WriteFile(path, raw, 0o600); err != nil { + t.Fatalf("write %s: %v", path, err) + } +} + +// r39SeedSourceStore 把本轮声明的来源行真的写进独立 schema,再独立读回: +// 封存清单的内容必须来自这次读回,不能来自"声明对象自己"。 +func r39SeedSourceStore(t *testing.T, fx *writeSetFixture, spec ds02Spec) (map[string][]map[string]any, map[string]any) { + t.Helper() + ctx := fx.ctx + if _, err := fx.pool.Exec(ctx, `DROP SCHEMA IF EXISTS `+r39SourceSchema+` CASCADE; CREATE SCHEMA `+r39SourceSchema); err != nil { + t.Fatalf("create source schema: %v", err) + } + for _, table := range ds02TargetTables { + statement := `CREATE TABLE ` + r39SourceSchema + `.` + table + ` (LIKE public.` + table + ` INCLUDING ALL)` + if _, err := fx.pool.Exec(ctx, statement); err != nil { + t.Fatalf("create source table %s: %v", table, err) + } + } + insert := `INSERT INTO ` + r39SourceSchema + `.%s SELECT * FROM jsonb_populate_record(NULL::` + r39SourceSchema + `.%s, $1::jsonb)` + canonical := `SELECT to_jsonb(jsonb_populate_record(NULL::` + r39SourceSchema + `.%s, $1::jsonb))::text` + declared := map[string][]string{} + for _, table := range ds02TargetTables { + rows := spec.rows[table] + if len(rows) == 0 { + t.Fatalf("source table %s is empty: a source capture claim would be vacuous", table) + } + for _, row := range rows { + raw, err := json.Marshal(row) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(ctx, fmt.Sprintf(insert, table, table), raw); err != nil { + t.Fatalf("seed source %s row %v: %v", table, row["id"], err) + } + var text string + if err := fx.pool.QueryRow(ctx, fmt.Sprintf(canonical, table), raw).Scan(&text); err != nil { + t.Fatalf("canonical source %s: %v", table, err) + } + declared[table] = append(declared[table], text) + } + } + readback := map[string][]map[string]any{} + counts := map[string]int64{} + for _, table := range ds02TargetTables { + var rows int64 + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM `+r39SourceSchema+`.`+table).Scan(&rows); err != nil { + t.Fatalf("count source %s: %v", table, err) + } + counts[table] = rows + // 两侧都用 PostgreSQL 自己的 jsonb 文本:键序与数字格式由服务器决定, + // 不拿 Go 的 map 排序冒充"逐字节一致"。 + readbackRows, err := fx.pool.Query(ctx, `SELECT to_jsonb(x)::text FROM `+r39SourceSchema+`.`+table+` AS x ORDER BY 1`) + if err != nil { + t.Fatalf("read back source %s: %v", table, err) + } + gotText := []string{} + for readbackRows.Next() { + var text string + if err := readbackRows.Scan(&text); err != nil { + readbackRows.Close() + t.Fatalf("scan source %s: %v", table, err) + } + gotText = append(gotText, text) + } + readbackRows.Close() + if err := readbackRows.Err(); err != nil { + t.Fatalf("read source %s: %v", table, err) + } + want := append([]string(nil), declared[table]...) + sort.Strings(want) + sort.Strings(gotText) + if !reflect.DeepEqual(want, gotText) { + t.Fatalf("source store readback for %s differs from the declaration: want %v / got %v", table, want, gotText) + } + if int64(len(want)) != rows { + t.Fatalf("source store %s counted %d rows but read %d", table, rows, len(want)) + } + readback[table] = ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM `+r39SourceSchema+`.`+table+` AS x ORDER BY 1`) + } + return readback, map[string]any{ + "schema": r39SourceSchema, + "tables": ds02TargetTables, + "row_counts": counts, + "declared_matches": true, + "independent_readback": "SELECT to_jsonb(x)::text ... ORDER BY 1, compared row by row with the declared canonical rows", + "note": "本轮来源行的落地位置;产品不读它,只用于证明封存内容来自真实 PostgreSQL 行", + } +} + +// r39JobRow 读一条队列作业的完整行(payload 用原文,便于逐字节留证)。 +func r39JobRow(t *testing.T, pool *pgxpool.Pool, id string) map[string]any { + t.Helper() + rows := ds02Read(t, &writeSetFixture{pool: pool, ctx: context.Background()}, + `SELECT to_jsonb(x)::text FROM jobs AS x WHERE id='`+id+`'`) + if len(rows) == 0 { + t.Fatalf("queue job %s not found", id) + } + return rows[0] +} + +func r39QueueState(t *testing.T, pool *pgxpool.Pool, id string) string { + t.Helper() + var state string + if err := pool.QueryRow(context.Background(), `SELECT state FROM jobs WHERE id=$1`, id).Scan(&state); err != nil { + t.Fatalf("read queue state %s: %v", id, err) + } + return state +} + +// r39GovernanceTables 是需要逐行比对的治理/网关表:重放前后任何新增执行都会出现在这里。 +var r39GovernanceTables = []string{ + "jobs", "library_jobs", "library_job_stages", "library_operations", "library_attempts", + "library_versions", "library_current_versions", "library_maintenance", "library_instance_maintenance", + "library_release_authorizations", "library_dead_letter_releases", "library_executor_status", + "kg_object_gateway_intents", "kg_object_gateway_receipts", "kg_object_gateway_deliveries", +} + +func r39DumpTables(t *testing.T, pool *pgxpool.Pool, tables []string) map[string][]string { + t.Helper() + out := map[string][]string{} + for _, table := range tables { + rows, err := pool.Query(context.Background(), `SELECT to_jsonb(x)::text FROM "`+table+`" AS x ORDER BY 1`) + if err != nil { + t.Fatalf("dump governance table %s: %v", table, err) + } + values := make([]string, 0, 16) + for rows.Next() { + var raw string + if err := rows.Scan(&raw); err != nil { + rows.Close() + t.Fatalf("scan %s: %v", table, err) + } + values = append(values, raw) + } + rows.Close() + if err := rows.Err(); err != nil { + t.Fatalf("dump %s: %v", table, err) + } + out[table] = values + } + return out +} + +func r39DiffDump(before, after map[string][]string) []string { + problems := []string{} + tables := make([]string, 0, len(before)) + for table := range before { + tables = append(tables, table) + } + sort.Strings(tables) + for _, table := range tables { + if len(before[table]) != len(after[table]) { + problems = append(problems, fmt.Sprintf("%s rows %d -> %d", table, len(before[table]), len(after[table]))) + continue + } + for i := range before[table] { + if before[table][i] != after[table][i] { + problems = append(problems, fmt.Sprintf("%s row %d content changed: %s", table, i, after[table][i])) + } + } + } + return problems +} + +func TestFormalPublishHTTPReplaySucceededR39(t *testing.T) { + root := os.Getenv("KG_R38_RUN") + if root == "" { + t.Skip("requires the dedicated publish-http isolated deployment (KG_R38_RUN)") + } + if scenario := os.Getenv("KG_R38_SCENARIO"); scenario != "publish-http" { + t.Fatalf("publish-http branch requires KG_R38_SCENARIO=publish-http, got %q", scenario) + } + ctx := context.Background() + result := &r39Result{Run: filepath.Base(root), Scenario: "publish-http", Checks: []map[string]any{}} + defer func() { + result.Finished = time.Now().UTC().Format(time.RFC3339Nano) + result.Assertion = len(result.Checks) + if len(result.Failed) == 0 { + result.Status = "passed" + } else { + result.Status = "failed" + } + raw, err := json.MarshalIndent(result, "", " ") + if err != nil { + t.Logf("encode assertions: %v", err) + return + } + if err := os.WriteFile(filepath.Join(root, "result-assertions.json"), raw, 0600); err != nil { + t.Logf("write assertions: %v", err) + } + }() + evidence := func(name string) string { return filepath.Join(root, name) } + agree := func(id, detail, path string, ok bool) { + t.Helper() + result.Checks = append(result.Checks, map[string]any{"id": id, "detail": detail, "passed": ok, "evidence": path}) + if !ok { + result.Failed = append(result.Failed, id) + } + } + require := func(id, detail, path string, ok bool) { + t.Helper() + agree(id, detail, path, ok) + if !ok { + t.Fatalf("%s: %s (evidence %s)", id, detail, path) + } + } + must := func(e error) { + t.Helper() + if e != nil { + t.Fatal(e) + } + } + save := func(name string, value any) { r39Write(t, evidence(name), value) } + saveIn := func(dir, name string, value any) { r39Write(t, filepath.Join(root, dir, name), value) } + + // ---------- 1) 来源/目标身份:先生成、先声明,再封存与登记 ---------- + sourceInstance := strings.TrimSpace(os.Getenv("KG_R38_SOURCE_INSTANCE")) + sourceProject := strings.TrimSpace(os.Getenv("KG_R38_SOURCE_PROJECT")) + sourceApp := strings.TrimSpace(os.Getenv("KG_R38_SOURCE_APP")) + sourceIdentity := governance.LibrarySourceIdentity{Project: sourceProject, App: sourceApp, + Scope: "internal", TenantID: wsSourceTenant, KnowledgeBaseID: wsSourceKB} + sourceID, err := sourceIdentity.ID() + must(err) + project := os.Getenv("KG_R38_PROJECT") + sourceArchive := os.Getenv("KG_R38_SOURCE_ARCHIVE") + executorArchive := os.Getenv("KG_R38_EXECUTOR_ARCHIVE") + require("source-identity-declared", "来源实例/项目/app 在生成前由运行器独立注入", evidence("01-source-target-contract.json"), + sourceInstance != "" && sourceProject != "" && sourceApp != "" && sourceID != "") + require("archives-separated", "源 archive 与 executor archive 必须是两个绝对路径目录", evidence("01-source-target-contract.json"), + filepath.IsAbs(sourceArchive) && filepath.IsAbs(executorArchive) && filepath.Clean(sourceArchive) != filepath.Clean(executorArchive)) + must(os.MkdirAll(executorArchive, 0o700)) + executorBefore := r39ArchiveListing(t, executorArchive) + require("executor-starts-without-snapshot", "executor archive 起始不得已有本次快照,否则首发只证明复用", + evidence("03-before/executor-archive-before.json"), executorBefore["versions_present"] == false) + + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, archiveRoot: sourceArchive, embeddingDimension: 1024}) + declaredBefore := r38SeedFullShape(t, fx) + // 适配层解析 embedding 模型/向量库需要这两列与两张表(与 r38 fullShape 同一装配)。 + _, err = fx.pool.Exec(ctx, `ALTER TABLE knowledge_bases ADD COLUMN embedding_model_id text, ADD COLUMN vector_store_id text; +CREATE TABLE models(id text PRIMARY KEY,name text,parameters jsonb,deleted_at timestamptz); +CREATE TABLE vector_stores(id text PRIMARY KEY,engine_type text,index_config jsonb,deleted_at timestamptz); +INSERT INTO models VALUES('r38-model','text-embedding-v4','{"embedding_parameters":{"dimension":1024}}',NULL); +INSERT INTO vector_stores VALUES('r38-vector','elasticsearch_v8','{}',NULL); +UPDATE knowledge_bases SET embedding_model_id='r38-model',vector_store_id='r38-vector';`) + must(err) + + // ---------- 2) 目标契约(冻结):真实隔离端点推导,不硬编码历史指纹 ---------- + env := r39BaseEnv(t, fx) + // 发布闸口开启时 appconfig 要求显式授权方与令牌文件:先落私有文件再解析配置, + // 后面的进程与本测试用同一份 env(凭据只在本轮私有文件里)。 + env["PRODUCTION_RELEASE_AUTHORIZER_REF"] = project + env["PRODUCTION_RELEASE_AUTH_TOKEN_FILE"] = filepath.Join(root, "authorization-token") + must(os.WriteFile(env["PRODUCTION_RELEASE_AUTH_TOKEN_FILE"], + []byte(objectgateway.Digest([]byte(root+"approval"))), 0600)) + cfg, err := appconfig.Load(func(key string) string { return env[key] }) + must(err) + targetFingerprint := cfg.LibraryTargetIdentity() + stateOfRun := r39ReadJSON(t, filepath.Join(root, "state.json")) + contract := map[string]any{ + "declared_at": time.Now().UTC().Format(time.RFC3339Nano), + "declared_before": "封存、版本登记与任何 HTTP 请求之前;以下值来自运行器注入的环境与本轮已建端点", + "source": map[string]any{ + "instance": sourceInstance, "project": sourceProject, "app": sourceApp, + "scope": "internal", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, + "source_id": sourceID, + "source_id_origin": "governance.LibrarySourceIdentity{project,app,scope,tenant,kb}.ID(),由上面的独立配置推导,不从 manifest 反填", + "source_store": r39SourceSchema + " schema in " + r39DatabaseName(t, env["LIBRARY_PRODUCTION_DATABASE_URL"]), + }, + "target": map[string]any{ + "instance": cfg.LibraryTargetInstance, "project": cfg.LibraryTargetProject, + "tenant_id": cfg.LibraryProductionTenantID, "knowledge_base_id": cfg.LibraryProductionInternalKB, + "index": cfg.LibraryProductionIndex, "bucket": cfg.LibraryProductionS3Bucket, + "database": map[string]any{"name": r39DatabaseName(t, env["LIBRARY_PRODUCTION_DATABASE_URL"]), + "oid": r39DatabaseOID(t, stateOfRun, r39DatabaseName(t, env["LIBRARY_PRODUCTION_DATABASE_URL"])), + "owner": r39DatabaseOwner(t, stateOfRun, r39DatabaseName(t, env["LIBRARY_PRODUCTION_DATABASE_URL"]))}, + "writers": cfg.LibraryTargetWriters, "ingress_service": cfg.LibraryTargetIngressService, + "ingress_url": cfg.LibraryTargetIngressURL, "journal_root": cfg.LibraryTargetJournalRoot, + "gateway": env["LIBRARY_OBJECT_GATEWAY_URL"], "fingerprint": targetFingerprint, + }, + "fingerprint_rule": "appconfig.Config.LibraryTargetIdentity() over instance/project/database/tenant/KB/index/provider/endpoint/bucket;API、release worker 与本测试用同一份 env 计算", + "boundary_note": "本轮只证明本地专用链(local transport + 真实 libraryctl + 真实库/索引/对象);不声称 SSH/云传输、不声称 Capture/Export HTTP 已验收", + } + save("01-source-target-contract.json", contract) + + // before-image 与外围哨兵:真实行,不是捏造 baseline。 + beforePG := universeDump(t, fx.pool) + saveIn("03-before", "pg-before.json", beforePG) + beforeTarget := r38TargetRows(t, fx) + beforeSentinels := r38SentinelRows(t, fx) + // 声明 → 读回:种子行(目标范围 + 邻域哨兵)必须原样落库,否则 before-image 只是文案。 + for _, table := range ds02TargetTables { + if len(declaredBefore[table]) == 0 { + t.Fatalf("declared before-image for %s is empty", table) + } + union := append(append([]map[string]any{}, beforeTarget[table]...), beforeSentinels[table]...) + if diff := r38CompareRows("seeded vs declared "+table, declaredBefore[table], union); diff != "" { + t.Fatalf("seeded before-image %s does not match its own declaration: %s", table, diff) + } + } + for _, table := range ds02TargetTables { + require("before-image-non-empty-"+table, "before-image 十表必须非空,否则全形状断言是空的", + evidence("03-before/pg-before.json"), len(beforePG[table]) > 0) + require("sentinel-non-empty-"+table, "外围哨兵必须真实存在", evidence("03-before/sentinels-before.json"), len(beforeSentinels[table]) > 0) + } + saveIn("03-before", "sentinels-before.json", beforeSentinels) + beforeIndex := recoveryIndexReadback(t, fx) + saveIn("03-before", "index-before.json", beforeIndex) + beforeObjects := objectInventoryR38(t, ctx, fx) + saveIn("03-before", "objects-before.json", beforeObjects) + beforeDigests := r38ObjectVersionDigests(t, ctx, fx, beforeObjects) + require("before-objects-have-versions", "before-image 必须有真实对象版本可供逐版本 GET", evidence("03-before/object-digests-before.json"), len(beforeDigests) > 0) + saveIn("03-before", "object-digests-before.json", beforeDigests) + saveIn("03-before", "executor-archive-before.json", executorBefore) + + // ---------- 3) 合法 fullshape 来源封存(来源行先落真实 PG,再封存) ---------- + spec := r38LegalSourceSpec(t, fx) + saveIn("03-before", "legal-source-proof.json", r38ProveLegalSourceContract(t, fx, spec)) + readback, sourceStoreEvidence := r39SeedSourceStore(t, fx, spec) + saveIn("03-before", "source-store.json", sourceStoreEvidence) + sealSpec := ds02Spec{rows: readback, vectors: ds02Vectors, objects: ds02Objects} + mapping, err := fx.target(t).Search().MappingSHA256(ctx) + must(err) + source := r38SealFullShape(t, fx, sealSpec, mapping) + saveIn("03-before", "sealed-source.json", map[string]any{"snapshot": source, "index_mapping_sha256": mapping, + "full_shape": true, "sealed_from": "r39_source independent readback"}) + sourceParts := r38SourcePartCounts(t, fx, source) + manifest, manifestRaw := r39Manifest(t, sourceArchive, source) + require("source-parts-non-empty", "十表部件必须全部非空", evidence("03-before/source-parts.json"), len(sourceParts) == len(ds02TargetTables)) + require("source-manifest-identity", "manifest 的 scope/tenant/KB 必须等于独立声明的来源身份", + evidence("03-before/source-manifest.json"), + manifest.Scope == "internal" && manifest.TenantID == wsSourceTenant && manifest.KnowledgeBaseID == wsSourceKB) + manifestSum := sha256.Sum256(manifestRaw) + require("source-manifest-address", "清单字节摘要必须等于快照 ID", evidence("03-before/source-manifest.json"), + hex.EncodeToString(manifestSum[:]) == source) + saveIn("03-before", "source-parts.json", sourceParts) + saveIn("03-before", "source-manifest.json", map[string]any{"snapshot": source, + "manifest_sha256": hex.EncodeToString(manifestSum[:]), "manifest": json.RawMessage(manifestRaw)}) + expectation := ds02Expected(t, fx, spec) + // 产品契约:knowledges.embedding_model_id 换成目标知识库绑定的模型 + // (library_scope_remap.retargetEmbeddingModelField)。期望侧独立读取目标 KB 的 + // 真实配置再施加同一规则,而不是从发布结果反填。 + targetModel := "" + must(fx.pool.QueryRow(ctx, `SELECT coalesce(embedding_model_id,'') FROM knowledge_bases WHERE id=$1 AND tenant_id=$2`, + wsTargetKB, wsTargetTenant).Scan(&targetModel)) + if targetModel != "" { + for _, row := range expectation.Rows["knowledges"] { + if _, ok := row["embedding_model_id"]; ok { + row["embedding_model_id"] = targetModel + } + } + } + // 复用 DS02 已验的期望组合:resources/resource_bindings 没有知识库列,发布按 + // 内容寻址复用同租户行;knowledge_tag_relations 按父文档归属删除。目标范围之外 + // 的这些行必须在期望里原样保留,否则"保住了"会被误判成"多出来"。 + expectation.Rows["resources"] = append(expectation.Rows["resources"], ds02SameTenantRows(t, fx, "resources")...) + // 绑定行按"所有者是否在目标范围"消失:被替换文档/分块的绑定必须删掉, + // 其它知识库的绑定原样保留(独立 SQL 先声明,再看发布结果)。 + expectation.Rows["resource_bindings"] = append(expectation.Rows["resource_bindings"], + ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM resource_bindings AS x + WHERE x.tenant_id=$1 + AND NOT ((x.owner_type='knowledge' AND x.owner_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)) + OR (x.owner_type='chunk' AND x.owner_id IN (SELECT id FROM chunks WHERE tenant_id=$1 AND knowledge_base_id=$2)))`, + wsTargetTenant, wsTargetKB)...) + expectation.Rows["knowledge_tag_relations"] = append(expectation.Rows["knowledge_tag_relations"], + ds02Read(t, fx, `SELECT to_jsonb(x)::text FROM knowledge_tag_relations AS x + WHERE knowledge_id NOT IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)`, + wsTargetTenant, wsTargetKB)...) + saveIn("03-before", "expected-target-rows.json", map[string]any{"remap": map[string]any{ + "embedding_model_id": targetModel, "rule": "knowledges.embedding_model_id -> 目标知识库绑定的模型", + "source": "knowledge_bases 真实 before-image 配置"}, + "preserved_rule": "resources 追加同租户现存行(内容寻址复用);resource_bindings 只追加所有者不在目标范围的行;knowledge_tag_relations 追加目标范围外关系", + "rows": expectation.Rows}) + require("executor-lacks-source-snapshot", "executor archive 在发布前不得已有本次快照", + evidence("03-before/executor-archive-before.json"), !r39ArchiveHas(t, executorArchive, source)) + + // ---------- 4) 目标当前版本:正式基线(HTTP,不动内容、不手写版本) ---------- + govDSN := os.Getenv("KG_R38_GOVERNANCE_DSN") + gov, err := pgxpool.New(ctx, govDSN) + must(err) + t.Cleanup(gov.Close) + must(postgresstore.ApplyMigrations(ctx, gov)) + _, err = gov.Exec(ctx, objectgateway.Schema) + must(err) + reader := gatewayReadOnlyGovernance(t, ctx, gov, govDSN) + proxy := newR38RefusalProxy(t, root, fx.searchBase) + proxy.setRefuseClean(false) + objectProxy := newR38ObjectRefusalProxy(t, root, "http://"+os.Getenv("KG_R38_GATEWAY_ADDR")) + store := postgresstore.NewStore(gov).WithLibraryTarget(targetFingerprint) + defer func() { + if !t.Failed() { + return + } + dump := map[string]any{} + for _, table := range r39GovernanceTables { + rows, err := gov.Query(context.Background(), `SELECT to_jsonb(x)::text FROM "`+table+`" AS x ORDER BY 1`) + if err != nil { + continue + } + values := []string{} + for rows.Next() { + var raw string + if rows.Scan(&raw) == nil { + values = append(values, raw) + } + } + rows.Close() + dump[table] = values + } + if raw, err := json.MarshalIndent(dump, "", " "); err == nil { + _ = os.WriteFile(filepath.Join(root, "99-failure-governance.json"), raw, 0600) + } + }() + + // 测试封存版本:登记的是本轮真实封存的快照与独立推导的 source_id。 + // 这不是 Capture/Export HTTP 的产物,证据里必须写明装配方式,不能冒充 agent 捕获。 + versionID := governance.LibraryVersionID(governance.LibraryVersionTestSealed, "internal", source) + must(store.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: versionID, Scope: "internal", + Kind: governance.LibraryVersionTestSealed, SnapshotID: source, + Evidence: map[string]any{ + "source_id": sourceID, "source_identity": sourceIdentity, + "capture_job": "r39-fixture-assembled-fullshape", + "assembly": map[string]any{"kind": "fixture-assembled-legal-fullshape", + "source_store": r39SourceSchema, + "settlement": "r38ProveLegalSourceContract(产品同一份结算 SQL)", + "note": "由本轮隔离 fixture 按 DS02 十表契约装配的合法 fullshape;不是 WeKnora agent 捕获,也不声称 Capture/Export HTTP 已验收", + "manifest_sha256": source, + "source_parts_row_counts": sourceParts}, + }, + CreatedBy: "admin", CreatedAt: time.Now().UTC()})) + candidate, found, err := store.LibrarySourceCandidate(ctx, "internal", sourceID) + must(err) + require("candidate-registered", "独立 source_id 必须命中唯一 test_sealed 候选", evidence("03-before/candidate.json"), + found && candidate.SnapshotID == source) + saveIn("03-before", "candidate.json", map[string]any{"version": candidate, "source_id": sourceID, + "source_identity": sourceIdentity, "requested_snapshot": source, "found": found}) + save("01a-source-target-bound.json", map[string]any{ + "frozen_contract": evidence("01-source-target-contract.json"), + "frozen_source_id": sourceID, + "frozen_source_identity": sourceIdentity, + "source_snapshot": source, + "manifest_sha256": hex.EncodeToString(manifestSum[:]), + "manifest_path": evidence("03-before/source-manifest.json"), + "parts_path": evidence("03-before/source-parts.json"), + "source_store_path": evidence("03-before/source-store.json"), + "candidate_registration": evidence("03-before/candidate.json"), + "candidate_http_readback": evidence("03-before/overview-before-baseline.json"), + "note": "声明先冻结;这里只记录封存后的实际绑定,身份字段必须与 01 逐项相同", + "source_identity_unchanged": candidate.SnapshotID == source && candidate.Evidence["source_id"] == sourceID, + }) + + // ---------- 5) 网关 / API / 两个角色 worker(真实进程,身份逐字节核对) ---------- + save("00-scenario.json", map[string]any{"scenario": "publish-http", "label": os.Getenv("KG_R38_LABEL"), + "commit": os.Getenv("KG_R38_COMMIT"), "version": os.Getenv("KG_R38_VERSION"), + "release_version": os.Getenv("KG_R38_RELEASE_VERSION"), + "publish_entry": "POST /api/v1/library/syncs (real listener, admin session)", + "handoff": "LIBRARY_HANDOFF_TRANSPORT=local + real libraryctl; SSH/cloud transport not proven"}) + testExecutable, err := os.Executable() + must(err) + testRaw, err := os.ReadFile(testExecutable) + must(err) + testSum := sha256.Sum256(testRaw) + testIdentity := map[string]any{"label": "test", "pid": os.Getpid(), "executable": testExecutable, + "executable_sha256": hex.EncodeToString(testSum[:]), "expected_sha256": os.Getenv("KG_R38_TEST_BINARY_SHA"), + "commit": os.Getenv("KG_R38_COMMIT"), "source_tree": os.Getenv("KG_R38_SOURCE_TREE")} + require("test-process-identity", "测试进程字节必须等于本轮构建产物", evidence("00-test-process-identity.json"), + testIdentity["expected_sha256"] != "" && testIdentity["executable_sha256"] == testIdentity["expected_sha256"]) + save("00-test-process-identity.json", testIdentity) + + // 授权令牌/审计文件:真实网关要读,凭据只在私有文件里。 + dataToken := objectgateway.Digest([]byte(root + "data")) + controlToken := objectgateway.Digest([]byte(root + "control")) + env["LIBRARY_PRODUCTION_ELASTIC_URL"] = proxy.url + env["LIBRARY_OBJECT_GATEWAY_URL"] = objectProxy.url + env["LIBRARY_OBJECT_GATEWAY_TOKEN"] = dataToken + env["LIBRARY_HANDOFF_LIBRARYCTL"] = filepath.Join(os.Getenv("KG_R38_BIN"), "libraryctl") + env["LIBRARY_HANDOFF_TRANSPORT"] = "local" + env["LIBRARY_HANDOFF_LOCAL_ROOT"] = executorArchive + env["LIBRARY_HANDOFF_REMOTE_ARCHIVE"] = executorArchive + env["LIBRARY_HANDOFF_BUNDLE_DIR"] = os.Getenv("KG_R38_EXECUTOR_BUNDLE") + env["LIBRARY_HANDOFF_STAGING_DIR"] = os.Getenv("KG_R38_SOURCE_STAGING") + for _, dir := range []string{env["LIBRARY_HANDOFF_BUNDLE_DIR"], env["LIBRARY_HANDOFF_STAGING_DIR"]} { + must(os.MkdirAll(dir, 0o700)) + } + cfg, err = appconfig.Load(func(key string) string { return env[key] }) + must(err) + require("config-fingerprint-stable", "加入网关/搬运配置后目标指纹必须不变(指纹只绑数据身份)", + evidence("01-source-target-contract.json"), cfg.LibraryTargetIdentity() == targetFingerprint) + env["LIBRARY_HANDOFF_LIBRARYCTL"] = filepath.Join(os.Getenv("KG_R38_BIN"), "libraryctl") + + // worker 的对象身份只读:对象写入只能经网关,receipt 因此必然来自真实生产写。 + readStore, err := NewS3ObjectStore(S3ObjectStoreConfig{Provider: "minio", Endpoint: env["LIBRARY_PRODUCTION_S3_ENDPOINT"], + Bucket: fx.bucket, AccessKeyID: env["LIBRARY_PRODUCTION_S3_ACCESS_KEY"], SecretAccessKey: env["LIBRARY_PRODUCTION_S3_SECRET_KEY"], + Region: "us-east-1", ForcePathStyle: true}) + must(err) + allowedRead, err := readStore.Open(ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, 10001, "res-target")) + must(err) + allowedBody, err := io.ReadAll(allowedRead) + allowedRead.Close() + must(err) + if denied := readStore.Put(ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, 10001, "r39-denied"), + bytes.NewReader([]byte("denied")), 6); denied == nil { + t.Fatal("worker readonly identity unexpectedly wrote an object") + } + save("02-target-identity.json", map[string]any{"worker_object_identity": "readonly", "gateway_only_writer": true, + "bucket": fx.bucket, "index": fx.index, "target": targetFingerprint, "project": project, + "readonly_read_bytes": string(allowedBody), "readonly_put_denied": true}) + + scope := objectgateway.Digest([]byte("minio\x00" + env["LIBRARY_PRODUCTION_S3_ENDPOINT"] + "\x00" + fx.bucket)) + pub, priv, err := ed25519.GenerateKey(rand.Reader) + must(err) + digestFile := func(name string) string { + raw, err := os.ReadFile(filepath.Join(root, name)) + must(err) + return objectgateway.Digest(raw) + } + initialDrain := filepath.Join(root, "initial-drain.json") + if _, err := os.Stat(initialDrain); err != nil { + t.Fatalf("runner must provide real initial drain evidence: %v", err) + } + payload, err := json.Marshal(objectgateway.Attestation{Protocol: objectgateway.Protocol, Scope: scope, GatewayID: project, + IssuedAt: time.Now().Add(-time.Second), ExpiresAt: time.Now().Add(50 * time.Minute), + WriterInventory: digestFile("02-target-identity.json"), PolicyEvidence: digestFile("02-target-identity.json"), + DenialEvidence: digestFile("02-target-identity.json"), DrainEvidence: digestFile("initial-drain.json")}) + must(err) + signedRaw, err := json.Marshal(objectgateway.SignedAttestation{Payload: payload, Signature: ed25519.Sign(priv, payload)}) + must(err) + must(os.WriteFile(filepath.Join(root, "audit.json"), signedRaw, 0600)) + + processes := []map[string]any{} + expectedBinaries := map[string]string{} + must(json.Unmarshal([]byte(os.Getenv("KG_R38_BINARY_SHA")), &expectedBinaries)) + start := func(binary, label string, values map[string]string) *exec.Cmd { + t.Helper() + cmd := exec.Command(filepath.Join(os.Getenv("KG_R38_BIN"), binary)) + cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} + for k, v := range values { + cmd.Env = append(cmd.Env, k+"="+v) + } + f, err := os.OpenFile(filepath.Join(root, label+".log"), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600) + must(err) + cmd.Stdout = f + cmd.Stderr = f + must(cmd.Start()) + executable, err := os.Readlink(fmt.Sprintf("/proc/%d/exe", cmd.Process.Pid)) + must(err) + raw, err := os.ReadFile(executable) + must(err) + sum := sha256.Sum256(raw) + digest := hex.EncodeToString(sum[:]) + record := map[string]any{"label": label, "role": label, "pid": cmd.Process.Pid, "binary": binary, + "executable": executable, "executable_sha256": digest, "expected_sha256": expectedBinaries[binary], + "match": expectedBinaries[binary] != "" && digest == expectedBinaries[binary], + "commit": os.Getenv("KG_R38_COMMIT"), "source_tree": os.Getenv("KG_R38_SOURCE_TREE"), + "started_at": time.Now().UTC()} + if !record["match"].(bool) { + t.Fatalf("%s process identity mismatch: %v", label, record) + } + processes = append(processes, record) + save("02-process-provenance.json", processes) + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); f.Close() }) + return cmd + } + genv := map[string]string{"OBJECT_GATEWAY_LISTEN": os.Getenv("KG_R38_GATEWAY_ADDR"), "OBJECT_GATEWAY_DATABASE_URL": govDSN, + "OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL": reader.Config().ConnString(), "OBJECT_GATEWAY_ARCHIVE_ROOT": executorArchive, + "OBJECT_GATEWAY_TARGET_ID": targetFingerprint, "OBJECT_GATEWAY_PROVIDER": "minio", + "OBJECT_GATEWAY_ENDPOINT": env["LIBRARY_PRODUCTION_S3_ENDPOINT"], "OBJECT_GATEWAY_BUCKET": fx.bucket, + "OBJECT_GATEWAY_REGION": "us-east-1", "OBJECT_GATEWAY_ACCESS_KEY": os.Getenv("KG_LIBRARY_TEST_S3_ACCESS_KEY"), + "OBJECT_GATEWAY_SECRET_KEY": os.Getenv("KG_LIBRARY_TEST_S3_SECRET_KEY"), "OBJECT_GATEWAY_DATA_TOKEN": dataToken, + "OBJECT_GATEWAY_CONTROL_TOKEN": controlToken, "OBJECT_GATEWAY_ID": project, + "OBJECT_GATEWAY_AUDIT_FILE": filepath.Join(root, "audit.json"), + "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY": base64.StdEncoding.EncodeToString(pub)} + start("object-gateway", "gateway", genv) + client, err := objectgateway.NewClient(env["LIBRARY_OBJECT_GATEWAY_URL"], dataToken, scope) + must(err) + ready := false + for i := 0; i < 100; i++ { + if client.ReadyForAcquisition(ctx) == nil { + ready = true + break + } + time.Sleep(100 * time.Millisecond) + } + if !ready { + t.Fatal("object gateway not ready; inspect gateway.log") + } + + apiAddr := os.Getenv("KG_R38_API_ADDR") + apiEnv := map[string]string{} + for k, v := range env { + apiEnv[k] = v + } + apiEnv["APP_ADDR"] = apiAddr + apiEnv["GOVERNANCE_SPOOL_ROOT"] = filepath.Join(root, "spool") + apiEnv["RELEASE_WORKER_ENABLED"] = "false" + apiEnv["LIBRARY_ARCHIVE_ROOT"] = sourceArchive + must(os.MkdirAll(apiEnv["GOVERNANCE_SPOOL_ROOT"], 0700)) + start("api", "api", apiEnv) + apiURL := "http://" + apiAddr + for i := 0; i < 120; i++ { + if response, err := http.Get(apiURL + "/health"); err == nil { + response.Body.Close() + if response.StatusCode == 200 { + break + } + } + if i == 119 { + t.Fatal("api /health never became 200") + } + time.Sleep(200 * time.Millisecond) + } + captureEnv := map[string]string{} + for k, v := range env { + captureEnv[k] = v + } + captureEnv["WORKER_ID"] = project + "-capture" + captureEnv["LIBRARY_WORKER_ROLE"] = "capture" + captureEnv["LIBRARY_ARCHIVE_ROOT"] = sourceArchive + start("worker", "capture", captureEnv) + releaseEnv := map[string]string{} + for k, v := range env { + releaseEnv[k] = v + } + releaseEnv["WORKER_ID"] = project + "-release" + releaseEnv["LIBRARY_WORKER_ROLE"] = "release-executor" + releaseEnv["LIBRARY_ARCHIVE_ROOT"] = executorArchive + start("worker", "release", releaseEnv) + libraryctlRaw, err := os.ReadFile(env["LIBRARY_HANDOFF_LIBRARYCTL"]) + must(err) + libraryctlSum := sha256.Sum256(libraryctlRaw) + require("libraryctl-identity", "capture 使用的 libraryctl 必须是本轮真实构建产物", + evidence("02-process-provenance.json"), hex.EncodeToString(libraryctlSum[:]) == expectedBinaries["libraryctl"]) + processes = append(processes, map[string]any{"label": "libraryctl", "role": "real-cli", + "binary": "libraryctl", "executable": env["LIBRARY_HANDOFF_LIBRARYCTL"], + "executable_sha256": hex.EncodeToString(libraryctlSum[:]), "expected_sha256": expectedBinaries["libraryctl"], + "match": true, "note": "由 capture 角色在每次 push 时跨进程调用(snapshot-unpack/snapshot-verify)"}) + save("02-process-provenance.json", processes) + + // 管理员会话(只改这一次性治理库里的 admin 口令;口令只存在内存里)。 + password := hex.EncodeToString(func() []byte { b := make([]byte, 18); _, _ = rand.Read(b); return b }()) + hash, err := bcrypt.GenerateFromPassword([]byte(password), 10) + must(err) + _, err = gov.Exec(ctx, `UPDATE users SET password_hash=$1, must_change_password=false, failed_attempts=0, + locked_until=NULL, state='active' WHERE username='admin'`, string(hash)) + must(err) + jar, err := cookiejar.New(nil) + must(err) + api := r38API{base: apiURL, client: &http.Client{Jar: jar, Timeout: 60 * time.Second}} + code, loginBody := api.do(t, http.MethodPost, "/api/v1/auth/login", map[string]string{"username": "admin", "password": password}) + loginUser, _ := loginBody["data"].(map[string]any) + require("admin-login", "管理员会话必须来自真实登录接口", evidence("07-session.json"), + code == http.StatusOK && loginUser != nil && loginUser["role"] == "admin") + save("07-session.json", map[string]any{"login_http": code, "role": "admin", "auth": "session cookie (password not recorded)"}) + + // HTTP 读回源候选:必须命中同一声明身份,而不是另一个更方便的候选。 + overviewCode, overview := api.do(t, http.MethodGet, "/api/v1/library/overview?scope=internal", nil) + saveIn("03-before", "overview-before-baseline.json", map[string]any{"http": overviewCode, "body": overview}) + candidateView, _ := overview["test_sealed"].(map[string]any) + require("candidate-http-readback", "overview.test_sealed 必须是本轮快照且带同一声明 source_id", + evidence("03-before/overview-before-baseline.json"), + overviewCode == http.StatusOK && candidateView != nil && candidateView["snapshot_id"] == source && candidateView["source_id"] == sourceID) + + // 发布授权:管理员通过真实接口签发,绑定目标快照与参数摘要。 + code, authBody := api.do(t, http.MethodPost, "/api/v1/library/authorizations", + map[string]any{"scope": "internal", "snapshot_id": source, "action": "sync", "expires_in_minutes": 120}) + authCode := code + require("authorization-issued", "sync 授权必须由真实接口签发", evidence("04-baseline-and-auth.json"), authCode == http.StatusCreated) + save("04-baseline-and-auth.json", map[string]any{"authorization_http": authCode, "authorization": authBody}) + + // 目标基线:目标非空且没有生效版本 → 只能走正式基线捕获。 + code, baseBody := api.do(t, http.MethodPost, "/api/v1/library/baselines", map[string]any{"scope": "internal"}) + baselineCode := code + require("baseline-accepted", "目标基线的唯一正式入口必须接受本次请求", evidence("04-baseline-and-auth.json"), baselineCode == http.StatusAccepted) + baseJob, _ := baseBody["job"].(map[string]any) + baselineJobID, _ := baseJob["id"].(string) + if baselineJobID == "" { + t.Fatalf("baseline response carries no job id: %v", baseBody) + } + baseline := r39WaitLibraryJob(t, store, baselineJobID, governance.LibraryJobSucceeded, 420) + save("04-baseline-and-auth.json", map[string]any{"authorization_http": authCode, "authorization": authBody, + "baseline": map[string]any{"http": baselineCode, "job": baselineJobID, "terminal": baseline}}) + require("baseline-succeeded", "基线必须由 release worker 真实捕获+校验+登记后成功", + evidence("04-baseline-and-auth.json"), baseline.State == governance.LibraryJobSucceeded) + baselineVersion, hasBaseline, err := store.LibraryCurrentVersion(ctx, "internal") + must(err) + _, err = librarysnapshot.Open(executorArchive, 256<<20) + must(err) + require("baseline-current-version", "基线必须是 production_effective 的目标整库真实捕获(带 target_baseline 证据)", + evidence("04-baseline-and-auth.json"), + hasBaseline && baselineVersion.Kind == governance.LibraryVersionProductionEffective && + baselineVersion.Evidence["action"] == "target_baseline_init" && baselineVersion.Evidence["origin"] == "target_baseline") + maintenanceAfterBaseline, err := store.LibraryMaintenanceOf(ctx, "internal") + must(err) + instanceAfterBaseline, err := store.InstanceMaintenanceOf(ctx, cfg.LibraryTargetInstance) + must(err) + entryAfterBaseline := r39EntryOpen(t, cfg.LibraryTargetIngressURL) + saveIn("06-terminal", "baseline-release.json", map[string]any{"job": baselineJobID, + "current_version": baselineVersion, "scope_maintenance": maintenanceAfterBaseline, + "instance_maintenance": instanceAfterBaseline, "entry": entryAfterBaseline}) + require("baseline-window-released", "基线收尾必须释放两把维护占用并把入口恢复", + evidence("06-terminal/baseline-release.json"), + maintenanceAfterBaseline != nil && maintenanceAfterBaseline.ReleasedAt != nil && + instanceAfterBaseline != nil && instanceAfterBaseline.ReleasedAt != nil && entryAfterBaseline["open"] == true) + + // ---------- 6) 唯一发布请求:真实监听 + 原 body ---------- + overviewCode, overview = api.do(t, http.MethodGet, "/api/v1/library/overview?scope=internal", nil) + gate, _ := overview["gate"].(map[string]any) + save("04-gate-before-publish.json", map[string]any{"http": overviewCode, "gate": gate, "production": overview["production"]}) + require("gate-open", "闸口必须放行(当前生效版本+有效授权+目标可读)", evidence("04-gate-before-publish.json"), gate["sync_allowed"] == true) + + operationKey := project + "-publish-op" + requestBody := map[string]any{"scope": "internal", "target_snapshot_id": source, + "operation_key": operationKey, "source_id": sourceID} + rawRequest, err := json.Marshal(requestBody) + must(err) + publishCode, publishBody := api.do(t, http.MethodPost, "/api/v1/library/syncs", json.RawMessage(rawRequest)) + published, _ := publishBody["job"].(map[string]any) + jobID, _ := published["id"].(string) + operationID, _ := published["operation_id"].(string) + require("publish-http-accepted", "POST /api/v1/library/syncs 必须返回 202 且新建作业(不是复用)", + evidence("04-publish-http.json"), + publishCode == http.StatusAccepted && jobID != "" && operationID != "" && publishBody["reused"] == false) + processes = append(processes, map[string]any{"label": "publish-request", "role": "http-request", + "at": time.Now().UTC(), "job": jobID, "operation": operationID, + "processes_in_this_request": []string{"api", "capture", "release", "gateway"}, + "note": "本条把四个真实进程与这一次 POST 关联起来;时间取自同一台机器"}) + save("02-process-provenance.json", processes) + save("04-publish-http.json", map[string]any{ + "method": "POST", "url": apiURL + "/api/v1/library/syncs", + "auth": "admin session cookie (credentials not recorded)", "status": publishCode, + "request_body": json.RawMessage(rawRequest), "response": publishBody, + "operation_id": operationID, "job_id": jobID, "reused": publishBody["reused"], + "handoff_enabled": true, "note": "真实监听 HTTP,不是 httptest,也不是直接调用 store.CreateLibraryDispatch"}) + + // ---------- 7) 自然消费:handoff → release → 业务成功 ---------- + handoffQueue := governance.LibraryHandoffQueueJobID(jobID) + releaseQueue := governance.QueueJobIDFor(jobID) + firstHandoff := r39FirstQueueObservation(t, gov, handoffQueue, 60) + require("handoff-enqueued", "发布作业必须先进入 library.snapshot.handoff 队列,而不是直接进 release", + evidence("05-handoff/queue.json"), firstHandoff["type"] == "library.snapshot.handoff") + r39WaitQueue(t, gov, handoffQueue, "completed", 300) + handoffQueueRow := r39JobRow(t, gov, handoffQueue) + require("handoff-completed", "capture 角色的 handoff 队列作业必须 completed", evidence("05-handoff/queue.json"), + handoffQueueRow["state"] == "completed") + r39WaitQueue(t, gov, releaseQueue, "completed", 420) + releaseQueueRow := r39JobRow(t, gov, releaseQueue) + require("release-completed", "release-executor 的发布队列作业必须 completed", evidence("06-terminal/queues.json"), + releaseQueueRow["state"] == "completed") + business := r39WaitLibraryJob(t, store, jobID, governance.LibraryJobSucceeded, 120) + save("06-terminal/job.json", map[string]any{"business": business, "handoff_queue": handoffQueueRow, + "release_queue": releaseQueueRow, "handoff_queue_id": handoffQueue, "release_queue_id": releaseQueue}) + require("business-succeeded", "业务作业必须是 succeeded(不是 pending/202/日志)", evidence("06-terminal/job.json"), + business.State == governance.LibraryJobSucceeded) + + // 持久行:阶段 / 代次 / 版本 / 当前指针 / 维护。 + stages := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM library_job_stages AS x WHERE job_id='`+jobID+`' ORDER BY stage`) + attempts := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM library_attempts AS x WHERE job_id='`+jobID+`' ORDER BY epoch`) + operations := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM library_operations AS x WHERE id='`+operationID+`'`) + versionsOfSnapshot := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM library_versions AS x WHERE scope='internal' AND snapshot_id='`+source+`' ORDER BY kind`) + currentRows := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM library_current_versions AS x WHERE scope='internal'`) + maintenanceRows := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM library_maintenance AS x WHERE scope='internal' ORDER BY acquired_at`) + instanceRows := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM library_instance_maintenance AS x ORDER BY acquired_at`) + journal := r39ReadJSON(t, filepath.Join(root, "maintenance", jobID+".json")) + save("06-terminal/durable.json", map[string]any{"stages": stages, "attempts": attempts, "operations": operations, + "versions_of_snapshot": versionsOfSnapshot, "current": currentRows, "maintenance": maintenanceRows, + "instance_maintenance": instanceRows, "journal": journal}) + effectiveCount := 0 + for _, row := range versionsOfSnapshot { + if row["kind"] == "production_effective" && row["superseded_at"] == nil { + effectiveCount++ + } + } + require("production-effective", "发布必须登记一条未 superseded 的 production_effective(绑定本轮 job/operation)", + evidence("06-terminal/durable.json"), effectiveCount == 1) + currentSnapshot := "" + for _, row := range currentRows { + currentSnapshot, _ = row["snapshot_id"].(string) + } + require("current-pointer", "当前生效版本指针必须指向本轮快照", evidence("06-terminal/durable.json"), currentSnapshot == source) + scopeRow, err := store.LibraryMaintenanceOf(ctx, "internal") + must(err) + instanceRow, err := store.InstanceMaintenanceOf(ctx, cfg.LibraryTargetInstance) + must(err) + entryAfter := r39EntryOpen(t, cfg.LibraryTargetIngressURL) + require("maintenance-released", "scope/instance 两把维护占用都必须释放", + evidence("06-terminal/maintenance.json"), + scopeRow != nil && scopeRow.ReleasedAt != nil && instanceRow != nil && instanceRow.ReleasedAt != nil) + require("entry-restored", "真实入口必须读回 200(不是只看进程健康)", evidence("06-terminal/entry.json"), entryAfter["open"] == true) + save("06-terminal/maintenance.json", map[string]any{"scope": scopeRow, "instance": instanceRow}) + save("06-terminal/entry.json", entryAfter) + save("06-terminal/journal.json", journal) + for _, pair := range [][2]string{{"api", "api.log"}, {"capture", "capture.log"}, {"release", "release.log"}, {"gateway", "gateway.log"}} { + raw, err := os.ReadFile(filepath.Join(root, pair[1])) + if err != nil { + t.Fatalf("read %s log: %v", pair[0], err) + } + must(os.WriteFile(filepath.Join(root, "06-terminal", pair[0]+".log"), raw, 0600)) + } + + // ---------- 8) 05-handoff:两端字节 + 真实 pack/unpack/verify ---------- + handoffEvidence := r39HandoffEvidence(t, gov, store, jobID, source, sourceArchive, executorArchive, + env["LIBRARY_HANDOFF_LIBRARYCTL"], filepath.Join(root, "05-handoff", "repack")) + saveIn("05-handoff", "queue.json", map[string]any{"handoff_queue": handoffQueue, "first_observation": firstHandoff, + "terminal": handoffQueueRow, "payload": handoffQueueRow["payload"], + "release_handover": map[string]any{"queue": releaseQueue, "idempotency_key": releaseQueueRow["idempotency_key"], + "type": releaseQueueRow["type"], "payload": releaseQueueRow["payload"], "state": releaseQueueRow["state"], + "handoff_stage": stages}}) + saveIn("05-handoff", "evidence.json", handoffEvidence) + require("handoff-executor-verified", "executor 端清单与每个 blob 必须逐字节等于源端", + evidence("05-handoff/evidence.json"), handoffEvidence["executor_matches_source"] == true) + require("handoff-libraryctl-pack-unpack-verify", "真实 libraryctl 的 pack/unpack/verify 必须全部 rc=0 且摘要一致", + evidence("05-handoff/libraryctl.json"), handoffEvidence["libraryctl_all_zero"] == true) + require("handoff-bundle-cleaned", "传输暂存 bundle 必须被清理(只留归档本体)", + evidence("05-handoff/evidence.json"), handoffEvidence["bundle_absent_after"] == true) + + // ---------- 9) 07-after:独立内容/映射/索引/对象读回 ---------- + afterPG := universeDump(t, fx.pool) + saveIn("07-after", "pg-after.json", afterPG) + afterTarget := r38TargetRows(t, fx) + afterSentinels := r38SentinelRows(t, fx) + pgDiffs, sentinelDiffs := []string{}, []string{} + for _, table := range ds02TargetTables { + actual := r39PublishedScope(t, fx, table, afterTarget[table]) + if diff := r38CompareRows("published "+table, expectation.Rows[table], actual); diff != "" { + pgDiffs = append(pgDiffs, diff) + } + if diff := r38CompareRows("sentinel "+table, beforeSentinels[table], afterSentinels[table]); diff != "" { + sentinelDiffs = append(sentinelDiffs, diff) + } + } + saveIn("07-after", "pg-verdict.json", map[string]any{"match": len(pgDiffs) == 0, "diffs": pgDiffs, + "tables": ds02TargetTables}) + require("published-pg-tables", "PG 十表的行身份与逐列内容必须与独立期望一致", + evidence("07-after/pg-verdict.json"), len(pgDiffs) == 0) + require("sentinels-intact", "目标范围之外的行/索引文档/对象必须逐列不变", + evidence("07-after/pg-verdict.json"), len(sentinelDiffs) == 0) + if len(pgDiffs) > 0 || len(sentinelDiffs) > 0 { + t.Fatalf("published content differs from the independent expectation:\n%s\n%s", + strings.Join(pgDiffs, "\n"), strings.Join(sentinelDiffs, "\n")) + } + saveIn("07-after", "sentinels-after.json", afterSentinels) + changedByPublish := 0 + for _, table := range ds02TargetTables { + if r38CompareRows("before-vs-after "+table, beforeTarget[table], afterTarget[table]) != "" { + changedByPublish++ + } + } + require("publish-changed-target", "发布必须真的改写目标范围内容(不是 before=after 的空操作)", + evidence("07-after/pg-after.json"), changedByPublish > 0) + references := r38RequireReferences(t, "after publish", afterTarget) + saveIn("07-after", "reference-promises.json", references) + afterIndex := recoveryIndexReadback(t, fx) + saveIn("07-after", "index-after.json", afterIndex) + indexDiff := r39CheckPublishedIndex(t, sealSpec, beforeIndex, afterIndex) + saveIn("07-after", "index-verdict.json", indexDiff) + require("index-published", "索引必须与独立期望逐文档一致(含向量),外围文档不变", + evidence("07-after/index-verdict.json"), indexDiff["match"] == true) + objectVerdict := r39CheckPublishedObjects(t, ctx, fx, sealSpec, expectation) + saveIn("07-after", "object-verdict.json", objectVerdict) + require("objects-published", "发布后的资源对象必须按版本 GET 到与来源逐字节相同的字节", + evidence("07-after/object-verdict.json"), objectVerdict["match"] == true) + ledger := r38FindWriteSet(t, executorArchive, jobID) + mappingDiffs := ds02CheckLocalIDMapping(r38LocalColumns(t, fx, spec, expectation), ledger.LocalIDs) + saveIn("06-terminal", "ledger.json", map[string]any{"writeset_digest": ledger.Digest, "job": ledger.JobID, + "target_snapshot": ledger.TargetSnapshotID, "backup_snapshot": ledger.BackupSnapshotID, + "local_ids": ledger.LocalIDs}) + saveIn("07-after", "publish-ledger.json", map[string]any{"writeset_digest": ledger.Digest, "job": ledger.JobID, + "target_snapshot": ledger.TargetSnapshotID, "backup_snapshot": ledger.BackupSnapshotID, + "local_ids": ledger.LocalIDs, "mapping_diffs": mappingDiffs}) + require("ledger-mapping", "写集合必须绑定本轮 job/operation/target 且通过独立映射 oracle", + evidence("07-after/publish-ledger.json"), len(ledger.LocalIDs) > 0 && len(mappingDiffs) == 0 && ledger.JobID == jobID) + receipts := ds02Read(t, &writeSetFixture{pool: gov, ctx: ctx}, + `SELECT to_jsonb(x)::text FROM kg_object_gateway_receipts AS x ORDER BY operation`) + saveIn("07-after", "receipts.json", receipts) + saveIn("06-terminal", "receipts.json", receipts) + require("gateway-receipts", "对象写入必须留下真实网关 receipt", evidence("07-after/receipts.json"), len(receipts) > 0) + + // ---------- 10) 08-replay:同一 body 原样重放 ---------- + beforeReplayGovernance := r39DumpTables(t, gov, r39GovernanceTables) + beforeReplayPG := universeDump(t, fx.pool) + beforeReplayIndex := recoveryIndexReadback(t, fx) + beforeReplayInventory := objectInventoryR38(t, ctx, fx) + beforeReplayObjects, beforeReplayDigests := r39ObjectVersionReadback(t, ctx, fx, beforeReplayInventory) + saveIn("08-replay", "before.json", map[string]any{"governance": beforeReplayGovernance, "pg": beforeReplayPG, + "index": beforeReplayIndex, "object_versions": beforeReplayObjects}) + replayCode, replayBody := api.do(t, http.MethodPost, "/api/v1/library/syncs", json.RawMessage(rawRequest)) + replayed, _ := replayBody["job"].(map[string]any) + require("replay-reused", "同一 body 重放必须 reused=true 并复用同一 operation/job", evidence("08-replay-http.json"), + replayCode == http.StatusAccepted && replayBody["reused"] == true && + replayed["id"] == jobID && replayed["operation_id"] == operationID) + afterReplayGovernance := r39DumpTables(t, gov, r39GovernanceTables) + afterReplayPG := universeDump(t, fx.pool) + afterReplayIndex := recoveryIndexReadback(t, fx) + afterReplayInventory := objectInventoryR38(t, ctx, fx) + afterReplayObjects, afterReplayDigests := r39ObjectVersionReadback(t, ctx, fx, afterReplayInventory) + objectByteProblems := r39CompareObjectVersionBytes("replay", beforeReplayObjects, afterReplayObjects, + beforeReplayDigests, afterReplayDigests) + saveIn("08-replay", "object-bytes.json", map[string]any{ + "before_count": len(beforeReplayObjects), "after_count": len(afterReplayObjects), + "before_versions": beforeReplayObjects, "after_versions": afterReplayObjects, + "match": len(objectByteProblems) == 0, "problems": objectByteProblems, + "method": "每个 key+versionId 单独 GET,本地 SHA256;ETag/size 只作旁证"}) + problems := r39DiffDump(beforeReplayGovernance, afterReplayGovernance) + problems = append(problems, r39DiffStrings("pg", r39Flatten(beforeReplayPG), r39Flatten(afterReplayPG))...) + if !reflect.DeepEqual(beforeReplayIndex, afterReplayIndex) { + problems = append(problems, "index readback changed on replay") + } + if !reflect.DeepEqual(beforeReplayObjects, afterReplayObjects) { + problems = append(problems, fmt.Sprintf("object versions changed on replay: %d -> %d", len(beforeReplayObjects), len(afterReplayObjects))) + } + problems = append(problems, objectByteProblems...) + replayRecord := map[string]any{"request_body": json.RawMessage(rawRequest), "status": replayCode, + "response": replayBody, "reused": replayBody["reused"], "job_id": replayed["id"], "operation_id": replayed["operation_id"], + "original_job_id": jobID, "original_operation_id": operationID, + "governance_diff": problems, "object_versions_before": len(beforeReplayObjects), + "object_versions_after": len(afterReplayObjects), "object_byte_problems": objectByteProblems, + "new_execution_evidence": map[string]any{ + "jobs": len(afterReplayGovernance["jobs"]) - len(beforeReplayGovernance["jobs"]), + "library_jobs": len(afterReplayGovernance["library_jobs"]) - len(beforeReplayGovernance["library_jobs"]), + "library_attempts": len(afterReplayGovernance["library_attempts"]) - len(beforeReplayGovernance["library_attempts"]), + "versions": len(afterReplayGovernance["library_versions"]) - len(beforeReplayGovernance["library_versions"]), + "receipts": len(afterReplayGovernance["kg_object_gateway_receipts"]) - len(beforeReplayGovernance["kg_object_gateway_receipts"]), + }} + save("08-replay-http.json", replayRecord) + saveIn("08-replay", "after.json", map[string]any{"governance": afterReplayGovernance, "pg": afterReplayPG, + "index": afterReplayIndex, "object_versions": afterReplayObjects}) + require("replay-object-version-bytes", "重放前后每个 key+versionId 实取 GET 的完整版本清单与 SHA256 必须完全相同", + evidence("08-replay/object-bytes.json"), len(objectByteProblems) == 0) + require("replay-zero-side-effects", "重放不得新增执行/写入:治理行、目标内容、索引、对象版本必须逐字节不变", + evidence("08-replay-http.json"), len(problems) == 0) + afterOrderPG := universeDump(t, fx.pool) + if diff := diffUniverse(afterPG, afterOrderPG); diff != "" { + t.Fatalf("target content changed during replay: %s", diff) + } + + // ---------- 11) 边界:不声称的能力 ---------- + save("10-boundaries.json", map[string]any{ + "candidate_ui": "not_tested", + "formal_8088": "not_deployed", + "ssh_cloud_transport": "not_proven (local transport only)", + "capture_export_http": "not_tested", + "ds01_kill_put_matrix": "open, not re-run in this scenario", + "deployment": "not_deployed; handed to GPT-6 Astra for review", + "production_or_cloud_write": "none", + }) +} diff --git a/internal/releaseadapter/v071/formal_recovery_integration_test.go b/internal/releaseadapter/v071/formal_recovery_integration_test.go new file mode 100644 index 0000000..04da305 --- /dev/null +++ b/internal/releaseadapter/v071/formal_recovery_integration_test.go @@ -0,0 +1,340 @@ +package v071 + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "syscall" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/jackc/pgx/v5/pgxpool" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/jobs" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +func recoveryIndexReadback(t *testing.T, fx *writeSetFixture) map[string]map[string]any { + t.Helper() + response, e := http.Get(fx.searchBase + "/" + fx.index + "/_search?size=100&seq_no_primary_term=true") + if e != nil { + t.Fatal(e) + } + defer response.Body.Close() + var body struct { + Hits struct { + Hits []map[string]any `json:"hits"` + } `json:"hits"` + } + if e = json.NewDecoder(response.Body).Decode(&body); e != nil { + t.Fatal(e) + } + if response.StatusCode != 200 || len(body.Hits.Hits) >= 100 { + t.Fatal("invalid independent index readback") + } + result := map[string]map[string]any{} + for _, hit := range body.Hits.Hits { + result[hit["_id"].(string)] = hit + } + return result +} + +// Only the worker executable performs recovery writes. Test code submits a new +// request, kills an actual recovery process, and independently compares stores. +func runRecoveryIntentProcess(t *testing.T, root string, fx *writeSetFixture, gov *pgxpool.Pool, store *postgresstore.Store, original governance.LibraryJob, env map[string]string, start func(string, string, map[string]string) *exec.Cmd, checkpoint func(string), save func(string, any)) { + t.Helper() + ctx := context.Background() + must := func(e error) { + t.Helper() + if e != nil { + t.Fatal(e) + } + } + inventory := func() *s3.ListObjectVersionsOutput { + v, e := fx.objects.s3.client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(fx.bucket)}) + must(e) + if aws.ToBool(v.IsTruncated) || len(v.DeleteMarkers) > 0 { + t.Fatal("invalid object inventory") + } + return v + } + readJSON := func(name string, out any) { + raw, e := os.ReadFile(filepath.Join(root, name)) + must(e) + must(json.Unmarshal(raw, out)) + } + kill := func(cmd *exec.Cmd, name string) { + must(cmd.Process.Kill()) + _ = cmd.Wait() + s := cmd.ProcessState.Sys().(syscall.WaitStatus) + if !s.Signaled() || s.Signal() != syscall.SIGKILL { + t.Fatal("not SIGKILL") + } + save(name, map[string]any{"pid": cmd.Process.Pid, "exit_code": cmd.ProcessState.ExitCode(), "signal": "SIGKILL"}) + } + beforeIndex := recoveryIndexReadback(t, fx) + save("index-before.json", beforeIndex) + env["KG_TEST_BARRIER_POINTS"] = "after:index" + env["WORKER_ID"] = "r9-publish" + publish := start("worker", "publish", env) + wait := func(queue, point string) string { + for i := 0; i < 600; i++ { + if point != "" { + if _, e := os.Stat(filepath.Join(root, "barriers", point+".hit")); e == nil { + return "hit" + } + } + var state, message string + must(gov.QueryRow(ctx, "SELECT state,COALESCE(last_error,'') FROM jobs WHERE id=$1", queue).Scan(&state, &message)) + if state == "completed" || state == "failed" { + save("queue-"+queue+"-terminal.json", map[string]any{"state": state, "error": message}) + return state + } + time.Sleep(100 * time.Millisecond) + } + checkpoint("timeout") + t.Fatal("formal process timeout", queue, point) + return "timeout" + } + queueID := original.QueueJobID + if queueID == "" { + must(gov.QueryRow(ctx, "SELECT queue_job_id FROM library_jobs WHERE id=$1", original.ID).Scan(&queueID)) + } + publishResult := wait(queueID, "after-index") + if got := publishResult; got != "hit" && !(os.Getenv("KG_R9_FAULT") == "apply-clean" && got == "failed") { + checkpoint("publish-failed") + t.Fatal("publish failed", got) + } + checkpoint("published-partial") + partialPG := universeDump(t, fx.pool) + partialIndex := recoveryIndexReadback(t, fx) + partialObjects := inventory() + if publishResult == "hit" { + if reflect.DeepEqual(partialIndex, beforeIndex) || partialIndex["chunk-src"] == nil || partialIndex["chunk-target"] != nil { + t.Fatal("publish kill did not follow real index replacement") + } + } + if publishResult == "hit" { + var owner string + must(gov.QueryRow(ctx, "SELECT lease_owner FROM jobs WHERE id=$1", queueID).Scan(&owner)) + kill(publish, "publish-kill.json") + must(store.FailTerminal(ctx, queueID, owner, "isolated operator requested recovery after SIGKILL", "r9_recover_requested", time.Now().UTC())) + } else { + must(publish.Process.Signal(syscall.SIGTERM)) + must(publish.Wait()) + if _, e := os.Stat(filepath.Join(root, "es-response-dropped")); e != nil { + t.Fatal("publish did not hit real ES commit fault") + } + } + time.Sleep(5 * time.Second) + var backup, plan, source string + must(gov.QueryRow(ctx, "SELECT snapshot_id,evidence->>'writeset_digest',evidence->>'writeset_target_snapshot' FROM library_versions WHERE kind='production_prebackup' AND source_job_id=$1", original.ID).Scan(&backup, &plan, &source)) + fields := map[string]string{"scope": "internal", "window_job_id": original.ID, "source_snapshot_id": source, "target_id": env["R9_TARGET_ID"], "original_operation_id": original.OperationID, "backup_snapshot_id": backup, "plan_digest": plan} + scenario := os.Getenv("KG_R9_SCENARIO") + if scenario == "wrong-job" { + must(store.CancelLibraryJob(ctx, original.ID, "negative fixture: operator parked original publication", time.Now().UTC())) + } + if scenario != "" { + key := map[string]string{"wrong-source": "source_snapshot_id", "wrong-target": "target_id", "wrong-job": "window_job_id", "wrong-plan": "plan_digest", "wrong-operation": "original_operation_id"}[scenario] + if key != "" { + fields[key] = "wrong-identity" + } else if scenario != "arbitrary-queue" { + t.Fatal("unknown scenario", scenario) + } + } + recoverID := governance.LibraryRecoveryQueueID(fields["window_job_id"]) + if scenario == "arbitrary-queue" { + recoverID = "unrelated-recovery-queue" + } + payload, e := json.Marshal(fields) + must(e) + request := jobs.EnqueueRequest{ID: recoverID, Type: "library.recover", Payload: payload, AvailableAt: time.Now().UTC(), MaxAttempts: 1, IdempotencyKey: "library.recover:" + fields["window_job_id"]} + queued, e := store.Enqueue(ctx, request, time.Now().UTC()) + must(e) + save("recovery-request.json", queued) + env["KG_TEST_BARRIER_POINTS"] = "restore:index" + env["WORKER_ID"] = "r9-recover-1" + worker := start("worker", "recovery-1", env) + if scenario != "" { + if got := wait(recoverID, ""); got != "failed" { + t.Fatal("invalid recovery accepted", scenario, got) + } + must(worker.Process.Signal(syscall.SIGTERM)) + must(worker.Wait()) + checkpoint("rejected") + if !reflect.DeepEqual(partialPG, universeDump(t, fx.pool)) || !reflect.DeepEqual(partialIndex, recoveryIndexReadback(t, fx)) || !reflect.DeepEqual(partialObjects.Versions, inventory().Versions) { + t.Fatal("rejected request changed business stores") + } + save("recovery-result.json", map[string]any{"scenario": scenario, "rejected": true, "business_stores_unchanged": true}) + return + } + if os.Getenv("KG_R9_FAULT") == "apply-clean" || os.Getenv("KG_R9_FAULT") == "restore-clean" { + if got := wait(recoverID, ""); got != "failed" { + t.Fatal("unattributable clean commit did not remain held", got) + } + must(worker.Process.Signal(syscall.SIGTERM)) + must(worker.Wait()) + checkpoint("clean-unknown-held") + if _, e := os.Stat(filepath.Join(root, "es-response-dropped")); e != nil { + t.Fatal("fault not exercised") + } + heldPG, heldIndex, heldObjects := universeDump(t, fx.pool), recoveryIndexReadback(t, fx), inventory() + wireBefore, e := os.ReadFile(filepath.Join(root, "es-wire.json")) + must(e) + time.Sleep(5 * time.Second) + retried, e := store.RetryLibraryRecovery(ctx, recoverID, original.ID, time.Now().UTC()) + must(e) + if !retried { + t.Fatal("retry unavailable") + } + env["WORKER_ID"] = "r9-clean-held-replay" + worker = start("worker", "clean-held-replay", env) + if got := wait(recoverID, ""); got != "failed" { + t.Fatal("clean unknown replay accepted", got) + } + must(worker.Process.Signal(syscall.SIGTERM)) + must(worker.Wait()) + wireAfter, e := os.ReadFile(filepath.Join(root, "es-wire.json")) + must(e) + if !reflect.DeepEqual(heldPG, universeDump(t, fx.pool)) || !reflect.DeepEqual(heldIndex, recoveryIndexReadback(t, fx)) || !reflect.DeepEqual(heldObjects.Versions, inventory().Versions) || string(wireBefore) != string(wireAfter) { + t.Fatal("held replay rewrote business state or resent ES mutation") + } + var journal map[string]any + readJSON("maintenance/"+original.ID+".json", &journal) + if journal["state"] != "held" { + t.Fatal("unknown not held", journal["state"]) + } + save("recovery-result.json", map[string]any{"fault": os.Getenv("KG_R9_FAULT"), "state": "held", "no_repeated_ES_mutations": true, "replay_stores_unchanged": true}) + return + } + if os.Getenv("KG_R9_FAULT") == "restore-write" { + if got := wait(recoverID, ""); got != "failed" { + t.Fatal("restore response fault not observed", got) + } + checkpoint("unknown-restore-red") + must(worker.Process.Signal(syscall.SIGTERM)) + must(worker.Wait()) + if _, e := os.Stat(filepath.Join(root, "es-response-dropped")); e != nil { + t.Fatal("no real ES response was dropped") + } + time.Sleep(5 * time.Second) + retried, e := store.RetryLibraryRecovery(ctx, recoverID, original.ID, time.Now().UTC()) + must(e) + if !retried { + t.Fatal("recovery retry not queued") + } + env["WORKER_ID"] = "r9-recover-after-unknown" + worker = start("worker", "recovery-after-unknown", env) + } + if got := wait(recoverID, "restore-index"); got != "hit" { + checkpoint("recovery-failed") + t.Fatal("recovery did not reach real restored-index boundary", got) + } + checkpoint("recovery-interrupted") + indexAtKill := recoveryIndexReadback(t, fx) + save("index-at-recovery-kill.json", indexAtKill) + kill(worker, "recovery-kill.json") + time.Sleep(5 * time.Second) + env["WORKER_ID"] = "r9-recover-2" + worker = start("worker", "recovery-2", env) + if got := wait(recoverID, ""); got != "completed" { + checkpoint("recovery-failed") + t.Fatal("recovery takeover failed", got) + } + checkpoint("recovery-complete") + if os.Getenv("KG_R9_FAULT") == "restore-write" { + var wire []map[string]any + readJSON("es-wire.json", &wire) + markedWrites := 0 + droppedWrites := 0 + for _, event := range wire { + if event["method"] == "PUT" && strings.Contains(event["request"].(string), indexRestoreClaimPrefix) { + markedWrites++ + if event["dropped"] == true { + droppedWrites++ + } + } + } + if markedWrites != 1 || droppedWrites != 1 { + t.Fatal("restore marker was resent or fault not exercised", markedWrites, droppedWrites) + } + } + var before map[string][]string + readJSON("pg-before.json", &before) + after := universeDump(t, fx.pool) + if !reflect.DeepEqual(before, after) { + t.Fatal("full PG before-image not restored") + } + finalIndex := recoveryIndexReadback(t, fx) + save("index-final.json", finalIndex) + if len(finalIndex) != len(beforeIndex) { + t.Fatal("index universe changed") + } + for id, old := range beforeIndex { + got, ok := finalIndex[id] + if !ok || !reflect.DeepEqual(old["_source"], got["_source"]) { + t.Fatal("original index source not restored", id) + } + if got["_seq_no"] == nil || got["_primary_term"] == nil { + t.Fatal("missing CAS") + } + if id == "chunk-target" && reflect.DeepEqual(old["_seq_no"], got["_seq_no"]) { + t.Fatal("restoration did not create a new CAS generation") + } + if id != "chunk-target" && !reflect.DeepEqual(old, got) { + t.Fatal("out-of-scope index CAS changed", id) + } + } + if !reflect.DeepEqual(indexAtKill, finalIndex) { + t.Fatal("replayed restoration repeated index mutations") + } + var objectsBefore s3.ListObjectVersionsOutput + readJSON("objects-before.json", &objectsBefore) + finalObjects := inventory() + if !reflect.DeepEqual(objectsBefore.Versions, finalObjects.Versions) { + t.Fatal("original exact object versions not restored") + } + var operations, events, receipts, deliveries int + must(gov.QueryRow(ctx, "SELECT count(*) FROM library_operations WHERE kind='recover'").Scan(&operations)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM library_versions WHERE kind='recovery_verified'").Scan(&events)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts").Scan(&receipts)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries").Scan(&deliveries)) + expectedDeliveries := 3 + if os.Getenv("KG_R9_FAULT") == "restore-write" { + expectedDeliveries++ + } + if operations != 1 || events != 1 || receipts != 2 || deliveries != expectedDeliveries { + t.Fatal("duplicate or missing durable identities", operations, events, receipts, deliveries) + } + replay, e := store.Enqueue(ctx, request, time.Now().UTC()) + must(e) + if replay.ID != recoverID || replay.State != jobs.StateCompleted { + t.Fatal("recovery replay not idempotent") + } + time.Sleep(400 * time.Millisecond) + if !reflect.DeepEqual(after, universeDump(t, fx.pool)) || !reflect.DeepEqual(finalIndex, recoveryIndexReadback(t, fx)) || !reflect.DeepEqual(finalObjects.Versions, inventory().Versions) { + t.Fatal("completed request replay mutated data") + } + must(worker.Process.Signal(syscall.SIGTERM)) + must(worker.Wait()) + save("recovery-result.json", map[string]any{"queue_job": recoverID, "window_job": original.ID, "original_operation": original.OperationID, "state": "completed", "recovery_sigkills": 1, "recover_operations": operations, "recovery_events": events, "deliveries": deliveries, "receipts": receipts, "full_before_image_verified": true, "index_replay_CAS_unchanged": true, "worker_exit": worker.ProcessState.ExitCode()}) + for _, v := range finalObjects.Versions { + _, e = fx.objects.s3.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(fx.bucket), Key: v.Key, VersionId: v.VersionId}) + must(e) + } + if len(inventory().Versions) != 0 { + t.Fatal("cleanup not empty") + } + _, e = fx.objects.s3.client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(fx.bucket)}) + must(e) + save("object-cleanup.json", map[string]any{"bucket": fx.bucket, "versions": 0, "delete_markers": 0}) + t.Log(fmt.Sprintf("recovery new request=%s original=%s full before-image restored", recoverID, original.ID)) +} diff --git a/internal/releaseadapter/v071/formal_worker_integration_test.go b/internal/releaseadapter/v071/formal_worker_integration_test.go new file mode 100644 index 0000000..6fb6856 --- /dev/null +++ b/internal/releaseadapter/v071/formal_worker_integration_test.go @@ -0,0 +1,446 @@ +package v071 + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "io" + "syscall" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + "knowledge-governance/internal/appconfig" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/librarysnapshot" + "knowledge-governance/internal/objectgateway" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// The harness only seeds and observes. All release writes run in cmd/worker +// executables, through the real Docker maintenance coordinator and gateway. +func TestFormalWorkerDoubleInterruption(t *testing.T) { runFormalWorkerScenario(t, false) } + +func TestFormalWorkerRecoveryIntent(t *testing.T) { runFormalWorkerScenario(t, true) } + +func runFormalWorkerScenario(t *testing.T, recoverIntent bool) { + root := os.Getenv("KG_R8_RUN") + if root == "" { + t.Skip("requires dedicated r8 real-process isolated deployment") + } + ctx := context.Background() + save := func(name string, value any) { + t.Helper() + raw, e := json.MarshalIndent(value, "", " ") + if e != nil { + t.Fatal(e) + } + if e = os.WriteFile(filepath.Join(root, name), raw, 0600); e != nil { + t.Fatal(e) + } + } + must := func(e error) { + t.Helper() + if e != nil { + t.Fatal(e) + } + } + archiveRoot := filepath.Join(root, "archive") + must(os.MkdirAll(archiveRoot, 0700)) + must(os.MkdirAll(filepath.Join(root, "maintenance"), 0700)) + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true, archiveRoot: archiveRoot, embeddingDimension: 1024}) + seedTargetData(t, fx) + if recoverIntent { + fx.indexDoc(t, "chunk-other", 10001, wsOtherKB, "doc-other", "other KB unchanged") + fx.indexDoc(t, "chunk-foreign", 20000, "kb-foreign", "doc-foreign", "other tenant unchanged") + } + objectInventory := func() *s3.ListObjectVersionsOutput { + t.Helper() + v, e := fx.objects.s3.client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(fx.bucket)}) + must(e) + if aws.ToBool(v.IsTruncated) || len(v.DeleteMarkers) != 0 { + t.Fatal("incomplete inventory or unexpected delete markers") + } + return v + } + originalObjects := objectInventory() + save("objects-before.json", originalObjects) + + // These tables are the real stack's metadata contract, absent in the narrower + // adapter fixture. No business data/schema outside this new test DB is touched. + _, e := fx.pool.Exec(ctx, `ALTER TABLE knowledge_bases ADD COLUMN embedding_model_id text, ADD COLUMN vector_store_id text; + CREATE TABLE models(id text PRIMARY KEY,name text,parameters jsonb,deleted_at timestamptz); + CREATE TABLE vector_stores(id text PRIMARY KEY,engine_type text,index_config jsonb,deleted_at timestamptz); + INSERT INTO models VALUES('r8-model','text-embedding-v4','{"embedding_parameters":{"dimension":1024}}',NULL); + INSERT INTO vector_stores VALUES('r8-vector','elasticsearch_v8','{}',NULL); + UPDATE knowledge_bases SET embedding_model_id='r8-model',vector_store_id='r8-vector';`) + must(e) + before := universeDump(t, fx.pool) + save("pg-before.json", before) + target := fx.target(t) + mapping, e := target.Search().MappingSHA256(ctx) + must(e) + // Seal a fresh, internally consistent fixture contract; historical seals stay unchanged. + source := sealSourceSnapshot(t, fx, nil) + archive, e := librarysnapshot.Open(archiveRoot, 256<<20) + must(e) + manifest, e := archive.Load(source) + must(e) + manifest.Compatibility.EmbeddingDimension = 1024 + manifest.Compatibility.IndexMappingSHA256 = mapping + snapshot, e := archive.Seal(manifest) + must(e) + archive.Close() + govDSN := os.Getenv("KG_R8_GOVERNANCE_DSN") + gov, e := pgxpool.New(ctx, govDSN) + must(e) + t.Cleanup(gov.Close) + must(postgresstore.ApplyMigrations(ctx, gov)) + _, e = gov.Exec(ctx, objectgateway.Schema) + must(e) + reader := gatewayReadOnlyGovernance(t, ctx, gov, govDSN) + project := os.Getenv("KG_R8_PROJECT") + workerElastic := fx.searchBase + if recoverIntent && os.Getenv("KG_R9_FAULT") != "" { + workerElastic = formalElasticFaultProxy(t, root, fx.searchBase, os.Getenv("KG_R9_FAULT")) + } + env := map[string]string{ + "KG_LIBRARY_TEST_ISOLATED": "1", "DATABASE_URL": govDSN, "LIBRARY_WORKER_ROLE": "release-executor", "WORKER_POLL_INTERVAL": "100ms", "WORKER_LEASE_DURATION": "4s", + "PRODUCTION_RELEASE_REQUESTS_ENABLED": "true", "PRODUCTION_BACKUP_RESTORE_VERIFIED": "true", + "LIBRARY_ARCHIVE_ROOT": archiveRoot, "LIBRARY_CAPACITY_BUDGET_BYTES": "1073741824", + "LIBRARY_PRODUCTION_DATABASE_URL": os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), "LIBRARY_PRODUCTION_ELASTIC_URL": workerElastic, "LIBRARY_PRODUCTION_INDEX": fx.index, + "LIBRARY_PRODUCTION_TENANT_ID": "10001", "LIBRARY_PRODUCTION_KB_INTERNAL": wsTargetKB, + "LIBRARY_PRODUCTION_S3_PROVIDER": "minio", "LIBRARY_PRODUCTION_S3_ENDPOINT": os.Getenv("KG_LIBRARY_TEST_S3_ENDPOINT"), "LIBRARY_PRODUCTION_S3_BUCKET": fx.bucket, + "LIBRARY_PRODUCTION_S3_ACCESS_KEY": os.Getenv("KG_R8_READER_KEY"), "LIBRARY_PRODUCTION_S3_SECRET_KEY": os.Getenv("KG_R8_READER_SECRET"), + "LIBRARY_TARGET_INSTANCE": project, "LIBRARY_TARGET_PROJECT": project, "LIBRARY_TARGET_WRITERS": "writer", + "LIBRARY_TARGET_NON_WRITERS": "ingress=entry gate,redis=queue,minio=object backend", + "LIBRARY_TARGET_INGRESS_URL": os.Getenv("KG_R8_INGRESS"), "LIBRARY_TARGET_INGRESS_SERVICE": "ingress", "LIBRARY_TARGET_INGRESS_DRAIN_FILE": filepath.Join(root, "gate/drain.json"), + "LIBRARY_TARGET_REDIS_ADDR": os.Getenv("KG_R8_REDIS_ADDR"), "LIBRARY_TARGET_REDIS_PASSWORD": os.Getenv("KG_R8_REDIS_PASSWORD"), "LIBRARY_TARGET_REDIS_DB": "0", + "LIBRARY_TARGET_JOURNAL_ROOT": filepath.Join(root, "maintenance"), "LIBRARY_EMBEDDING_DIMENSION": "1024", + "KG_TEST_BARRIER_DIR": filepath.Join(root, "barriers"), "KG_TEST_BARRIER_POINTS": "after:database,after:resources", "KG_TEST_BARRIER_TIMEOUT": "180s", + } + env["PRODUCTION_RELEASE_AUTHORIZER_REF"] = project + env["PRODUCTION_RELEASE_AUTH_TOKEN_FILE"] = filepath.Join(root, "authorization-token") + must(os.WriteFile(env["PRODUCTION_RELEASE_AUTH_TOKEN_FILE"], []byte(objectgateway.Digest([]byte(root+"approval"))), 0600)) + cfg, e := appconfig.Load(func(k string) string { return env[k] }) + must(e) + dataToken := objectgateway.Digest([]byte(root + "data")) + controlToken := objectgateway.Digest([]byte(root + "control")) + env["LIBRARY_OBJECT_GATEWAY_URL"] = "http://" + os.Getenv("KG_R8_GATEWAY_ADDR") + env["LIBRARY_OBJECT_GATEWAY_TOKEN"] = dataToken + // Independently prove worker's object identity cannot PUT, before any job exists. + readStore, e := NewS3ObjectStore(S3ObjectStoreConfig{Provider: "minio", Endpoint: env["LIBRARY_PRODUCTION_S3_ENDPOINT"], Bucket: fx.bucket, AccessKeyID: env["LIBRARY_PRODUCTION_S3_ACCESS_KEY"], SecretAccessKey: env["LIBRARY_PRODUCTION_S3_SECRET_KEY"], Region: "us-east-1", ForcePathStyle: true}) + must(e) + allowedRead, e := readStore.Open(ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, 10001, "res-target")) + must(e) + allowedBody, e := io.ReadAll(allowedRead) + allowedRead.Close() + must(e) + if !bytes.Equal(allowedBody, []byte("12345678")) { + t.Fatal("readonly identity could not read original bytes") + } + denied := readStore.Put(ctx, "minio", wsLocator("backend-target", "minio", fx.bucket, 10001, "r8-denied"), bytes.NewReader([]byte("denied")), 6) + if denied == nil { + t.Fatal("worker readonly identity unexpectedly wrote object") + } + save("denial.json", map[string]any{"readonly_put_denied": true}) + scope := objectgateway.Digest([]byte("minio\x00" + env["LIBRARY_PRODUCTION_S3_ENDPOINT"] + "\x00" + fx.bucket)) + pub, priv, e := ed25519.GenerateKey(rand.Reader) + must(e) + digestFile := func(name string) string { + raw, e := os.ReadFile(filepath.Join(root, name)) + must(e) + return objectgateway.Digest(raw) + } + save("writer-inventory.json", map[string]any{"project": project, "worker_object_identity": "readonly", "gateway_only_writer": true, "bucket": fx.bucket, "index": fx.index, "target": cfg.LibraryTargetIdentity()}) + save("policy.json", map[string]any{"worker": "readonly MinIO policy", "isolated_minio": os.Getenv("KG_R8_MINIO"), "scope": scope}) + payload, e := json.Marshal(objectgateway.Attestation{Protocol: objectgateway.Protocol, Scope: scope, GatewayID: project, IssuedAt: time.Now().Add(-time.Second), ExpiresAt: time.Now().Add(50 * time.Minute), WriterInventory: digestFile("writer-inventory.json"), PolicyEvidence: digestFile("policy.json"), DenialEvidence: digestFile("denial.json"), DrainEvidence: digestFile("initial-drain.json")}) + must(e) + signedRaw, e := json.Marshal(objectgateway.SignedAttestation{Payload: payload, Signature: ed25519.Sign(priv, payload)}) + must(e) + must(os.WriteFile(filepath.Join(root, "audit.json"), signedRaw, 0600)) + genv := map[string]string{"OBJECT_GATEWAY_LISTEN": os.Getenv("KG_R8_GATEWAY_ADDR"), "OBJECT_GATEWAY_DATABASE_URL": govDSN, "OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL": reader.Config().ConnString(), "OBJECT_GATEWAY_ARCHIVE_ROOT": archiveRoot, "OBJECT_GATEWAY_TARGET_ID": cfg.LibraryTargetIdentity(), "OBJECT_GATEWAY_PROVIDER": "minio", "OBJECT_GATEWAY_ENDPOINT": env["LIBRARY_PRODUCTION_S3_ENDPOINT"], "OBJECT_GATEWAY_BUCKET": fx.bucket, "OBJECT_GATEWAY_REGION": "us-east-1", "OBJECT_GATEWAY_ACCESS_KEY": os.Getenv("KG_LIBRARY_TEST_S3_ACCESS_KEY"), "OBJECT_GATEWAY_SECRET_KEY": os.Getenv("KG_LIBRARY_TEST_S3_SECRET_KEY"), "OBJECT_GATEWAY_DATA_TOKEN": dataToken, "OBJECT_GATEWAY_CONTROL_TOKEN": controlToken, "OBJECT_GATEWAY_ID": project, "OBJECT_GATEWAY_AUDIT_FILE": filepath.Join(root, "audit.json"), "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY": base64.StdEncoding.EncodeToString(pub)} + if os.Getenv("KG_R8_KEEP_SCENE") == "1" { + // 保留现场时把网关启动所需的审计公钥与两枚派生令牌落到 0600 文件, + // 这样父做 UI 验收期间网关可以独立重启,不需要重跑发布链。 + secrets := fmt.Sprintf("AUDIT_PUBLIC_KEY=%s\nDATA_TOKEN=%s\nCONTROL_TOKEN=%s\nGATEWAY_ID=%s\n", + base64.StdEncoding.EncodeToString(pub), dataToken, controlToken, project) + must(os.WriteFile(filepath.Join(root, "gateway-secrets.env"), []byte(secrets), 0600)) + } + processes := []map[string]any{} + start := func(binary, label string, values map[string]string) *exec.Cmd { + t.Helper() + bin := "r8-bin" + if recoverIntent { + bin = "r9-bin" + } + cmd := exec.Command(filepath.Join(filepath.Dir(root), bin, binary)) + cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} + for k, v := range values { + cmd.Env = append(cmd.Env, k+"="+v) + } + f, e := os.OpenFile(filepath.Join(root, label+".log"), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600) + must(e) + cmd.Stdout = f + cmd.Stderr = f + must(cmd.Start()) + processes = append(processes, map[string]any{"label": label, "pid": cmd.Process.Pid, "binary": binary}) + save("processes.json", processes) + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); f.Close() }) + return cmd + } + start("object-gateway", "gateway", genv) + client, e := objectgateway.NewClient(env["LIBRARY_OBJECT_GATEWAY_URL"], dataToken, scope) + must(e) + ready := false + for i := 0; i < 100; i++ { + if client.ReadyForAcquisition(ctx) == nil { + ready = true + break + } + time.Sleep(100 * time.Millisecond) + } + if !ready { + t.Fatal("gateway not ready; inspect gateway.log") + } + store := postgresstore.NewStore(gov).WithLibraryTarget(cfg.LibraryTargetIdentity()) + now := time.Now().UTC() + digest, e := governance.LibraryRequestDigest("internal", governance.LibraryJobSync, map[string]any{"target_snapshot_id": snapshot}) + must(e) + must(store.CreateLibraryAuthorization(ctx, governance.LibraryReleaseAuthorization{ID: project + "-auth", Scope: "internal", SnapshotID: snapshot, ParamsDigest: digest, ExpiresAt: now.Add(time.Hour), CreatedAt: now})) + op, _, e := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ID: project + "-operation", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: snapshot, RequestDigest: digest, OperationKey: project, CreatedAt: now}) + must(e) + job, _, e := store.CreateLibraryDispatch(ctx, governance.LibraryJob{ID: project + "-job", OperationID: op.ID, Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: snapshot, IdempotencyKey: project, RequestDigest: digest}, governance.SyncStages(), false, now) + must(e) + save("identity.json", map[string]any{"job": job.ID, "operation": job.OperationID, "snapshot": snapshot, "bucket": fx.bucket, "index": fx.index, "target": cfg.LibraryTargetIdentity()}) + checkpoint := func(label string) { + t.Helper() + for _, table := range []string{"jobs", "library_jobs", "library_attempts", "library_operations", "library_versions", "kg_object_gateway_deliveries", "kg_object_gateway_intents", "kg_object_gateway_receipts"} { + var raw []byte + e := gov.QueryRow(ctx, "SELECT COALESCE(jsonb_agg(to_jsonb(t)),'[]') FROM "+table+" t").Scan(&raw) + must(e) + must(os.WriteFile(filepath.Join(root, label+"-"+table+".json"), raw, 0600)) + } + save(label+"-pg.json", universeDump(t, fx.pool)) + save(label+"-objects.json", objectInventory()) + } + if recoverIntent { + env["R9_TARGET_ID"] = cfg.LibraryTargetIdentity() + runRecoveryIntentProcess(t, root, fx, gov, store, job, env, start, checkpoint, save) + return + } + for n, point := range []string{"after-database", "after-resources", "finished"} { + env["WORKER_ID"] = fmt.Sprintf("%s-worker-%d", project, n+1) + cmd := start("worker", fmt.Sprintf("worker-%d", n+1), env) + hit := false + for i := 0; i < 1200; i++ { + current, e := store.LibraryJob(ctx, job.ID) + must(e) + if point == "finished" && current.State == governance.LibraryJobSucceeded { + hit = true + break + } + if point != "finished" { + if _, e = os.Stat(filepath.Join(root, "barriers", point+".hit")); e == nil { + hit = true + break + } + } + if current.State == governance.LibraryJobFailed { + checkpoint(fmt.Sprintf("failed-%d", n+1)) + t.Fatalf("formal worker %d failed: %s", n+1, current.Error) + } + time.Sleep(100 * time.Millisecond) + } + if !hit { + checkpoint(fmt.Sprintf("timeout-%d", n+1)) + t.Fatalf("formal worker %d did not reach %s", n+1, point) + } + checkpoint(fmt.Sprintf("stage-%d", n+1)) + if point != "finished" { + must(cmd.Process.Kill()) + err := cmd.Wait() + status := cmd.ProcessState.Sys().(syscall.WaitStatus) + if !status.Signaled() || status.Signal() != syscall.SIGKILL { + t.Fatalf("expected SIGKILL: %v", err) + } + save(fmt.Sprintf("kill-%d.json", n+1), map[string]any{"pid": cmd.Process.Pid, "signal": "SIGKILL", "exit_code": cmd.ProcessState.ExitCode(), "point": point}) + time.Sleep(5 * time.Second) + } else { + must(cmd.Process.Signal(syscall.SIGTERM)) + must(cmd.Wait()) + save("worker-final-exit.json", map[string]any{"pid": cmd.Process.Pid, "exit_code": cmd.ProcessState.ExitCode()}) + } + } + // Independent final checks; exact rows outside the owned target must survive. + after := universeDump(t, fx.pool) + save("pg-final.json", after) + var docs, attempts, deliveries, receipts int + must(fx.pool.QueryRow(ctx, "SELECT count(*) FROM knowledges WHERE tenant_id=10001 AND knowledge_base_id=$1", wsTargetKB).Scan(&docs)) + if docs != 1 { + t.Fatalf("target documents=%d", docs) + } + must(gov.QueryRow(ctx, "SELECT count(*) FROM library_attempts WHERE job_id=$1", job.ID).Scan(&attempts)) + if attempts != 3 { + t.Fatalf("attempts=%d", attempts) + } + must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries").Scan(&deliveries)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts").Scan(&receipts)) + response, e := http.Get(fx.searchBase + "/" + fx.index + "/_search?size=100") + must(e) + defer response.Body.Close() + var search any + must(json.NewDecoder(response.Body).Decode(&search)) + save("index-final.json", search) + if deliveries != 3 || receipts != 1 { + t.Fatalf("delivery/receipt count mismatch: %d/%d", deliveries, receipts) + } + var receiptRaw []byte + must(gov.QueryRow(ctx, "SELECT receipt FROM kg_object_gateway_receipts").Scan(&receiptRaw)) + var receipt objectgateway.Receipt + must(json.Unmarshal(receiptRaw, &receipt)) + if receipt.Request.Grant.Epoch != 2 || receipt.Request.Key != "10001/res-src/a.png" { + t.Fatal("original send identity changed", receipt.Request) + } + versions, e := (&objectgateway.S3Backend{Client: fx.objects.s3.client, Bucket: fx.bucket, MaxBytes: 1 << 20}).List(ctx, receipt.Request.Key) + must(e) + if len(versions) != 1 || versions[0] != receipt.Version { + t.Fatal("duplicate or changed object version", versions) + } + save("object-final.json", versions) + finalObjects := objectInventory() + save("objects-final.json", finalObjects) + if len(finalObjects.Versions) != len(originalObjects.Versions)+1 { + t.Fatal("unexpected object version growth") + } + for _, beforeVersion := range originalObjects.Versions { + found := false + for _, v := range finalObjects.Versions { + if aws.ToString(v.Key) == aws.ToString(beforeVersion.Key) && aws.ToString(v.VersionId) == aws.ToString(beforeVersion.VersionId) && aws.ToString(v.ETag) == aws.ToString(beforeVersion.ETag) { + found = true + } + } + if !found { + t.Fatal("out-of-plan original version changed", aws.ToString(beforeVersion.Key)) + } + } + a, e := os.ReadFile(filepath.Join(root, "stage-2-kg_object_gateway_receipts.json")) + must(e) + z, e := os.ReadFile(filepath.Join(root, "stage-3-kg_object_gateway_receipts.json")) + must(e) + if !bytes.Equal(a, z) { + t.Fatal("receipt changed across replay") + } + // Original rows of other KBs, other tenants and orphan/shared resources are byte-identical. + for table, rows := range before { + for _, row := range rows { + var item map[string]any + must(json.Unmarshal([]byte(row), &item)) + id, _ := item["id"].(string) + keep := id == "doc-other" || id == "chunk-other" || id == "res-other" || id == "bind-other" || id == "res-orphan" || id == "res-shared" || id == "bind-shared-other" || id == "doc-foreign" || id == "chunk-foreign" || id == "res-foreign" || id == "bind-foreign" + if keep { + found := false + for _, got := range after[table] { + if got == row { + found = true + } + } + if !found { + t.Fatalf("out-of-scope row changed: %s/%s", table, id) + } + } + } + } + for _, table := range []string{"knowledges", "chunks", "resources", "resource_bindings", "wiki_pages"} { + var duplicate int + must(fx.pool.QueryRow(ctx, "SELECT count(*) FROM (SELECT id FROM "+table+" GROUP BY id HAVING count(*)>1) x").Scan(&duplicate)) + if duplicate != 0 { + t.Fatal("duplicate PG identities", table) + } + } + searchMap := search.(map[string]any) + hits := searchMap["hits"].(map[string]any)["hits"].([]any) + if len(hits) != 1 { + t.Fatalf("index documents=%d", len(hits)) + } + hit := hits[0].(map[string]any) + doc := hit["_source"].(map[string]any) + if hit["_id"] != "chunk-src" || doc["knowledge_id"] != "doc-src" || doc["knowledge_base_id"] != wsTargetKB || doc["tenant_id"] != float64(wsTargetTenant) { + t.Fatal("index identity mismatch", hit) + } + var prebackups, effective, plans int + must(gov.QueryRow(ctx, "SELECT count(*) FROM library_versions WHERE kind='production_prebackup'").Scan(&prebackups)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_plans").Scan(&plans)) + must(gov.QueryRow(ctx, "SELECT count(*) FROM library_versions WHERE source_job_id=$1 AND kind='production_effective' AND superseded_at IS NULL", job.ID).Scan(&effective)) + if prebackups != 1 || plans != 1 || effective != 1 { + t.Fatalf("immutable anchors/prebackup/effective %d/%d/%d", plans, prebackups, effective) + } + // Compare delivery plans and exact attempt ownership without changing historic identity. + rows, e := gov.Query(ctx, "SELECT claim,grant_body FROM kg_object_gateway_deliveries ORDER BY attempt_epoch") + must(e) + defer rows.Close() + i := 0 + for rows.Next() { + var cRaw, gRaw []byte + must(rows.Scan(&cRaw, &gRaw)) + var c objectgateway.Claim + var g objectgateway.Grant + must(json.Unmarshal(cRaw, &c)) + must(json.Unmarshal(gRaw, &g)) + i++ + if c.JobID != job.ID || c.OperationID != op.ID || c.AttemptEpoch != int64(i) || g.Epoch != int64(i) || c.PlanDigest != receipt.Request.Grant.Plan { + t.Fatal("delivery replaced original plan/operation") + } + } + must(rows.Err()) + // Latest read must return the original committed bytes, not merely a matching count. + got, e := fx.objects.s3.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(fx.bucket), Key: aws.String(receipt.Request.Key)}) + must(e) + body, e := io.ReadAll(got.Body) + got.Body.Close() + must(e) + if !bytes.Equal(body, []byte("12345678")) { + t.Fatal("latest body mismatch") + } + + save("result.json", map[string]any{"formal_worker_sigkills": 2, "attempts": attempts, "deliveries": deliveries, "receipts": receipts, "job": job.ID, "state": "succeeded", "snapshot": snapshot}) + + // 供 UI 验收保留现场时不做对象清理:这是隔离演练的一次性桶,保留它才能让 + // 页面对真实目标发起恢复。默认(不设该变量)行为不变:断言后精确清理。 + if os.Getenv("KG_R8_KEEP_SCENE") == "1" { + save("scene-retained.json", map[string]any{"bucket": fx.bucket, "versions": len(finalObjects.Versions), + "index": fx.index, "archive_root": archiveRoot, "job": job.ID, "snapshot": snapshot}) + t.Logf("scene retained for UI acceptance: bucket=%s job=%s", fx.bucket, job.ID) + return + } + // Exact version cleanup only after all assertions; failures preserve the bucket. + for _, v := range finalObjects.Versions { + _, e = fx.objects.s3.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(fx.bucket), Key: v.Key, VersionId: v.VersionId}) + must(e) + } + empty := objectInventory() + if len(empty.Versions) != 0 { + t.Fatal("cleanup left object versions") + } + _, e = fx.objects.s3.client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(fx.bucket)}) + must(e) + _, e = fx.objects.s3.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(fx.bucket)}) + var status interface{ HTTPStatusCode() int } + if !errors.As(e, &status) || status.HTTPStatusCode() != 404 { + t.Fatal("bucket absence not independently confirmed", e) + } + save("object-cleanup.json", map[string]any{"bucket": fx.bucket, "versions": 0, "delete_markers": 0, "bucket_absent": true}) + t.Logf("formal worker twice SIGKILL succeeded: job=%s attempts=%d deliveries=%d receipts=%d", job.ID, attempts, deliveries, receipts) +} diff --git a/internal/releaseadapter/v071/gateway_authority.go b/internal/releaseadapter/v071/gateway_authority.go new file mode 100644 index 0000000..b3d41e1 --- /dev/null +++ b/internal/releaseadapter/v071/gateway_authority.go @@ -0,0 +1,137 @@ +package v071 + +import ( + "context" + "errors" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/objectgateway" + "log" + "path/filepath" +) + +// GatewayGovernanceAuthority runs only in the trusted gateway control domain. +// Its governance connection is SELECT-only; the ordinary worker never receives +// the gateway control credential or backend write credential. Archive contents +// are trusted only after their immutable digest is found in the original +// persisted prebackup event belonging to the currently leased attempt. +type GatewayGovernanceAuthority struct { + Pool *pgxpool.Pool + ArchiveRoot string + TargetID string + Provider string + Bucket string +} + +func (a *GatewayGovernanceAuthority) Ready(ctx context.Context) error { + if a == nil || a.Pool == nil || !filepath.IsAbs(a.ArchiveRoot) || a.TargetID == "" || a.Provider == "" || a.Bucket == "" { + return objectgateway.ErrAuthority + } + var safe bool + e := a.Pool.QueryRow(ctx, `SELECT NOT rolsuper AND NOT rolcreatedb AND NOT rolcreaterole FROM pg_roles WHERE rolname=current_user`).Scan(&safe) + if e != nil || !safe { + return objectgateway.ErrAuthorityPrivileges + } + for _, table := range []string{"library_jobs", "library_operations", "library_attempts", "library_versions", "jobs"} { + e = a.Pool.QueryRow(ctx, `SELECT has_table_privilege(current_user,$1,'SELECT') AND NOT has_table_privilege(current_user,$1,'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER')`, table).Scan(&safe) + if e != nil || !safe { + return objectgateway.ErrAuthorityPrivileges + } + } + return nil +} +func (a *GatewayGovernanceAuthority) Load(ctx context.Context, c objectgateway.Claim) (objectgateway.Plan, error) { + if e := a.Ready(ctx); e != nil { + return objectgateway.Plan{}, e + } + if a == nil || a.Pool == nil || !filepath.IsAbs(a.ArchiveRoot) || a.TargetID == "" || a.Provider == "" || a.Bucket == "" { + return objectgateway.Plan{}, objectgateway.ErrAuthority + } + recovery, err := a.verifyRecoveryClaim(ctx, c) + if err != nil { + return objectgateway.Plan{}, err + } + var scope, backup, snapshot string + var matches int + e := a.Pool.QueryRow(ctx, `SELECT j.scope,v.snapshot_id,v.evidence->>'writeset_target_snapshot',count(*) OVER() + FROM library_jobs j + JOIN library_operations o ON o.id=j.operation_id AND o.target_id=j.target_id + JOIN library_attempts a ON a.operation_id=j.operation_id AND a.epoch=j.attempt_epoch AND a.job_id=j.id + JOIN library_versions v ON v.source_job_id=j.id AND v.operation_id=j.operation_id AND v.scope=j.scope AND v.kind='production_prebackup' AND v.target_id=j.target_id + WHERE j.id=$1 AND j.operation_id=$2 AND j.attempt_epoch=$3 AND j.lease_owner=$4 AND j.target_id=$6 + AND j.lease_until>clock_timestamp() AND (j.state='running' OR $7) + AND a.owner=$4 AND a.state IN ('claimed','running') AND a.lease_until>clock_timestamp() + AND v.evidence->>'writeset_digest'=$5 + AND v.evidence->>'job'=j.id AND v.evidence->>'backup_snapshot'=v.snapshot_id + AND (o.target_snapshot_id='' OR o.target_snapshot_id=v.evidence->>'writeset_target_snapshot') + AND NOT EXISTS(SELECT 1 FROM library_attempts newer WHERE newer.operation_id=a.operation_id AND newer.epoch>a.epoch)`, c.JobID, c.OperationID, c.AttemptEpoch, c.Owner, c.PlanDigest, a.TargetID, recovery).Scan(&scope, &backup, &snapshot, &matches) + if errors.Is(e, pgx.ErrNoRows) { + return objectgateway.Plan{}, objectgateway.ErrEpoch + } + if e != nil { + return objectgateway.Plan{}, objectgateway.ErrPersistence + } + if matches != 1 { + log.Printf("gateway authority: claim matches=%d job=%s op=%s epoch=%d", matches, c.JobID, c.OperationID, c.AttemptEpoch) + return objectgateway.Plan{}, objectgateway.ErrConflict + } + set, e := LoadWriteSet(a.ArchiveRoot, c.PlanDigest) + if e != nil || set == nil { + log.Printf("gateway authority: writeset %s unavailable: %v", c.PlanDigest, e) + return objectgateway.Plan{}, objectgateway.ErrConflict + } + if set.Version != libraryrelease.MigrationWriteSetVersion || set.JobID != c.JobID || set.Target != scope || set.BackupSnapshotID != backup || set.TargetSnapshotID != snapshot { + log.Printf("gateway authority: writeset mismatch version=%d/%d job=%s/%s target=%s/%s backup=%s/%s target_snap=%s/%s", + set.Version, libraryrelease.MigrationWriteSetVersion, set.JobID, c.JobID, set.Target, scope, + set.BackupSnapshotID, backup, set.TargetSnapshotID, snapshot) + return objectgateway.Plan{}, objectgateway.ErrConflict + } + for _, obj := range set.Objects { + if obj.Provider != a.Provider || obj.Bucket != a.Bucket { + return objectgateway.Plan{}, objectgateway.ErrConflict + } + } + return ObjectGatewayPlan(*set) +} + +// Recovery authorization does not replace c.JobID/c.OperationID (the original +// send domain). Its separate queue and operation must both be durable, leased, +// and bound to the same before-image, source, target and frozen plan. +func (a *GatewayGovernanceAuthority) verifyRecoveryClaim(ctx context.Context, c objectgateway.Claim) (bool, error) { + if c.RecoveryJobID == "" && c.RecoveryOperationID == "" { + return false, nil + } + if c.RecoveryJobID != governance.LibraryRecoveryQueueID(c.JobID) { + return false, objectgateway.ErrConflict + } + var scope, backup, source, recorded string + e := a.Pool.QueryRow(ctx, `SELECT j.scope,v.snapshot_id,v.evidence->>'writeset_target_snapshot',o.request_digest + FROM library_jobs j JOIN library_versions v ON v.source_job_id=j.id AND v.operation_id=j.operation_id + AND v.target_id=j.target_id AND v.scope=j.scope AND v.kind='production_prebackup' + JOIN jobs q ON q.id=$3 AND q.type='library.recover' AND q.state='running' + JOIN library_operations o ON o.id=$4 AND o.kind='recover' AND o.scope=j.scope AND o.target_id=j.target_id + WHERE j.id=$1 AND j.operation_id=$2 AND j.target_id=$5 + AND q.payload->>'scope'=j.scope AND q.payload->>'window_job_id'=j.id + AND COALESCE(NULLIF(q.payload->>'source_snapshot_id',''),v.evidence->>'writeset_target_snapshot')=v.evidence->>'writeset_target_snapshot' + AND COALESCE(NULLIF(q.payload->>'target_id',''),j.target_id)=j.target_id + AND COALESCE(NULLIF(q.payload->>'original_operation_id',''),j.operation_id)=j.operation_id + AND COALESCE(NULLIF(q.payload->>'backup_snapshot_id',''),v.snapshot_id)=v.snapshot_id + AND COALESCE(NULLIF(q.payload->>'plan_digest',''),$7)=$7 + AND q.idempotency_key='library.recover:'||j.id AND q.lease_until>clock_timestamp() + AND q.lease_owner||'#'||q.id||'#'||q.attempt::text=$6 + AND o.operation_key=q.id AND o.target_snapshot_id=v.snapshot_id + AND v.evidence->>'writeset_digest'=$7`, c.JobID, c.OperationID, c.RecoveryJobID, c.RecoveryOperationID, a.TargetID, c.Owner, c.PlanDigest).Scan(&scope, &backup, &source, &recorded) + if errors.Is(e, pgx.ErrNoRows) { + return false, objectgateway.ErrConflict + } + if e != nil { + return false, objectgateway.ErrPersistence + } + digest, e := governance.LibraryRecoveryDigest(scope, c.RecoveryJobID, c.JobID, c.OperationID, a.TargetID, source, backup, c.PlanDigest) + if e != nil || recorded != digest || c.RecoveryOperationID != governance.LibraryOperationID(scope, governance.LibraryJobRecover, c.RecoveryJobID) { + return false, objectgateway.ErrConflict + } + return true, nil +} diff --git a/internal/releaseadapter/v071/gateway_authority_integration_test.go b/internal/releaseadapter/v071/gateway_authority_integration_test.go new file mode 100644 index 0000000..5b4d1d1 --- /dev/null +++ b/internal/releaseadapter/v071/gateway_authority_integration_test.go @@ -0,0 +1,236 @@ +package v071 + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/objectgateway" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/platform/postgres/pgtest" + "net/http/httptest" + "net/url" + "os" + "sync/atomic" + "testing" + "time" +) + +type gatewayCountBackend struct { + objectgateway.Backend + puts atomic.Int64 +} + +func (b *gatewayCountBackend) Put(ctx context.Context, key string, body []byte, owner string) (objectgateway.Version, error) { + b.puts.Add(1) + return b.Backend.Put(ctx, key, body, owner) +} + +func gatewayReadOnlyGovernance(t *testing.T, ctx context.Context, admin *pgxpool.Pool, dsn string) *pgxpool.Pool { + t.Helper() + random := make([]byte, 24) + if _, e := rand.Read(random); e != nil { + t.Fatal(e) + } + suffix := hex.EncodeToString(random) + role := "kg_gateway_reader_" + suffix[:12] + // This role is created only in the explicitly disposable fixture cluster. + if _, e := admin.Exec(ctx, "CREATE ROLE "+pgx.Identifier{role}.Sanitize()+" LOGIN PASSWORD '"+suffix+"'"); e != nil { + t.Fatal("create isolated reader role failed") + } + var schema string + if admin.QueryRow(ctx, "SELECT current_schema()").Scan(&schema) != nil { + t.Fatal("fixture schema") + } + t.Cleanup(func() { + cleanup := context.Background() + if _, e := admin.Exec(cleanup, "DROP OWNED BY "+pgx.Identifier{role}.Sanitize()); e != nil { + t.Errorf("reader role privilege cleanup failed") + } + if _, e := admin.Exec(cleanup, "DROP ROLE "+pgx.Identifier{role}.Sanitize()); e != nil { + t.Errorf("reader role cleanup failed") + } + }) + if _, e := admin.Exec(ctx, "GRANT USAGE ON SCHEMA "+pgx.Identifier{schema}.Sanitize()+" TO "+pgx.Identifier{role}.Sanitize()); e != nil { + t.Fatal("reader schema grant") + } + if _, e := admin.Exec(ctx, "GRANT SELECT ON library_jobs,library_operations,library_attempts,library_versions,jobs TO "+pgx.Identifier{role}.Sanitize()); e != nil { + t.Fatal("reader table grant") + } + parsed, e := url.Parse(dsn) + if e != nil { + t.Fatal("fixture DSN") + } + parsed.User = url.UserPassword(role, suffix) + config, e := pgxpool.ParseConfig(parsed.String()) + if e != nil { + t.Fatal("reader config") + } + config.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on" + pool, e := pgxpool.NewWithConfig(ctx, config) + if e != nil { + t.Fatal("reader connect") + } + t.Cleanup(pool.Close) + t.Log("isolated SELECT-only governance role created; exact role cleanup registered:", role) + return pool +} + +// This is real authority/PG/HTTP/storage integration, not the formal worker +// process test: no grant decorator or control credential is given to the target. +func TestContractGatewayAuthorityFrozenPlanIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + ctx := fx.ctx + dsn := pgtest.IsolatedDatabaseURL(t, os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")) + governancePool, e := pgxpool.New(ctx, dsn) + if e != nil { + t.Fatal("governance pool") + } + t.Cleanup(governancePool.Close) + if e = postgresstore.ApplyMigrations(ctx, governancePool); e != nil { + t.Fatal(e) + } + if _, e = governancePool.Exec(ctx, objectgateway.Schema); e != nil { + t.Fatal(e) + } + reader := gatewayReadOnlyGovernance(t, ctx, governancePool, dsn) + const jobID = "gateway-authority-job" + const targetID = "gateway-authority-target" + store := postgresstore.NewStore(governancePool).WithLibraryTarget(targetID) + snapshot := sealSourceSnapshot(t, fx, nil) + now := time.Now().UTC() + op := governance.LibraryOperation{ID: "gateway-authority-operation", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: snapshot, RequestDigest: "gateway-authority-params", OperationKey: "gateway-authority-key", CreatedAt: now} + if _, _, e = store.EnsureLibraryOperation(ctx, op); e != nil { + t.Fatal(e) + } + if _, _, e = store.CreateLibraryJob(ctx, governance.LibraryJob{ID: jobID, Scope: "internal", Kind: governance.LibraryJobSync, OperationID: op.ID, IdempotencyKey: jobID, RequestDigest: op.RequestDigest, TargetSnapshotID: snapshot}, governance.SyncStages(), now); e != nil { + t.Fatal(e) + } + attempt, e := store.BeginLibraryAttempt(ctx, jobID, "worker-first", time.Hour, now) + if e != nil { + t.Fatal(e) + } + if _, e = governancePool.Exec(ctx, "UPDATE library_jobs SET state='running' WHERE id=$1", jobID); e != nil { + t.Fatal(e) + } + authority := &GatewayGovernanceAuthority{Pool: reader, ArchiveRoot: fx.archiveRoot, TargetID: targetID, Provider: "minio", Bucket: fx.bucket} + if e = authority.Ready(ctx); e != nil { + t.Fatal(e) + } + privileged := *authority + privileged.Pool = governancePool + if privileged.Ready(ctx) == nil { + t.Fatal("privileged controller reader accepted") + } + backend := &gatewayCountBackend{Backend: &objectgateway.S3Backend{Client: fx.objects.s3.client, Bucket: fx.bucket, MaxBytes: 1 << 20}} + gateway := &objectgateway.Gateway{Pool: governancePool, Scope: fx.bucket, Backend: backend, Authority: authority, MaxBytes: 1 << 20} + data := objectgateway.Digest([]byte("authority-data")) + server := httptest.NewServer(objectgateway.HTTPServer{Gateway: gateway, DataToken: data, ControlToken: objectgateway.Digest([]byte("authority-control"))}) + defer server.Close() + client, e := objectgateway.NewClient(server.URL, data, fx.bucket) + if e != nil { + t.Fatal(e) + } + claim := objectgateway.Claim{JobID: jobID, OperationID: op.ID, AttemptEpoch: int64(attempt.Epoch), Owner: attempt.Owner} + objects := &GatewayObjectStore{Client: client, Provider: "minio", Bucket: fx.bucket, Automatic: true, Claim: claim} + target := fx.target(t) + target.config.Objects = objects + current, e := target.Current(ctx) + if e != nil { + t.Fatal(e) + } + backup, e := fx.backups(t, target).Prepare(ctx, snapshot, current) + if e != nil { + t.Fatal(e) + } + set, e := target.PlanWriteSet(ctx, libraryrelease.WriteSetPlan{JobID: jobID, Target: "internal", BackupSnapshotID: backup.SnapshotID, TargetSnapshotID: snapshot, Universe: backup.Universe}) + if e != nil { + t.Fatal(e) + } + claim.PlanDigest = set.Digest + before := universeDump(t, fx.pool) + if e = target.Apply(ctx, libraryrelease.StageDatabase, snapshot); e == nil { + t.Fatal("unanchored plan permitted first PG write") + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatal("unanchored apply mutated PG", diff) + } + if e = store.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: governance.LibraryVersionEventID(governance.LibraryVersionProductionPrebackup, "internal", backup.SnapshotID, op.ID), Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup, SnapshotID: backup.SnapshotID, SourceJobID: jobID, OperationID: op.ID, AttemptEpoch: attempt.Epoch, AttemptOwner: attempt.Owner, CreatedAt: now, Evidence: map[string]any{"job": jobID, "backup_snapshot": backup.SnapshotID, "backup_bytes": backup.Bytes, "writeset_digest": set.Digest, "writeset_target_snapshot": snapshot}}); e != nil { + t.Fatal(e) + } + for _, bad := range []objectgateway.Claim{{JobID: jobID, OperationID: op.ID, AttemptEpoch: claim.AttemptEpoch, Owner: "other-worker", PlanDigest: set.Digest}, {JobID: jobID, OperationID: op.ID, AttemptEpoch: claim.AttemptEpoch, Owner: claim.Owner, PlanDigest: objectgateway.Digest([]byte("replacement"))}} { + if _, e = client.Acquire(ctx, bad); e == nil { + t.Fatal("untrusted claim admitted") + } + } + if e = target.Apply(ctx, libraryrelease.StageDatabase, snapshot); e != nil { + t.Fatal(e) + } + if e = target.Apply(ctx, libraryrelease.StageResources, snapshot); e != nil { + t.Fatal(e) + } + count := backend.puts.Load() + if count == 0 { + t.Fatal("no actual object send") + } + firstRequests := objects.requests + if e = store.FinishLibraryAttempt(ctx, attempt, governance.LibraryAttemptFailed, "isolated takeover", time.Now().UTC()); e != nil { + t.Fatal(e) + } + next, e := store.BeginLibraryAttempt(ctx, jobID, "worker-second", time.Hour, time.Now().UTC()) + if e != nil { + t.Fatal(e) + } + nextClaim := claim + nextClaim.AttemptEpoch = int64(next.Epoch) + nextClaim.Owner = next.Owner + nextObjects := &GatewayObjectStore{Client: client, Provider: "minio", Bucket: fx.bucket, Automatic: true, Claim: nextClaim} + nextTarget := fx.target(t) + nextTarget.config.Objects = nextObjects + if e = nextTarget.AdoptWriteSet(set); e != nil { + t.Fatal(e) + } + if e = nextObjects.EnsureObjectGrant(ctx); e != nil { + t.Fatal(e) + } + for key, original := range firstRequests { + if nextObjects.requests[key] != original { + t.Fatal("send identity replaced during new epoch", key) + } + } + if nextObjects.authorization.Epoch <= objects.authorization.Epoch { + t.Fatal("authorization did not advance") + } + if _, e = client.Acquire(ctx, claim); !errors.Is(e, objectgateway.ErrEpoch) { + t.Fatal("old active owner admitted", e) + } + if e = nextTarget.Apply(ctx, libraryrelease.StageResources, snapshot); e != nil { + t.Fatal(e) + } + if backend.puts.Load() != count { + t.Fatal("resumed object send duplicated") + } + for _, obj := range set.Objects { + if obj.Existing { + continue + } + locator := obj.Locator + observation, e := nextObjects.ObserveObject(ctx, obj.Provider, locator) + if e != nil { + t.Fatal(e) + } + if e = nextObjects.RemoveObject(ctx, obj.Provider, locator, observation); e != nil { + t.Fatal(e) + } + versions, e := backend.List(ctx, obj.Key) + if e != nil || len(versions) != 0 { + t.Fatal("created object version residue", e) + } + } + t.Logf("real readonly governance authority -> data-only HTTP acquisition -> PG/MinIO; first-PG anchor denial, new epoch unchanged send identity, PUTs=%d, original version exact cleanup", count) +} diff --git a/internal/releaseadapter/v071/gateway_backend.go b/internal/releaseadapter/v071/gateway_backend.go new file mode 100644 index 0000000..0f0d661 --- /dev/null +++ b/internal/releaseadapter/v071/gateway_backend.go @@ -0,0 +1,66 @@ +package v071 + +import ( + "context" + "errors" + + "knowledge-governance/internal/objectgateway" +) + +// NewGatewayBackend is server-side only. Clients never receive this credentialed object. +func NewGatewayBackend(c S3ObjectStoreConfig) (objectgateway.Backend, error) { + if c.Provider == "oss" { + s, e := newOSSVersionStore(c) + if e != nil { + return nil, e + } + return ossGatewayBackend{s}, nil + } + if c.Provider != "s3" && c.Provider != "minio" { + return nil, errors.New("gateway_backend_provider_unsupported") + } + s, e := NewS3ObjectStore(c) + if e != nil { + return nil, e + } + return &objectgateway.S3Backend{Client: s.client, Bucket: s.bucket, MaxBytes: s.maxObjectBytes}, nil +} + +type ossGatewayBackend struct{ s *ossVersionStore } + +func toGateway(v objectObservation) objectgateway.Version { + return objectgateway.Version{ID: v.VersionID, Owner: v.Owner, SHA256: v.SHA256, Bytes: v.Bytes, ETag: v.ETag} +} +func fromGateway(v objectgateway.Version) objectObservation { + return objectObservation{Exists: true, VersionID: v.ID, Owner: v.Owner, SHA256: v.SHA256, Bytes: v.Bytes, ETag: v.ETag} +} +func (b ossGatewayBackend) Ready(ctx context.Context) error { return b.s.versioning(ctx) } +func (b ossGatewayBackend) Observe(ctx context.Context, key, id string) (objectgateway.Version, bool, error) { + v, e := b.s.observeVersion(ctx, key, id) + return toGateway(v), v.Exists, e +} +func (b ossGatewayBackend) Put(ctx context.Context, key string, body []byte, owner string) (objectgateway.Version, error) { + v, e := b.s.appendVersion(ctx, key, body, owner) + return toGateway(v), e +} +func (b ossGatewayBackend) Delete(ctx context.Context, key string, v objectgateway.Version) error { + return b.s.removeVersion(ctx, key, fromGateway(v)) +} +func (b ossGatewayBackend) List(ctx context.Context, key string) ([]objectgateway.Version, error) { + listing, e := b.s.listExactVersions(ctx, key) + if e != nil { + return nil, e + } + if len(listing.DeleteMarkers) != 0 { + return nil, errors.New("gateway_backend_delete_marker_conflict") + } + var out []objectgateway.Version + for _, v := range listing.Versions { + o, e := b.s.observeVersion(ctx, key, v.VersionID) + if e != nil || !o.Exists { + return nil, errors.New("gateway_backend_listing_changed") + } + out = append(out, toGateway(o)) + } + return out, nil +} diff --git a/internal/releaseadapter/v071/gateway_grant.go b/internal/releaseadapter/v071/gateway_grant.go new file mode 100644 index 0000000..4aad64f --- /dev/null +++ b/internal/releaseadapter/v071/gateway_grant.go @@ -0,0 +1,49 @@ +package v071 + +import ( + "context" + "encoding/json" + "errors" + "path/filepath" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/objectgateway" +) + +// PrepareObjectGatewayGrant runs only in the trusted control plane. The data +// worker receives the immutable grant file, never the control bearer token. +// Replay uses the original expected epoch; it does not guess the latest epoch. +func PrepareObjectGatewayGrant(ctx context.Context, client *objectgateway.Client, set libraryrelease.WriteSet, expected int64, provider, bucket, directory string) error { + if client == nil || !filepath.IsAbs(directory) || expected < 0 { + return errors.New("gateway grant controller configuration invalid") + } + plan, e := ObjectGatewayPlan(set) + if e != nil { + return e + } + for _, obj := range set.Objects { + if obj.Provider != provider || obj.Bucket != bucket { + return errors.New("gateway grant target does not match frozen object plan") + } + } + grant := objectgateway.Grant{Epoch: expected + 1, Owner: plan.Owner, Plan: plan.Digest} + if grant.Epoch < 1 { + return errors.New("gateway epoch exhausted") + } + raw, e := json.Marshal(grant) + if e != nil { + return e + } + if e = persistImmutableJSON(filepath.Join(directory, set.Digest+".intent.json"), raw); e != nil { + return e + } + // Network outcomes may be unknown. Both endpoints compare immutable identity + // on a repeat, so no caller invents another epoch or another operation ID. + if e = client.InstallPlan(ctx, plan); e != nil { + return e + } + if e = client.Advance(ctx, expected, grant); e != nil { + return e + } + return persistImmutableJSON(filepath.Join(directory, set.Digest+".json"), raw) +} diff --git a/internal/releaseadapter/v071/gateway_object_store.go b/internal/releaseadapter/v071/gateway_object_store.go new file mode 100644 index 0000000..6edc48d --- /dev/null +++ b/internal/releaseadapter/v071/gateway_object_store.go @@ -0,0 +1,256 @@ +package v071 + +import ( + "context" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "strings" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/objectgateway" +) + +// GatewayObjectStore has no write credentials or direct-write fallback. The +// separate reader must be deployed with read-only rights (audit prerequisite). +type GatewayObjectStore struct { + Automatic bool + Claim objectgateway.Claim + frozen *libraryrelease.WriteSet + authorization objectgateway.Grant + Client *objectgateway.Client + Provider, Bucket, GrantDirectory string + requests map[string]objectgateway.Request + owners map[string]string +} + +func (s *GatewayObjectStore) ConditionalCapability(ctx context.Context) error { + if s.Client == nil || s.Provider == "" || s.Bucket == "" || (!s.Automatic && !filepath.IsAbs(s.GrantDirectory)) { + return errors.New("object gateway configuration/grant directory missing") + } + if s.Automatic { + return s.Client.ReadyForAcquisition(ctx) + } + return s.Client.Ready(ctx) +} + +// ObjectGatewayPlan derives the controller allowlist from the verified original +// write set. Existing shared objects remain read-only, never write-authorized. +func ObjectGatewayPlan(set libraryrelease.WriteSet) (objectgateway.Plan, error) { + if err := set.Verify(); err != nil { + return objectgateway.Plan{}, err + } + p := objectgateway.Plan{Digest: set.Digest, Owner: objectgateway.Digest([]byte(set.JobID))} + for _, obj := range set.Objects { + if !obj.Existing { + p.Objects = append(p.Objects, objectgateway.ObjectBinding{Operation: gatewayCreateOperation(set.Digest, obj.OwnerToken), Key: obj.Key, SHA256: obj.SHA256, Bytes: obj.Bytes}) + } + } + return p, nil +} +func gatewayCreateOperation(plan, owner string) string { + return objectgateway.Digest([]byte(plan + "\x00" + owner + "\x00create")) +} + +// OwnedAttemptClaim 暴露本装配冻结的 attempt claim:受限演练计划/回放必须与它一致。 +func (s *GatewayObjectStore) OwnedAttemptClaim() (objectgateway.Claim, bool) { + return s.Claim, s.Automatic +} + +func (s *GatewayObjectStore) BindObjectPlan(set libraryrelease.WriteSet) error { + if !validLowerSHA256(set.Digest) || set.JobID == "" { + return errors.New("gateway frozen plan identity missing") + } + if _, e := ObjectGatewayPlan(set); e != nil { + return e + } + if s.frozen != nil && s.frozen.Digest != set.Digest { + return errors.New("gateway store cannot replace frozen identity") + } + if s.Automatic { + if s.frozen == nil { + copy := set + s.frozen = © + } + return nil + } + path := filepath.Join(s.GrantDirectory, set.Digest+".json") + info, e := os.Lstat(path) + if e != nil || !info.Mode().IsRegular() || info.Size() > 4096 || info.Mode().Perm()&0022 != 0 { + return errors.New("gateway controller grant unavailable") + } + raw, e := os.ReadFile(path) + if e != nil { + return errors.New("gateway controller grant unavailable") + } + var grant objectgateway.Grant + if json.Unmarshal(raw, &grant) != nil || grant.Epoch < 1 || grant.Plan != set.Digest || grant.Owner != objectgateway.Digest([]byte(set.JobID)) { + return errors.New("gateway controller grant differs from frozen job/plan") + } + return s.bindGrant(context.Background(), set, grant) +} +func (s *GatewayObjectStore) EnsureObjectGrant(ctx context.Context) error { + if !s.Automatic || s.requests != nil { + return nil + } + if s.frozen == nil || s.Claim.JobID != s.frozen.JobID { + return errors.New("gateway active attempt/frozen plan missing") + } + claim := s.Claim + claim.PlanDigest = s.frozen.Digest + grant, e := s.Client.Acquire(ctx, claim) + if e != nil { + return e + } + return s.bindGrant(ctx, *s.frozen, grant) +} +func (s *GatewayObjectStore) bindGrant(ctx context.Context, set libraryrelease.WriteSet, grant objectgateway.Grant) error { + requests := map[string]objectgateway.Request{} + owners := map[string]string{} + for _, obj := range set.Objects { + if obj.Provider != s.Provider || obj.Bucket != s.Bucket { + return errors.New("gateway plan target mismatch") + } + if obj.Existing { + continue + } + req := objectgateway.Request{Grant: grant, Operation: gatewayCreateOperation(set.Digest, obj.OwnerToken), Key: obj.Key, Action: "create", SHA256: obj.SHA256, Bytes: obj.Bytes} + original, e := s.Client.Resolve(ctx, req) + if e != nil { + return e + } + requests[obj.Key] = original + owners[obj.Key] = obj.OwnerToken + } + s.authorization = grant + s.requests = requests + s.owners = owners + return nil +} +func (s *GatewayObjectStore) key(provider, locator string) (string, error) { + if provider != s.Provider || !validObjectKey(locator) { + return "", errors.New("gateway provider/locator mismatch") + } + parts := strings.SplitN(strings.TrimPrefix(locator, "storage://"), "/", 2) + if !strings.HasPrefix(locator, "storage://") || len(parts) != 2 || parts[0] == "" { + return "", errors.New("gateway explicit locator required") + } + prefix := s.Provider + "://" + s.Bucket + "/" + if !strings.HasPrefix(parts[1], prefix) { + return "", errors.New("gateway bucket mismatch") + } + key := strings.TrimPrefix(parts[1], prefix) + if key == "" { + return "", errors.New("gateway key missing") + } + return key, nil +} +func (s *GatewayObjectStore) ObserveObject(ctx context.Context, provider, locator string) (objectObservation, error) { + if s.frozen != nil { + if e := s.EnsureObjectGrant(ctx); e != nil { + return objectObservation{}, e + } + } + key, e := s.key(provider, locator) + if e != nil { + return objectObservation{}, e + } + v, exists, e := s.Client.Observe(ctx, key, "") + if e != nil { + return objectObservation{}, e + } + if !exists { + return objectObservation{}, nil + } + o := fromGateway(v) + if req, ok := s.requests[key]; ok && v.Owner == req.Claim() { + o.Owner = s.owners[key] + } + return o, nil +} +func (s *GatewayObjectStore) CreateObject(ctx context.Context, provider, locator string, body io.Reader, size int64, owner string) error { + if e := s.EnsureObjectGrant(ctx); e != nil { + return e + } + key, e := s.key(provider, locator) + if e != nil { + return e + } + r, ok := s.requests[key] + if !ok || owner != s.owners[key] || size != r.Bytes { + return errObjectWriteRejected + } + raw, e := io.ReadAll(io.LimitReader(body, size+1)) + if e != nil || int64(len(raw)) != size || objectgateway.Digest(raw) != r.SHA256 { + return errObjectWriteRejected + } + receipt, e := s.Client.ExecuteAuthorized(ctx, s.authorization, r, raw) + if e != nil { + return e + } + if receipt.State == "rejected" { + return errObjectWriteRejected + } + if receipt.State != "committed" { + return errors.New("gateway create not committed") + } + return nil +} +func (s *GatewayObjectStore) RemoveObject(ctx context.Context, provider, locator string, want objectObservation) error { + if e := s.EnsureObjectGrant(ctx); e != nil { + return e + } + key, e := s.key(provider, locator) + if e != nil { + return e + } + create, ok := s.requests[key] + if !ok || want.Owner != s.owners[key] { + return errors.New("gateway cleanup lacks frozen ownership") + } + receipt, e := s.Client.Reconcile(ctx, create) + if e != nil { + return e + } + raw := want + raw.Owner = create.Claim() + if receipt.State != "committed" || receipt.Version != toGateway(raw) { + return errors.New("gateway cleanup receipt mismatch") + } + req := create + req.Grant = s.authorization + req.Operation = objectgateway.Digest([]byte(create.Operation + "\x00delete")) + req.Action = "delete" + req.CreatedBy = create.Operation + req.Version = receipt.Version + original, e := s.Client.Resolve(ctx, req) + if e != nil { + return e + } + deleted, e := s.Client.ExecuteAuthorized(ctx, s.authorization, original, nil) + if e != nil { + return e + } + if deleted.State != "removed" { + return errors.New("gateway deletion not confirmed") + } + return nil +} +func (s *GatewayObjectStore) Put(context.Context, string, string, io.Reader, int64) error { + return errors.New("gateway refuses unplanned Put; frozen object plan required") +} +func (s *GatewayObjectStore) Copy(context.Context, string, string, string) error { + return errors.New("gateway refuses unplanned Copy; frozen object plan required") +} +func (s *GatewayObjectStore) Stat(ctx context.Context, provider, locator string) (int64, string, error) { + o, e := s.ObserveObject(ctx, provider, locator) + if e != nil { + return 0, "", e + } + if !o.Exists { + return 0, "", errors.New("gateway object absent") + } + return o.Bytes, o.SHA256, nil +} diff --git a/internal/releaseadapter/v071/gateway_object_store_test.go b/internal/releaseadapter/v071/gateway_object_store_test.go new file mode 100644 index 0000000..1a1d49d --- /dev/null +++ b/internal/releaseadapter/v071/gateway_object_store_test.go @@ -0,0 +1,82 @@ +package v071 + +import ( + "context" + "net/http/httptest" + "testing" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/objectgateway" +) + +// Test controller issues the grant only after the saga has frozen its actual +// plan. Production controller delivery is a separate integration prerequisite. +type gatewayFixtureController struct { + *GatewayObjectStore + control *objectgateway.Client +} + +func (s *gatewayFixtureController) BindObjectPlan(set libraryrelease.WriteSet) error { + if e := PrepareObjectGatewayGrant(context.Background(), s.control, set, 0, s.Provider, s.Bucket, s.GrantDirectory); e != nil { + return e + } + return s.GatewayObjectStore.BindObjectPlan(set) +} +func TestContractGatewayActualSagaRollbackIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, e := fx.pool.Exec(fx.ctx, objectgateway.Schema); e != nil { + t.Fatal(e) + } + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + gateway := &objectgateway.Gateway{Pool: fx.pool, Scope: fx.bucket, Backend: &objectgateway.S3Backend{Client: fx.objects.s3.client, Bucket: fx.bucket, MaxBytes: 1 << 20}, MaxBytes: 1 << 20} + token := objectgateway.Digest([]byte("data-fixture")) + server := httptest.NewServer(objectgateway.HTTPServer{Gateway: gateway, DataToken: token, ControlToken: objectgateway.Digest([]byte("control-fixture"))}) + defer server.Close() + client, e := objectgateway.NewClient(server.URL, token, fx.bucket) + if e != nil { + t.Fatal(e) + } + store := &GatewayObjectStore{Client: client, Provider: "minio", Bucket: fx.bucket, GrantDirectory: t.TempDir()} + control, e := objectgateway.NewClient(server.URL, objectgateway.Digest([]byte("control-fixture")), fx.bucket) + if e != nil { + t.Fatal(e) + } + target.config.Objects = &gatewayFixtureController{store, control} + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, fx.backups(t, target), nil) + if outcome.State != "rolled_back" { + t.Fatalf("actual gateway saga: %+v", outcome) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatal(diff) + } + key := wsLocator("backend-target", "minio", fx.bucket, wsTargetTenant, "res-src") + observed, e := store.ObserveObject(fx.ctx, "minio", key) + if e != nil || observed.Exists { + t.Fatal("gateway object residue", e) + } + physical, e := store.key("minio", key) + if e != nil { + t.Fatal(e) + } + versions, e := gateway.Backend.List(fx.ctx, physical) + if e != nil || len(versions) != 0 { + t.Fatal("exact created key version residue", e) + } + var n int + if fx.pool.QueryRow(fx.ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE scope=$1", fx.bucket).Scan(&n) != nil || n != 2 { + t.Fatalf("gateway saga receipts=%d", n) + } + t.Log("actual release.Run -> plan adoption -> gateway HTTP -> PG/MinIO -> late Wiki failure -> exact-version rollback; all original PG rows retained") +} +func TestGatewayUnplannedWriteNeverFallsBack(t *testing.T) { + store := &GatewayObjectStore{} + if store.Put(context.Background(), "oss", "key", nil, 0) == nil || store.Copy(context.Background(), "oss", "from", "to") == nil { + t.Fatal("unplanned direct-write fallback") + } + if store.BindObjectPlan(libraryrelease.WriteSet{}) == nil { + t.Fatal("unbound plan accepted") + } +} diff --git a/internal/releaseadapter/v071/graph_gate_test.go b/internal/releaseadapter/v071/graph_gate_test.go new file mode 100644 index 0000000..75ce144 --- /dev/null +++ b/internal/releaseadapter/v071/graph_gate_test.go @@ -0,0 +1,26 @@ +package v071 + +import ( + "errors" + "strings" + "testing" +) + +// 目标开图谱 = 拒绝发布(本模块只写 PG/ES/OSS,不写 Neo4j)。 +func TestVerifyTargetGraphGateRefusesGraphEnabledTarget(t *testing.T) { + if err := verifyTargetGraphGate(false, nil); err != nil { + t.Fatalf("graph disabled must allow publish, got %v", err) + } + err := verifyTargetGraphGate(true, nil) + if err == nil || !strings.Contains(err.Error(), "graph_enabled") { + t.Fatalf("graph enabled must refuse with graph_enabled reason, got %v", err) + } +} + +// 读不到开关也是未知 → 拒绝(不能把"未知"当成"没开")。 +func TestVerifyTargetGraphGateFailsClosedWhenUnknown(t *testing.T) { + err := verifyTargetGraphGate(false, errors.New("connection reset")) + if err == nil || !strings.Contains(err.Error(), "未知") { + t.Fatalf("unknown graph state must fail closed, got %v", err) + } +} diff --git a/internal/releaseadapter/v071/index_mapping.go b/internal/releaseadapter/v071/index_mapping.go new file mode 100644 index 0000000..fde09da --- /dev/null +++ b/internal/releaseadapter/v071/index_mapping.go @@ -0,0 +1,35 @@ +package v071 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" +) + +// IndexMappingDigest 与线上读取路径(SearchExporter.inspectMapping)用同一套规范化: +// 取 ES `/{index}/_mapping` 响应里该索引的 mappings,规范 JSON 后取 sha256。 +// +// 单独暴露它是为了能用**真实抓下来的映射**证明摘要可算,并证明 0.7.1 与 0.9.0 +// 的映射是两个不同契约(不能因为"都是 1024 维"就当同一份)。 +func IndexMappingDigest(raw []byte) (string, error) { + var response map[string]json.RawMessage + if err := json.Unmarshal(raw, &response); err != nil || len(response) != 1 { + return "", errors.New("Elasticsearch mapping response is invalid") + } + for _, indexRaw := range response { + var index struct { + Mappings json.RawMessage `json:"mappings"` + } + if err := json.Unmarshal(indexRaw, &index); err != nil || len(index.Mappings) == 0 { + return "", errors.New("Elasticsearch mapping response is invalid") + } + canonical, err := canonicalJSON(index.Mappings) + if err != nil { + return "", errors.New("Elasticsearch mapping response is invalid") + } + digest := sha256.Sum256(canonical) + return hex.EncodeToString(digest[:]), nil + } + return "", errors.New("Elasticsearch mapping response is invalid") +} diff --git a/internal/releaseadapter/v071/legacy_object_gate_test.go b/internal/releaseadapter/v071/legacy_object_gate_test.go new file mode 100644 index 0000000..60d68f4 --- /dev/null +++ b/internal/releaseadapter/v071/legacy_object_gate_test.go @@ -0,0 +1,27 @@ +package v071 + +import ( + "context" + "testing" +) + +func TestLegacyObjectImporterCannotStageOrPromote(t *testing.T) { + data := []byte("hello") + snapshot := ObjectSnapshot{Objects: []AssetObject{{ResourceID: "res-1", Handle: "ABCDEFGHIJKLMNOPQRSTUV", Provider: "minio", PhysicalPath: "storage://source-backend/10000/knowledge/source.txt", Size: 5, SHA256: shaBytes(data), Data: data}}, TotalBytes: 5} + snapshot.SHA256 = objectSnapshotDigest(snapshot.Objects) + store := &fakeObjectStore{objects: map[string][]byte{}} + importer, e := NewObjectImporter(store, TargetObjectConfig{StorageBackendID: "target-backend", Provider: "minio"}) + if e != nil { + t.Fatal(e) + } + if _, e = importer.Stage(context.Background(), "legacy-bypass", snapshot); e == nil { + t.Fatal("legacy importer emitted unplanned stage PUT") + } + stage := ObjectStage{ReleaseRevision: "legacy-bypass", Provider: "minio", Objects: []StagedObject{{Handle: snapshot.Objects[0].Handle, StagingPath: "stage/object", FinalPath: "target/object", Size: 5, SHA256: shaBytes(data)}}} + if e = importer.Promote(context.Background(), stage); e == nil { + t.Fatal("legacy importer emitted unplanned promotion COPY") + } + if len(store.objects) != 0 { + t.Fatal("legacy importer mutated object store") + } +} diff --git a/internal/releaseadapter/v071/library_archive.go b/internal/releaseadapter/v071/library_archive.go index 750fa48..1b11ac6 100644 --- a/internal/releaseadapter/v071/library_archive.go +++ b/internal/releaseadapter/v071/library_archive.go @@ -22,6 +22,12 @@ func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archi if err := validateLibraryCandidate(identity, pg, es); err != nil { return "", err } + return archiveLibraryRows(ctx, archive, scope, identity, contract, pg, es, objects, createdAt) +} + +// Private: callers must distinguish a validated source candidate from raw +// target before-images. Never run source semantic filtering on recovery bytes. +func archiveLibraryRows(ctx context.Context, archive *librarysnapshot.Archive, scope string, identity PostgresIdentity, contract librarysnapshot.Compatibility, pg PostgresSnapshot, es SearchSnapshot, objects ObjectReader, createdAt time.Time) (string, error) { // 空生产基线:索引不存在时没有映射可比,契约仍按目标快照记录; // 只要这次导出的文档是零条,就不存在"拿错映射"的风险。 emptyIndex := len(es.Documents) == 0 @@ -43,6 +49,15 @@ func ArchiveLibraryCandidate(ctx context.Context, archive *librarysnapshot.Archi manifest.Parts = append(manifest.Parts, p) return nil } + if pg.Catalog != nil { + raw, err := json.Marshal(pg.Catalog) + if err != nil { + return "", err + } + if err = put("schema", "migration-catalog", 1, raw); err != nil { + return "", err + } + } for _, table := range pg.Tables { rows := table.Rows if rows == nil { @@ -124,19 +139,25 @@ type libraryRow struct { Content string `json:"content"` Title string `json:"title"` ChunkType string `json:"chunk_type"` - ChunkStatus int `json:"-"` + ParentChunkID string `json:"parent_chunk_id"` SourceID string `json:"source_id"` Questions map[string]string `json:"-"` } func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es SearchSnapshot) error { - required := map[string]bool{"resources": true} - for _, entry := range libraryContentQueries { - required[entry.name] = true + // 必需表来自 profile,不是固定清单:0.9.0 没有 wiki_log_entries 就不要求它, + // 但只要表在 profile 里是必需的,缺了就必须失败。 + profile, err := pg.schemaProfile() + if err != nil { + return err + } + required := map[string]bool{} + for _, name := range profile.RequiredTables { + required[name] = true } tables := map[string]map[string]libraryRow{} for _, table := range pg.Tables { - if !required[table.Name] || tables[table.Name] != nil || table.RowCount != len(table.Rows) || table.SHA256 != newTableSnapshot(table.Name, table.Rows).SHA256 { + if !profile.HasTable(table.Name) || tables[table.Name] != nil || table.RowCount != len(table.Rows) || table.SHA256 != newTableSnapshot(table.Name, table.Rows).SHA256 { return errors.New("invalid library table inventory") } rows := map[string]libraryRow{} @@ -162,11 +183,10 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es if json.Unmarshal(raw, &row) != nil { return errors.New("invalid library content row") } - // Status is table-specific: chunks use integers, Wiki pages/issues - // use strings. Decode chunk metadata only for its owning table. + // Decode chunk metadata only for its owning table; question metadata + // remains an integrity check, while index coverage is source-owned. if table.Name == "chunks" { var metadata struct { - Status int `json:"status"` Metadata struct { GeneratedQuestions []struct { ID string `json:"id"` @@ -177,7 +197,6 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es if json.Unmarshal(raw, &metadata) != nil { return errors.New("invalid library chunk status") } - row.ChunkStatus = metadata.Status row.Questions = map[string]string{} for _, question := range metadata.Metadata.GeneratedQuestions { sourceID := row.ID + "-" + question.ID @@ -211,10 +230,21 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es return errors.New("missing library table") } } + if err := validateLibraryStructuredReferences(pg); err != nil { + return err + } for _, chunk := range tables["chunks"] { if _, ok := tables["knowledges"][chunk.KnowledgeID]; !ok { return errors.New("orphan library chunk") } + // A parent link must point at a real parent chunk of the same document; + // standalone text has an empty field and is never forced into a relation. + if chunk.ParentChunkID != "" { + parent, ok := tables["chunks"][chunk.ParentChunkID] + if !ok || parent.KnowledgeID != chunk.KnowledgeID { + return errors.New("invalid library parent chunk reference") + } + } } for _, relation := range tables["knowledge_tag_relations"] { _, hasKnowledge := tables["knowledges"][relation.KnowledgeID] @@ -243,10 +273,14 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es handles[resource.Handle] = true } var bodies []json.RawMessage - for _, name := range []string{"knowledges", "chunks", "wiki_pages"} { - bodies = append(bodies, pg.Table(name).Rows...) + for _, table := range pg.Tables { + bodies = append(bodies, table.Rows...) } - for _, handle := range referencedResourceHandles(bodies) { + references, err := libraryResourceHandles(bodies) + if err != nil { + return err + } + for _, handle := range references { if !handles[handle] { return errors.New("unresolved library resource") } @@ -261,7 +295,6 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es return errors.New("invalid library index digest") } seen := map[string]bool{} - indexedChunks := map[string]bool{} indexedQuestions := map[string]map[string]bool{} for _, document := range es.Documents { var row libraryRow @@ -291,27 +324,17 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es if strings.TrimSpace(row.Content) == "" { return errors.New("empty library index content") } - indexedChunks[row.ChunkID] = true } } - // v0.7.1 ChunkStatusIndexed is 2. One chunk can have several search - // records, so compare identities rather than counts. Stored-only parent - // chunks intentionally have no index and must not be rejected as missing. - // Text ingestion also leaves indexed chunks at the legacy default status - // zero. Without an archived no-index policy, absence is unverified, not - // proof that indexing was disabled. Parent chunks are context-only. + // 原文索引是源端自己的选择:治理不根据 status/type/parent 推断某个 + // chunk “必须有”基础正文记录。问题索引仍按 source_id 精确核对,防止 + // 把问题记录冒充正文或漏掉问题;正文、向量按实际导出集合原样保存。 for id, chunk := range tables["chunks"] { for sourceID := range chunk.Questions { if !indexedQuestions[id][sourceID] { return errors.New("missing library generated question index") } } - if chunk.ChunkStatus == 0 && chunk.ChunkType != "parent_text" && !indexedChunks[id] { - return errors.New("unverified legacy library chunk index coverage") - } - if chunk.ChunkStatus == 2 && !indexedChunks[id] { - return errors.New("missing indexed library chunk") - } } return nil } diff --git a/internal/releaseadapter/v071/library_archive_native_test.go b/internal/releaseadapter/v071/library_archive_native_test.go new file mode 100644 index 0000000..7e347be --- /dev/null +++ b/internal/releaseadapter/v071/library_archive_native_test.go @@ -0,0 +1,346 @@ +package v071 + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "strconv" + "strings" + "testing" + "time" + + "knowledge-governance/internal/librarysnapshot" +) + +// Source v0.7.1 chooses which chunks receive an original-text index. R3f +// removes governance's attempt to infer that choice (status/type/parent): +// capture the actual PG and ES sets, while still checking question metadata, +// scopes, digests, resources, Wiki references and real parent identities. +func TestArchiveLibraryCandidateAcceptsNativeMixedParentChild(t *testing.T) { + ArchiveLibraryCandidateAcceptance(t, true) +} + +func TestArchiveLibraryCandidateCapturesFlatDocumentWithoutIndex(t *testing.T) { + fixture := nativeMixedFixture(false, true) + if _, _, err := archiveNativeFixture(t, fixture); err != nil { + t.Fatalf("flat document without body index must be captured as-is: %v", err) + } +} + +func TestArchiveLibraryCandidateCapturesParentedChildWithoutIndex(t *testing.T) { + fixture := nativeMixedFixture(true, true) + // Remove only the child body index; question/summary/flat indexes stay. + fixture.es.Documents = append([]SearchDocument{}, fixture.es.Documents[1:]...) + fixture.es.DocumentsSHA256, _ = searchDocumentsDigest(fixture.es.Documents) + if _, _, err := archiveNativeFixture(t, fixture); err != nil { + t.Fatalf("parented child without body index must be captured as-is: %v", err) + } +} + +func TestArchiveLibraryCandidateCapturesExplicitChunkWithoutIndex(t *testing.T) { + fixture := nativeMixedFixture(true, true) + fixture.pg.Tables = replaceChunkStatusForTest(fixture.pg.Tables, "chunk-standalone", 2) + if _, _, err := archiveNativeFixture(t, fixture); err != nil { + t.Fatalf("status=2 chunk without body index must be captured as-is: %v", err) + } +} + +type nativeMixedFixtureState struct { + pg PostgresSnapshot + es SearchSnapshot +} + +func nativeMixedFixture(includeFlatIndex, includeChildIndex bool) nativeMixedFixtureState { + knowledges := []json.RawMessage{ + json.RawMessage(`{"id":"doc-mixed","tenant_id":10000,"knowledge_base_id":"kb-safe","parse_status":"completed","file_path":"resource://ABCDEFGHIJKLMNOPQRSTUV"}`), + json.RawMessage(`{"id":"doc-flat","tenant_id":10000,"knowledge_base_id":"kb-safe","parse_status":"completed","file_path":"resource://ABCDEFGHIJKLMNOPQRSTUV"}`), + } + chunks := []json.RawMessage{ + json.RawMessage(`{"id":"chunk-parent","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-mixed","chunk_type":"parent_text","content":"parent","status":0}`), + json.RawMessage(`{"id":"chunk-child","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-mixed","chunk_type":"text","parent_chunk_id":"chunk-parent","content":"child","status":0}`), + json.RawMessage(`{"id":"chunk-standalone","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-mixed","chunk_type":"text","content":"standalone","status":0,"metadata":{"generated_questions":[{"id":"q-1","question":"Question?"}]}}`), + json.RawMessage(`{"id":"chunk-summary","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-mixed","chunk_type":"summary","parent_chunk_id":"chunk-child","content":"summary","status":0}`), + json.RawMessage(`{"id":"chunk-flat","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-flat","chunk_type":"text","content":"flat","status":0}`), + } + tables := []TableSnapshot{ + newTableSnapshot("knowledges", knowledges), + newTableSnapshot("chunks", chunks), + newTableSnapshot("resources", []json.RawMessage{json.RawMessage(`{"id":"res-safe","tenant_id":10000,"handle":"ABCDEFGHIJKLMNOPQRSTUV","provider":"oss","physical_path":"oss://fixture/source.txt","size":4}`)}), + } + for _, name := range []string{"resource_bindings", "knowledge_tags", "knowledge_tag_relations", "wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} { + tables = append(tables, newTableSnapshot(name, nil)) + } + es := SearchSnapshot{MappingSHA256: shaBytes([]byte("mapping"))} + if includeChildIndex { + es.Documents = append(es.Documents, SearchDocument{ID: "es-child", Source: json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-mixed","chunk_id":"chunk-child","content":"child","vector":[0.125,-0.5]}`)}) + // The standalone text has a generated-question index but deliberately + // no original-text index; the index must not be counted as body coverage. + es.Documents = append(es.Documents, SearchDocument{ID: "es-question", Source: json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-mixed","chunk_id":"chunk-standalone","source_id":"chunk-standalone-q-1","content":"Question?","vector":[0.25,0.75]}`)}) + es.Documents = append(es.Documents, SearchDocument{ID: "es-summary", Source: json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-mixed","chunk_id":"chunk-summary","source_id":"chunk-summary","content":"summary","vector":[0.5,-0.25]}`)}) + } + if includeFlatIndex { + es.Documents = append(es.Documents, SearchDocument{ID: "es-flat", Source: json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-flat","chunk_id":"chunk-flat","content":"flat","vector":[0.0,1.0]}`)}) + } + es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents) + return nativeMixedFixtureState{pg: PostgresSnapshot{Tables: tables}, es: es} +} + +func derivedFlatFixture(kind string, keepBody bool) (PostgresSnapshot, SearchSnapshot) { + pg, es, _ := libraryCandidateFixture() + chunks := []json.RawMessage{ + json.RawMessage(`{"id":"chunk-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"body","status":0,"chunk_type":"text"}`), + json.RawMessage(`{"id":"derived-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"derived","status":0,"chunk_type":"` + kind + `","parent_chunk_id":"chunk-safe"}`), + } + pg.Tables[1] = newTableSnapshot("chunks", chunks) + if !keepBody { + es.Documents = nil + } + es.Documents = append(es.Documents, SearchDocument{ID: "derived-index", Source: json.RawMessage(`{"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"derived-safe","source_id":"derived-safe","content":"derived","vector":[0.5,0.5]}`)}) + es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents) + return pg, es +} + +func TestDerivedParentRoleIsAccepted(t *testing.T) { + for _, kind := range []string{"summary", "image_ocr", "image_caption"} { + t.Run(kind, func(t *testing.T) { + pg, es := derivedFlatFixture(kind, true) + if err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es); err != nil { + t.Fatalf("native %s -> text link rejected: %v", kind, err) + } + }) + } +} + +func TestDerivedParentDoesNotAffectFlatBodyCapture(t *testing.T) { + pg, es := derivedFlatFixture("summary", false) + if err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es); err != nil { + t.Fatalf("derived parent must not create an index-coverage gate: %v", err) + } +} + +func TestArchiveBodyWithoutOriginalIndexIsAccepted(t *testing.T) { + for _, status := range []int{0, 2} { + t.Run("status="+strconv.Itoa(status), func(t *testing.T) { + pg, es := derivedFlatFixture("summary", false) + pg.Tables = replaceChunkStatusForTest(pg.Tables, "chunk-safe", status) + _, _, err := archiveNativeFixture(t, nativeMixedFixtureState{pg: pg, es: es}) + if err != nil { + t.Fatalf("body without original index must be captured as-is: %v", err) + } + }) + } +} + +func TestArchiveParentTypePairingIsNotEnforced(t *testing.T) { + pg, es := derivedFlatFixture("image_ocr", true) + pg.Tables = replaceChunkTypeForTest(pg.Tables, "chunk-safe", "summary") + _, _, err := archiveNativeFixture(t, nativeMixedFixtureState{pg: pg, es: es}) + if err != nil { + t.Fatalf("an existing same-knowledge parent must not be rejected by type: %v", err) + } +} + +func archiveNativeFixture(t *testing.T, fixture nativeMixedFixtureState) (string, librarysnapshot.Manifest, error) { + t.Helper() + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + archive, err := librarysnapshot.Open(root, 1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + id, err := ArchiveLibraryCandidate(context.Background(), archive, "internal", + PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, + librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: fixture.es.MappingSHA256}, + fixture.pg, fixture.es, &libraryCandidateReader{data: []byte("file")}, + time.Date(2026, 11, 5, 0, 0, 0, 0, time.UTC)) + if err != nil { + return "", librarysnapshot.Manifest{}, err + } + saved, err := archive.Load(id) + if err == nil { + err = validateArchivedLibraryClosure(archive, saved) + } + if err == nil { + err = verifyNativeArchiveReadback(archive, saved, fixture) + } + return id, saved, err +} + +func canonicalJSONForTest(raw []byte) (string, error) { + var value any + decoder := json.NewDecoder(strings.NewReader(string(raw))) + decoder.UseNumber() + if err := decoder.Decode(&value); err != nil { + return "", err + } + encoded, err := json.Marshal(value) + return string(encoded), err +} + +func verifyNativeArchiveReadback(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest, fixture nativeMixedFixtureState) error { + pgTables := map[string][]json.RawMessage{} + for _, table := range fixture.pg.Tables { + pgTables[table.Name] = table.Rows + } + for _, part := range manifest.Parts { + if part.Kind != "database" && part.Kind != "wiki" && part.Kind != "index" { + continue + } + reader, err := archive.OpenPart(part) + if err != nil { + return err + } + raw, readErr := io.ReadAll(reader) + _ = reader.Close() + if readErr != nil { + return readErr + } + if part.Kind == "index" { + var got []SearchDocument + if err := json.Unmarshal(raw, &got); err != nil { + return err + } + if len(got) != len(fixture.es.Documents) { + return fmt.Errorf("readback index count=%d want=%d", len(got), len(fixture.es.Documents)) + } + for i := range got { + if got[i].ID != fixture.es.Documents[i].ID { + return fmt.Errorf("readback index id changed at %d", i) + } + want, _ := canonicalJSONForTest(fixture.es.Documents[i].Source) + have, err := canonicalJSONForTest(got[i].Source) + if err != nil || have != want { + return fmt.Errorf("readback index source changed at %d", i) + } + } + continue + } + var got []json.RawMessage + if err := json.Unmarshal(raw, &got); err != nil { + return err + } + wantRows, ok := pgTables[part.Name] + if !ok { + continue + } + if len(got) != len(wantRows) { + return fmt.Errorf("readback %s count=%d want=%d", part.Name, len(got), len(wantRows)) + } + for i := range got { + have, a := canonicalJSONForTest(got[i]) + want, b := canonicalJSONForTest(wantRows[i]) + if a != nil || b != nil || have != want { + return fmt.Errorf("readback %s row %d changed", part.Name, i) + } + } + } + return nil +} + +func TestArchiveLibraryCandidateRejectsDanglingParentReference(t *testing.T) { + fixture := nativeMixedFixture(true, true) + fixture.pg.Tables = replaceChunkParentForTest(fixture.pg.Tables, "chunk-child", "missing-parent") + _, _, err := archiveNativeFixture(t, fixture) + if err == nil || !strings.Contains(err.Error(), "parent_chunk_id reference") { + t.Fatalf("dangling parent reference must be rejected, got %v", err) + } +} + +func replaceChunkParentForTest(tables []TableSnapshot, chunkID, parentID string) []TableSnapshot { + out := make([]TableSnapshot, 0, len(tables)) + for _, table := range tables { + if table.Name != "chunks" { + out = append(out, table) + continue + } + rows := make([]json.RawMessage, 0, len(table.Rows)) + for _, raw := range table.Rows { + var row map[string]any + _ = json.Unmarshal(raw, &row) + if row["id"] == chunkID { + row["parent_chunk_id"] = parentID + encoded, _ := json.Marshal(row) + rows = append(rows, encoded) + } else { + rows = append(rows, raw) + } + } + out = append(out, newTableSnapshot("chunks", rows)) + } + return out +} + +func replaceChunkTypeForTest(tables []TableSnapshot, chunkID, chunkType string) []TableSnapshot { + out := make([]TableSnapshot, 0, len(tables)) + for _, table := range tables { + if table.Name != "chunks" { + out = append(out, table) + continue + } + rows := make([]json.RawMessage, 0, len(table.Rows)) + for _, raw := range table.Rows { + var row map[string]any + _ = json.Unmarshal(raw, &row) + if row["id"] == chunkID { + row["chunk_type"] = chunkType + encoded, _ := json.Marshal(row) + rows = append(rows, encoded) + } else { + rows = append(rows, raw) + } + } + out = append(out, newTableSnapshot("chunks", rows)) + } + return out +} + +func replaceChunkStatusForTest(tables []TableSnapshot, chunkID string, status int) []TableSnapshot { + out := make([]TableSnapshot, 0, len(tables)) + for _, table := range tables { + if table.Name != "chunks" { + out = append(out, table) + continue + } + rows := make([]json.RawMessage, 0, len(table.Rows)) + for _, raw := range table.Rows { + var row map[string]any + _ = json.Unmarshal(raw, &row) + if row["id"] == chunkID { + row["status"] = status + encoded, _ := json.Marshal(row) + rows = append(rows, encoded) + } else { + rows = append(rows, raw) + } + } + out = append(out, newTableSnapshot("chunks", rows)) + } + return out +} + +// ArchiveLibraryCandidateAcceptance is a named helper so the positive case can +// fail with a clear message while the test still calls the real archive entry. +func ArchiveLibraryCandidateAcceptance(t *testing.T, includeFlatIndex bool) { + t.Helper() + _, saved, err := archiveNativeFixture(t, nativeMixedFixture(includeFlatIndex, true)) + if err != nil { + t.Fatalf("native mixed parent-child candidate rejected: %v", err) + } + var chunks, index int64 + for _, part := range saved.Parts { + if part.Kind == "database" && part.Name == "chunks" { + chunks = part.Count + } + if part.Kind == "index" { + index = part.Count + } + } + if chunks != 5 || index != 4 { + t.Fatalf("archive filtered rows: chunks=%d index=%d", chunks, index) + } +} diff --git a/internal/releaseadapter/v071/library_backup_store.go b/internal/releaseadapter/v071/library_backup_store.go index 6970b0a..ccb5f32 100644 --- a/internal/releaseadapter/v071/library_backup_store.go +++ b/internal/releaseadapter/v071/library_backup_store.go @@ -17,8 +17,8 @@ import ( // (PG RepeatableRead + ES 导出一致快照 + 资源对象),密封成归档里的一个版本。 // // 为什么要有静默检查:预备份期间生产若仍在变,导出的 PG/ES/对象就不是同一个切点, -// 恢复它等于恢复到"没人见过的状态"。所以导出前后各读一次行数,不一致就失败, -// 让作业重试,而不是拿一个不一致的备份当恢复点。 +// 恢复它等于恢复到"没人见过的状态"。PG逐行指纹与对象精确版本在导出前后 +// 必须一致;执行器另行核对索引before-image。此检测不能代替独占写审核。 type ProductionBackupStore struct { pool *pgxpool.Pool search *SearchExporter @@ -30,6 +30,8 @@ type ProductionBackupStore struct { maxDocuments int maxObjectByte int64 now func() time.Time + // tables 是目标库解析出的知识域表集合(0.9.0 没有 wiki_log_entries)。 + tables []string } type ProductionBackupConfig struct { @@ -58,10 +60,16 @@ func NewProductionBackupStore(config ProductionBackupConfig) (*ProductionBackupS if now == nil { now = time.Now } + // 预备份的表集合必须与写入/校验同源:按 0.7.1 固定清单会在 0.9.0 目标上 + // 查询不存在的 wiki_log_entries。 + schema, err := ResolveSchemaProfile(context.Background(), config.Pool, "prebackup target") + if err != nil { + return nil, err + } return &ProductionBackupStore{pool: config.Pool, search: config.Search, objects: config.Objects, archiveRoot: config.ArchiveRoot, scope: config.Scope, identity: config.Identity, compatibility: config.Compatibility, maxDocuments: config.MaxDocuments, - maxObjectByte: config.MaxObjectByte, now: now}, nil + maxObjectByte: config.MaxObjectByte, now: now, tables: schema.Tables}, nil } // tableFingerprint 是一张表的"数量 + 内容摘要"指纹:同数量改写也会被识别。 @@ -73,32 +81,56 @@ type tableFingerprint struct { // fingerprints 读取当前生产指纹;Prepare 在导出前后各取一次做一致性判断。 func (s *ProductionBackupStore) fingerprints(ctx context.Context) (map[string]tableFingerprint, error) { result := map[string]tableFingerprint{} - for _, table := range productionLibraryTables { - rows, err := s.pool.Query(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`, + exporter := PostgresExporter{db: s.pool} + var bodies, bindings []json.RawMessage + for _, table := range s.tables { + if table == "resources" { + continue + } + rows, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`, table, table, scopeWhere(table)), s.identity.TenantID, s.identity.KnowledgeBaseID) if err != nil { return nil, fmt.Errorf("读取生产 %s 指纹失败", table) } - digests := make([]string, 0, 64) - for rows.Next() { - var raw map[string]json.RawMessage - if err := rows.Scan(&raw); err != nil { - rows.Close() + if table != "resource_bindings" && table != "knowledge_tag_relations" { + bodies = append(bodies, rows...) + } + if table == "resource_bindings" { + bindings = rows + } + digests := make([]string, 0, len(rows)) + for _, raw := range rows { + var value map[string]json.RawMessage + if err := json.Unmarshal(raw, &value); err != nil { return nil, err } - digest, err := canonicalRowDigest(raw) + digest, err := canonicalRowDigest(value) if err != nil { - rows.Close() return nil, err } digests = append(digests, digest) } - rows.Close() - if err := rows.Err(); err != nil { - return nil, err - } result[table] = tableFingerprint{Count: int64(len(digests)), Digest: combineRowDigests(digests)} } + // F01: resolve the resources once from exact binding ids and body handles + // instead of scanning every tenant resource with a correlated body filter. + rows, err := scopedResourceRows(ctx, &exporter, s.identity, true, bodies, bindings) + if err != nil { + return nil, fmt.Errorf("读取生产 resources 指纹失败: %w", err) + } + digests := make([]string, 0, len(rows)) + for _, raw := range rows { + var value map[string]json.RawMessage + if err := json.Unmarshal(raw, &value); err != nil { + return nil, err + } + digest, err := canonicalRowDigest(value) + if err != nil { + return nil, err + } + digests = append(digests, digest) + } + result["resources"] = tableFingerprint{Count: int64(len(digests)), Digest: combineRowDigests(digests)} return result, nil } @@ -119,12 +151,16 @@ func (s *ProductionBackupStore) Prepare(ctx context.Context, _ string, current l if err != nil { return libraryrelease.BackupRef{}, err } - pg, err := ExportLibrary(ctx, s.pool, s.identity) + pg, err := exportLibraryBeforeImage(ctx, s.pool, s.identity) if err != nil { return libraryrelease.BackupRef{}, fmt.Errorf("读取生产整库失败: %w", err) } - // 整库导出用 ExportLibrary(按租户+知识库,不带单文档身份), - // 与封存路径复用同一份实现,避免两套范围规则。 + // Every row the actual delete predicate can reach must be present. + for _, table := range pg.Tables { + if int64(len(table.Rows)) != before[table.Name].Count { + return libraryrelease.BackupRef{}, fmt.Errorf("before-image coverage mismatch: %s", table.Name) + } + } es, err := s.search.ExportLibrary(ctx, SearchIdentity{TenantID: s.identity.TenantID, KnowledgeBaseID: s.identity.KnowledgeBaseID}, s.maxDocuments) if err != nil { @@ -143,9 +179,13 @@ func (s *ProductionBackupStore) Prepare(ctx context.Context, _ string, current l return libraryrelease.BackupRef{}, errors.New("生产索引映射与归档契约不一致") } } + objectBefore, err := s.objectVersions(ctx, pg) + if err != nil { + return libraryrelease.BackupRef{}, err + } // ArchiveLibraryCandidate 自己按 resources 行读取对象字节并计算摘要, // 所以这里直接给它生产对象读取器,不再重复导出一次资源。 - snapshotID, err := ArchiveLibraryCandidate(ctx, archive, s.scope, s.identity, s.compatibility, pg, es, s.objects, createdAt) + snapshotID, err := archiveLibraryRows(ctx, archive, s.scope, s.identity, s.compatibility, pg, es, s.objects, createdAt) if err != nil { return libraryrelease.BackupRef{}, fmt.Errorf("密封预备份失败: %w", err) } @@ -179,17 +219,63 @@ func (s *ProductionBackupStore) Prepare(ctx context.Context, _ string, current l if err != nil { return libraryrelease.BackupRef{}, errors.New("预备份封存后无法校验") } + objectAfter, err := s.objectVersions(ctx, pg) + if err != nil { + return libraryrelease.BackupRef{}, err + } + for id, before := range objectBefore { + if objectAfter[id] != before { + return libraryrelease.BackupRef{}, errors.New("object changed during prebackup; inconsistent version boundary") + } + } var total int64 for _, part := range manifest.Parts { + if part.Kind == "resource" { + observed, ok := objectBefore[part.Name] + if !ok || observed.SHA256 != part.SHA256 || observed.Bytes != part.Bytes { + return libraryrelease.BackupRef{}, errors.New("archived object differs from prebackup version boundary") + } + } total += part.Bytes } return libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID, Bytes: total, CreatedAt: createdAt, Universe: universeBefore}, nil } +// Exact versions, not just bytes, bind the multi-store backup read interval. +// An unchanged byte string in a new version is still a different restore base. +func (s *ProductionBackupStore) objectVersions(ctx context.Context, pg PostgresSnapshot) (map[string]objectObservation, error) { + out := map[string]objectObservation{} + reader, ok := s.objects.(interface { + ObserveObject(context.Context, string, string) (objectObservation, error) + }) + for _, raw := range pg.Table("resources").Rows { + if !ok { + return nil, errors.New("prebackup reader lacks exact object-version observations") + } + var row struct { + ID string `json:"id"` + Provider string `json:"provider"` + Path string `json:"physical_path"` + } + if e := json.Unmarshal(raw, &row); e != nil { + return nil, e + } + observed, e := reader.ObserveObject(ctx, row.Provider, row.Path) + if e != nil { + return nil, e + } + if !observed.Exists || observed.VersionID == "" || observed.VersionID == "null" || observed.SHA256 == "" { + return nil, errors.New("prebackup requires an existing versioned object") + } + out[row.ID] = observed + } + return out, nil +} + func (s *ProductionBackupStore) rowCounts(ctx context.Context) (map[string]int64, error) { counts := map[string]int64{} - for _, table := range productionLibraryTables { + for _, table := range s.tables { var count int64 if err := s.pool.QueryRow(ctx, fmt.Sprintf(`SELECT count(*) FROM %s WHERE %s`, table, scopeWhere(table)), s.identity.TenantID, s.identity.KnowledgeBaseID).Scan(&count); err != nil { diff --git a/internal/releaseadapter/v071/library_beforeimage.go b/internal/releaseadapter/v071/library_beforeimage.go new file mode 100644 index 0000000..e3f965a --- /dev/null +++ b/internal/releaseadapter/v071/library_beforeimage.go @@ -0,0 +1,85 @@ +package v071 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "github.com/jackc/pgx/v5" +) + +// Recovery bytes are not a source candidate. The selection must equal the +// destructive target predicate, including tombstones and their relationships. +// Semantic source validation would discard/reject exactly those historical +// rows that an exact rollback must preserve. +func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identity PostgresIdentity) (PostgresSnapshot, error) { + tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}) + if err != nil { + return PostgresSnapshot{}, err + } + defer tx.Rollback(context.WithoutCancel(ctx)) + profile, err := ResolveSchemaProfile(ctx, tx, "before-image source") + if err != nil { + return PostgresSnapshot{}, err + } + exporter := PostgresExporter{db: tx} + rowsByTable := map[string][]json.RawMessage{} + var bodies, bindings []json.RawMessage + for _, table := range profile.Tables { + if table == "resources" { + continue + } + rows, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s ORDER BY (%s)::text`, table, table, scopeWhereFor(profile.Tables, table), identityExpr(table)), identity.TenantID, identity.KnowledgeBaseID) + if err != nil { + return PostgresSnapshot{}, err + } + rowsByTable[table] = rows + if table != "resource_bindings" && table != "knowledge_tag_relations" { + bodies = append(bodies, rows...) + } + if table == "resource_bindings" { + bindings = rows + } + } + // F01: the before-image needs exact rollback rows, including deleted + // resources, but must not rescan every tenant resource per body table. + resources, err := scopedResourceRows(ctx, &exporter, identity, true, bodies, bindings) + if err != nil { + return PostgresSnapshot{}, err + } + rowsByTable["resources"] = resources + snapshot := PostgresSnapshot{SchemaVersion: profile.SchemaVersion, Profile: profile.Name} + for _, table := range profile.Tables { + snapshot.Tables = append(snapshot.Tables, newTableSnapshot(table, rowsByTable[table])) + } + handles, err := libraryResourceHandles(bodies) + if err != nil { + return PostgresSnapshot{}, err + } + resourceHandles := map[string]bool{} + resourceIDs := []string{} + for _, raw := range snapshot.Table("resources").Rows { + var row struct { + ID string `json:"id"` + Handle string `json:"handle"` + } + if err := json.Unmarshal(raw, &row); err != nil { + return PostgresSnapshot{}, err + } + resourceHandles[row.Handle] = true + resourceIDs = append(resourceIDs, row.ID) + } + for _, handle := range handles { + if !resourceHandles[handle] { + return PostgresSnapshot{}, errors.New("before-image contains unresolved resource reference") + } + } + if err := verifyLibraryResourceOwners(ctx, tx, resourceIDs); err != nil { + return PostgresSnapshot{}, err + } + if err := tx.Commit(ctx); err != nil { + return PostgresSnapshot{}, err + } + return snapshot, nil +} diff --git a/internal/releaseadapter/v071/library_chunk_sequence_integration_test.go b/internal/releaseadapter/v071/library_chunk_sequence_integration_test.go new file mode 100644 index 0000000..0f21887 --- /dev/null +++ b/internal/releaseadapter/v071/library_chunk_sequence_integration_test.go @@ -0,0 +1,43 @@ +package v071 + +import ( + "knowledge-governance/internal/libraryrelease" + "testing" +) + +// Cross-database snapshots may reuse a local serial value already owned by an +// unrelated KB. UUIDs remain stable; the destination allocates its own serial. +func TestLibraryChunkSequenceIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, err := fx.pool.Exec(fx.ctx, `ALTER TABLE chunks ADD COLUMN seq_id bigserial UNIQUE`); err != nil { + t.Fatal(err) + } + var occupied int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT seq_id FROM chunks WHERE knowledge_base_id=$1 LIMIT 1`, wsOtherKB).Scan(&occupied); err != nil { + t.Fatal(err) + } + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { parts["chunks"][0]["seq_id"] = occupied }) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "succeeded" { + t.Fatalf("cross-database publish must allocate local sequence: %+v", outcome) + } + var allocated int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT seq_id FROM chunks WHERE id=$1`, expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-src")).Scan(&allocated); err != nil { + t.Fatal(err) + } + if allocated == occupied || allocated <= 0 { + t.Fatalf("invalid destination serial %d (occupied %d)", allocated, occupied) + } + if err := target.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: snapshot}); err != nil { + t.Fatalf("content verification: %v", err) + } + if err := target.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatalf("restore must preserve original serial values: %v", err) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("restored universe differs: %s", diff) + } +} diff --git a/internal/releaseadapter/v071/library_chunk_sequence_test.go b/internal/releaseadapter/v071/library_chunk_sequence_test.go new file mode 100644 index 0000000..8bb9b9a --- /dev/null +++ b/internal/releaseadapter/v071/library_chunk_sequence_test.go @@ -0,0 +1,35 @@ +package v071 + +import ( + "encoding/json" + "testing" +) + +func TestChunkSequenceProjectionKeepsContent(t *testing.T) { + for _, restore := range []bool{false, true} { + target := &ProductionLibraryTarget{scope: ProductionScope{TenantID: 10001, KnowledgeBaseID: "kb-target"}, snapshotTenant: 10002, snapshotKB: "kb-source", preserveChunkSequence: restore} + row := map[string]json.RawMessage{"id": json.RawMessage(`"chunk-src"`), "tenant_id": json.RawMessage(`10002`), "knowledge_base_id": json.RawMessage(`"kb-source"`), "seq_id": json.RawMessage(`7`), "content": json.RawMessage(`"exact content"`)} + if err := target.rowTransform("chunks")(row); err != nil { + t.Fatal(err) + } + _, present := row["seq_id"] + if present != restore { + t.Fatalf("restore=%v seq_id present=%v", restore, present) + } + if string(row["content"]) != `"exact content"` || string(row["id"]) != `"chunk-src"` { + t.Fatal("content identity was changed") + } + before, err := canonicalRowDigest(row) + if err != nil { + t.Fatal(err) + } + row["content"] = json.RawMessage(`"corrupted"`) + after, err := canonicalRowDigest(row) + if err != nil { + t.Fatal(err) + } + if before == after { + t.Fatal("content corruption was hidden") + } + } +} diff --git a/internal/releaseadapter/v071/library_contract_durability_test.go b/internal/releaseadapter/v071/library_contract_durability_test.go new file mode 100644 index 0000000..512f187 --- /dev/null +++ b/internal/releaseadapter/v071/library_contract_durability_test.go @@ -0,0 +1,80 @@ +package v071 + +import ( + "encoding/json" + "os" + "sync" + "testing" + "time" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +func TestContractIndexPreservesLargeInteger(t *testing.T) { + a, err := canonicalJSON(json.RawMessage(`{"n":9007199254740993}`)) + if err != nil { + t.Fatal(err) + } + if string(a) != `{"n":9007199254740993}` { + t.Fatalf("integer rounded: %s", a) + } +} + +func TestContractOrphanQueryFailureIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + fx.indexDoc(t, "chunk-src", wsTargetTenant, wsTargetKB, "doc-src", "来源正文 resource://"+wsHandleSource) + archive, err := librarysnapshot.Open(fx.archiveRoot, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + manifest, err := archive.Load(snapshot) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(fx.ctx, `ALTER TABLE knowledges RENAME TO unavailable_knowledges`); err != nil { + t.Fatal(err) + } + if err := target.verifyIndexDigest(fx.ctx, archive, manifest); err == nil { + t.Fatal("database oracle error accepted as no orphans") + } +} + +func TestContractImmutableWriteSetConcurrent(t *testing.T) { + root := t.TempDir() + set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: "job", Target: "internal", TenantID: 1, KnowledgeBaseID: "kb", + BackupSnapshotID: "backup", TargetSnapshotID: "snapshot", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"chunks": {Count: 0, Digest: "empty"}}} + if err := set.Seal(); err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + errs := make(chan error, 32) + for i := 0; i < 32; i++ { + wg.Add(1) + go func() { defer wg.Done(); copy := set; _, err := PersistWriteSet(root, ©); errs <- err }() + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Errorf("immutable concurrent commit: %v", err) + } + } + loaded, err := LoadWriteSet(root, set.Digest) + if err != nil { + t.Fatal(err) + } + if loaded.Digest != set.Digest { + t.Fatal("digest changed") + } + entries, err := os.ReadDir(root + "/writesets") + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 { + t.Fatalf("temporary files leaked: %d", len(entries)) + } +} diff --git a/internal/releaseadapter/v071/library_contract_external_test.go b/internal/releaseadapter/v071/library_contract_external_test.go new file mode 100644 index 0000000..3333cbc --- /dev/null +++ b/internal/releaseadapter/v071/library_contract_external_test.go @@ -0,0 +1,43 @@ +package v071 + +import ( + "knowledge-governance/internal/libraryrelease" + "testing" +) + +func TestContractIndexConflictBeforeAnyWriteIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + fx.indexDoc(t, "chunk-src", wsTargetTenant, wsOtherKB, "doc-other", "protected foreign vector") + before := universeDump(t, fx.pool) + puts := fx.objects.puts.Load() + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "failed" || outcome.FailedAt != "" { + t.Fatalf("index collision must fail preflight: %+v", outcome) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("preflight changed PG: %s", diff) + } + if fx.objects.puts.Load() != puts { + t.Fatal("index conflict detected after object write") + } +} + +func TestContractSharedBackupResourceCannotChangeIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshotScope(t, fx, wsSourceTenant, wsSourceKB, func(parts map[string][]map[string]any) { + parts["resources"] = append(parts["resources"], map[string]any{"id": "res-shared", "handle": "gggggggggggggggggggggg", "tenant_id": wsSourceTenant, "storage_backend_id": "backend-source", "provider": "oss", "physical_path": wsLocator("backend-source", "oss", "source-bucket", wsSourceTenant, "res-shared"), "size": int64(8)}) + }, map[string]string{"res-shared": "12345678"}) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "failed" || outcome.FailedAt != "" { + t.Fatalf("shared resource difference must fail preflight: %+v", outcome) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("shared resource overwritten: %s", diff) + } +} diff --git a/internal/releaseadapter/v071/library_contract_plan_integration_test.go b/internal/releaseadapter/v071/library_contract_plan_integration_test.go new file mode 100644 index 0000000..0149fe4 --- /dev/null +++ b/internal/releaseadapter/v071/library_contract_plan_integration_test.go @@ -0,0 +1,171 @@ +package v071 + +import ( + "encoding/json" + "testing" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +func TestContractLocalNumbersAndReplayIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + for _, sql := range []string{ + `ALTER TABLE chunks ADD COLUMN seq_id bigserial UNIQUE`, + `ALTER TABLE knowledge_tags ADD COLUMN seq_id bigserial UNIQUE`, + `CREATE SEQUENCE wiki_log_entries_id_seq; ALTER TABLE wiki_log_entries ALTER COLUMN id SET DEFAULT nextval('wiki_log_entries_id_seq'); ALTER SEQUENCE wiki_log_entries_id_seq OWNED BY wiki_log_entries.id; ALTER TABLE wiki_log_entries ADD PRIMARY KEY(id)`, + `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id) VALUES('other-tag',10001,'kb-other')`, + `INSERT INTO wiki_log_entries(tenant_id,knowledge_base_id) VALUES(10001,'kb-other')`, + } { + if _, err := fx.pool.Exec(fx.ctx, sql); err != nil { + t.Fatal(err) + } + } + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { + parts["chunks"][0]["seq_id"] = 1 + parts["knowledge_tags"] = []map[string]any{{"id": "tag-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "seq_id": 1}} + parts["wiki_log_entries"] = []map[string]any{{"id": 1, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB}, {"id": 2, "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB}} + }) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "succeeded" { + t.Fatalf("typed local numbers must publish: %+v", outcome) + } + published := universeDump(t, fx.pool) + if err := target.Apply(fx.ctx, libraryrelease.StageIndex, outcome.Backup.SnapshotID); err == nil { + t.Fatal("frozen plan accepted another snapshot in index Apply") + } + for _, name := range []string{"wrong-source-tenant", "wrong-source-kb", "missing-mapping", "missing-wiki-row", "legacy-plan-with-local-ids", "missing-object", "wrong-object-bytes"} { + t.Run(name, func(t *testing.T) { + raw, _ := json.Marshal(outcome.Backup.WriteSet) + var invalid libraryrelease.WriteSet + if err := json.Unmarshal(raw, &invalid); err != nil { + t.Fatal(err) + } + switch name { + case "missing-object": + invalid.Objects = nil + case "wrong-object-bytes": + invalid.Objects[0].Bytes++ + case "wrong-source-tenant": + invalid.SourceTenantID++ + case "wrong-source-kb": + invalid.SourceKnowledgeBaseID = "different-source" + case "missing-mapping": + invalid.LocalIDs = nil + case "missing-wiki-row": + for i, row := range invalid.Rows { + if row.Table == "wiki_log_entries" { + invalid.Rows = append(invalid.Rows[:i], invalid.Rows[i+1:]...) + break + } + } + case "legacy-plan-with-local-ids": + invalid.ContractVersion = 0 + invalid.LocalIDs = nil + invalid.SourceTenantID = 0 + invalid.SourceKnowledgeBaseID = "" + } + if err := invalid.Seal(); err != nil { + t.Fatal(err) + } + if err := fx.target(t).AdoptWriteSet(invalid); err == nil { + t.Fatal("accepted incomplete/source-mismatched persisted plan") + } + }) + } + // Recreate the adapter, consume only the exact persisted plan, and replay. + next := fx.target(t) + if err := next.AdoptWriteSet(*outcome.Backup.WriteSet); err != nil { + t.Fatal(err) + } + for _, stage := range libraryrelease.Stages() { + if err := next.Apply(fx.ctx, stage, snapshot); err != nil { + t.Fatal(err) + } + } + if diff := diffUniverse(published, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("replay reassigned local values: %s", diff) + } + if err := next.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: snapshot}); err != nil { + t.Fatal(err) + } + if err := next.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatal(err) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("rollback lost local values: %s", diff) + } +} + +func TestContractBackupIncludesDeletedRowsIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + for _, sql := range []string{ + `INSERT INTO knowledges(id,tenant_id,knowledge_base_id,deleted_at) VALUES('deleted-doc',10001,'kb-target',now())`, + `INSERT INTO chunks(id,tenant_id,knowledge_base_id,knowledge_id,deleted_at) VALUES('deleted-chunk',10001,'kb-target','deleted-doc',now())`, + `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,deleted_at) VALUES('deleted-tag',10001,'kb-target',now())`, + `INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES('deleted-doc','deleted-tag')`, + `INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,deleted_at) VALUES('deleted-page',10001,'kb-target','deleted',now())`, + } { + if _, err := fx.pool.Exec(fx.ctx, sql); err != nil { + t.Fatal(err) + } + } + target := fx.target(t) + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatal(err) + } + backup, err := fx.backups(t, target).Prepare(fx.ctx, "", current) + if err != nil { + t.Fatal(err) + } + archive, err := librarysnapshot.Open(fx.archiveRoot, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + manifest, err := archive.Load(backup.SnapshotID) + if err != nil { + t.Fatal(err) + } + counts := map[string]int64{} + for _, part := range manifest.Parts { + if part.Kind == "database" || part.Kind == "wiki" { + counts[part.Name] = part.Count + } + } + for _, table := range []string{"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", "wiki_pages"} { + if counts[table] != current.Counts[table] { + t.Fatalf("before-image omits actual delete rows in %s: backup=%d affected=%d", table, counts[table], current.Counts[table]) + } + } + // Keep this check independent of the normalization used by the importer. + for _, part := range manifest.Parts { + if part.Name != "knowledges" { + continue + } + reader, err := archive.OpenPart(part) + if err != nil { + t.Fatal(err) + } + var rows []map[string]json.RawMessage + err = json.NewDecoder(reader).Decode(&rows) + reader.Close() + if err != nil { + t.Fatal(err) + } + found := false + for _, row := range rows { + if string(row["id"]) == `"deleted-doc"` && string(row["deleted_at"]) != "null" { + found = true + } + } + if !found { + t.Fatal("deleted before-image absent") + } + } +} diff --git a/internal/releaseadapter/v071/library_evidence_directory.go b/internal/releaseadapter/v071/library_evidence_directory.go new file mode 100644 index 0000000..7478649 --- /dev/null +++ b/internal/releaseadapter/v071/library_evidence_directory.go @@ -0,0 +1,40 @@ +package v071 + +import ( + "errors" + "os" + "path/filepath" +) + +// Validate each ancestor before descending; MkdirAll can follow an ancestor +// symlink before the leaf Lstat ever sees it. Sync every directory entry's parent, +// not merely the last two levels of a newly-created effect hierarchy. +func ensureEvidenceDirectory(path string, syncDirectory func(string) error) error { + absolute, err := filepath.Abs(path) + if err != nil { + return err + } + parent := filepath.Dir(absolute) + if parent != absolute { + if err = ensureEvidenceDirectory(parent, syncDirectory); err != nil { + return err + } + } + info, err := os.Lstat(absolute) + if errors.Is(err, os.ErrNotExist) { + if err = os.Mkdir(absolute, 0700); err != nil && !errors.Is(err, os.ErrExist) { + return err + } + info, err = os.Lstat(absolute) + } + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("evidence ancestor is not a real directory") + } + if parent != absolute { + return syncDirectory(parent) + } + return nil +} diff --git a/internal/releaseadapter/v071/library_evidence_directory_test.go b/internal/releaseadapter/v071/library_evidence_directory_test.go new file mode 100644 index 0000000..a31d8c0 --- /dev/null +++ b/internal/releaseadapter/v071/library_evidence_directory_test.go @@ -0,0 +1,47 @@ +package v071 + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +func TestContractEvidenceRejectsAncestorSymlinkBeforeWrite(t *testing.T) { + root := t.TempDir() + outside := t.TempDir() + if err := os.Symlink(outside, filepath.Join(root, "effects")); err != nil { + t.Fatal(err) + } + if err := persistImmutableJSON(filepath.Join(root, "effects", "job", "index", "id", "intent.json"), []byte(`{"intent":true}`)); err == nil { + t.Fatal("ancestor symlink accepted") + } + entries, err := os.ReadDir(outside) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatal("refusal wrote through ancestor symlink") + } +} + +func TestContractEvidenceSyncsEveryAncestorAndPropagatesFailure(t *testing.T) { + root := t.TempDir() + leaf := filepath.Join(root, "effects", "plan", "index", "id") + synced := map[string]bool{} + if err := ensureEvidenceDirectory(leaf, func(path string) error { synced[path] = true; return syncEvidenceDirectory(path) }); err != nil { + t.Fatal(err) + } + for path := filepath.Dir(leaf); ; path = filepath.Dir(path) { + if !synced[path] { + t.Fatalf("unsynced directory entry parent: %s", path) + } + if filepath.Dir(path) == path { + break + } + } + failure := errors.New("injected directory fsync error") + if err := ensureEvidenceDirectory(leaf, func(string) error { return failure }); !errors.Is(err, failure) { + t.Fatalf("fsync error not propagated: %v", err) + } +} diff --git a/internal/releaseadapter/v071/library_export.go b/internal/releaseadapter/v071/library_export.go index c1ff3c1..7948d4a 100644 --- a/internal/releaseadapter/v071/library_export.go +++ b/internal/releaseadapter/v071/library_export.go @@ -29,10 +29,10 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi return PostgresSnapshot{}, errors.New("begin library snapshot") } defer tx.Rollback(context.WithoutCancel(ctx)) - var version int - var dirty bool - if err := tx.QueryRow(ctx, `SELECT version,dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { - return PostgresSnapshot{}, errors.New("source library schema contract mismatch") + // 版本号只用来选 profile;放行条件是随后的表/列能力探测。 + profile, err := ResolveSchemaProfile(ctx, tx, "source library") + if err != nil { + return PostgresSnapshot{}, err } var graph bool if err := tx.QueryRow(ctx, `SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean,false) FROM knowledge_bases WHERE tenant_id=$1 AND id=$2 AND deleted_at IS NULL`, identity.TenantID, identity.KnowledgeBaseID).Scan(&graph); err != nil { @@ -58,9 +58,23 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi return PostgresSnapshot{}, errors.New("library has unfinished or failed processing; semantic acceptance is still required after settlement") } } + if err := verifyLibraryRelationalClosure(ctx, tx, identity, false); err != nil { + return PostgresSnapshot{}, err + } exporter := PostgresExporter{db: tx} - var snapshot PostgresSnapshot + snapshot := PostgresSnapshot{SchemaVersion: profile.SchemaVersion, Profile: profile.Name} + snapshot.Catalog, _, err = captureMigrationCatalogFor(ctx, tx, profile.CatalogTables()) + if err != nil { + return PostgresSnapshot{}, err + } + if err = validateMigrationCatalogFor(snapshot.Catalog, profile.CatalogTables(), profile.Profile); err != nil { + return PostgresSnapshot{}, err + } for _, entry := range libraryContentQueries { + // 0.9.0 没有 wiki_log_entries:不产生该部件,也不去查不存在的表。 + if !profile.HasTable(entry.name) { + continue + } rows, err := exporter.queryRows(ctx, entry.sql, identity.TenantID, identity.KnowledgeBaseID) if err != nil { return PostgresSnapshot{}, err @@ -70,11 +84,18 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi // Resources can be owned by a document/chunk or only referenced in body text. // The latter includes Wiki manual pages, which document bundles used to miss. var bodies []json.RawMessage - for _, name := range []string{"knowledges", "chunks", "wiki_pages"} { - bodies = append(bodies, snapshot.Table(name).Rows...) + for _, table := range snapshot.Tables { + if table.Name == "resource_bindings" || table.Name == "knowledge_tag_relations" { + continue + } + bodies = append(bodies, table.Rows...) } - handles := referencedResourceHandles(bodies) - resources, err := exporter.queryRows(ctx, libraryResourcesSQL, identity.TenantID, identity.KnowledgeBaseID, handles) + handles, err := libraryResourceHandles(bodies) + if err != nil { + return PostgresSnapshot{}, err + } + resources, err := scopedResourceRows(ctx, &exporter, identity, false, bodies, + snapshot.Table("resource_bindings").Rows) if err != nil { return PostgresSnapshot{}, err } @@ -104,6 +125,13 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi return PostgresSnapshot{}, errors.New("library binding references an unavailable resource") } } + ids := make([]string, 0, len(resourceIDs)) + for id := range resourceIDs { + ids = append(ids, id) + } + if err := verifyLibraryResourceOwners(ctx, tx, ids); err != nil { + return PostgresSnapshot{}, err + } snapshot.Tables = append(snapshot.Tables, newTableSnapshot("resources", resources)) if err = tx.Commit(ctx); err != nil { return PostgresSnapshot{}, errors.New("commit library snapshot") @@ -131,4 +159,48 @@ var libraryContentQueries = []struct{ name, sql string }{ {"wiki_log_entries", `SELECT to_jsonb(w) FROM wiki_log_entries w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 ORDER BY w.id`}, } -const libraryResourcesSQL = `SELECT to_jsonb(r) FROM resources r WHERE r.tenant_id=$1 AND r.deleted_at IS NULL AND (r.handle=ANY($3::text[]) OR EXISTS (SELECT 1 FROM resource_bindings b WHERE b.resource_id=r.id AND b.tenant_id=$1 AND ((b.owner_type='knowledge' AND EXISTS (SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL)) OR (b.owner_type='chunk' AND EXISTS (SELECT 1 FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL AND k.deleted_at IS NULL))))) ORDER BY r.id` +// F01: resources were previously selected by an OR over a per-row EXISTS that +// re-scanned every body table, so a small KB in a large tenant paid for all +// unrelated resources. The caller now extracts the exact binding ids and body +// handles first; both are indexed identities, never filename guesses. +const libraryResourcesSQL = `SELECT to_jsonb(r) FROM resources r +WHERE r.tenant_id=$1 AND ($4::boolean OR r.deleted_at IS NULL) + AND (r.id=ANY($2::text[]) OR r.handle=ANY($3::text[])) +ORDER BY r.id` + +// scopedResourceRows is the single F01 read path: binding ids and body handles +// are extracted once from already scoped rows, then both are resolved through +// indexed resource identities. The old per-resource EXISTS/position filter +// rescanned every body table for every tenant resource. +func scopedResourceRows(ctx context.Context, exporter *PostgresExporter, identity PostgresIdentity, + includeDeleted bool, bodies, bindings []json.RawMessage) ([]json.RawMessage, error) { + handles, err := libraryResourceHandles(bodies) + if err != nil { + return nil, err + } + ids, err := libraryBindingResourceIDs(bindings) + if err != nil { + return nil, err + } + return exporter.queryRows(ctx, libraryResourcesSQL, identity.TenantID, ids, handles, includeDeleted) +} + +// libraryBindingResourceIDs reads the exact resource ids owned by the already +// scoped resource_bindings rows. It does not infer ownership from names. +func libraryBindingResourceIDs(rows []json.RawMessage) ([]string, error) { + seen := map[string]bool{} + ids := make([]string, 0, len(rows)) + for _, raw := range rows { + var row struct { + ResourceID string `json:"resource_id"` + } + if err := json.Unmarshal(raw, &row); err != nil || row.ResourceID == "" { + return nil, errors.New("invalid scoped resource binding") + } + if !seen[row.ResourceID] { + seen[row.ResourceID] = true + ids = append(ids, row.ResourceID) + } + } + return ids, nil +} diff --git a/internal/releaseadapter/v071/library_export_integration_test.go b/internal/releaseadapter/v071/library_export_integration_test.go index 808244b..cb683ae 100644 --- a/internal/releaseadapter/v071/library_export_integration_test.go +++ b/internal/releaseadapter/v071/library_export_integration_test.go @@ -28,6 +28,11 @@ func TestLibraryExportIsolatedPostgres(t *testing.T) { t.Fatal(err) } defer db.Close() + // 同一个隔离库会被本包的多个用例复用:不清掉上一次的 schema 就会 + // "relation already exists",让人误以为是导出本身坏了。 + if _, err = db.Exec(ctx, `DROP SCHEMA public CASCADE; CREATE SCHEMA public`); err != nil { + t.Fatal(err) + } if _, err = db.Exec(ctx, libraryTestSchema); err != nil { t.Fatal(err) } diff --git a/internal/releaseadapter/v071/library_export_test.go b/internal/releaseadapter/v071/library_export_test.go index 4b8a012..ee05672 100644 --- a/internal/releaseadapter/v071/library_export_test.go +++ b/internal/releaseadapter/v071/library_export_test.go @@ -103,6 +103,10 @@ func (d *libraryFixtureTx) Query(_ context.Context, q string, _ ...any) (pgx.Row if d.queryError { return nil, errors.New("fixture failure") } + // 能力探测走真实 SQL:假库按 0.7.1 profile 回答,避免"桩放行"。 + if strings.Contains(q, "information_schema.columns") { + return legacySchemaProbeRows(), nil + } // 死信行按真实形状返回:解除判定必须逐字节比对指纹,空结果会让"存在即阻断"失效。 if strings.Contains(q, "to_jsonb(d)") && d.failed > 0 { return &jsonRows{values: []json.RawMessage{json.RawMessage(fixtureDeadLetter)}}, nil @@ -120,6 +124,17 @@ type libraryFixtureRow struct { func (r libraryFixtureRow) Scan(dest ...any) error { switch { + case strings.Contains(r.sql, "library-relational-closure"), strings.Contains(r.sql, "library-resource-owner-closure"): + *dest[0].(*bool) = false + case strings.Contains(r.sql, "jsonb_agg(to_jsonb(q))"): + *dest[0].(*[]byte) = []byte(`[]`) + if strings.Contains(r.sql, "relrowsecurity") { + rows := []map[string]any{} + for _, table := range productionLibraryTables { + rows = append(rows, map[string]any{"table_name": table, "kind": "r"}) + } + *dest[0].(*[]byte), _ = json.Marshal(rows) + } case strings.Contains(r.sql, "library-source-settlement"): *dest[0].(*int64) = r.d.unsettled *dest[1].(*int64) = r.d.pending + r.d.sourcePending diff --git a/internal/releaseadapter/v071/library_identity_contract.go b/internal/releaseadapter/v071/library_identity_contract.go new file mode 100644 index 0000000..17467d0 --- /dev/null +++ b/internal/releaseadapter/v071/library_identity_contract.go @@ -0,0 +1,83 @@ +package v071 + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" +) + +// The contract names physical identities, not inferred *_id conventions. A +// string ID is preserved byte-for-byte (older archives also contain non-UUID +// varchar IDs). Database-local integers must never pass through float64. +const migrationIdentityContractVersion = 1 + +type rowIdentityContract struct { + Columns []string + Kind string + LocalColumn string + Sequence string +} + +var migrationIdentityContracts = map[string]rowIdentityContract{ + "knowledges": {Columns: []string{"id"}, Kind: "stable-string"}, + "chunks": {Columns: []string{"id"}, Kind: "stable-string", LocalColumn: "seq_id", Sequence: "chunks_seq_id_seq"}, + "knowledge_tags": {Columns: []string{"id"}, Kind: "stable-string", LocalColumn: "seq_id", Sequence: "knowledge_tags_seq_id_seq"}, + "knowledge_tag_relations": {Columns: []string{"knowledge_id", "tag_id"}, Kind: "tuple"}, + "resources": {Columns: []string{"id"}, Kind: "stable-string"}, + "resource_bindings": {Columns: []string{"id"}, Kind: "stable-string"}, + "wiki_folders": {Columns: []string{"id"}, Kind: "stable-string"}, + "wiki_pages": {Columns: []string{"id"}, Kind: "stable-string"}, + "wiki_page_issues": {Columns: []string{"id"}, Kind: "stable-string"}, + "wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"}, +} + +type typedRowIdentity struct { + Kind string + Values []string +} + +// key retains the V1 ledger representation, but tuple components are validated +// independently and used as separate SQL parameters, never as a single column. +func (id typedRowIdentity) key() string { return strings.Join(id.Values, ":") } + +func positiveBigint(raw json.RawMessage) (string, error) { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 { + return "", errors.New("missing integer") + } + for _, b := range raw { + if b < '0' || b > '9' { + return "", errors.New("expected JSON integer, not string/fraction/exponent") + } + } + n, err := strconv.ParseInt(string(raw), 10, 64) + if err != nil || n <= 0 || strconv.FormatInt(n, 10) != string(raw) { + return "", errors.New("integer out of positive bigint range or noncanonical") + } + return string(raw), nil +} + +func parseRowIdentity(table string, row map[string]json.RawMessage) (typedRowIdentity, error) { + contract, ok := migrationIdentityContracts[table] + if !ok { + return typedRowIdentity{}, fmt.Errorf("unknown migration identity contract: %s", table) + } + id := typedRowIdentity{Kind: contract.Kind} + for _, column := range contract.Columns { + var value string + if contract.Kind == "local-bigint" { + n, err := positiveBigint(row[column]) + if err != nil { + return id, fmt.Errorf("%s.%s: %w", table, column, err) + } + value = n + } else if err := json.Unmarshal(row[column], &value); err != nil || !validSearchIdentifier(value) || strings.Contains(value, ":") { + return id, fmt.Errorf("invalid %s.%s identity", table, column) + } + id.Values = append(id.Values, value) + } + return id, nil +} diff --git a/internal/releaseadapter/v071/library_identity_contract_test.go b/internal/releaseadapter/v071/library_identity_contract_test.go new file mode 100644 index 0000000..ea2588e --- /dev/null +++ b/internal/releaseadapter/v071/library_identity_contract_test.go @@ -0,0 +1,108 @@ +package v071 + +import ( + "bytes" + "encoding/json" + "os" + "testing" + + "knowledge-governance/internal/librarysnapshot" +) + +func TestContractNumericIdentityIsNotLost(t *testing.T) { + row := map[string]json.RawMessage{"id": json.RawMessage(`9007199254740993`)} + if got := archiveRowIdentity("wiki_log_entries", row); got != "9007199254740993" { + t.Fatalf("bigint identity lost: %q", got) + } +} + +func TestContractUnknownNonemptyIdentityRejected(t *testing.T) { + for _, tc := range []struct{ name, table, body string }{ + {"missing", "chunks", `[{}]`}, + {"numeric_string", "wiki_log_entries", `[{"id":"18"}]`}, + {"fraction", "wiki_log_entries", `[{"id":18.5}]`}, + {"unknown_table", "unreviewed", `[{"id":"uuid"}]`}, + {"duplicate", "chunks", `[{"id":"same"},{"id":"same"}]`}, + } { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + archive, err := librarysnapshot.Open(root, 1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + part, err := archive.Put(bytes.NewBufferString(tc.body)) + if err != nil { + t.Fatal(err) + } + part.Name = tc.table + if ids, err := archivedRowIdentities(archive, part); err == nil { + t.Fatalf("unsafe identity accepted: %v", ids) + } + }) + } +} + +func TestContractContentPreservesIntegersAndExpiry(t *testing.T) { + for _, pair := range [][2]string{ + {`{"metadata":{"n":9007199254740992}}`, `{"metadata":{"n":9007199254740993}}`}, + {`{"expires_at":"2026-01-01T00:00:00Z"}`, `{"expires_at":"2027-01-01T00:00:00Z"}`}, + } { + var a, b map[string]json.RawMessage + if err := json.Unmarshal([]byte(pair[0]), &a); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal([]byte(pair[1]), &b); err != nil { + t.Fatal(err) + } + x, err := canonicalRowDigest(a) + if err != nil { + t.Fatal(err) + } + y, err := canonicalRowDigest(b) + if err != nil { + t.Fatal(err) + } + if x == y { + t.Fatalf("distinct content collapsed: %s vs %s", pair[0], pair[1]) + } + } +} + +func TestContractExactTupleAndSameTenantIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, err := fx.pool.Exec(fx.ctx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id) VALUES('tag-target',10001,'kb-target'); INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES('doc-target','tag-target')`); err != nil { + t.Fatal(err) + } + target := fx.target(t) + owners, err := target.existingRowOwners(fx.ctx, "knowledge_tag_relations", []string{"doc-target:tag-target", "doc-target:absent"}) + if err != nil { + t.Fatal(err) + } + if len(owners) != 1 || owners["doc-target:tag-target"] != "10001/kb-target" { + t.Fatalf("tuple existence wrong: %v", owners) + } + snapshot := sealSourceSnapshotScope(t, fx, wsTargetTenant, wsSourceKB, nil, nil) + archive, err := librarysnapshot.Open(fx.archiveRoot, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + manifest, err := archive.Load(snapshot) + if err != nil { + t.Fatal(err) + } + if _, err := fx.pool.Exec(fx.ctx, `INSERT INTO knowledges(id,tenant_id,knowledge_base_id) VALUES('doc-src',10001,'kb-target')`); err != nil { + t.Fatal(err) + } + if err := target.bindSnapshotScope(manifestScope{tenantID: wsTargetTenant, knowledgeBaseID: wsSourceKB}); err != nil { + t.Fatal(err) + } + if err := target.assertNoSourceScopeRows(fx.ctx, archive, manifest); err != nil { + t.Fatalf("correct same-tenant target mistaken for source residue: %v", err) + } +} diff --git a/internal/releaseadapter/v071/library_immutable.go b/internal/releaseadapter/v071/library_immutable.go new file mode 100644 index 0000000..c22d5f5 --- /dev/null +++ b/internal/releaseadapter/v071/library_immutable.go @@ -0,0 +1,89 @@ +package v071 + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" +) + +// Publish without replacement: a second writer can only verify the already +// committed bytes. Sync both the file and directory entries before returning an +// anchor that another process may act on. This is not a power-loss test. +func persistImmutableJSON(path string, raw []byte) error { + directory := filepath.Dir(path) + if err := ensureEvidenceDirectory(directory, syncEvidenceDirectory); err != nil { + return err + } + info, err := os.Lstat(directory) + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("immutable evidence directory is not a real directory") + } + existing := func() error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return errors.New("immutable evidence is not a regular file") + } + body, err := os.ReadFile(path) + if err != nil { + return err + } + if !bytes.Equal(body, raw) { + return errors.New("immutable evidence already exists with different bytes") + } + return syncEvidenceDirectory(directory) + } + if _, err := os.Lstat(path); err == nil { + return existing() + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + file, err := os.CreateTemp(directory, ".evidence-*") + if err != nil { + return err + } + temporary := file.Name() + defer os.Remove(temporary) + defer file.Close() + if _, err := file.Write(raw); err != nil { + return err + } + if err := file.Chmod(0444); err != nil { + return err + } + if err := file.Sync(); err != nil { + return err + } + if err := file.Close(); err != nil { + return err + } + if err := os.Link(temporary, path); err != nil { + if errors.Is(err, os.ErrExist) { + return existing() + } + return fmt.Errorf("commit immutable evidence: %w", err) + } + if err := os.Remove(temporary); err != nil { + return err + } + return syncEvidenceDirectory(directory) +} + +func syncEvidenceDirectory(path string) error { + directory, err := os.Open(path) + if err != nil { + return err + } + defer directory.Close() + if err := directory.Sync(); err != nil { + return fmt.Errorf("sync evidence directory: %w", err) + } + return nil +} diff --git a/internal/releaseadapter/v071/library_index_claim.go b/internal/releaseadapter/v071/library_index_claim.go new file mode 100644 index 0000000..c64cd4b --- /dev/null +++ b/internal/releaseadapter/v071/library_index_claim.go @@ -0,0 +1,112 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + + "knowledge-governance/internal/libraryrelease" +) + +const indexClaimPrefix = "kg-release-transient-claim:" + +// The transient marker is only visible inside the maintenance window. Final +// content is byte-equivalent to the frozen source, without control-plane fields. +// A matching payload alone never establishes ownership of an ambiguous write. +func (t *ProductionLibraryTarget) indexClaimBody(c libraryrelease.IndexWrite) (json.RawMessage, error) { + if len(c.After) == 0 { + return nil, errors.New("deleted index document has no ownership marker") + } + var body map[string]json.RawMessage + if json.Unmarshal(c.After, &body) != nil || body == nil { + return nil, errors.New("invalid index claim source") + } + var content string + if json.Unmarshal(body["content"], &content) != nil { + return nil, errors.New("index claim requires existing string content field") + } + sum := sha256.Sum256([]byte(t.activePlan.Digest + "\x00" + c.Index + "\x00" + c.ID + "\x00apply")) + body["content"], _ = json.Marshal(indexClaimPrefix + hex.EncodeToString(sum[:]) + "\n" + content) + encoded, err := json.Marshal(body) + if err != nil { + return nil, err + } + return canonicalJSON(encoded) +} +func (t *ProductionLibraryTarget) applyIndexClaim(ctx context.Context, c libraryrelease.IndexWrite) (indexReceipt, error) { + if len(c.After) == 0 { + return t.mutatePlannedIndex(ctx, c, nil, c.SeqNo, c.PrimaryTerm, false) + } + body, err := t.indexClaimBody(c) + if err != nil { + return indexReceipt{}, err + } + receipt, err := t.mutatePlannedIndex(ctx, c, body, c.SeqNo, c.PrimaryTerm, len(c.Before) == 0) + if err != nil { + return receipt, err + } + receipt.Marked = true + if err = t.saveIndexEffect(c, "claimed", &receipt); err != nil { + return receipt, err + } + return t.finalizeIndexClaim(ctx, c) +} +func (t *ProductionLibraryTarget) reconcileIndexClaim(ctx context.Context, c libraryrelease.IndexWrite) (indexReceipt, error) { + empty := indexReceipt{} + intent, err := t.loadIndexEffect(c, "apply-intent") + if err != nil { + return empty, err + } + if intent == nil { + return empty, errors.New("index claim has no durable intent") + } + finalizing, err := t.loadIndexEffect(c, "finalize-intent") + if err != nil { + return empty, err + } + if finalizing != nil { + return empty, errors.New("unknown clean finalization cannot be attributed by appearance") + } + body, err := t.indexClaimBody(c) + if err != nil { + return empty, err + } + g, err := t.observePlannedIndex(ctx, c) + if err != nil { + return empty, err + } + if !indexBytesEqual(g, body) || g.SeqNo == nil || g.PrimaryTerm == nil { + return empty, errors.New("unknown index effect lacks exact operation marker/content/CAS") + } + claimed, err := t.loadIndexEffect(c, "claimed") + if err != nil { + return empty, err + } + if claimed != nil { + if claimed.Receipt == nil || !claimed.Receipt.Marked || !sameIndexGeneration(g, claimed.Receipt.SeqNo, claimed.Receipt.PrimaryTerm) { + return empty, errors.New("claimed index generation changed") + } + return *claimed.Receipt, nil + } + result := "updated" + if len(c.Before) == 0 { + result = "created" + } + receipt := indexReceipt{Index: c.Index, ID: c.ID, Result: result, SeqNo: g.SeqNo, PrimaryTerm: g.PrimaryTerm, Marked: true} + if err = t.saveIndexEffect(c, "claimed", &receipt); err != nil { + return empty, err + } + return receipt, nil +} +func (t *ProductionLibraryTarget) finalizeIndexClaim(ctx context.Context, c libraryrelease.IndexWrite) (indexReceipt, error) { + receipt, err := t.reconcileIndexClaim(ctx, c) + if err != nil { + return indexReceipt{}, err + } + if err = t.saveIndexEffect(c, "finalize-intent", &receipt); err != nil { + return indexReceipt{}, err + } + return t.mutatePlannedIndex(ctx, c, c.After, receipt.SeqNo, receipt.PrimaryTerm, false) +} diff --git a/internal/releaseadapter/v071/library_index_claim_test.go b/internal/releaseadapter/v071/library_index_claim_test.go new file mode 100644 index 0000000..81ff5af --- /dev/null +++ b/internal/releaseadapter/v071/library_index_claim_test.go @@ -0,0 +1,128 @@ +package v071 + +import ( + "encoding/json" + "net/http" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +func TestContractIndexUnknownEvidenceBoundariesIsolated(t *testing.T) { + for _, scenario := range []string{"wrong-marker", "changed-content", "changed-generation", "unrecorded-finalize"} { + t.Run(scenario, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatal(err) + } + backup, err := fx.backups(t, target).Prepare(fx.ctx, snapshot, current) + if err != nil { + t.Fatal(err) + } + backup.WriteSet = planLedgerWithUniverse(t, target, snapshot, backup.SnapshotID, backup.Universe) + var change libraryrelease.IndexWrite + for _, c := range backup.WriteSet.Index { + if len(c.Before) == 0 && len(c.After) > 0 { + change = c + break + } + } + if change.ID == "" { + t.Fatal("fixture has no new ID") + } + if err = target.saveIndexEffect(change, "apply-intent", nil); err != nil { + t.Fatal(err) + } + body, err := target.indexClaimBody(change) + if err != nil { + t.Fatal(err) + } + receipt, err := target.mutatePlannedIndex(fx.ctx, change, body, nil, nil, true) + if err != nil { + t.Fatal(err) + } + receipt.Marked = true + switch scenario { + case "wrong-marker", "changed-content": + var data map[string]json.RawMessage + if err = json.Unmarshal(body, &data); err != nil { + t.Fatal(err) + } + if scenario == "wrong-marker" { + data["content"] = json.RawMessage(`"foreign-owner-marker"`) + } else { + data["knowledge_id"] = json.RawMessage(`"different-knowledge"`) + } + body, err = json.Marshal(data) + if err != nil { + t.Fatal(err) + } + case "changed-generation", "unrecorded-finalize": + if err = target.saveIndexEffect(change, "claimed", &receipt); err != nil { + t.Fatal(err) + } + if scenario == "unrecorded-finalize" { + if err = target.saveIndexEffect(change, "finalize-intent", &receipt); err != nil { + t.Fatal(err) + } + body = change.After + } + } + if _, err = target.mutatePlannedIndex(fx.ctx, change, body, receipt.SeqNo, receipt.PrimaryTerm, false); err != nil { + t.Fatal(err) + } + before, err := target.observePlannedIndex(fx.ctx, change) + if err != nil { + t.Fatal(err) + } + next := fx.target(t) + if err = next.Restore(fx.ctx, backup); err == nil { + t.Fatal("unattributable write was compensated") + } + after, err := next.observePlannedIndex(fx.ctx, change) + if err != nil || !sameIndexGeneration(after, before.SeqNo, before.PrimaryTerm) || !indexBytesEqual(after, mustCanonicalIndex(t, before.Source)) { + t.Fatal("refused recovery changed foreign content", err) + } + }) + } +} +func mustCanonicalIndex(t *testing.T, raw json.RawMessage) json.RawMessage { + t.Helper() + body, err := canonicalJSON(raw) + if err != nil { + t.Fatal(err) + } + return body +} + +func TestContractIndexClaimDoesNotAlterMappingIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + before, err := target.Search().MappingSHA256(fx.ctx) + if err != nil { + t.Fatal(err) + } + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if result.State != "succeeded" { + t.Fatalf("apply: %+v", result) + } + after, err := target.Search().MappingSHA256(fx.ctx) + if err != nil || before != after { + t.Fatal("operation provenance mutated business mapping", err) + } + for _, change := range result.Backup.WriteSet.Index { + observed, err := target.observePlannedIndex(fx.ctx, change) + if err != nil || !indexBytesEqual(observed, change.After) { + t.Fatal("transient marker survived successful release", err) + } + } +} + +// Compile-time guard: test transport continues to implement the real interface. +var _ http.RoundTripper = (*indexLostResponseTransport)(nil) diff --git a/internal/releaseadapter/v071/library_index_completeness_test.go b/internal/releaseadapter/v071/library_index_completeness_test.go index 762ec64..3fa8421 100644 --- a/internal/releaseadapter/v071/library_index_completeness_test.go +++ b/internal/releaseadapter/v071/library_index_completeness_test.go @@ -4,47 +4,19 @@ import ( "context" "encoding/json" "os" - "strings" "testing" "time" "knowledge-governance/internal/librarysnapshot" ) -func TestLibraryCandidateIndexCompletenessUsesChunkIdentity(t *testing.T) { - for _, mode := range []string{"stored-parent", "multiple-records-one-chunk", "same-count-missing-chunk"} { - t.Run(mode, func(t *testing.T) { - pg, es, _ := libraryCandidateFixture() - rows := []json.RawMessage{json.RawMessage(`{"id":"chunk-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"chunk","status":2,"chunk_type":"text"}`)} - if mode == "stored-parent" { - rows = append(rows, json.RawMessage(`{"id":"parent-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"context","status":1,"chunk_type":"parent_text"}`)) - } else { - es.Documents = append(es.Documents, SearchDocument{ID: "es-second", Source: append(json.RawMessage(nil), es.Documents[0].Source...)}) - if mode == "same-count-missing-chunk" { - rows = append(rows, json.RawMessage(`{"id":"chunk-second","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"second","status":2,"chunk_type":"text"}`)) - } - } - pg.Tables[1] = newTableSnapshot("chunks", rows) - es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents) - err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es) - if mode == "same-count-missing-chunk" { - if err == nil || !strings.Contains(err.Error(), "missing indexed library chunk") { - t.Fatalf("same counts masked a missing chunk: %v", err) - } - } else if err != nil { - t.Fatalf("valid index shape rejected: %v", err) - } - }) - } -} - -func TestLibraryCandidateRejectsMissingIndexedChunk(t *testing.T) { +// R3f: the source owns whether a body chunk has an original-text index. +// Governance captures the actual PG/ES sets and must not infer an index from +// status, chunk type or parent shape. This replaces the old missing-index +// negative test, which encoded that inferred rule. +func TestLibraryCandidateCapturesBodyWithoutIndex(t *testing.T) { pg, es, objects := libraryCandidateFixture() pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-safe","tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","content":"chunk","status":2,"chunk_type":"text"}`)}) - identity := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"} - if err := validateLibraryCandidate(identity, pg, es); err != nil { - t.Fatalf("complete indexed chunk rejected: %v", err) - } es.Documents = nil es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents) root := t.TempDir() @@ -57,15 +29,16 @@ func TestLibraryCandidateRejectsMissingIndexedChunk(t *testing.T) { } defer archive.Close() contract := librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "fixture-model", EmbeddingDimension: 1024, IndexMappingSHA256: es.MappingSHA256} - id, err := ArchiveLibraryCandidate(context.Background(), archive, "internal", identity, contract, pg, es, objects, time.Now().UTC()) - if err == nil || id != "" { - t.Fatal("sealed a supposedly complete library with an indexed PostgreSQL chunk missing from Elasticsearch") + id, err := ArchiveLibraryCandidate(context.Background(), archive, "internal", + PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, contract, pg, es, objects, time.Now().UTC()) + if err != nil || id == "" { + t.Fatalf("body without original-text index must be captured as-is: id=%q err=%v", id, err) } - if !strings.Contains(err.Error(), "missing indexed library chunk") { - t.Fatalf("unexpected refusal: %v", err) + manifest, err := archive.Load(id) + if err != nil { + t.Fatal(err) } - versions, err := os.ReadDir(root + "/versions") - if err != nil || len(versions) != 0 { - t.Fatalf("incomplete candidate became visible: versions=%d err=%v", len(versions), err) + if err := validateArchivedLibraryClosure(archive, manifest); err != nil { + t.Fatalf("readback of the captured body failed: %v", err) } } diff --git a/internal/releaseadapter/v071/library_index_delete_reconcile.go b/internal/releaseadapter/v071/library_index_delete_reconcile.go new file mode 100644 index 0000000..bb44ab4 --- /dev/null +++ b/internal/releaseadapter/v071/library_index_delete_reconcile.go @@ -0,0 +1,57 @@ +package v071 + +import ( + "bytes" + "context" + "encoding/json" + "errors" + + "knowledge-governance/internal/libraryrelease" +) + +// Unlike an ambiguous create, deletion of a known CAS generation can settle on +// absence: a delayed delete still carries that old seq_no/primary_term and cannot +// delete a subsequently recreated generation. This never infers PUT completion. +func (t *ProductionLibraryTarget) reconcileIndexCompensationDelete(ctx context.Context, c libraryrelease.IndexWrite) (bool, error) { + if len(c.Before) != 0 || len(c.After) == 0 { + return false, nil + } + intent, e := t.loadIndexEffect(c, "restore-intent") + if e != nil || intent == nil { + return false, e + } + if intent.Receipt == nil || *intent.Receipt.SeqNo < 0 || *intent.Receipt.PrimaryTerm < 1 { + return false, errors.New("index delete compensation lacks known generation") + } + proof, e := t.loadIndexEffect(c, "applied") + if e != nil { + return false, e + } + if proof == nil { + proof, e = t.loadIndexEffect(c, "claimed") + if e != nil { + return false, e + } + } + if proof == nil || proof.Receipt == nil { + return false, errors.New("index delete compensation lacks persisted ownership") + } + want, _ := json.Marshal(proof.Receipt) + got, _ := json.Marshal(intent.Receipt) + if !bytes.Equal(want, got) { + return false, errors.New("index delete compensation CAS differs from owned receipt") + } + observation, e := t.observePlannedIndex(ctx, c) + if e != nil { + return false, e + } + if observation.Found { + return false, nil + } + // No fabricated DELETE response/generation: proof is the bound restore intent, + // persisted ownership receipt and independent authoritative absent observation. + if e = t.saveIndexEffect(c, "restored", nil); e != nil { + return false, e + } + return true, nil +} diff --git a/internal/releaseadapter/v071/library_index_delete_reconcile_test.go b/internal/releaseadapter/v071/library_index_delete_reconcile_test.go new file mode 100644 index 0000000..a421398 --- /dev/null +++ b/internal/releaseadapter/v071/library_index_delete_reconcile_test.go @@ -0,0 +1,108 @@ +package v071 + +import ( + "errors" + "net/http" + "net/url" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +type indexDeleteLostResponse struct { + inner http.RoundTripper + id string + dropped bool + sends int +} + +func (f *indexDeleteLostResponse) RoundTrip(r *http.Request) (*http.Response, error) { + if r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/_doc/"+url.PathEscape(f.id)) { + f.sends++ + } + resp, e := f.inner.RoundTrip(r) + if e == nil && !f.dropped && r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/_doc/"+url.PathEscape(f.id)) && resp.StatusCode == 200 { + f.dropped = true + resp.Body.Close() + return nil, errors.New("injected response loss after exact CAS delete") + } + return resp, e +} +func TestContractIndexDeleteCompensationLostResponseIsolated(t *testing.T) { + runIndexDeleteReconcile(t, false) +} +func TestContractIndexDeleteRecreatedGenerationRefusedIsolated(t *testing.T) { + runIndexDeleteReconcile(t, true) +} +func runIndexDeleteReconcile(t *testing.T, recreate bool) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "succeeded" { + t.Fatalf("fixture release failed: %+v", outcome) + } + id := "" + var created libraryrelease.IndexWrite + for _, c := range outcome.Backup.WriteSet.Index { + if len(c.Before) == 0 && len(c.After) > 0 { + id = c.ID + created = c + break + } + } + if id == "" { + t.Fatal("valid newly-created index fixture missing") + } + client := *target.search.client + transport := client.Transport + if transport == nil { + transport = http.DefaultTransport + } + fault := &indexDeleteLostResponse{inner: transport, id: id} + client.Transport = fault + target.search.client = &client + if e := target.Restore(fx.ctx, outcome.Backup); e == nil || !fault.dropped { + t.Fatal("real CAS delete response loss not exercised", e) + } + next := fx.target(t) + next.search.client = &client + if recreate { + replacement, e := next.mutatePlannedIndex(fx.ctx, created, created.After, nil, nil, true) + if e != nil { + t.Fatal(e) + } + if e = next.Restore(fx.ctx, outcome.Backup); e == nil { + t.Fatal("recreated generation accepted as absent") + } + observed, e := next.observePlannedIndex(fx.ctx, created) + if e != nil || !sameIndexGeneration(observed, replacement.SeqNo, replacement.PrimaryTerm) || !indexBytesEqual(observed, created.After) { + t.Fatal("foreign successor changed", e) + } + if fault.sends != 1 { + t.Fatal("delete reissued against successor") + } + return + } + if e := next.Restore(fx.ctx, outcome.Backup); e != nil { + t.Fatal("known-generation delete absence did not reconcile", e) + } + repeated := fx.target(t) + repeated.search.client = &client + if e := repeated.Restore(fx.ctx, outcome.Backup); e != nil { + t.Fatal("repeated exact restoration", e) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatal(diff) + } + if e := next.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: outcome.Backup.SnapshotID}); e != nil { + t.Fatal(e) + } + if fault.sends != 1 { + t.Fatal("exact CAS delete blindly replayed", fault.sends) + } + t.Log("real ES CAS deletion committed with response lost; fresh target restored exact backup without reissuing delete") +} diff --git a/internal/releaseadapter/v071/library_index_ds01_fixes_test.go b/internal/releaseadapter/v071/library_index_ds01_fixes_test.go new file mode 100644 index 0000000..e1b0b9c --- /dev/null +++ b/internal/releaseadapter/v071/library_index_ds01_fixes_test.go @@ -0,0 +1,383 @@ +package v071 + +import ( + "context" + "errors" + "os" + "reflect" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +// ds01StubGate 只用于分类测试:不产生许可,只返回给定的台账视图。 +type ds01StubGate struct { + inspectStatus libraryrelease.RestoreDispatchStatus + inspectFound bool + records []libraryrelease.RestoreDispatchRecord + confirmed int +} + +func (g *ds01StubGate) InspectRestoreMarker(context.Context, libraryrelease.RestoreMarkerBinding) (libraryrelease.RestoreDispatchStatus, bool, error) { + return g.inspectStatus, g.inspectFound, nil +} +func (g *ds01StubGate) PrepareRestoreMarker(context.Context, libraryrelease.RestoreMarkerBinding) (libraryrelease.RestoreDispatchStatus, error) { + return libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchPrepared}, nil +} +func (g *ds01StubGate) AcquireRestoreMarker(context.Context, libraryrelease.RestoreMarkerBinding) (*libraryrelease.RestoreSendPermit, libraryrelease.RestoreDispatchStatus, error) { + return nil, g.inspectStatus, libraryrelease.ErrRestoreDispatchHeld +} +func (g *ds01StubGate) ConfirmRestoreMarker(context.Context, libraryrelease.RestoreMarkerBinding, []byte) error { + g.confirmed++ + return nil +} +func (g *ds01StubGate) UnresolvedRestoreDispatches(context.Context, string, string, string) ([]libraryrelease.RestoreDispatchRecord, error) { + return g.records, nil +} + +func ds01FreezeBindingInputs(t *testing.T, target *ProductionLibraryTarget, backup libraryrelease.BackupRef) { + t.Helper() + target.restoreScope = "internal" + target.restoreSourceSnapshot = backup.WriteSet.TargetSnapshotID + target.restoreBackupSnapshot = backup.SnapshotID +} + +// DS01-F1:绑定必须来自原锚点——来源快照 != 写前镜像,且带真实目标实例/指纹/UUID。 +func TestDS01BindingUsesFrozenSourceAndRealBackup(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + ledger := outcome.Backup.WriteSet + if ledger.TargetSnapshotID == "" || outcome.Backup.SnapshotID == "" { + t.Fatal("fixture lacks a source snapshot or backup image") + } + if ledger.TargetSnapshotID == outcome.Backup.SnapshotID { + t.Fatalf("fixture plan uses one snapshot for both source and backup: %s", ledger.TargetSnapshotID) + } + if err := target.AdoptWriteSet(*ledger); err != nil { + t.Fatal(err) + } + ds01FreezeBindingInputs(t, target, outcome.Backup) + change := indexChangeOf(t, ledger, "chunk-target") + body, err := target.restoreIndexClaimBody(change) + if err != nil { + t.Fatal(err) + } + binding, err := target.restoreMarkerBinding(fx.ctx, change, body) + if err != nil { + t.Fatalf("real binding: %v", err) + } + if binding.SourceSnapshot != ledger.TargetSnapshotID { + t.Fatalf("binding source = %q, plan source = %q", binding.SourceSnapshot, ledger.TargetSnapshotID) + } + if binding.BackupSnapshot != outcome.Backup.SnapshotID { + t.Fatalf("binding backup = %q, real backup = %q", binding.BackupSnapshot, outcome.Backup.SnapshotID) + } + if binding.SourceSnapshot == binding.BackupSnapshot { + t.Fatal("binding still uses the same snapshot for source and backup") + } + if binding.Scope == "" || binding.TargetInstance != ds01TargetInstance || + binding.TargetFingerprint != authority.targetFingerprint || binding.IndexUUID != authority.indexUUID { + t.Fatalf("binding lacks the real target identity: %+v", binding) + } + status, found, err := authority.store.InspectRestoreMarker(fx.ctx, binding) + if err != nil || !found || status.State != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("real ledger rejected the frozen binding: %+v found=%v err=%v", status, found, err) + } + // 缺任一锚点都必须失败关闭。 + target.restoreSourceSnapshot = "" + if _, err := target.restoreMarkerBinding(fx.ctx, change, body); err == nil { + t.Fatal("binding accepted without a source snapshot anchor") + } +} + +// DS01-F4:绑定冲突(prepared + Held)必须在任何目标写之前拒绝,不能继续 replay。 +func TestDS01BindingConflictHeldBeforeAnyWrite(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + if err := target.AdoptWriteSet(*outcome.Backup.WriteSet); err != nil { + t.Fatal(err) + } + ds01FreezeBindingInputs(t, target, outcome.Backup) + target.config.RestoreDispatch = &ds01StubGate{inspectFound: true, + inspectStatus: libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchPrepared, Held: true, + Reason: "binding differs"}} + beforePG := universeDump(t, fx.pool) + beforeIndex := recoveryIndexReadback(t, fx) + beforeObjects := objectVersionSet(t, fx) + beforeDispatch := wire.dispatch + + err := target.Restore(fx.ctx, outcome.Backup) + if err == nil || !strings.Contains(err.Error(), "held") { + t.Fatalf("binding conflict admission = %v", err) + } + if wire.dispatch != beforeDispatch { + t.Fatalf("binding conflict forwarded %d marker writes", wire.dispatch-beforeDispatch) + } + if diff := diffUniverse(beforePG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("binding conflict wrote PG before admission: %s", diff) + } + if after := recoveryIndexReadback(t, fx); !reflect.DeepEqual(beforeIndex, after) { + t.Fatal("binding conflict changed the index") + } + if after := objectVersionSet(t, fx); !reflect.DeepEqual(beforeObjects, after) { + t.Fatal("binding conflict changed objects") + } +} + +// DS01-F4.binding:绑定冲突是**类型化**分类——prepared/dispatching/marker_confirmed/ +// done 任一状态、准入/确认/收尾任一入口都必须拒绝;合法 dispatching + 精确 marker +// (不冲突)仍允许确认,不能用"拒绝全部 Held"掩盖。 +func TestDS01BindingConflictRejectedInEveryState(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + ledger := outcome.Backup.WriteSet + if err := target.AdoptWriteSet(*ledger); err != nil { + t.Fatal(err) + } + ds01FreezeBindingInputs(t, target, outcome.Backup) + change := indexChangeOf(t, ledger, "chunk-target") + body, err := target.restoreIndexClaimBody(change) + if err != nil { + t.Fatal(err) + } + // 在目标上写入精确 marker:这样 dispatching 状态本来是可确认的,冲突检查必须 + // 独立地拒绝它,而不是靠"marker 不在"。 + applied, err := target.loadIndexEffect(change, "applied") + if err != nil || applied == nil || applied.Receipt == nil { + t.Fatalf("applied receipt missing: %v", err) + } + method, path, payload, err := target.indexMutation(change, body, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm, true) + if err != nil { + t.Fatal(err) + } + var marker indexReceipt + if err := target.search.requestJSON(fx.ctx, method, path, payload, &marker); err != nil { + t.Fatalf("exact marker write: %v", err) + } + observed, err := target.observePlannedIndex(fx.ctx, change) + if err != nil { + t.Fatal(err) + } + // 从这里开始只允许确认,不允许任何新的 marker create。 + beforeDispatch := wire.dispatch + conflict := func(state string) *ds01StubGate { + return &ds01StubGate{inspectFound: true, inspectStatus: libraryrelease.RestoreDispatchStatus{ + State: state, Held: true, BindingConflict: true, Reason: "binding differs"}, + records: []libraryrelease.RestoreDispatchRecord{{PlanDigest: ledger.Digest, Index: change.Index, + DocumentID: change.ID, State: libraryrelease.RestoreDispatchMarkerConfirmed}}} + } + for _, state := range []string{ + libraryrelease.RestoreDispatchPrepared, + libraryrelease.RestoreDispatchDispatching, + libraryrelease.RestoreDispatchMarkerConfirmed, + } { + gate := conflict(state) + target.config.RestoreDispatch = gate + if err := target.admitRestorePlan(fx.ctx); err == nil || !strings.Contains(err.Error(), "冲突") { + t.Fatalf("admission accepted a binding conflict in %s: %v", state, err) + } + if err := target.confirmDispatchedMarker(fx.ctx, change, body, observed); err == nil || !strings.Contains(err.Error(), "冲突") { + t.Fatalf("confirmation accepted a binding conflict in %s: %v", state, err) + } + if gate.confirmed != 0 { + t.Fatalf("binding conflict in %s still recorded a confirmation", state) + } + } + + // done 状态:restored 文件已在,准入仍必须因绑定冲突拒绝(旧实现只看状态)。 + receipt := indexReceipt{Index: change.Index, ID: change.ID, Result: "created", + SeqNo: marker.SeqNo, PrimaryTerm: marker.PrimaryTerm} + if err := target.saveIndexEffect(change, "restored", &receipt); err != nil { + t.Fatal(err) + } + target.config.RestoreDispatch = conflict(libraryrelease.RestoreDispatchMarkerConfirmed) + if err := target.admitRestorePlan(fx.ctx); err == nil || !strings.Contains(err.Error(), "冲突") { + t.Fatalf("admission accepted a binding conflict on a completed effect: %v", err) + } + // 收尾:记录状态看起来是 marker_confirmed、restored 也存在,但绑定冲突必须拒绝。 + gate := conflict(libraryrelease.RestoreDispatchMarkerConfirmed) + target.config.RestoreDispatch = gate + if err := target.verifyRestoreEffectsClosed(fx.ctx); err == nil || !strings.Contains(err.Error(), "冲突") { + t.Fatalf("closeout accepted a binding conflict: %v", err) + } + if gate.confirmed != 0 { + t.Fatal("closeout recorded a confirmation for a conflicting binding") + } + + // 正例:合法 dispatching + 精确 marker(不冲突)仍可确认,且只确认一次。 + okGate := &ds01StubGate{inspectFound: true, + inspectStatus: libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchDispatching, Held: true, + Reason: "dispatch outcome unknown: no further create is permitted"}} + target.config.RestoreDispatch = okGate + if err := target.confirmDispatchedMarker(fx.ctx, change, body, observed); err != nil { + t.Fatalf("legitimate dispatching marker confirmation: %v", err) + } + if okGate.confirmed != 1 { + t.Fatalf("legitimate marker confirmation count = %d", okGate.confirmed) + } + if wire.dispatch != beforeDispatch { + t.Fatalf("confirmation path forwarded %d marker writes", wire.dispatch-beforeDispatch) + } +} + +// DS01-F4:prepared 台账却已在目标上出现精确 marker —— 证据矛盾,必须 held; +// 旧实现会把它当成"已存在的标记"认领并 clean。 +func TestDS01PreparedWithMarkerIsContradictionHeld(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("boundary state = %s", state) + } + ledger := outcome.Backup.WriteSet + if err := target.AdoptWriteSet(*ledger); err != nil { + t.Fatal(err) + } + ds01FreezeBindingInputs(t, target, outcome.Backup) + change := indexChangeOf(t, ledger, "chunk-target") + body, err := target.restoreIndexClaimBody(change) + if err != nil { + t.Fatal(err) + } + // 模拟一个绕过协议的旧 writer:目标上直接出现精确 marker,但台账仍是 prepared。 + applied, err := target.loadIndexEffect(change, "applied") + if err != nil || applied == nil || applied.Receipt == nil { + t.Fatalf("applied receipt missing: %v", err) + } + method, path, payload, err := target.indexMutation(change, body, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm, true) + if err != nil { + t.Fatal(err) + } + var receipt indexReceipt + if err := target.search.requestJSON(fx.ctx, method, path, payload, &receipt); err != nil { + t.Fatalf("foreign marker write: %v", err) + } + beforePG := universeDump(t, fx.pool) + beforeDispatch := wire.dispatch + + err = target.Restore(fx.ctx, outcome.Backup) + if err == nil || !strings.Contains(err.Error(), "held") { + t.Fatalf("prepared+marker admission = %v", err) + } + if wire.dispatch != beforeDispatch { + t.Fatalf("prepared+marker forwarded %d marker writes", wire.dispatch-beforeDispatch) + } + if diff := diffUniverse(beforePG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("prepared+marker wrote PG before admission: %s", diff) + } + requireIndexEffect(t, fx, ledger, change, "restored", false) + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("dispatch state moved to %s", state) + } +} + +// DS01-F4:收尾必须用原 window 的权威未决全集;计划外记录与 prepared 记录都拒绝。 +func TestDS01CloseoutUsesAuthoritativeWindowSet(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + ledger := outcome.Backup.WriteSet + if err := target.AdoptWriteSet(*ledger); err != nil { + t.Fatal(err) + } + ds01FreezeBindingInputs(t, target, outcome.Backup) + change := indexChangeOf(t, ledger, "chunk-target") + + // 台账里的 prepared 记录本身就必须拒绝收尾(旧实现只拒绝 dispatching)。 + if err := target.verifyRestoreEffectsClosed(fx.ctx); err == nil || !strings.Contains(err.Error(), "未决") { + t.Fatalf("closeout accepted a prepared dispatch record: %v", err) + } + // 计划外原窗口记录:即使当前 plan 的 effect 看起来都已完成,也必须拒绝。 + target.config.RestoreDispatch = &ds01StubGate{inspectFound: true, + inspectStatus: libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchMarkerConfirmed}, + records: []libraryrelease.RestoreDispatchRecord{{ + PlanDigest: ledger.Digest, Index: change.Index, DocumentID: "ghost-document", + State: libraryrelease.RestoreDispatchMarkerConfirmed}}} + if err := target.verifyRestoreEffectsClosed(fx.ctx); err == nil || !strings.Contains(err.Error(), "计划外") { + t.Fatalf("closeout accepted a plan-outside record: %v", err) + } + // 换 plan 别名也必须拒绝。 + target.config.RestoreDispatch = &ds01StubGate{inspectFound: true, + inspectStatus: libraryrelease.RestoreDispatchStatus{State: libraryrelease.RestoreDispatchMarkerConfirmed}, + records: []libraryrelease.RestoreDispatchRecord{{ + PlanDigest: "another-plan", Index: change.Index, DocumentID: change.ID, + State: libraryrelease.RestoreDispatchMarkerConfirmed}}} + if err := target.verifyRestoreEffectsClosed(fx.ctx); err == nil || !strings.Contains(err.Error(), "另一份计划") { + t.Fatalf("closeout accepted a plan alias: %v", err) + } +} + +// DS01-F5:prepared 已提交、mark-intent 文件写失败 ⇒ 重启后可补同内容并只派发一次; +// 无台账的旧意图仍按 legacy held(本文件同时守住两个方向)。 +func TestDS01PreparedWithoutIntentResumesOnce(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + changeID := "chunk-target" + target.restoreIntentFault = func(c libraryrelease.IndexWrite) error { + if c.ID == changeID { + return errors.New("injected mark-intent file write failure") + } + return nil + } + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, backups, nil) + if outcome.State != "rollback_failed" || !strings.Contains(outcome.Rollback, "mark-intent") { + t.Fatalf("intent write failure not reached: state=%q rollback=%q", outcome.State, outcome.Rollback) + } + ledger := outcome.Backup.WriteSet + change := indexChangeOf(t, ledger, changeID) + requireIndexEffect(t, fx, ledger, change, "restore-intent", true) + requireIndexEffect(t, fx, ledger, change, "restore-mark-intent", false) + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("after intent failure dispatch row = %s", state) + } + if wire.dispatch != 0 { + t.Fatalf("intent failure forwarded %d marker writes", wire.dispatch) + } + + // 新调用(同一 attempt)看到 prepared + 无 mark-intent:补同内容意图后继续。 + if err := target.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatalf("prepared-without-intent resume: %v", err) + } + requireIndexEffect(t, fx, ledger, change, "restore-mark-intent", true) + requireIndexEffect(t, fx, ledger, change, "restored", true) + if wire.dispatch != 1 { + t.Fatalf("resume forwarded %d marker creates, want 1", wire.dispatch) + } + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchMarkerConfirmed { + t.Fatalf("terminal state = %s", state) + } +} + +// 无台账的旧意图仍然 held:补意图的能力只对新协议 prepared 区段开放。 +func TestDS01LegacyIntentWithoutLedgerStillHeld(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + legacy := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + ledger := legacy.Backup.WriteSet + change := indexChangeOf(t, ledger, "chunk-target") + // 删掉 mark-intent,模拟"只剩旧意图、没有新台账"的历史现场。 + if err := os.Remove(target.indexEffectPath(change, "restore-mark-intent")); err != nil { + t.Fatal(err) + } + err := target.Restore(fx.ctx, legacy.Backup) + if err == nil || !strings.Contains(err.Error(), "legacy") { + t.Fatalf("legacy intent without ledger = %v", err) + } + if wire.dispatch != 0 { + t.Fatalf("legacy intent forwarded %d marker writes", wire.dispatch) + } + if rows := authority.dispatchRows(t); rows != 0 { + t.Fatalf("legacy intent created %d dispatch rows", rows) + } +} diff --git a/internal/releaseadapter/v071/library_index_ds01_test.go b/internal/releaseadapter/v071/library_index_ds01_test.go new file mode 100644 index 0000000..ee1a2d3 --- /dev/null +++ b/internal/releaseadapter/v071/library_index_ds01_test.go @@ -0,0 +1,628 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/libraryrelease" + postgresstore "knowledge-governance/internal/platform/postgres" + "knowledge-governance/internal/platform/postgres/pgtest" + "knowledge-governance/internal/version" +) + +// DS01:删除型恢复派发协议的 adapter 层验收。 +// +// 前置是真 ES、真 PG;治理台账放在**独立的治理 schema**(不是业务目标 schema)。 +// 这里不制造"prepared 且从未派发"的假正例:prepared 一律由真实 Prepare 产生。 + +const ds01TargetIdentity = "kg-ds01-test-target" +const ds01TargetInstance = "inst-ds01" + +type ds01Authority struct { + store *postgresstore.Store + pool *pgxpool.Pool + dsn string + operationID string + jobID string + owner string + epoch int64 + targetIdentity string + snapshot string + targetFingerprint string + indexUUID string +} + +func newDS01Authority(t *testing.T, jobID, snapshot string) *ds01Authority { + t.Helper() + base := os.Getenv("KG_DS01_GOVERNANCE_DSN") + if base == "" { + t.Skip("requires an isolated governance database (KG_DS01_GOVERNANCE_DSN)") + } + dsn := pgtest.IsolatedDatabaseURL(t, base) + ctx := context.Background() + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatalf("connect governance: %v", err) + } + t.Cleanup(pool.Close) + if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { + t.Fatalf("apply governance migrations: %v", err) + } + store := postgresstore.NewStore(pool) + now := time.Now().UTC() + op, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{ + ID: "op-" + jobID, Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: snapshot, + RequestDigest: "digest-" + jobID, OperationKey: jobID, Actor: "ds01-test", CreatedAt: now, + }) + if err != nil { + t.Fatalf("ensure operation: %v", err) + } + if _, _, err := store.CreateLibraryJob(ctx, governance.LibraryJob{ + ID: jobID, Scope: "internal", Kind: governance.LibraryJobSync, OperationID: op.ID, + IdempotencyKey: "library.job:" + op.ID, RequestDigest: "digest-" + jobID, + TargetSnapshotID: snapshot, Actor: "ds01-test", + }, governance.SyncStages(), now); err != nil { + t.Fatalf("create job: %v", err) + } + attempt, err := store.BeginLibraryAttempt(ctx, jobID, "worker-ds01#queue#1", 10*time.Minute, now) + if err != nil { + t.Fatalf("begin attempt: %v", err) + } + return &ds01Authority{store: store, pool: pool, dsn: dsn, operationID: attempt.OperationID, + jobID: attempt.JobID, owner: attempt.Owner, epoch: int64(attempt.Epoch), + targetIdentity: ds01TargetIdentity, snapshot: snapshot} +} + +// attach 把真实治理台账与本次 attempt 身份接到目标上。 +func (a *ds01Authority) attach(target *ProductionLibraryTarget) { + target.config.RestoreDispatch = a.store + target.config.RestoreTargetIdentity = a.targetIdentity + target.config.RestoreScope = "internal" + target.config.RestoreOperationID = a.operationID + target.config.RestoreWindowJobID = a.jobID + target.config.RestoreAttemptOwner = a.owner + target.config.RestoreAttemptEpoch = a.epoch + target.config.RestoreInstance = ds01TargetInstance + fingerprint, indexUUID, err := target.observeRestoreTarget(context.Background()) + if err != nil { + panic(err) + } + if _, err := a.pool.Exec(context.Background(), ` +INSERT INTO library_instance_maintenance (instance, owner_job_id, owner_scope, target_fingerprint, state, + original_service_state, note, acquired_at, updated_at) +VALUES ($1,$2,'internal',$3,'acquired','app:running','ds01-test',$4,$4) +ON CONFLICT (instance) DO UPDATE SET owner_job_id=EXCLUDED.owner_job_id, owner_scope=EXCLUDED.owner_scope, + target_fingerprint=EXCLUDED.target_fingerprint, released_at=NULL, state='acquired', updated_at=EXCLUDED.updated_at`, + ds01TargetInstance, a.jobID, fingerprint, time.Now().UTC()); err != nil { + panic(err) + } + a.targetFingerprint, a.indexUUID = fingerprint, indexUUID + if err := activateDS01(context.Background(), a.store, a.pool, ds01TargetIdentity, fingerprint); err != nil { + panic(err) + } +} + +func (a *ds01Authority) dispatchRow(t *testing.T) (state, owner string) { + t.Helper() + if err := a.pool.QueryRow(context.Background(), + `SELECT state, dispatch_owner FROM library_index_restore_dispatch`).Scan(&state, &owner); err != nil { + t.Fatalf("read dispatch row: %v", err) + } + return state, owner +} + +func (a *ds01Authority) dispatchEvidence(t *testing.T) string { + t.Helper() + var state, owner, nonce, receipt, binding string + var epoch int64 + if err := a.pool.QueryRow(context.Background(), + `SELECT state, dispatch_owner, dispatch_epoch, dispatch_nonce, binding_digest, + COALESCE(marker_receipt::text,'') + FROM library_index_restore_dispatch`).Scan(&state, &owner, &epoch, &nonce, &binding, &receipt); err != nil { + t.Fatalf("read dispatch evidence: %v", err) + } + return fmt.Sprintf("state=%s owner=%q epoch=%d nonce=%s binding=%s receipt=%s", state, owner, epoch, nonce, binding, receipt) +} + +func (a *ds01Authority) dispatchRows(t *testing.T) int { + t.Helper() + var count int + if err := a.pool.QueryRow(context.Background(), `SELECT count(*) FROM library_index_restore_dispatch`).Scan(&count); err != nil { + t.Fatal(err) + } + return count +} + +// ds01RunToBoundary 走真实应用→wiki 失败→自动 rollback:在删除型恢复标记的边界上 +// 用控制流故障拒绝,留下 prepared + 意图 + 0 次转发。 +func ds01RunToBoundary(t *testing.T, fx *writeSetFixture, snapshot string, target *ProductionLibraryTarget, + backups *ProductionBackupStore, wire *restoreMarkerWire) libraryrelease.Outcome { + t.Helper() + target.restoreMarkerFault = func(c libraryrelease.IndexWrite) error { + if c.ID != "chunk-target" { + return nil + } + return errDS01BoundaryRefusal + } + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, backups, nil) + if outcome.State != "rollback_failed" || !strings.Contains(outcome.Rollback, errDS01BoundaryRefusal.Error()) { + t.Fatalf("rollback_failed with DS01 boundary refusal expected, got state=%q rollback=%q", outcome.State, outcome.Rollback) + } + if wire.dispatch != 0 { + t.Fatalf("boundary refusal dispatched %d marker writes", wire.dispatch) + } + return outcome +} + +var errDS01BoundaryRefusal = &ds01BoundaryError{} + +type ds01BoundaryError struct{} + +func (*ds01BoundaryError) Error() string { + return "injected DS01 boundary refusal before dispatch CAS" +} + +func ds01Fixture(t *testing.T) (*writeSetFixture, string, *ProductionLibraryTarget, *ProductionBackupStore, *restoreMarkerWire) { + t.Helper() + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + client := *target.search.client + inner := client.Transport + if inner == nil { + inner = http.DefaultTransport + } + wire := &restoreMarkerWire{inner: inner} + client.Transport = wire + target.search.client = &client + return fx, snapshot, target, backups, wire +} + +// A7:旧 intent + missing、无台账 ⇒ 在任何 PG/resources 写之前 held。 +func TestDS01LegacyIntentWithoutLedgerStaysHeldBeforeAnyWrite(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + // 先用旧协议(未接线)造出"既存意图、无台账"的现场。 + legacy := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + ledger := legacy.Backup.WriteSet + change := indexChangeOf(t, ledger, "chunk-target") + requireIndexEffect(t, fx, ledger, change, "restore-mark-intent", true) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + if rows := authority.dispatchRows(t); rows != 0 { + t.Fatalf("legacy run created %d dispatch rows", rows) + } + beforePG := universeDump(t, fx.pool) + beforeIndex := recoveryIndexReadback(t, fx) + beforeObjects := objectVersionSet(t, fx) + beforeDispatch := wire.dispatch + + authority.attach(target) + target.restoreMarkerFault = nil + err := target.Restore(fx.ctx, legacy.Backup) + if err == nil || !strings.Contains(err.Error(), "held") { + t.Fatalf("legacy intent without ledger must stay held, got %v", err) + } + if wire.dispatch != beforeDispatch { + t.Fatalf("held legacy restoration dispatched %d marker writes", wire.dispatch-beforeDispatch) + } + if diff := diffUniverse(beforePG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("held legacy restoration wrote PG before admission: %s", diff) + } + if after := recoveryIndexReadback(t, fx); !reflect.DeepEqual(beforeIndex, after) { + t.Fatal("held legacy restoration changed the index") + } + if after := objectVersionSet(t, fx); !reflect.DeepEqual(beforeObjects, after) { + t.Fatal("held legacy restoration changed objects") + } + if rows := authority.dispatchRows(t); rows != 0 { + t.Fatalf("legacy path wrote %d dispatch rows", rows) + } +} + +// A9(同进程):prepared + 意图,边界拒绝 0 转发;新调用用同一 window/backup/plan +// 完成恢复,create 恰好转发一次,台账 marker_confirmed。 +func TestDS01PreparedEffectResumesToTerminalState(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + if state, owner := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchPrepared || owner != "" { + t.Fatalf("after boundary refusal row = %s/%s", state, owner) + } + t.Logf("boundary refusal: forwards=%d ledger=%s", wire.dispatch, authority.dispatchEvidence(t)) + ledger := outcome.Backup.WriteSet + change := indexChangeOf(t, ledger, "chunk-target") + requireIndexEffect(t, fx, ledger, change, "restore-claimed", false) + + target.restoreMarkerFault = nil + if err := target.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatalf("prepared effect did not resume: %v", err) + } + if wire.dispatch != 1 { + t.Fatalf("marker create forwarded %d times, want exactly 1", wire.dispatch) + } + t.Logf("resume: forwards=%d ledger=%s", wire.dispatch, authority.dispatchEvidence(t)) + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchMarkerConfirmed { + t.Fatalf("terminal dispatch state = %s", state) + } + requireIndexEffect(t, fx, ledger, change, "restored", true) + if err := target.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: outcome.Backup.SnapshotID}); err != nil { + t.Fatalf("restoration verify: %v", err) + } + // 重放同一次恢复:不再产生新的 create。 + if err := target.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatalf("replayed restoration: %v", err) + } + if wire.dispatch != 1 { + t.Fatalf("replayed restoration dispatched %d marker creates", wire.dispatch) + } +} + +// A8:commit 已落地、Do 之前进程死掉 ⇒ dispatching+missing 永久 held,零新发送, +// PG/对象/索引不变;第二次仍 held。 +func TestDS01DispatchingMissingStaysHeldWithZeroWrites(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + + // 模拟"CAS 提交成功、发送前进程死掉":真实 Acquire 把行推进到 dispatching,但不发送。 + ledger := outcome.Backup.WriteSet + if err := target.AdoptWriteSet(*ledger); err != nil { + t.Fatalf("adopt plan: %v", err) + } + change := indexChangeOf(t, ledger, "chunk-target") + body, err := target.restoreIndexClaimBody(change) + if err != nil { + t.Fatal(err) + } + binding, err := target.restoreMarkerBinding(fx.ctx, change, body) + if err != nil { + t.Fatal(err) + } + permit, _, err := authority.store.AcquireRestoreMarker(fx.ctx, binding) + if err != nil || permit == nil { + t.Fatalf("simulate committed dispatch: %v", err) + } + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchDispatching { + t.Fatalf("simulated state = %s", state) + } + beforePG := universeDump(t, fx.pool) + beforeIndex := recoveryIndexReadback(t, fx) + beforeObjects := objectVersionSet(t, fx) + beforeDispatch := wire.dispatch + + target.restoreMarkerFault = nil + for attempt := 0; attempt < 2; attempt++ { + err := target.Restore(fx.ctx, outcome.Backup) + if err == nil || !strings.Contains(err.Error(), "held") { + t.Fatalf("attempt %d: dispatching+missing must stay held, got %v", attempt, err) + } + } + if wire.dispatch != beforeDispatch { + t.Fatalf("dispatching+missing dispatched %d marker writes", wire.dispatch-beforeDispatch) + } + if diff := diffUniverse(beforePG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("dispatching+missing changed PG: %s", diff) + } + if after := recoveryIndexReadback(t, fx); !reflect.DeepEqual(beforeIndex, after) { + t.Fatal("dispatching+missing changed the index") + } + if after := objectVersionSet(t, fx); !reflect.DeepEqual(beforeObjects, after) { + t.Fatal("dispatching+missing changed objects") + } + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchDispatching { + t.Fatalf("state regressed to %s", state) + } + t.Logf("dispatching+missing: forwards=%d ledger=%s", wire.dispatch, authority.dispatchEvidence(t)) +} + +// A11(单元级):收尾检查拒绝仍停在 dispatching 的 effect,即使内容看起来已恢复。 +func TestDS01CloseoutRejectsUnresolvedDispatch(t *testing.T) { + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + ledger := outcome.Backup.WriteSet + if err := target.AdoptWriteSet(*ledger); err != nil { + t.Fatal(err) + } + change := indexChangeOf(t, ledger, "chunk-target") + body, err := target.restoreIndexClaimBody(change) + if err != nil { + t.Fatal(err) + } + binding, err := target.restoreMarkerBinding(fx.ctx, change, body) + if err != nil { + t.Fatal(err) + } + if permit, _, err := authority.store.AcquireRestoreMarker(fx.ctx, binding); err != nil || permit == nil { + t.Fatalf("acquire: %v", err) + } + if err := target.verifyRestoreEffectsClosed(fx.ctx); err == nil || + !strings.Contains(err.Error(), "held") { + t.Fatalf("closeout accepted an unresolved dispatch: %v", err) + } +} + +// A10:唯一发送必须不可被传输层重放(GetBody=nil),且默认路径仍可重放。 +func TestDS01MarkerRequestIsNotReplayable(t *testing.T) { + var replayable []bool + transport := ds01RoundTripFunc(func(r *http.Request) (*http.Response, error) { + replayable = append(replayable, r.GetBody != nil) + body := `{"_index":"i","_id":"d","result":"created","_seq_no":1,"_primary_term":1}` + return &http.Response{StatusCode: http.StatusOK, Request: r, + Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{"Content-Type": {"application/json"}}}, nil + }) + exporter, err := NewSearchExporter(SearchExporterConfig{BaseURL: "http://127.0.0.1:19200", Index: "i", PageSize: 10, + HTTPClient: &http.Client{Transport: transport}}) + if err != nil { + t.Fatal(err) + } + var receipt indexReceipt + if err := exporter.requestJSONOnce(context.Background(), http.MethodPut, "/i/_create/d?refresh=true", map[string]any{"content": "x"}, &receipt); err != nil { + t.Fatal(err) + } + if err := exporter.requestJSON(context.Background(), http.MethodPut, "/i/_doc/d?refresh=true", map[string]any{"content": "x"}, &receipt); err != nil { + t.Fatal(err) + } + if len(replayable) != 2 { + t.Fatalf("requests = %d", len(replayable)) + } + if replayable[0] { + t.Fatal("single-send request is still replayable by the transport") + } + if !replayable[1] { + t.Fatal("default request lost its normal replay semantics") + } +} + +type ds01RoundTripFunc func(*http.Request) (*http.Response, error) + +func (f ds01RoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +// A9(新操作系统进程):父进程留下 prepared+意图后退出该 attempt 的进程,子进程用 +// 同一 archive/index/backup/ledger 与同一 attempt 身份完成恢复。 +func TestDS01FreshProcessResumesPreparedEffect(t *testing.T) { + if os.Getenv("KG_DS01_CHILD") == "1" { + t.Skip("child process only") + } + fx, snapshot, target, backups, wire := ds01Fixture(t) + authority := newDS01Authority(t, requestFor(snapshot).JobID, snapshot) + authority.attach(target) + outcome := ds01RunToBoundary(t, fx, snapshot, target, backups, wire) + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchPrepared { + t.Fatalf("parent state = %s", state) + } + raw, err := json.Marshal(outcome.Backup) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + backupPath := filepath.Join(dir, "backup.json") + if err := os.WriteFile(backupPath, raw, 0o600); err != nil { + t.Fatal(err) + } + resultPath := filepath.Join(dir, "result.json") + command := exec.Command(os.Args[0], "-test.run=^TestDS01RestoreHelper$", "-test.v") + command.Env = append(os.Environ(), + "KG_DS01_CHILD=1", + "KG_DS01_ARCHIVE="+fx.archiveRoot, + "KG_DS01_INDEX="+fx.index, + "KG_DS01_BACKUP="+backupPath, + "KG_DS01_RESULT="+resultPath, + "KG_DS01_GOV_DSN="+authority.dsn, + "KG_DS01_TARGET_ID="+authority.targetIdentity, + "KG_DS01_OP="+authority.operationID, + "KG_DS01_JOB="+authority.jobID, + "KG_DS01_OWNER="+authority.owner, + "KG_DS01_EPOCH="+strconv.FormatInt(authority.epoch, 10), + "KG_DS01_SNAPSHOT="+snapshot, + ) + output, err := command.CombinedOutput() + t.Logf("child output:\n%s", output) + if err != nil { + t.Fatalf("fresh process restore failed: %v", err) + } + var result struct { + Dispatch int `json:"dispatch"` + State string `json:"state"` + Restored bool `json:"restored_doc"` + } + rawResult, err := os.ReadFile(resultPath) + if err != nil { + t.Fatalf("child result missing: %v", err) + } + if err := json.Unmarshal(rawResult, &result); err != nil { + t.Fatal(err) + } + if result.Dispatch != 1 || result.State != libraryrelease.RestoreDispatchMarkerConfirmed { + t.Fatalf("child result = %+v", result) + } + if !result.Restored { + t.Fatal("child did not restore chunk-target to its frozen before-image") + } + if wire.dispatch != 0 { + t.Fatalf("parent sent %d marker writes", wire.dispatch) + } + if state, _ := authority.dispatchRow(t); state != libraryrelease.RestoreDispatchMarkerConfirmed { + t.Fatalf("persisted state after child = %s", state) + } +} + +func TestDS01RestoreHelper(t *testing.T) { + if os.Getenv("KG_DS01_CHILD") != "1" { + t.Skip("isolated subprocess only") + } + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{ + archiveRoot: os.Getenv("KG_DS01_ARCHIVE"), index: os.Getenv("KG_DS01_INDEX")}) + raw, err := os.ReadFile(os.Getenv("KG_DS01_BACKUP")) + if err != nil { + t.Fatal(err) + } + var backup libraryrelease.BackupRef + if err := json.Unmarshal(raw, &backup); err != nil { + t.Fatal(err) + } + ledger, err := LoadWriteSet(fx.archiveRoot, backup.WriteSet.Digest) + if err != nil { + t.Fatal(err) + } + backup.WriteSet = ledger + + ctx := context.Background() + pool, err := pgxpool.New(ctx, os.Getenv("KG_DS01_GOV_DSN")) + if err != nil { + t.Fatalf("child governance connect: %v", err) + } + defer pool.Close() + store := postgresstore.NewStore(pool) + epoch, err := strconv.ParseInt(os.Getenv("KG_DS01_EPOCH"), 10, 64) + if err != nil { + t.Fatal(err) + } + target := fx.target(t) + target.config.RestoreDispatch = store + target.config.RestoreTargetIdentity = os.Getenv("KG_DS01_TARGET_ID") + target.config.RestoreScope = "internal" + target.config.RestoreOperationID = os.Getenv("KG_DS01_OP") + target.config.RestoreWindowJobID = os.Getenv("KG_DS01_JOB") + target.config.RestoreAttemptOwner = os.Getenv("KG_DS01_OWNER") + target.config.RestoreAttemptEpoch = epoch + target.config.RestoreInstance = ds01TargetInstance + + client := *target.search.client + inner := client.Transport + if inner == nil { + inner = http.DefaultTransport + } + wire := &restoreMarkerWire{inner: inner} + client.Transport = wire + target.search.client = &client + + if err := target.Restore(ctx, backup); err != nil { + t.Fatalf("fresh process restore: %v", err) + } + if wire.dispatch != 1 { + t.Fatalf("fresh process dispatched %d marker creates", wire.dispatch) + } + var state string + if err := pool.QueryRow(ctx, `SELECT state FROM library_index_restore_dispatch`).Scan(&state); err != nil { + t.Fatal(err) + } + change := indexChangeOf(t, ledger, "chunk-target") + observed, err := target.observePlannedIndex(ctx, change) + if err != nil { + t.Fatal(err) + } + result, err := json.Marshal(map[string]any{"dispatch": wire.dispatch, "state": state, + "restored_doc": indexBytesEqual(observed, change.Before)}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(os.Getenv("KG_DS01_RESULT"), result, 0o600); err != nil { + t.Fatal(err) + } +} + +// activateDS01 用一份真实维护 journal + 治理库维护行登记激活。 +// +// 这里不能再用"调用方自填 stopped=true + sha256(drain)":激活门消费的是维护窗口 +// 写下的 journal 字节与治理库行(见 library_restore_dispatch_activation.go)。 +// 测试替身只负责造这两个真实来源,不替产品做判断。 +func activateDS01(ctx context.Context, store *postgresstore.Store, pool *pgxpool.Pool, + targetIdentity, fingerprint string) error { + var database, systemIdentifier, databaseOID, job string + if err := pool.QueryRow(ctx, ` +SELECT current_database(), + (SELECT system_identifier::text FROM pg_control_system()), + (SELECT oid::text FROM pg_database WHERE datname = current_database())`).Scan( + &database, &systemIdentifier, &databaseOID); err != nil { + return err + } + if err := pool.QueryRow(ctx, `SELECT owner_job_id FROM library_instance_maintenance WHERE instance=$1`, + ds01TargetInstance).Scan(&job); err != nil { + return err + } + now := time.Now().UTC() + journal := map[string]any{ + "version": 1, "source": ds01TargetInstance, "job": job, "state": "held", "level": "instance", + "ingress": "http://127.0.0.1:18080/", "ingress_closed": true, "drain_verified": true, + "target_fingerprint": fingerprint, + "started_at": now.Add(-10 * time.Minute).Format(time.RFC3339Nano), + "gate": map[string]any{"closed": true, "drained": true, "active_at_close": 0, "served": 2, + "detail": "gate exit=0 phase=drained drain_ms=1 active_at_close=0"}, + "quiesce": map[string]any{ + "after_ingress": now.Add(-9 * time.Minute).Format(time.RFC3339Nano), "samples": 3, "stable_ms": 1600, + "depth": 0, "pending_ops": 0, "unsettled": 0, + "digest": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "proven_at": now.Add(-8 * time.Minute).Format(time.RFC3339Nano), + "post_stop_depth": 0, "post_stop_at": now.Add(-7 * time.Minute).Format(time.RFC3339Nano), + "post_stop_digest": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + }, + "services": []any{map[string]any{"id": "worker-ds01", "running": true, "healthy": true, + "exit_code": 0, "stop_requested": true, "stop_verified": false, "restored": false}}, + } + rawJournal, err := json.Marshal(journal) + if err != nil { + return err + } + dir := filepath.Join(os.TempDir(), "ds01-journal-"+job) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + if err := os.Chmod(dir, 0o700); err != nil { + return err + } + if err := os.WriteFile(filepath.Join(dir, job+".json"), rawJournal, 0o600); err != nil { + return err + } + journalSum := sha256.Sum256(rawJournal) + if _, err := pool.Exec(ctx, ` +UPDATE library_instance_maintenance SET services=$2::jsonb, owner_scope='internal', level='instance', + state='needs_restore', released_at=NULL, target_fingerprint=$3, + acquired_at=LEAST(acquired_at, now()-interval '20 minutes'), updated_at=now() +WHERE instance=$1`, ds01TargetInstance, `["worker-ds01"]`, fingerprint); err != nil { + return err + } + evidence := libraryrelease.RestoreDispatchActivationEvidence{ + ProtocolVersion: libraryrelease.RestoreDispatchActivationProtocolVersion, + ProtocolEpoch: libraryrelease.RestoreDispatchProtocolEpoch, + TargetIdentity: targetIdentity, TargetFingerprint: fingerprint, + RestoreTargetFingerprint: fingerprint, TargetInstance: ds01TargetInstance, GovernanceDatabase: database, + GovernanceAuthority: libraryrelease.RestoreDispatchGovernanceAuthority{SystemIdentifier: systemIdentifier, DatabaseOID: databaseOID}, + ProtocolBuild: version.DisplayVersion(), ProtocolBuildSHA: version.CommitSHA, + AttestedBy: "ds01-test", AttestedAt: now, + MaintenanceJob: job, MaintenanceJournal: job + ".json", + MaintenanceJournalSHA256: hex.EncodeToString(journalSum[:]), + Writers: []libraryrelease.RestoreDispatchWriterDrain{{Name: "worker-ds01", Kind: "worker", InstanceID: "worker-ds01"}}, + } + raw, err := json.Marshal(evidence) + if err != nil { + return err + } + path := filepath.Join(dir, "activation.json") + if err := os.WriteFile(path, raw, 0o600); err != nil { + return err + } + sum := sha256.Sum256(raw) + return store.WithRestoreDispatchEvidence(dir).ActivateRestoreDispatch( + ctx, path, hex.EncodeToString(sum[:]), targetIdentity, fingerprint, now) +} diff --git a/internal/releaseadapter/v071/library_index_effects.go b/internal/releaseadapter/v071/library_index_effects.go new file mode 100644 index 0000000..9daeeab --- /dev/null +++ b/internal/releaseadapter/v071/library_index_effects.go @@ -0,0 +1,366 @@ +package v071 + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "path/filepath" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +type indexReceipt struct { + Index string `json:"_index"` + ID string `json:"_id"` + Result string `json:"result"` + SeqNo *int64 `json:"_seq_no"` + PrimaryTerm *int64 `json:"_primary_term"` + Marked bool `json:"marked,omitempty"` +} +type indexEffect struct { + Plan string `json:"plan"` + Change libraryrelease.IndexWrite `json:"change"` + Receipt *indexReceipt `json:"receipt,omitempty"` +} + +// beginRestoreMarker 在第一次恢复写入派发之前,把恢复标记意图原子落盘。 +// 证据只描述"我们要写什么",不记录任何用来证明"没写过"的计数: +// ES 的写计数器是分片生命周期内的统计量(分片迁移/节点替换会清零), +// 不是不可变事务日志,不能作为放行写入的授权依据。 +func (t *ProductionLibraryTarget) beginRestoreMarker(ctx context.Context, c libraryrelease.IndexWrite, applied indexReceipt) error { + if t.restoreIntentFault != nil { + fault := t.restoreIntentFault + t.restoreIntentFault = nil + if err := fault(c); err != nil { + return err + } + } + raw, err := json.Marshal(indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: &applied}) + if err != nil { + return err + } + return persistImmutableJSON(t.indexEffectPath(c, "restore-mark-intent"), raw) +} + +func (t *ProductionLibraryTarget) indexEffectPath(c libraryrelease.IndexWrite, phase string) string { + sum := sha256.Sum256([]byte(c.Index + "\x00" + c.ID)) + return filepath.Join(t.config.ArchiveRoot, "effects", t.activePlan.Digest, "index", hex.EncodeToString(sum[:]), phase+".json") +} +func (t *ProductionLibraryTarget) saveIndexEffect(c libraryrelease.IndexWrite, phase string, r *indexReceipt) error { + raw, err := json.Marshal(indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: r}) + if err != nil { + return err + } + return persistImmutableJSON(t.indexEffectPath(c, phase), raw) +} +func (t *ProductionLibraryTarget) loadIndexEffect(c libraryrelease.IndexWrite, phase string) (*indexEffect, error) { + path := t.indexEffectPath(c, phase) + exists, err := effectExists(path) + if err != nil || !exists { + return nil, err + } + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var e indexEffect + if json.Unmarshal(raw, &e) != nil { + return nil, errors.New("invalid index effect evidence") + } + want, _ := json.Marshal(c) + got, _ := json.Marshal(e.Change) + if e.Plan != t.activePlan.Digest || !bytes.Equal(want, got) { + return nil, errors.New("index effect binding differs from immutable plan") + } + if e.Receipt != nil && (e.Receipt.Index != c.Index || e.Receipt.ID != c.ID || e.Receipt.SeqNo == nil || e.Receipt.PrimaryTerm == nil) { + return nil, errors.New("incomplete index receipt") + } + return &e, nil +} +func (t *ProductionLibraryTarget) observePlannedIndex(ctx context.Context, c libraryrelease.IndexWrite) (indexWriteGuard, error) { + guards, err := t.search.indexWriteGuards(ctx, []librarysnapshot.IndexDocument{{ID: c.ID}}, SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID, NoTenantField: !t.schema.IndexTenantField}) + if err != nil { + return indexWriteGuard{}, err + } + return guards[c.ID], nil +} +func indexBytesEqual(g indexWriteGuard, want json.RawMessage) bool { + if len(want) == 0 { + return !g.Found + } + if !g.Found { + return false + } + raw, err := canonicalJSON(g.Source) + return err == nil && bytes.Equal(raw, want) +} +func sameIndexGeneration(g indexWriteGuard, seq, term *int64) bool { + return g.Found && g.SeqNo != nil && g.PrimaryTerm != nil && seq != nil && term != nil && *g.SeqNo == *seq && *g.PrimaryTerm == *term +} + +// refuseRestoreWrite 是恢复写入的派发边界(生产恒为 nil):验收用例在这里制造 +// "边界上确定失败"——方法在派发前返回错误,真实 ES 一个字节都收不到,这与断线、 +// 响应丢失(写入结果未知,按 B19 必须 held)是两件不同的事。 +func (t *ProductionLibraryTarget) refuseRestoreWrite(c libraryrelease.IndexWrite) error { + if t.restoreMarkerFault == nil { + return nil + } + return t.restoreMarkerFault(c) +} + +// Each network mutation has an immutable intent before send and a per-ID +// server generation receipt. A lost response is UNKNOWN, never "did not write". +// No retry is issued for an unresolved intent; downstream ownership fencing is +// required before unknown operations can be conclusively reconciled. +func (t *ProductionLibraryTarget) applyPlannedIndex(ctx context.Context) error { + for _, c := range t.activePlan.Index { + if bytes.Equal(c.Before, c.After) { + continue + } + applied, err := t.loadIndexEffect(c, "applied") + if err != nil { + return err + } + if applied != nil { + if applied.Receipt == nil { + return errors.New("index receipt missing") + } + g, err := t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if !indexBytesEqual(g, c.After) || (len(c.After) > 0 && !sameIndexGeneration(g, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm)) { + return errors.New("index changed after confirmed apply") + } + continue + } + intent, err := t.loadIndexEffect(c, "apply-intent") + if err != nil { + return err + } + if intent != nil { + if _, err := t.reconcileIndexClaim(ctx, c); err != nil { + return err + } + receipt, err := t.finalizeIndexClaim(ctx, c) + if err != nil { + return err + } + if err := t.saveIndexEffect(c, "applied", &receipt); err != nil { + return err + } + continue + } + g, err := t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if !indexBytesEqual(g, c.Before) || (len(c.Before) > 0 && !sameIndexGeneration(g, c.SeqNo, c.PrimaryTerm)) { + return errors.New("index changed since frozen plan") + } + if err = t.saveIndexEffect(c, "apply-intent", nil); err != nil { + return err + } + receipt, err := t.applyIndexClaim(ctx, c) + if err != nil { + return err + } + if err = t.saveIndexEffect(c, "applied", &receipt); err != nil { + return err + } + g, err = t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if !indexBytesEqual(g, c.After) || (len(c.After) > 0 && !sameIndexGeneration(g, receipt.SeqNo, receipt.PrimaryTerm)) { + return errors.New("index readback differs from receipt") + } + } + return nil +} +func (t *ProductionLibraryTarget) indexMutation(c libraryrelease.IndexWrite, body json.RawMessage, seq, term *int64, create bool) (string, string, any, error) { + method := http.MethodPut + endpoint := "_doc" + if create { + endpoint = "_create" + } + if len(body) == 0 { + method = http.MethodDelete + } + query := url.Values{"refresh": {"true"}} + if !create { + if seq == nil || term == nil { + return "", "", nil, errors.New("index mutation lacks CAS") + } + query.Set("if_seq_no", fmt.Sprint(*seq)) + query.Set("if_primary_term", fmt.Sprint(*term)) + } + path := "/" + url.PathEscape(c.Index) + "/" + endpoint + "/" + url.PathEscape(c.ID) + "?" + query.Encode() + var payload any + if len(body) > 0 { + payload = body + } + return method, path, payload, nil +} + +func validateIndexReceipt(c libraryrelease.IndexWrite, hasBody bool, receipt indexReceipt) error { + if receipt.ID != c.ID || receipt.Index != c.Index || receipt.SeqNo == nil || receipt.PrimaryTerm == nil { + return errors.New("index mutation receipt incomplete") + } + if !hasBody && receipt.Result != "deleted" || hasBody && receipt.Result != "created" && receipt.Result != "updated" { + return errors.New("index mutation receipt not confirmed") + } + return nil +} + +func (t *ProductionLibraryTarget) mutatePlannedIndex(ctx context.Context, c libraryrelease.IndexWrite, body json.RawMessage, seq, term *int64, create bool) (indexReceipt, error) { + method, path, payload, err := t.indexMutation(c, body, seq, term, create) + if err != nil { + return indexReceipt{}, err + } + var receipt indexReceipt + if err := t.search.requestJSON(ctx, method, path, payload, &receipt); err != nil { + return receipt, fmt.Errorf("index effect outcome unknown: %w", err) + } + if err := validateIndexReceipt(c, len(body) > 0, receipt); err != nil { + return receipt, err + } + return receipt, nil +} +func (t *ProductionLibraryTarget) restorePlannedIndex(ctx context.Context) error { + for _, c := range t.activePlan.Index { + intent, err := t.loadIndexEffect(c, "apply-intent") + if err != nil { + return err + } + if intent == nil { + continue + } + // Completed compensation is read back before attempting to reconcile an + // old marked apply; the marker was intentionally removed by restoration. + done, err := t.loadIndexEffect(c, "restored") + if err != nil { + return err + } + if done != nil { + g, err := t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if !indexBytesEqual(g, c.Before) || (len(c.Before) > 0 && (done.Receipt == nil || !sameIndexGeneration(g, done.Receipt.SeqNo, done.Receipt.PrimaryTerm))) { + return errors.New("restored index changed") + } + continue + } + if reconciled, err := t.reconcileIndexCompensationDelete(ctx, c); err != nil { + return err + } else if reconciled { + continue + } + applied, err := t.loadIndexEffect(c, "applied") + if err != nil { + return err + } + if applied == nil { + receipt, err := t.reconcileIndexClaim(ctx, c) + if err != nil { + return err + } + applied = &indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: &receipt} + } + if applied.Receipt == nil { + return errors.New("missing index compensation receipt") + } + g, err := t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + restoring, err := t.loadIndexEffect(c, "restore-intent") + if err != nil { + return err + } + if restoring != nil { + if len(c.Before) > 0 { + if err := t.restoreClaimedIndexBefore(ctx, c, *applied.Receipt, false); err != nil { + return err + } + continue + } + // 删除型补偿:删除落地必然移除文档并推进世代;文档仍是 applied 结果、 + // 世代仍是 applied 回执,才证明那次 DELETE 没有落地,可按同一 CAS 重放。 + expected := c.After + if applied.Receipt.Marked { + expected, err = t.indexClaimBody(c) + if err != nil { + return err + } + } + if !indexBytesEqual(g, expected) || !sameIndexGeneration(g, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm) { + return errors.New("unknown index compensation requires reconciliation") + } + if err := t.refuseRestoreWrite(c); err != nil { + return err + } + receipt, err := t.mutatePlannedIndex(ctx, c, c.Before, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm, false) + if err != nil { + return err + } + if err = t.saveIndexEffect(c, "restored", &receipt); err != nil { + return err + } + g, err = t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if !indexBytesEqual(g, c.Before) { + return errors.New("index compensation readback failed") + } + continue + } + expected := c.After + if applied.Receipt.Marked { + expected, err = t.indexClaimBody(c) + if err != nil { + return err + } + } + if !indexBytesEqual(g, expected) || (len(expected) > 0 && !sameIndexGeneration(g, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm)) { + return errors.New("another writer changed index; compensation refused") + } + if err = t.saveIndexEffect(c, "restore-intent", applied.Receipt); err != nil { + return err + } + if len(c.Before) > 0 { + if err := t.restoreClaimedIndexBefore(ctx, c, *applied.Receipt, true); err != nil { + return err + } + continue + } + if err := t.refuseRestoreWrite(c); err != nil { + return err + } + receipt, err := t.mutatePlannedIndex(ctx, c, c.Before, applied.Receipt.SeqNo, applied.Receipt.PrimaryTerm, len(c.After) == 0) + if err != nil { + return err + } + if err = t.saveIndexEffect(c, "restored", &receipt); err != nil { + return err + } + g, err = t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if !indexBytesEqual(g, c.Before) { + return errors.New("index compensation readback failed") + } + } + return nil +} diff --git a/internal/releaseadapter/v071/library_index_effects_test.go b/internal/releaseadapter/v071/library_index_effects_test.go new file mode 100644 index 0000000..d149277 --- /dev/null +++ b/internal/releaseadapter/v071/library_index_effects_test.go @@ -0,0 +1,102 @@ +package v071 + +import ( + "errors" + "io" + "knowledge-governance/internal/libraryrelease" + "net/http" + "path/filepath" + "strings" + "testing" +) + +type indexLostResponseTransport struct { + inner http.RoundTripper + dropped bool +} + +func (t *indexLostResponseTransport) RoundTrip(r *http.Request) (*http.Response, error) { + resp, err := t.inner.RoundTrip(r) + if err == nil && !t.dropped && r.Method == http.MethodPut && strings.Contains(r.URL.Path, "/_create/") && resp.StatusCode < 300 { + t.dropped = true + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + return nil, errors.New("injected lost response after real ES commit") + } + return resp, err +} + +func TestContractIndexLostResponseNeverDeletesUnknownIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + client := *target.search.client + transport := client.Transport + if transport == nil { + transport = http.DefaultTransport + } + fault := &indexLostResponseTransport{inner: transport} + client.Transport = fault + target.search.client = &client + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatal(err) + } + backup, err := fx.backups(t, target).Prepare(fx.ctx, snapshot, current) + if err != nil { + t.Fatal(err) + } + backup.WriteSet = planLedgerWithUniverse(t, target, snapshot, backup.SnapshotID, backup.Universe) + var unknown *libraryrelease.IndexWrite + for i, c := range target.activePlan.Index { + if len(c.Before) == 0 && len(c.After) > 0 { + unknown = &target.activePlan.Index[i] + break + } + } + if unknown == nil { + t.Fatal("fixture lacks a new ID") + } + if err = target.saveIndexEffect(*unknown, "apply-intent", nil); err != nil { + t.Fatal(err) + } + // A legacy/unattributable successful write: identical content has NO marker. + if _, err = target.mutatePlannedIndex(fx.ctx, *unknown, unknown.After, nil, nil, true); err == nil || !fault.dropped { + t.Fatal("response-loss fixture not exercised") + } + + observed, err := target.observePlannedIndex(fx.ctx, *unknown) + if err != nil || !indexBytesEqual(observed, unknown.After) { + t.Fatalf("unknown create was deleted or bytes lost: %v", err) + } + next := fx.target(t) + if err = next.AdoptWriteSet(*backup.WriteSet); err != nil { + t.Fatal(err) + } + if err = next.Restore(fx.ctx, backup); err == nil { + t.Fatal("fresh adapter treated unknown as failed create") + } + observed, err = next.observePlannedIndex(fx.ctx, *unknown) + if err != nil || !indexBytesEqual(observed, unknown.After) { + t.Fatalf("fresh adapter deleted unknown effect: %v", err) + } +} + +func TestContractIndexWritesHaveDurableReceiptsIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, fx.backups(t, target), nil) + if outcome.State != "rolled_back" { + t.Fatalf("rollback: %+v", outcome) + } + receipts, err := filepath.Glob(filepath.Join(fx.archiveRoot, "effects", "*", "index", "*", "applied.json")) + if err != nil { + t.Fatal(err) + } + if len(receipts) == 0 { + t.Fatal("index side effects completed without durable per-ID receipts") + } +} diff --git a/internal/releaseadapter/v071/library_index_guard.go b/internal/releaseadapter/v071/library_index_guard.go new file mode 100644 index 0000000..e09f4ad --- /dev/null +++ b/internal/releaseadapter/v071/library_index_guard.go @@ -0,0 +1,135 @@ +package v071 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "net/http" + "sort" + + "knowledge-governance/internal/librarysnapshot" +) + +type indexWriteGuard struct { + ID string `json:"_id"` + Index string `json:"_index"` + Found bool `json:"found"` + Source json.RawMessage `json:"_source"` + SeqNo *int64 `json:"_seq_no"` + PrimaryTerm *int64 `json:"_primary_term"` + Error json.RawMessage `json:"error"` +} + +// Elasticsearch IDs belong to the entire index, not to a KB. Every requested +// ID must be explicitly present or absent in the response, never inferred from +// a truncated/malformed response or a transport error. +func (e *SearchExporter) indexWriteGuards(ctx context.Context, documents []librarysnapshot.IndexDocument, identity SearchIdentity) (map[string]indexWriteGuard, error) { + guards := map[string]indexWriteGuard{} + for start := 0; start < len(documents); start += 500 { + end := start + 500 + if end > len(documents) { + end = len(documents) + } + ids := []string{} + wanted := map[string]bool{} + for _, doc := range documents[start:end] { + if doc.ID == "" || wanted[doc.ID] { + return nil, errors.New("invalid or duplicate index identity") + } + if _, exists := guards[doc.ID]; exists { + return nil, errors.New("duplicate index identity") + } + wanted[doc.ID] = true + ids = append(ids, doc.ID) + } + var response struct { + Docs []indexWriteGuard `json:"docs"` + } + if err := e.requestJSON(ctx, http.MethodPost, "/"+e.index+"/_mget", map[string]any{"ids": ids}, &response); err != nil { + return nil, err + } + if len(response.Docs) != len(ids) { + return nil, errors.New("incomplete index identity preflight") + } + for _, doc := range response.Docs { + if !wanted[doc.ID] || doc.Index != e.index || len(doc.Error) > 0 && string(doc.Error) != "null" { + return nil, errors.New("invalid index identity preflight") + } + if _, exists := guards[doc.ID]; exists { + return nil, errors.New("duplicate index preflight result") + } + if doc.Found { + var owner struct { + Tenant uint64 `json:"tenant_id"` + KB string `json:"knowledge_base_id"` + } + if json.Unmarshal(doc.Source, &owner) != nil || owner.KB != identity.KnowledgeBaseID || + (!identity.NoTenantField && owner.Tenant != identity.TenantID) { + log.Printf("index guard conflict id=%s owner_kb=%q want_kb=%q owner_tenant=%d want_tenant=%d no_tenant_field=%t", + doc.ID, owner.KB, identity.KnowledgeBaseID, owner.Tenant, identity.TenantID, identity.NoTenantField) + return nil, fmt.Errorf("index-level ID conflict: %s is not owned by target tenant/KB", doc.ID) + } + if doc.SeqNo == nil || doc.PrimaryTerm == nil { + return nil, errors.New("index lacks optimistic concurrency identity") + } + } + guards[doc.ID] = doc + } + } + return guards, nil +} + +func (t *ProductionLibraryTarget) preflightArchiveIndex(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error { + for _, part := range manifest.Parts { + if part.Kind != "index" { + continue + } + reader, err := archive.OpenPart(part) + if err != nil { + return err + } + docs, err := librarysnapshot.ReadIndexDocuments(reader) + reader.Close() + if err != nil { + return err + } + if t.mappingActive { + // Plan/Apply 的索引身份已在 planIndex/ApplyIndex 统一映射;前置预检 + // 必须对同一目标物理 _id 做归属检查,否则旧库占用源 _id 会被误报冲突。 + mapped := make(map[string]json.RawMessage, len(docs)) + for _, doc := range docs { + id, source, err := t.targetIDs.remapIndexDocument(doc.ID, doc.Source) + if err != nil { + return err + } + if _, exists := mapped[id]; exists { + return errors.New("index target id collision") + } + mapped[id] = source + } + ids := make([]string, 0, len(mapped)) + for id := range mapped { + ids = append(ids, id) + } + sort.Strings(ids) + docs = make([]librarysnapshot.IndexDocument, 0, len(ids)) + for _, id := range ids { + docs = append(docs, librarysnapshot.IndexDocument{ID: id, Source: mapped[id]}) + } + } + if _, err := t.search.indexWriteGuards(ctx, docs, SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID, NoTenantField: !t.schema.IndexTenantField}); err != nil { + return err + } + } + return nil +} + +func (e *SearchExporter) BulkIndexGuarded(ctx context.Context, documents []librarysnapshot.IndexDocument, identity SearchIdentity) error { + guards, err := e.indexWriteGuards(ctx, documents, identity) + if err != nil { + return err + } + return e.bulkIndex(ctx, documents, identity, guards) +} diff --git a/internal/releaseadapter/v071/library_index_known_recovery_test.go b/internal/releaseadapter/v071/library_index_known_recovery_test.go new file mode 100644 index 0000000..30fcdba --- /dev/null +++ b/internal/releaseadapter/v071/library_index_known_recovery_test.go @@ -0,0 +1,183 @@ +package v071 + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "net/http" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +// restoreMarkerWire 只旁路计数:真正派发到真实 ES 的"恢复标记写入"次数。 +// +// 为什么要有它:本用例要证明第一次失败发生在**派发之前**(控制流在边界上拒绝), +// 不是断线、也不是响应丢失。只靠错误文本分不出这两者,次数能分:边界拒绝 = 0 次派发, +// 断线 = 1 次派发且结果未知。它不改写请求与响应,ES 仍是唯一权威。 +type restoreMarkerWire struct { + inner http.RoundTripper + dispatch int +} + +func (w *restoreMarkerWire) RoundTrip(r *http.Request) (*http.Response, error) { + if r.Body != nil { + raw, err := io.ReadAll(r.Body) + if err != nil { + return nil, err + } + r.Body = io.NopCloser(bytes.NewReader(raw)) + if r.Method == http.MethodPut && bytes.Contains(raw, []byte(indexRestoreClaimPrefix)) { + w.dispatch++ + } + } + return w.inner.RoundTrip(r) +} + +func indexChangeOf(t *testing.T, plan *libraryrelease.WriteSet, id string) libraryrelease.IndexWrite { + t.Helper() + if plan == nil { + t.Fatal("write set missing: recovery would have no bound plan") + } + for _, change := range plan.Index { + if change.ID == id { + return change + } + } + t.Fatalf("index plan lacks %s", id) + return libraryrelease.IndexWrite{} +} + +// indexEffectFile 与生产代码的落盘路径同构(sha256(index\x00id)),用于直接读证据文件。 +func indexEffectFile(fx *writeSetFixture, plan *libraryrelease.WriteSet, change libraryrelease.IndexWrite, phase string) string { + sum := sha256.Sum256([]byte(change.Index + "\x00" + change.ID)) + return filepath.Join(fx.archiveRoot, "effects", plan.Digest, "index", hex.EncodeToString(sum[:]), phase+".json") +} + +func requireIndexEffect(t *testing.T, fx *writeSetFixture, plan *libraryrelease.WriteSet, change libraryrelease.IndexWrite, phase string, want bool) string { + t.Helper() + path := indexEffectFile(fx, plan, change, phase) + info, err := os.Stat(path) + if want && err != nil { + t.Fatalf("index effect %s/%s not durable: %v", change.ID, phase, err) + } + if !want && err == nil { + t.Fatalf("index effect %s/%s exists unexpectedly: %s", change.ID, phase, info.Name()) + } + return path +} + +// r37:删除型恢复(Before 非空、After 为空,恢复写入是独占 `_create`)在持久意图 +// 落盘之后、派发之前"确定失败"。撤掉故障后**不能**自动重做:文档缺失与"从未写过" +// 在索引里完全同形,服务端没有可持久、不可重用的"没写进去"证据。测试侧的派发次数 +// 是内存观测,不是可复核的持久证据;ES `_stats` 写计数器是分片生命周期统计(分片 +// 迁移/节点替换会清零,见官方 `_stats` 文档),索引 uuid 不变不绑定统计生命周期, +// 清零后重新累计到同一数值(ABA)无法排除。因此本状态必须 held(B19 不放宽)。 +// +// 故障边界(target.restoreMarkerFault):在恢复标记的持久意图落盘之后、网络派发之前 +// 返回错误——真实 ES 一个字节都没收到(用例用派发次数 0 证明),但"证明"只存在于 +// 测试进程里,不能变成生产可用的授权。 +func TestContractRestoreMarkerAfterBoundaryFaultIsHeldIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + + target := fx.target(t) + backups := fx.backups(t, target) + client := *target.search.client + inner := client.Transport + if inner == nil { + inner = http.DefaultTransport + } + wire := &restoreMarkerWire{inner: inner} + client.Transport = wire + target.search.client = &client + + var faulted []string + target.restoreMarkerFault = func(c libraryrelease.IndexWrite) error { + if c.ID != "chunk-target" { + return nil + } + faulted = append(faulted, c.ID) + return errors.New("injected restore boundary fault: dispatch refused before any index write") + } + + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, backups, nil) + if outcome.State != "rollback_failed" { + t.Fatalf("state = %q (rollback=%q error=%q), want rollback_failed: a failed index restoration must be held, never admitted", + outcome.State, outcome.Rollback, outcome.Error) + } + if outcome.FailedAt != libraryrelease.StageWiki { + t.Fatalf("failed_at = %q, want wiki (the injected apply failure)", outcome.FailedAt) + } + if !strings.Contains(outcome.Rollback, "injected restore boundary fault") { + t.Fatalf("rollback failure does not name the injected index boundary fault: %q", outcome.Rollback) + } + if len(faulted) != 1 || faulted[0] != "chunk-target" { + t.Fatalf("fault fired %v, want exactly one chunk-target restore attempt", faulted) + } + if wire.dispatch != 0 { + t.Fatalf("boundary fault dispatched %d restore marker writes; a control-flow refusal must send nothing", wire.dispatch) + } + + // 应用期的真实逐 ID 回执必须已在故障之前落盘:恢复读的是证据,不是目标现状。 + plan := outcome.Backup.WriteSet + if plan == nil || plan.JobID != requestFor(snapshot).JobID { + t.Fatalf("backup is not bound to the original job: %+v", plan) + } + applied, err := filepath.Glob(filepath.Join(fx.archiveRoot, "effects", plan.Digest, "index", "*", "applied.json")) + if err != nil || len(applied) != 2 { + t.Fatalf("applied index receipts = %d (%v), want 2 durable per-ID receipts", len(applied), err) + } + change := indexChangeOf(t, plan, "chunk-target") + if len(change.Before) == 0 { + t.Fatal("fixture lost the chunk-target before-image") + } + requireIndexEffect(t, fx, plan, change, "apply-intent", true) + requireIndexEffect(t, fx, plan, change, "applied", true) + // 恢复意图已落盘,但恢复标记在测试进程里从未派发。这条"没派发"只存在于 + // 内存计数里,不是生产可复核的持久证据。 + requireIndexEffect(t, fx, plan, change, "restore-mark-intent", true) + requireIndexEffect(t, fx, plan, change, "restore-claimed", false) + requireIndexEffect(t, fx, plan, change, "restored", false) + + // held 期间业务存储不许被"顺手恢复一半再报成功":索引仍是应用后的样子。 + heldIndex := recoveryIndexReadback(t, fx) + heldPG := universeDump(t, fx.pool) + heldObjects := objectVersionSet(t, fx) + if _, ok := heldIndex["chunk-src"]; ok { + t.Fatal("index still carries the applied chunk-src after a failed index restoration") + } + if _, ok := heldIndex["chunk-target"]; ok { + t.Fatal("chunk-target came back without the restoration marker ever being dispatched") + } + + // 撤掉故障。删除型恢复写入是独占 `_create`,文档缺失与"从未写过"同形;服务端 + // 没有可持久、不可重用的未发送证据(ES 统计随分片迁移清零,不能当证据), + // 所以必须 held,不能凭测试侧"派发 0 次"放行写入。 + target.restoreMarkerFault = nil + beforeDispatch := wire.dispatch + if err := target.Restore(fx.ctx, outcome.Backup); err == nil { + t.Fatal("delete-type restoration without a durable not-dispatched proof must stay held") + } else if !strings.Contains(err.Error(), "held") { + t.Fatalf("held error must say held, got: %v", err) + } + if wire.dispatch != beforeDispatch { + t.Fatalf("held restoration dispatched %d restore marker writes", wire.dispatch-beforeDispatch) + } + if diff := diffUniverse(heldPG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("held restoration changed PG: %s", diff) + } + if after := recoveryIndexReadback(t, fx); !reflect.DeepEqual(heldIndex, after) { + t.Fatal("held restoration changed the index") + } + if after := objectVersionSet(t, fx); !reflect.DeepEqual(heldObjects, after) { + t.Fatalf("held restoration changed object versions:\n before=%v\n after=%v", heldObjects, after) + } +} diff --git a/internal/releaseadapter/v071/library_index_plan.go b/internal/releaseadapter/v071/library_index_plan.go new file mode 100644 index 0000000..781517f --- /dev/null +++ b/internal/releaseadapter/v071/library_index_plan.go @@ -0,0 +1,172 @@ +package v071 + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "sort" + "strings" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +func archiveIndexMap(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) (map[string]json.RawMessage, error) { + out := map[string]json.RawMessage{} + for _, part := range manifest.Parts { + if part.Kind != "index" { + continue + } + reader, err := archive.OpenPart(part) + if err != nil { + return nil, err + } + docs, err := librarysnapshot.ReadIndexDocuments(reader) + reader.Close() + if err != nil { + return nil, err + } + for _, doc := range docs { + if doc.ID == "" { + return nil, errors.New("empty index ID") + } + if _, ok := out[doc.ID]; ok { + return nil, errors.New("duplicate index ID") + } + raw, err := canonicalJSON(doc.Source) + if err != nil { + return nil, err + } + out[doc.ID] = raw + } + } + return out, nil +} +func targetIndexSource(raw json.RawMessage, tenant uint64, kb string, withTenant bool) (json.RawMessage, error) { + var source map[string]json.RawMessage + if json.Unmarshal(raw, &source) != nil || source == nil { + return nil, errors.New("index source must be object") + } + var content string + if json.Unmarshal(source["content"], &content) != nil || strings.HasPrefix(content, indexClaimPrefix) { + return nil, errors.New("index source lacks string content or contains an unfinished transient claim") + } + if withTenant { + source["tenant_id"], _ = json.Marshal(tenant) + } + source["knowledge_base_id"], _ = json.Marshal(kb) + encoded, err := json.Marshal(source) + if err != nil { + return nil, err + } + return canonicalJSON(encoded) +} +func (t *ProductionLibraryTarget) planIndex(ctx context.Context, archive *librarysnapshot.Archive, source librarysnapshot.Manifest, set *libraryrelease.WriteSet) error { + backup, err := archive.Load(set.BackupSnapshotID) + if err != nil { + return err + } + before, err := archiveIndexMap(archive, backup) + if err != nil { + return err + } + after, err := archiveIndexMap(archive, source) + if err != nil { + return err + } + after, err = t.remapIndexMap(after) + if err != nil { + return err + } + ids := map[string]bool{} + for id := range before { + ids[id] = true + } + for id := range after { + ids[id] = true + } + sorted := make([]string, 0, len(ids)) + for id := range ids { + sorted = append(sorted, id) + } + sort.Strings(sorted) + docs := make([]librarysnapshot.IndexDocument, 0, len(ids)) + for _, id := range sorted { + docs = append(docs, librarysnapshot.IndexDocument{ID: id}) + } + guards, err := t.search.indexWriteGuards(ctx, docs, SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID, NoTenantField: !t.schema.IndexTenantField}) + if err != nil { + return err + } + for _, id := range sorted { + g := guards[id] + expected, existed := before[id] + if existed != g.Found { + return errors.New("index before-image no longer covers exact write set") + } + if existed { + raw, err := canonicalJSON(g.Source) + if err != nil || !bytes.Equal(raw, expected) { + return errors.New("index changed since before-image") + } + } + var wanted json.RawMessage + if raw, ok := after[id]; ok { + wanted, err = targetIndexSource(raw, t.scope.TenantID, t.scope.KnowledgeBaseID, t.schema.IndexTenantField) + if err != nil { + return err + } + } + set.Index = append(set.Index, libraryrelease.IndexWrite{Index: t.search.index, ID: id, Before: expected, SeqNo: g.SeqNo, PrimaryTerm: g.PrimaryTerm, After: wanted}) + } + return nil +} + +func (t *ProductionLibraryTarget) validateIndexPlanBinding(archive *librarysnapshot.Archive, source, backup librarysnapshot.Manifest, set libraryrelease.WriteSet) error { + before, err := archiveIndexMap(archive, backup) + if err != nil { + return err + } + after, err := archiveIndexMap(archive, source) + if err != nil { + return err + } + after, err = t.remapIndexMap(after) + if err != nil { + return err + } + ids := map[string]bool{} + for id := range before { + ids[id] = true + } + for id := range after { + ids[id] = true + } + if len(ids) != len(set.Index) { + return errors.New("index plan coverage mismatch") + } + for _, change := range set.Index { + if !ids[change.ID] || change.Index != t.search.index { + return errors.New("index plan physical identity mismatch") + } + delete(ids, change.ID) + var wanted json.RawMessage + if raw, ok := after[change.ID]; ok { + wanted, err = targetIndexSource(raw, set.TenantID, set.KnowledgeBaseID, t.schema.IndexTenantField) + if err != nil { + return err + } + } + if !bytes.Equal(before[change.ID], change.Before) || !bytes.Equal(wanted, change.After) { + return errors.New("index plan bytes differ from immutable archives") + } + if len(change.Before) > 0 && (change.SeqNo == nil || change.PrimaryTerm == nil) { + return errors.New("existing index document lacks CAS identity") + } + if len(change.Before) == 0 && (change.SeqNo != nil || change.PrimaryTerm != nil) { + return errors.New("absent index document has invalid CAS identity") + } + } + return nil +} diff --git a/internal/releaseadapter/v071/library_index_preflight_integration_test.go b/internal/releaseadapter/v071/library_index_preflight_integration_test.go new file mode 100644 index 0000000..be31a97 --- /dev/null +++ b/internal/releaseadapter/v071/library_index_preflight_integration_test.go @@ -0,0 +1,188 @@ +package v071 + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +type esDocReadback struct { + ID string `json:"_id"` + Found bool `json:"found"` + Source struct { + Tenant uint64 `json:"tenant_id"` + KB string `json:"knowledge_base_id"` + Content string `json:"content"` + ChunkID string `json:"chunk_id"` + } `json:"_source"` +} + +func (fx *writeSetFixture) getIndexDoc(t *testing.T, id string) esDocReadback { + t.Helper() + request, err := http.NewRequestWithContext(fx.ctx, "GET", fmt.Sprintf("%s/%s/_doc/%s", fx.searchBase, fx.index, id), nil) + if err != nil { + t.Fatal(err) + } + response, err := fx.client.Do(request) + if err != nil { + t.Fatalf("get index %s: %v", id, err) + } + defer response.Body.Close() + var doc esDocReadback + if response.StatusCode == 404 { + return doc // found=false + } + if response.StatusCode != 200 { + t.Fatalf("get index %s => %d", id, response.StatusCode) + } + if err := json.NewDecoder(response.Body).Decode(&doc); err != nil { + t.Fatal(err) + } + return doc +} + +// 目标库为空、同 tenant 旧库占用源 DB 主键且占用源 ES 物理 _id: +// PlanWriteSet 的早期 index preflight 必须用映射后的目标 _id,而不是把源 _id +// 当成本目标写入预检;同时旧库 ES 文档/DB 行必须原样保留。 +func TestIndexPreflightUsesMappedTargetIDIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + oldRows := []string{ + `INSERT INTO knowledges VALUES('doc-src',10001,'` + wsOtherKB + `','completed',0,'',NULL)`, + `INSERT INTO chunks VALUES('chunk-src',10001,'` + wsOtherKB + `','doc-src','旧库正文',NULL)`, + `INSERT INTO resources VALUES('res-src','` + wsHandleSource + `',10001,'` + wsLocator("backend-target", "minio", wsBucket, 10001, "res-src") + `',NULL,'minio',8,'backend-target')`, + `INSERT INTO resource_bindings VALUES('bind-old-src',10001,'res-src','knowledge','doc-src',NULL)`, + } + for _, statement := range oldRows { + if _, err := fx.pool.Exec(fx.ctx, statement); err != nil { + t.Fatalf("seed old db: %v\n%s", err, statement) + } + } + // 旧库在共享索引里真实占用源物理 _id(同 tenant,不同 KB)。 + fx.indexDoc(t, "chunk-src", wsTargetTenant, wsOtherKB, "doc-src", "旧库索引正文") + if err := fx.objects.s3.Put(fx.ctx, "minio", wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-src"), + strings.NewReader("12345678"), 8); err != nil { + t.Fatal(err) + } + oldIndex := fx.getIndexDoc(t, "chunk-src") + if !oldIndex.Found || oldIndex.Source.KB != wsOtherKB { + t.Fatalf("old index fixture missing: %+v", oldIndex) + } + beforeObj, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-src")) + if err != nil { + t.Fatal(err) + } + + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatal(err) + } + backup, err := backups.Prepare(fx.ctx, snapshot, current) + if err != nil { + t.Fatal(err) + } + set, err := target.PlanWriteSet(fx.ctx, libraryrelease.WriteSetPlan{JobID: "index-preflight-map", + Target: "internal", BackupSnapshotID: backup.SnapshotID, TargetSnapshotID: snapshot, Universe: backup.Universe}) + if err != nil { + t.Fatalf("index preflight must use mapped target id, got: %v", err) + } + mapped := expectedIndexID("chunk-src") + for _, row := range set.Index { + if row.ID == "chunk-src" { + t.Fatal("write set still carries source index id") + } + if row.ID == mapped { + // ok + } + } + // 计划持久化后由新实例重新 adopt,再走真实 Apply/Verify。 + next := fx.target(t) + if err := next.AdoptWriteSet(set); err != nil { + t.Fatalf("adopt persisted plan: %v", err) + } + for _, stage := range []libraryrelease.Stage{libraryrelease.StageDatabase, libraryrelease.StageWiki, + libraryrelease.StageResources, libraryrelease.StageIndex} { + if err := next.Apply(fx.ctx, stage, snapshot); err != nil { + t.Fatalf("apply %s: %v", stage, err) + } + } + if err := next.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: snapshot}); err != nil { + t.Fatalf("verify: %v", err) + } + + oldAfter := fx.getIndexDoc(t, "chunk-src") + if !oldAfter.Found || oldAfter.Source.KB != wsOtherKB || oldAfter.Source.Content != "旧库索引正文" || oldAfter.Source.ChunkID != "chunk-src" { + t.Fatalf("old KB index document changed: %+v", oldAfter) + } + var oldDB int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM chunks WHERE id='chunk-src' AND knowledge_base_id=$1 AND content='旧库正文'`, wsOtherKB).Scan(&oldDB); err != nil || oldDB != 1 { + t.Fatalf("old DB row changed: %d %v", oldDB, err) + } + newDoc := fx.getIndexDoc(t, mapped) + if !newDoc.Found || newDoc.Source.Tenant != wsTargetTenant || newDoc.Source.KB != wsTargetKB || + !strings.Contains(newDoc.Source.Content, wsHandleTarget) && !strings.Contains(newDoc.Source.Content, "来源正文") { + t.Fatalf("mapped target index doc missing/wrong: %+v", newDoc) + } + if newDoc.Source.ChunkID != expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-src") { + t.Fatalf("mapped doc chunk_id is not target id: %s", newDoc.Source.ChunkID) + } + afterObj, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-src")) + if err != nil || beforeObj.Exists != afterObj.Exists || beforeObj.SHA256 != afterObj.SHA256 || beforeObj.Bytes != afterObj.Bytes { + t.Fatalf("shared resource object changed: %+v -> %+v %v", beforeObj, afterObj, err) + } +} + +func TestIndexPreflightRejectsMappedIDOwnedByOtherKBIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + mapped := expectedIndexID("chunk-src") + fx.indexDoc(t, mapped, wsTargetTenant, wsOtherKB, "chunk-src", "别的库占用了映射后的物理 id") + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatal(err) + } + backup, err := fx.backups(t, target).Prepare(fx.ctx, snapshot, current) + if err != nil { + t.Fatal(err) + } + _, err = target.PlanWriteSet(fx.ctx, libraryrelease.WriteSetPlan{JobID: "mapped-index-collision", Target: "internal", + BackupSnapshotID: backup.SnapshotID, TargetSnapshotID: snapshot, Universe: backup.Universe}) + if err == nil || !strings.Contains(err.Error(), mapped) || !strings.Contains(err.Error(), "not owned") { + t.Fatalf("mapped index id occupied by another KB must be rejected on that id, got %v", err) + } +} + +func TestLegacyIndexPreflightStillRejectsSourceIDConflictIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + fx.indexDoc(t, "chunk-src", wsTargetTenant, wsOtherKB, "doc-src", "旧库源 id") + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + archive, err := librarysnapshot.Open(fx.archiveRoot, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + manifest, err := archive.Load(snapshot) + if err != nil { + t.Fatal(err) + } + target.disableTargetMapping() + if err := target.bindSnapshotScope(manifestScope{tenantID: manifest.TenantID, knowledgeBaseID: manifest.KnowledgeBaseID}); err != nil { + t.Fatal(err) + } + err = target.preflightArchiveIndex(fx.ctx, archive, manifest) + if err == nil || !strings.Contains(err.Error(), "chunk-src") || !strings.Contains(err.Error(), "not owned") { + t.Fatalf("legacy/no-mapping preflight must still reject source id conflict, got %v", err) + } +} diff --git a/internal/releaseadapter/v071/library_index_recovery_gaps_test.go b/internal/releaseadapter/v071/library_index_recovery_gaps_test.go new file mode 100644 index 0000000..c23545f --- /dev/null +++ b/internal/releaseadapter/v071/library_index_recovery_gaps_test.go @@ -0,0 +1,634 @@ +package v071 + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "reflect" + "strconv" + "strings" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + + "knowledge-governance/internal/libraryrelease" +) + +// restorePhaseWire 只旁路计数,不改写请求/响应: +// - creates / createWithCAS:真正派发的 `_create`(独占 create)次数,以及其中带 +// if_seq_no 的次数。独占 create 是恢复"删除型"变更时唯一允许的重放操作: +// 目标已存在则 409,永远不覆盖别人的字节。 +// - clean:标记体之外的 PUT(干净收尾写入)。 +// - deletes:DELETE(删除补偿)。 +// - marker:带恢复标记前缀的 PUT。 +type restorePhaseWire struct { + inner http.RoundTripper + creates int + createWithCAS int + clean int + deletes int + marker int +} + +func (w *restorePhaseWire) RoundTrip(r *http.Request) (*http.Response, error) { + var raw []byte + if r.Body != nil { + body, err := io.ReadAll(r.Body) + if err != nil { + return nil, err + } + r.Body = io.NopCloser(bytes.NewReader(body)) + raw = body + } + create := strings.Contains(r.URL.Path, "/_create/") + doc := create || strings.Contains(r.URL.Path, "/_doc/") + switch { + case !doc: + // `_pit` 之类的控制面请求不是文档写入,不能算进派发次数。 + case r.Method == http.MethodDelete: + w.deletes++ + case r.Method == http.MethodPut && create: + w.creates++ + if r.URL.Query().Get("if_seq_no") != "" || r.URL.Query().Get("if_primary_term") != "" { + w.createWithCAS++ + } + if bytes.Contains(raw, []byte(indexRestoreClaimPrefix)) { + w.marker++ + } + case r.Method == http.MethodPut && bytes.Contains(raw, []byte(indexRestoreClaimPrefix)): + w.marker++ + case r.Method == http.MethodPut: + w.clean++ + } + return w.inner.RoundTrip(r) +} + +type wireCounts struct { + creates, createWithCAS, marker, clean, deletes int +} + +func (w *restorePhaseWire) counts() wireCounts { + return wireCounts{w.creates, w.createWithCAS, w.marker, w.clean, w.deletes} +} + +// since 返回基线之后的增量:Run 的 apply 阶段也会写索引,绝对计数不是恢复阶段的证据。 +func (w *restorePhaseWire) since(base wireCounts) wireCounts { + now := w.counts() + return wireCounts{ + creates: now.creates - base.creates, + createWithCAS: now.createWithCAS - base.createWithCAS, + marker: now.marker - base.marker, + clean: now.clean - base.clean, + deletes: now.deletes - base.deletes, + } +} + +// objectVersionSet 是对象存储的版本级精确证据:键 + versionId -> ETag/字节数/是否当前版本。 +// ListObjectsV2 只枚举"当前可见对象",不能证明历史版本;这里显式枚举版本与删除标记。 +func objectVersionSet(t *testing.T, fx *writeSetFixture) map[string]string { + t.Helper() + out := map[string]string{} + pages := s3.NewListObjectVersionsPaginator(fx.objects.s3.client, &s3.ListObjectVersionsInput{ + Bucket: aws.String(fx.bucket), + }) + for pages.HasMorePages() { + page, err := pages.NextPage(fx.ctx) + if err != nil { + t.Fatalf("list object versions: %v", err) + } + for _, version := range page.Versions { + out[aws.ToString(version.Key)+"@"+aws.ToString(version.VersionId)] = "v/" + aws.ToString(version.ETag) + "/" + strconv.FormatInt(aws.ToInt64(version.Size), 10) + } + for _, marker := range page.DeleteMarkers { + out[aws.ToString(marker.Key)+"@"+aws.ToString(marker.VersionId)] = "delete-marker/" + strconv.FormatBool(aws.ToBool(marker.IsLatest)) + } + } + return out +} + +// indexCounters 是测试侧独立读取的索引写计数器(不经过生产代码的类型)。 +// r37 起它只作**诊断**:证明真实写入确实推进了统计,而统计本身不是授权证据。 +type indexCounters struct { + IndexUUID string + Indexed int64 + Deleted int64 +} + +func readIndexCounters(t *testing.T, fx *writeSetFixture, index string) indexCounters { + t.Helper() + response, err := fx.client.Get(fx.searchBase + "/" + index + "/_stats?level=indices") + if err != nil { + t.Fatalf("read index counters: %v", err) + } + defer response.Body.Close() + var body struct { + Indices map[string]struct { + UUID string `json:"uuid"` + } `json:"indices"` + All struct { + Primaries struct { + Indexing struct { + IndexTotal int64 `json:"index_total"` + DeleteTotal int64 `json:"delete_total"` + } `json:"indexing"` + } `json:"primaries"` + } `json:"_all"` + } + if err := json.NewDecoder(response.Body).Decode(&body); err != nil { + t.Fatalf("decode index counters: %v", err) + } + meta, ok := body.Indices[index] + if !ok || meta.UUID == "" { + t.Fatalf("index %s has no uuid in stats", index) + } + return indexCounters{IndexUUID: meta.UUID, Indexed: body.All.Primaries.Indexing.IndexTotal, Deleted: body.All.Primaries.Indexing.DeleteTotal} +} + +// rawEffectKeys 读取不可变证据文件的顶层字段名:用来证明"判据所需证据真的落盘了", +// 而不是只看某个 Go 字段(字段不存在时测试仍然要红)。 +func rawEffectKeys(t *testing.T, fx *writeSetFixture, plan *libraryrelease.WriteSet, change libraryrelease.IndexWrite, phase string) map[string]json.RawMessage { + t.Helper() + raw, err := os.ReadFile(indexEffectFile(fx, plan, change, phase)) + if err != nil { + t.Fatalf("read %s evidence: %v", phase, err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + t.Fatalf("decode %s evidence: %v", phase, err) + } + return fields +} + +// 反例:恢复 marker 已真实写入、回执丢失,随后 marker 被删除 —— 观测到的"缺失" +// 与"从未发送"在索引里完全同形。缺失本身不是"证明未发送",因此必须 held, +// 不能凭 !Found 直接重建(那等于把 CAS create 的不覆盖性质冒充成历史证明)。 +func TestContractRestoreMarkerWrittenThenDeletedIsNotProvablyUnsentIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + + target := fx.target(t) + backups := fx.backups(t, target) + client := *target.search.client + inner := client.Transport + if inner == nil { + inner = http.DefaultTransport + } + wire := &restorePhaseWire{inner: inner} + client.Transport = wire + target.search.client = &client + + target.restoreMarkerFault = func(c libraryrelease.IndexWrite) error { + if c.ID != "chunk-target" { + return nil + } + return errors.New("injected restore boundary fault: dispatch refused before any index write") + } + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, backups, nil) + if outcome.State != "rollback_failed" { + t.Fatalf("state = %q, want rollback_failed (held)", outcome.State) + } + plan := outcome.Backup.WriteSet + change := indexChangeOf(t, plan, "chunk-target") + marker, err := target.restoreIndexClaimBody(change) + if err != nil { + t.Fatal(err) + } + requireIndexEffect(t, fx, plan, change, "restore-mark-intent", true) + + // marker 写入真实成功(服务器已回执),但调用方没收到:不保存 restore-claimed。 + written, err := target.mutatePlannedIndex(fx.ctx, change, marker, nil, nil, true) + if err != nil { + t.Fatalf("real marker create: %v", err) + } + // 随后 marker 被删除:现在观测为"缺失",与从未写入不可区分。 + if _, err := target.mutatePlannedIndex(fx.ctx, change, nil, written.SeqNo, written.PrimaryTerm, false); err != nil { + t.Fatalf("delete the marker after its lost response: %v", err) + } + observed, err := target.observePlannedIndex(fx.ctx, change) + if err != nil || observed.Found { + t.Fatalf("precondition: marker must be absent, observed=%+v err=%v", observed, err) + } + requireIndexEffect(t, fx, plan, change, "restore-claimed", false) + requireIndexEffect(t, fx, plan, change, "restored", false) + heldPG := universeDump(t, fx.pool) + heldIndex := recoveryIndexReadback(t, fx) + heldObjects := objectVersionSet(t, fx) + + // 撤掉故障后只允许"可证明未发送"的重做;这里历史已经发生,必须 held。 + target.restoreMarkerFault = nil + base := wire.counts() + if err := target.Restore(fx.ctx, outcome.Backup); err == nil { + t.Fatal("absence after a lost marker write is indistinguishable from never-sent; restoration must be held, not rebuilt") + } else if !strings.Contains(err.Error(), "held") { + t.Fatalf("held error must say held, got: %v", err) + } + + // r37:ES 写计数器不是不可变证据(分片迁移/节点替换会清零,索引 uuid 不变不 + // 绑定统计生命周期),因此删除型恢复既不再落盘计数器栅栏,也不得据它放行写入。 + if _, ok := rawEffectKeys(t, fx, plan, change, "restore-mark-intent")["fence"]; ok { + t.Fatal("restore-mark-intent must not record a counter fence as authorization evidence") + } + + // held 不许偷偷写入,也不许改动任何真实存储。 + if sent := wire.since(base); sent.creates != 0 || sent.marker != 0 || sent.clean != 0 || sent.deletes != 0 { + t.Fatalf("held restoration dispatched writes: %+v", sent) + } + if diff := diffUniverse(heldPG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("held restoration changed PG: %s", diff) + } + if afterIndex := recoveryIndexReadback(t, fx); !reflect.DeepEqual(heldIndex, afterIndex) { + t.Fatal("held restoration changed the index") + } + if after := objectVersionSet(t, fx); !reflect.DeepEqual(heldObjects, after) { + t.Fatalf("held restoration changed object versions:\n before=%v\n after=%v", heldObjects, after) + } +} + +// resetStatsTransport 模拟 `_stats` 的分片迁移/统计清零后重新累计(ABA): +// +// 第一次 stats 响应原样转发并记住;此后所有 stats 请求都返回**这一份旧响应**。 +// +// 于是索引 uuid 与 (indexed, deleted) 与冻结时逐位相同,而真实索引里文档已经被 +// 写过又删掉。这是**传输层的 stats 故障模拟**:文档写入走真实 ES,没有重启共享 ES, +// 也没有伪造文档观测结果。 +type resetStatsTransport struct { + inner http.RoundTripper + frozen []byte + restores int + replayed int +} + +func (w *resetStatsTransport) RoundTrip(r *http.Request) (*http.Response, error) { + if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/_stats") { + w.restores++ + if w.frozen == nil { + response, err := w.inner.RoundTrip(r) + if err != nil { + return nil, err + } + body, err := io.ReadAll(response.Body) + response.Body.Close() + if err != nil { + return nil, err + } + w.frozen = body + response.Body = io.NopCloser(bytes.NewReader(body)) + return response, nil + } + w.replayed++ + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewReader(w.frozen)), + Request: r, + }, nil + } + return w.inner.RoundTrip(r) +} + +func statsCountersOf(t *testing.T, body []byte, index string) indexCounters { + t.Helper() + var decoded struct { + Indices map[string]struct { + UUID string `json:"uuid"` + } `json:"indices"` + All struct { + Primaries struct { + Indexing struct { + IndexTotal int64 `json:"index_total"` + DeleteTotal int64 `json:"delete_total"` + } `json:"indexing"` + } `json:"primaries"` + } `json:"_all"` + } + if err := json.Unmarshal(body, &decoded); err != nil { + t.Fatalf("decode frozen stats: %v (%s)", err, body) + } + meta, ok := decoded.Indices[index] + if !ok || meta.UUID == "" { + t.Fatalf("frozen stats has no uuid for %s: %s", index, body) + } + return indexCounters{IndexUUID: meta.UUID, Indexed: decoded.All.Primaries.Indexing.IndexTotal, Deleted: decoded.All.Primaries.Indexing.DeleteTotal} +} + +// r37 反例:分片迁移/节点替换会清掉分片级统计(官方 `_stats` 文档明确写了这一点), +// 索引 uuid 不变并不绑定统计生命周期;清零后再累计到与冻结值相同的情况(ABA)无法排除。 +// 因此"统计逐位相同"不是不可变证据:marker 真的写过又被删掉时,观测仍是缺失,必须 held。 +// +// 现场:先让恢复在派发前确定失败(restore-mark-intent 落盘),再**真实**写入 marker、 +// **真实**删除 marker;stats 端点则一直返回测试侧预先取得的那份响应(同 uuid 同计数), +// 模拟分片迁移清零后又累计回同一数值。旧实现据此判定"未发送"并重建; +// 本用例要求 held、零写入,且删除型恢复不得再读取统计。 +func TestContractRestoreMarkerAfterStatsResetABAIsHeldIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + + target := fx.target(t) + backups := fx.backups(t, target) + client := *target.search.client + inner := client.Transport + if inner == nil { + inner = http.DefaultTransport + } + wire := &restorePhaseWire{inner: inner} + // 测试侧自己先取一份统计快照作为"冻结值",之后 stats 端点一直返回它; + // 快照不依赖生产代码是否读取统计,避免用例被"实现先读一次"绑死。 + statsResponse, err := fx.client.Get(fx.searchBase + "/" + fx.index + "/_stats?level=indices") + if err != nil { + t.Fatalf("read stats snapshot: %v", err) + } + statsBody, err := io.ReadAll(statsResponse.Body) + statsResponse.Body.Close() + if err != nil { + t.Fatalf("read stats snapshot body: %v", err) + } + stats := &resetStatsTransport{inner: wire, frozen: statsBody} + client.Transport = stats + target.search.client = &client + + target.restoreMarkerFault = func(c libraryrelease.IndexWrite) error { + if c.ID != "chunk-target" { + return nil + } + return errors.New("injected restore boundary fault: dispatch refused before any index write") + } + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, backups, nil) + if outcome.State != "rollback_failed" { + t.Fatalf("state = %q, want rollback_failed (held)", outcome.State) + } + plan := outcome.Backup.WriteSet + change := indexChangeOf(t, plan, "chunk-target") + marker, err := target.restoreIndexClaimBody(change) + if err != nil { + t.Fatal(err) + } + requireIndexEffect(t, fx, plan, change, "restore-mark-intent", true) + requireIndexEffect(t, fx, plan, change, "restore-claimed", false) + requireIndexEffect(t, fx, plan, change, "restored", false) + + // 恢复意图落盘(真实派发 0 次),随后 marker 真实写入、真实删除。 + written, err := target.mutatePlannedIndex(fx.ctx, change, marker, nil, nil, true) + if err != nil { + t.Fatalf("real marker create: %v", err) + } + if _, err := target.mutatePlannedIndex(fx.ctx, change, nil, written.SeqNo, written.PrimaryTerm, false); err != nil { + t.Fatalf("delete the marker after its lost response: %v", err) + } + observed, err := target.observePlannedIndex(fx.ctx, change) + if err != nil || observed.Found { + t.Fatalf("precondition: marker must be absent, observed=%+v err=%v", observed, err) + } + + // 预先取得的统计必须真的与现场不符:真实写入+删除推进了计数器, + // 而 stats 端点返回的仍是派发前的同 uuid 同计数(模拟清零后 ABA)。 + frozen := statsCountersOf(t, stats.frozen, change.Index) + live := readIndexCounters(t, fx, change.Index) + if frozen.IndexUUID != live.IndexUUID { + t.Fatalf("fixture index uuid changed: frozen=%s live=%s", frozen.IndexUUID, live.IndexUUID) + } + if frozen.Indexed == live.Indexed && frozen.Deleted == live.Deleted { + t.Fatalf("real marker write+delete must advance the live counters, live=%+v", live) + } + + heldPG := universeDump(t, fx.pool) + heldIndex := recoveryIndexReadback(t, fx) + heldObjects := objectVersionSet(t, fx) + + // 撤掉故障:stats 仍然"逐位相同"。统计相等不构成不可变证据,恢复必须 held。 + target.restoreMarkerFault = nil + base := wire.counts() + err = target.Restore(fx.ctx, outcome.Backup) + if err == nil { + t.Fatal("stats counters that happen to match after a reset are not immutable evidence; restoration must be held, not rebuilt") + } + if !strings.Contains(err.Error(), "held") { + t.Fatalf("held error must say held, got: %v", err) + } + if sent := wire.since(base); sent.creates != 0 || sent.marker != 0 || sent.clean != 0 || sent.deletes != 0 { + t.Fatalf("held restoration dispatched writes: %+v", sent) + } + if diff := diffUniverse(heldPG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("held restoration changed PG: %s", diff) + } + if after := recoveryIndexReadback(t, fx); !reflect.DeepEqual(heldIndex, after) { + t.Fatal("held restoration changed the index") + } + if after := objectVersionSet(t, fx); !reflect.DeepEqual(heldObjects, after) { + t.Fatalf("held restoration changed object versions:\n before=%v\n after=%v", heldObjects, after) + } + + // 契约:删除型恢复不得再读取 / 依赖 ES 写计数器放行写入。 + if stats.restores != 0 { + t.Fatalf("restoration consulted %d stats snapshots; ES counters are diagnostic only", stats.restores) + } + if _, ok := rawEffectKeys(t, fx, plan, change, "restore-mark-intent")["fence"]; ok { + t.Fatal("restore-mark-intent still records a counter fence as authorization evidence") + } +} + +// 缺口 2a:restore-finalize-intent 已落盘、干净收尾写入在派发边界上被拒绝。 +// 重试必须能凭"标记体仍停在自己那份世代上"证明干净写入没有落地,并继续收尾; +// 不能因为 finalize-intent 存在就永久 held(那是同一状态的死路)。 +func TestContractKnownIndexRecoveryAfterCleanDispatchFaultIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + beforePG := universeDump(t, fx.pool) + beforeIndex := recoveryIndexReadback(t, fx) + beforeObjects := objectVersionSet(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + + target := fx.target(t) + backups := fx.backups(t, target) + client := *target.search.client + inner := client.Transport + if inner == nil { + inner = http.DefaultTransport + } + wire := &restorePhaseWire{inner: inner} + client.Transport = wire + target.search.client = &client + + refusals := 0 + var base wireCounts + target.restoreMarkerFault = func(c libraryrelease.IndexWrite) error { + if c.ID != "chunk-target" { + return nil + } + refusals++ + if refusals == 1 { + // 标记写入派发前的基线:之后的增量只属于恢复阶段。 + base = wire.counts() + return nil + } + if refusals == 2 { + return errors.New("injected clean dispatch fault: refused before any clean write") + } + return nil + } + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, backups, nil) + if outcome.State != "rollback_failed" { + t.Fatalf("state = %q (rollback=%q error=%q), want rollback_failed", outcome.State, outcome.Rollback, outcome.Error) + } + if refusals != 2 { + t.Fatalf("refusals = %d, want marker allowed + clean refused = 2", refusals) + } + plan := outcome.Backup.WriteSet + change := indexChangeOf(t, plan, "chunk-target") + marker, err := target.restoreIndexClaimBody(change) + if err != nil { + t.Fatal(err) + } + requireIndexEffect(t, fx, plan, change, "restore-mark-intent", true) + requireIndexEffect(t, fx, plan, change, "restore-claimed", true) + requireIndexEffect(t, fx, plan, change, "restore-finalize-intent", true) + requireIndexEffect(t, fx, plan, change, "restored", false) + first := wire.since(base) + if first.marker != 1 || first.creates != 1 || first.createWithCAS != 0 || first.clean != 0 || first.deletes != 0 { + t.Fatalf("first attempt dispatched %+v, want exactly one exclusive marker create and no clean write", first) + } + held, err := target.observePlannedIndex(fx.ctx, change) + if err != nil || !indexBytesEqual(held, marker) { + t.Fatalf("held index must still carry the marker body: %v", err) + } + + // 撤故障后:标记体 + 它自己的世代证明干净写入从未落地,必须继续而不是死路。 + target.restoreMarkerFault = nil + resumeBase := wire.counts() + if err := target.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatalf("clean dispatch refusal must be resumable from its own marker generation, got: %v", err) + } + if resumed := wire.since(resumeBase); resumed.marker != 0 || resumed.creates != 0 || resumed.clean != 1 || resumed.deletes != 0 { + t.Fatalf("resume dispatched %+v, want exactly one clean write and no marker rewrite", resumed) + } + + if diff := diffUniverse(beforePG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("post-recovery PG differs from the before-image: %s", diff) + } + if err := target.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: outcome.Backup.SnapshotID}); err != nil { + t.Fatalf("post-recovery verification: %v", err) + } + afterIndex := recoveryIndexReadback(t, fx) + if len(afterIndex) != len(beforeIndex) { + t.Fatalf("index ID set changed: %d -> %d", len(beforeIndex), len(afterIndex)) + } + for id, old := range beforeIndex { + got, ok := afterIndex[id] + if !ok || !reflect.DeepEqual(old["_source"], got["_source"]) { + t.Fatalf("index document %s not restored to its before-image", id) + } + if id == "chunk-target" && reflect.DeepEqual(old["_seq_no"], got["_seq_no"]) { + t.Fatal("restoration reused the applied generation instead of writing a new one") + } + } + if after := objectVersionSet(t, fx); !reflect.DeepEqual(beforeObjects, after) { + t.Fatalf("object versions differ from the before-image:\n before=%v\n after=%v", beforeObjects, after) + } + restored, err := target.loadIndexEffect(change, "restored") + if err != nil || restored == nil || restored.Receipt == nil { + t.Fatalf("restored receipt missing: %v", err) + } + live, err := target.observePlannedIndex(fx.ctx, change) + if err != nil || !sameIndexGeneration(live, restored.Receipt.SeqNo, restored.Receipt.PrimaryTerm) || !indexBytesEqual(live, change.Before) { + t.Fatalf("restored receipt does not match the live before-image: %v", err) + } + + // 重放同一份预备份:不得再派发任何恢复写入。 + replayBase := wire.counts() + next := fx.target(t) + if err := next.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatalf("replayed restoration: %v", err) + } + if replayed := wire.since(replayBase); replayed.creates != 0 || replayed.marker != 0 || replayed.clean != 0 || replayed.deletes != 0 { + t.Fatalf("replay dispatched recovery writes: %+v", replayed) + } + if replay := recoveryIndexReadback(t, fx); !reflect.DeepEqual(afterIndex, replay) { + t.Fatal("replayed restoration rewrote index generations") + } +} + +// 缺口 2b:删除补偿(Before 为空、恢复写入是 DELETE)在派发边界上被拒绝。 +// restore-intent 已落盘,重试必须凭"文档仍是 applied 结果、世代仍是 applied 回执"证明 +// 删除没有落地并重放 DELETE;不能退化成永久 "requires reconciliation"。 +func TestContractKnownIndexRecoveryAfterDeleteCompensationFaultIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + beforePG := universeDump(t, fx.pool) + beforeIndex := recoveryIndexReadback(t, fx) + beforeObjects := objectVersionSet(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + + target := fx.target(t) + backups := fx.backups(t, target) + client := *target.search.client + inner := client.Transport + if inner == nil { + inner = http.DefaultTransport + } + wire := &restorePhaseWire{inner: inner} + client.Transport = wire + target.search.client = &client + + var base wireCounts + target.restoreMarkerFault = func(c libraryrelease.IndexWrite) error { + if c.ID != expectedIndexID("chunk-src") { + return nil + } + base = wire.counts() + return errors.New("injected delete compensation boundary fault") + } + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, backups, nil) + if outcome.State != "rollback_failed" { + t.Fatalf("state = %q (rollback=%q error=%q), want rollback_failed", outcome.State, outcome.Rollback, outcome.Error) + } + plan := outcome.Backup.WriteSet + change := indexChangeOf(t, plan, expectedIndexID("chunk-src")) + if len(change.Before) != 0 || len(change.After) == 0 { + t.Fatalf("fixture change is not a created document: %+v", change) + } + requireIndexEffect(t, fx, plan, change, "restore-intent", true) + requireIndexEffect(t, fx, plan, change, "restored", false) + if refused := wire.since(base); refused.deletes != 0 || refused.clean != 0 || refused.creates != 0 { + t.Fatalf("boundary fault dispatched %+v; refusal must send nothing", refused) + } + if _, ok := recoveryIndexReadback(t, fx)[expectedIndexID("chunk-src")]; !ok { + t.Fatal("precondition: the created document must still be present after the refused delete") + } + + target.restoreMarkerFault = nil + resumeBase := wire.counts() + if err := target.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatalf("refused delete compensation must resume from the applied generation, got: %v", err) + } + if resumed := wire.since(resumeBase); resumed.deletes != 1 || resumed.marker != 1 || resumed.clean != 1 { + t.Fatalf("resume dispatched %+v, want one delete compensation + one marker create + one clean write", resumed) + } + if diff := diffUniverse(beforePG, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("post-recovery PG differs from the before-image: %s", diff) + } + if err := target.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: outcome.Backup.SnapshotID}); err != nil { + t.Fatalf("post-recovery verification: %v", err) + } + afterIndex := recoveryIndexReadback(t, fx) + if len(afterIndex) != len(beforeIndex) { + t.Fatalf("index ID set changed: %d -> %d", len(beforeIndex), len(afterIndex)) + } + for id, old := range beforeIndex { + got, ok := afterIndex[id] + if !ok || !reflect.DeepEqual(old["_source"], got["_source"]) { + t.Fatalf("index document %s not restored to its before-image", id) + } + if id == "chunk-target" && reflect.DeepEqual(old["_seq_no"], got["_seq_no"]) { + t.Fatal("restoration reused the applied generation instead of writing a new one") + } + } + if after := objectVersionSet(t, fx); !reflect.DeepEqual(beforeObjects, after) { + t.Fatalf("object versions differ from the before-image:\n before=%v\n after=%v", beforeObjects, after) + } +} diff --git a/internal/releaseadapter/v071/library_index_restart_test.go b/internal/releaseadapter/v071/library_index_restart_test.go new file mode 100644 index 0000000..d379ddb --- /dev/null +++ b/internal/releaseadapter/v071/library_index_restart_test.go @@ -0,0 +1,109 @@ +package v071 + +import ( + "encoding/json" + "net/http" + "os" + "os/exec" + "path/filepath" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +func TestIndexRecoveryHelper(t *testing.T) { + if os.Getenv("KG_INDEX_RECOVERY_CHILD") != "1" { + t.Skip("isolated subprocess only") + } + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{archiveRoot: os.Getenv("KG_INDEX_RECOVERY_ARCHIVE"), index: os.Getenv("KG_INDEX_RECOVERY_INDEX")}) + raw, err := os.ReadFile(os.Getenv("KG_INDEX_RECOVERY_BACKUP")) + if err != nil { + t.Fatal(err) + } + var backup libraryrelease.BackupRef + if err = json.Unmarshal(raw, &backup); err != nil { + t.Fatal(err) + } + ledger, err := LoadWriteSet(fx.archiveRoot, backup.WriteSet.Digest) + if err != nil { + t.Fatal(err) + } + backup.WriteSet = ledger + target := fx.target(t) + if err = target.Restore(fx.ctx, backup); err != nil { + t.Fatal(err) + } + // A second restart/recovery must not need the now-deleted transient marker. + next := fx.target(t) + if err = next.Restore(fx.ctx, backup); err != nil { + t.Fatal("replayed restoration", err) + } + if err = next.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: backup.SnapshotID}); err != nil { + t.Fatal(err) + } +} + +func TestContractIndexLostResponseRestartCompensatesIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatal(err) + } + backup, err := fx.backups(t, target).Prepare(fx.ctx, snapshot, current) + if err != nil { + t.Fatal(err) + } + backup.WriteSet = planLedgerWithUniverse(t, target, snapshot, backup.SnapshotID, backup.Universe) + client := *target.search.client + transport := client.Transport + if transport == nil { + transport = http.DefaultTransport + } + fault := &indexLostResponseTransport{inner: transport} + client.Transport = fault + target.search.client = &client + for _, stage := range []libraryrelease.Stage{libraryrelease.StageDatabase, libraryrelease.StageResources} { + if err = target.Apply(fx.ctx, stage, snapshot); err != nil { + t.Fatal(err) + } + } + if err = target.Apply(fx.ctx, libraryrelease.StageIndex, snapshot); err == nil || !fault.dropped { + t.Fatal("real ES commit/response loss not exercised", err) + } + // Persist only the same backup/plan identity needed by a new executable. + raw, err := json.Marshal(backup) + if err != nil { + t.Fatal(err) + } + state := filepath.Join(t.TempDir(), "backup.json") + if err = persistImmutableJSON(state, raw); err != nil { + t.Fatal(err) + } + command := exec.Command(os.Args[0], "-test.run=^TestIndexRecoveryHelper$", "-test.v") + command.Env = append(os.Environ(), "KG_INDEX_RECOVERY_CHILD=1", "KG_INDEX_RECOVERY_ARCHIVE="+fx.archiveRoot, "KG_INDEX_RECOVERY_INDEX="+fx.index, "KG_INDEX_RECOVERY_BACKUP="+state) + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("fresh process compensation failed: %v\n%s", err, output) + } + t.Log(string(output)) + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatal(diff) + } + paths, err := filepath.Glob(filepath.Join(fx.archiveRoot, "effects", backup.WriteSet.Digest, "index", "*", "claimed.json")) + if err != nil || len(paths) == 0 { + t.Fatal("reconciled receipt not durable", err) + } + for _, path := range paths { + info, err := os.Stat(path) + if err != nil || info.Mode().Perm()&0222 != 0 { + t.Fatal("receipt not immutable", err) + } + } + if err = target.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: backup.SnapshotID}); err != nil { + t.Fatal(err) + } +} diff --git a/internal/releaseadapter/v071/library_index_restore_claim.go b/internal/releaseadapter/v071/library_index_restore_claim.go new file mode 100644 index 0000000..d275cdd --- /dev/null +++ b/internal/releaseadapter/v071/library_index_restore_claim.go @@ -0,0 +1,294 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "knowledge-governance/internal/libraryrelease" +) + +const indexRestoreClaimPrefix = "kg-release-transient-restore-claim:" + +// restorationProvablyUnsent 判定"这份恢复意图确实没有到达索引"。 +// +// 判据只能是"每成功写一次必然会在服务端留下的东西": +// - 更新型:观察到的内容必须仍是 applied 结果,且世代与 applied 回执完全相同; +// - 删除型(恢复写入是独占 create):服务端没有持久、不可重用的证据。文档缺失与 +// "从未写过"在索引里完全同形;ES 的写计数器只是分片生命周期内的统计量(官方 +// `_stats` 文档:分片迁到别的节点时该分片的统计会被清零),索引 uuid 不变并不 +// 绑定统计生命周期,清零后重新累计到同一数值(ABA)无法排除。删除型只有当 +// **本次尝试开始时不存在任何恢复意图**(freshIntent:先落意图、后派发的不变量 +// 说明本作业从未派发过)且文档确实缺失时才能重做;既存意图一律 held(B19)。 +// +// 任何"内容看起来对但世代对不上"的状态都只能 held,不认领。 +func (t *ProductionLibraryTarget) restorationProvablyUnsent(ctx context.Context, observed indexWriteGuard, c libraryrelease.IndexWrite, applied indexReceipt, freshIntent bool) (bool, error) { + if len(c.After) == 0 { + return freshIntent && !observed.Found, nil + } + if !sameIndexGeneration(observed, applied.SeqNo, applied.PrimaryTerm) { + return false, nil + } + if indexBytesEqual(observed, c.After) { + return true, nil + } + if applied.Marked { + // 应用期停在"标记态"(claim 未收尾)时,applied 回执说的就是那份标记体。 + claim, err := t.indexClaimBody(c) + if err != nil { + return false, err + } + return indexBytesEqual(observed, claim), nil + } + return false, nil +} + +func (t *ProductionLibraryTarget) restoreIndexClaimBody(c libraryrelease.IndexWrite) (json.RawMessage, error) { + var body map[string]json.RawMessage + if json.Unmarshal(c.Before, &body) != nil || body == nil { + return nil, errors.New("restore claim requires frozen before-image") + } + var content string + if json.Unmarshal(body["content"], &content) != nil { + return nil, errors.New("restore claim requires existing content field") + } + sum := sha256.Sum256([]byte(t.activePlan.Digest + "\x00" + c.Index + "\x00" + c.ID + "\x00restore")) + body["content"], _ = json.Marshal(indexRestoreClaimPrefix + hex.EncodeToString(sum[:]) + "\n" + content) + encoded, err := json.Marshal(body) + if err != nil { + return nil, err + } + return canonicalJSON(encoded) +} + +// Only a plan-specific marker plus the entire frozen body can reconcile a lost +// restore-write response. Equal clean content is not proof of who wrote it. +// Old unknown writes without this pre-send intent remain held, not adopted. +func (t *ProductionLibraryTarget) restoreClaimedIndexBefore(ctx context.Context, c libraryrelease.IndexWrite, applied indexReceipt, start bool) error { + body, err := t.restoreIndexClaimBody(c) + if err != nil { + return err + } + markIntent, err := t.loadIndexEffect(c, "restore-mark-intent") + if err != nil { + return err + } + // 本次尝试开始时没有任何恢复意图,才可能证明"本作业从未派发过": + // 生产路径先落意图再派发,意图不可覆盖。既存意图的派发历史无法由缺失证明。 + freshIntent := markIntent == nil + claimed, err := t.loadIndexEffect(c, "restore-claimed") + if err != nil { + return err + } + if markIntent == nil { + if !start { + // DS01-F5:prepared 已提交、mark-intent 未落盘的窄区段。旧实现一律按 + // legacy 拒绝,把设计允许补同内容意图的区段永久堵死。先精确核对: + // 原台账存在、绑定一致、仍是 prepared、且没有任何 claimed/finalize/restored + // 矛盾——全部成立才允许补写同一份意图;否则仍是旧协议未知历史。 + resumed, err := t.resumePreparedWithoutIntent(ctx, c, body, applied) + if err != nil { + return err + } + if !resumed { + return errors.New("legacy unknown index restoration lacks attributable marker intent") + } + if markIntent, err = t.loadIndexEffect(c, "restore-mark-intent"); err != nil { + return err + } + freshIntent = false + } else { + // 新协议:先在治理库建立 prepared(文件意图之前),再落文件意图。文件失败只留 + // prepared(零派发,下一进程可补写同内容意图);反过来"先文件后台账"则会造出 + // 无法证明未派发的旧证据。 + if t.config.RestoreDispatch != nil && len(c.After) == 0 { + binding, err := t.restoreMarkerBinding(ctx, c, body) + if err != nil { + return err + } + status, err := t.config.RestoreDispatch.PrepareRestoreMarker(ctx, binding) + if err != nil { + return err + } + if status.Held { + return heldRestoreMarker(status, "首次恢复不能建立 prepared") + } + } + if err = t.beginRestoreMarker(ctx, c, applied); err != nil { + return err + } + if markIntent, err = t.loadIndexEffect(c, "restore-mark-intent"); err != nil { + return err + } + } + } else if t.config.RestoreDispatch != nil && len(c.After) == 0 { + // 既有意图必须能在新台账里找到同一 effect:找不到就是旧协议的未知历史, + // 不能借"文件看起来完整"补一份 prepared。 + binding, err := t.restoreMarkerBinding(ctx, c, body) + if err != nil { + return err + } + status, found, err := t.config.RestoreDispatch.InspectRestoreMarker(ctx, binding) + if err != nil { + return err + } + if !found { + return fmt.Errorf("%w: 既存意图没有派发台账(旧协议未知历史)", libraryrelease.ErrRestoreDispatchHeld) + } + if status.BindingConflict { + return heldRestoreMarker(status, "既存意图的派发台账绑定与本次计划冲突") + } + if status.State == libraryrelease.RestoreDispatchPrepared && claimed != nil { + return heldRestoreMarker(status, "prepared 台账却已有 claimed 证据:协议证据矛盾") + } + } + finalizing, err := t.loadIndexEffect(c, "restore-finalize-intent") + if err != nil { + return err + } + observed, err := t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + // 台账停在 dispatching 时,只有"精确 marker+完整内容+可靠世代"才允许沿原确认 + // 分支继续;确认失败即 held,绝不为了活性重发 create。 + if err := t.confirmDispatchedMarker(ctx, c, body, observed); err != nil { + return err + } + if finalizing != nil { + // 干净写入在派发边界上被拒绝时,标记体会原样停在自己那份世代上;落地过一次 + // 干净写入必然换掉内容并推进世代。两条同时成立才证明没写过,否则 held。 + if finalizing.Receipt == nil || !indexBytesEqual(observed, body) || !sameIndexGeneration(observed, finalizing.Receipt.SeqNo, finalizing.Receipt.PrimaryTerm) { + return errors.New("unknown clean restoration cannot be attributed by appearance; held") + } + return t.finishRestoreCleanWrite(ctx, c, *finalizing.Receipt) + } + if !indexBytesEqual(observed, body) { + // The marker is absent: either the intent never reached the index (a + // deterministic refusal before dispatch) or its write outcome is unknown. + // 删除型的恢复写入是独占 create:服务端没有"从未写过"的可持久证据。 + // 新协议只允许台账里 prepared 的 effect 重新竞争一次发送许可;旧意图没有 + // 台账、或台账已 dispatching 的,一律 held(上面的分支已拒绝)。 + if len(c.After) == 0 && t.config.RestoreDispatch != nil { + receipt, err := t.dispatchRestoreMarkerCreate(ctx, c, body) + if err != nil { + return err + } + receipt.Marked = true + if err = t.saveIndexEffect(c, "restore-claimed", &receipt); err != nil { + return err + } + claimed = &indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: &receipt} + observed, err = t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + } else { + unsent, err := t.restorationProvablyUnsent(ctx, observed, c, applied, freshIntent) + if err != nil { + return err + } + if !unsent { + return errors.New("unknown restoration lacks exact operation marker/content/CAS; held") + } + if err := t.refuseRestoreWrite(c); err != nil { + return err + } + receipt, err := t.mutatePlannedIndex(ctx, c, body, applied.SeqNo, applied.PrimaryTerm, len(c.After) == 0) + if err != nil { + return err + } + receipt.Marked = true + if err = t.saveIndexEffect(c, "restore-claimed", &receipt); err != nil { + return err + } + claimed = &indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: &receipt} + observed, err = t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + } + } + if !indexBytesEqual(observed, body) || observed.SeqNo == nil || observed.PrimaryTerm == nil { + return errors.New("unknown restoration lacks exact operation marker/content/CAS; held") + } + if claimed == nil { + receipt := indexReceipt{Index: c.Index, ID: c.ID, Result: "updated", SeqNo: observed.SeqNo, PrimaryTerm: observed.PrimaryTerm, Marked: true} + if len(c.After) == 0 { + receipt.Result = "created" + } + if err = t.saveIndexEffect(c, "restore-claimed", &receipt); err != nil { + return err + } + claimed = &indexEffect{Plan: t.activePlan.Digest, Change: c, Receipt: &receipt} + } + if claimed.Receipt == nil || !claimed.Receipt.Marked || !sameIndexGeneration(observed, claimed.Receipt.SeqNo, claimed.Receipt.PrimaryTerm) { + return errors.New("restoration claim generation changed; held") + } + if err = t.saveIndexEffect(c, "restore-finalize-intent", claimed.Receipt); err != nil { + return err + } + return t.finishRestoreCleanWrite(ctx, c, *claimed.Receipt) +} + +// resumePreparedWithoutIntent 处理"prepared 已提交、mark-intent 还没落盘"的窄区段。 +// +// 只有同时满足以下各项才允许补写同一份意图并继续:台账存在、绑定一致、状态仍是 +// prepared,且没有 claimed/finalize/restored 任何矛盾证据。没有台账的旧意图仍按 +// legacy 处理(返回 false),不回填、不推测。 +func (t *ProductionLibraryTarget) resumePreparedWithoutIntent(ctx context.Context, c libraryrelease.IndexWrite, + body json.RawMessage, applied indexReceipt) (bool, error) { + if t.config.RestoreDispatch == nil || len(c.After) != 0 { + return false, nil + } + binding, err := t.restoreMarkerBinding(ctx, c, body) + if err != nil { + return false, err + } + status, found, err := t.config.RestoreDispatch.InspectRestoreMarker(ctx, binding) + if err != nil { + return false, err + } + if !found || status.State != libraryrelease.RestoreDispatchPrepared || status.Held { + return false, nil + } + for _, phase := range []string{"restore-claimed", "restore-finalize-intent", "restored"} { + effect, err := t.loadIndexEffect(c, phase) + if err != nil { + return false, err + } + if effect != nil { + return false, fmt.Errorf("%w: prepared 台账却已有 %s 证据", libraryrelease.ErrRestoreDispatchHeld, phase) + } + } + if err := t.beginRestoreMarker(ctx, c, applied); err != nil { + return false, err + } + return true, nil +} + +// finishRestoreCleanWrite 派发"标记体 -> 冻结 before-image"的 CAS 收尾,并把回执与 +// 实时观察逐位核对。finalize-intent 存在时,只有标记体仍停在它自己的世代上才会 +// 走到这里:落地过干净写入必然换掉内容并推进世代。 +func (t *ProductionLibraryTarget) finishRestoreCleanWrite(ctx context.Context, c libraryrelease.IndexWrite, marker indexReceipt) error { + if err := t.refuseRestoreWrite(c); err != nil { + return err + } + receipt, err := t.mutatePlannedIndex(ctx, c, c.Before, marker.SeqNo, marker.PrimaryTerm, false) + if err != nil { + return err + } + if err = t.saveIndexEffect(c, "restored", &receipt); err != nil { + return err + } + observed, err := t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if !indexBytesEqual(observed, c.Before) || !sameIndexGeneration(observed, receipt.SeqNo, receipt.PrimaryTerm) { + return errors.New("restoration clean readback differs from receipt") + } + return nil +} diff --git a/internal/releaseadapter/v071/library_index_restore_dispatch.go b/internal/releaseadapter/v071/library_index_restore_dispatch.go new file mode 100644 index 0000000..00213c5 --- /dev/null +++ b/internal/releaseadapter/v071/library_index_restore_dispatch.go @@ -0,0 +1,460 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "time" + + "knowledge-governance/internal/libraryrelease" +) + +// DS01:删除型恢复(Before 非空、After 为空)的标记 create 是唯一会"无中生有"的 +// 恢复写:ES 里文档缺失与"从未写过"完全同形,所以它不能靠外观、stats 或内存计数 +// 放行。新协议把"是否已经有人取得发送许可"放进治理库的单调台账;本文件是 adapter +// 侧的全部接入点——准入、唯一派发、确认与收尾检查。 +// +// 明确不保证:ES 端 fence;已 dispatching 的旧 owner 绝不迟到一次。协议只保证 +// 遵守协议的派发者不会得到第二次许可,且 dispatching 永不回退。 + +// restoreMarkerBinding 用**原持久锚点**构造不可变绑定: +// - scope 来自真实装配; +// - source 是发布基线(WriteSet.TargetSnapshotID),backup 是本次写前镜像; +// - target instance/fingerprint/index UUID 实时观察并与本次恢复的冻结值比较。 +func (t *ProductionLibraryTarget) restoreMarkerBinding(ctx context.Context, c libraryrelease.IndexWrite, body json.RawMessage) (libraryrelease.RestoreMarkerBinding, error) { + if t.config.RestoreDispatch == nil { + return libraryrelease.RestoreMarkerBinding{}, errors.New("restore dispatch protocol is not wired") + } + if t.activePlan == nil { + return libraryrelease.RestoreMarkerBinding{}, errors.New("restore dispatch requires the frozen plan") + } + if t.config.RestoreTargetIdentity == "" || t.config.RestoreInstance == "" || + t.config.RestoreOperationID == "" || t.config.RestoreWindowJobID == "" || + t.config.RestoreAttemptOwner == "" || t.config.RestoreAttemptEpoch <= 0 { + return libraryrelease.RestoreMarkerBinding{}, errors.New("restore dispatch lacks the original job/attempt identity") + } + if t.restoreScope == "" || t.restoreSourceSnapshot == "" || t.restoreBackupSnapshot == "" { + return libraryrelease.RestoreMarkerBinding{}, errors.New("restore dispatch lacks the original scope/snapshot anchors") + } + if t.restoreSourceSnapshot == t.restoreBackupSnapshot { + return libraryrelease.RestoreMarkerBinding{}, errors.New("restore dispatch would use one snapshot as both source and backup") + } + fingerprint, indexUUID, err := t.frozenRestoreTarget(ctx) + if err != nil { + return libraryrelease.RestoreMarkerBinding{}, err + } + changeRaw, err := json.Marshal(c) + if err != nil { + return libraryrelease.RestoreMarkerBinding{}, err + } + changeDigest := sha256.Sum256(changeRaw) + markerDigest := sha256.Sum256(body) + method, path, _, err := t.indexMutation(c, body, nil, nil, true) + if err != nil { + return libraryrelease.RestoreMarkerBinding{}, err + } + requestDigest := sha256.Sum256([]byte(method + "\x00" + path)) + return libraryrelease.RestoreMarkerBinding{ + Key: libraryrelease.RestoreMarkerKey{ + TargetIdentity: t.config.RestoreTargetIdentity, + OperationID: t.config.RestoreOperationID, + WindowJobID: t.config.RestoreWindowJobID, + PlanDigest: t.activePlan.Digest, + Index: c.Index, + DocumentID: c.ID, + Phase: libraryrelease.RestoreMarkerPhaseCreate, + }, + Scope: t.restoreScope, + SourceSnapshot: t.restoreSourceSnapshot, + BackupSnapshot: t.restoreBackupSnapshot, + TargetInstance: t.config.RestoreInstance, + TargetFingerprint: fingerprint, + IndexUUID: indexUUID, + RecoveryJobID: t.config.RestoreRecoveryJobID, + RecoveryOperationID: t.config.RestoreRecoveryOperationID, + ChangeDigest: hex.EncodeToString(changeDigest[:]), + MarkerDigest: hex.EncodeToString(markerDigest[:]), + RequestDigest: hex.EncodeToString(requestDigest[:]), + Owner: t.config.RestoreAttemptOwner, + Epoch: t.config.RestoreAttemptEpoch, + }, nil +} + +func heldRestoreMarker(status libraryrelease.RestoreDispatchStatus, context string) error { + return fmt.Errorf("%w: %s(state=%s)", libraryrelease.ErrRestoreDispatchHeld, context, status.State) +} + +// planEffect 按 index/document 找到当前冻结计划里的 effect(用于权威全集与文件证据对照)。 +func (t *ProductionLibraryTarget) planEffect(index, document string) (libraryrelease.IndexWrite, bool) { + for _, c := range t.activePlan.Index { + if c.Index == index && c.ID == document { + return c, true + } + } + return libraryrelease.IndexWrite{}, false +} + +// admitRestorePlan 是 Restore 在**任何** PG/对象/索引写之前的纯读准入。 +// +// 删除型恢复一旦开始写 recovery 的行/对象,后面才发现某个 effect 的派发结果未知, +// 目标已经从"未动"变成"半恢复"。所以先按整份冻结计划逐 effect 判定,并先对照原 +// window 的权威台账全集(跨 plan): +// - 台账不存在(旧世界):只有"没有任何恢复意图"才算首次恢复;有意图就 held; +// - prepared:唯一可续作区段,但出现 marker/claimed/finalize/restored 任一矛盾即 held; +// - dispatching:只有精确 marker+世代才可走确认分支,否则 held; +// - marker_confirmed:只允许确认后的 clean 路径。 +func (t *ProductionLibraryTarget) admitRestorePlan(ctx context.Context) error { + gate := t.config.RestoreDispatch + if gate != nil { + records, err := gate.UnresolvedRestoreDispatches(ctx, t.config.RestoreTargetIdentity, + t.config.RestoreOperationID, t.config.RestoreWindowJobID) + if err != nil { + return fmt.Errorf("恢复准入读不到权威派发台账:%w", err) + } + for _, record := range records { + if record.PlanDigest != t.activePlan.Digest { + return fmt.Errorf("%w: 原 window 存在另一份计划的派发记录(plan=%s index=%s doc=%s)", + libraryrelease.ErrRestoreDispatchHeld, record.PlanDigest, record.Index, record.DocumentID) + } + if _, ok := t.planEffect(record.Index, record.DocumentID); !ok { + return fmt.Errorf("%w: 原 window 存在计划外派发记录(index=%s doc=%s state=%s)", + libraryrelease.ErrRestoreDispatchHeld, record.Index, record.DocumentID, record.State) + } + } + } + for _, c := range t.activePlan.Index { + if len(c.After) != 0 { + continue + } + body, err := t.restoreIndexClaimBody(c) + if err != nil { + return err + } + intent, err := t.loadIndexEffect(c, "restore-mark-intent") + if err != nil { + return err + } + claimed, err := t.loadIndexEffect(c, "restore-claimed") + if err != nil { + return err + } + finalize, err := t.loadIndexEffect(c, "restore-finalize-intent") + if err != nil { + return err + } + // 已完成 clean 的 effect 是终态:恢复内容与证据都在时,重放不是未决。 + done, err := t.loadIndexEffect(c, "restored") + if err != nil { + return err + } + if gate != nil { + binding, bindErr := t.restoreMarkerBinding(ctx, c, body) + if bindErr != nil { + return bindErr + } + status, found, inspErr := gate.InspectRestoreMarker(ctx, binding) + if inspErr != nil { + return fmt.Errorf("恢复准入读不到派发台账:%w", inspErr) + } + if found { + // 绑定冲突是类型化分类:任何状态(含已完成 clean 的终态)都必须拒绝。 + // 它不能与"仅禁止第二次 create"的 dispatching-held 混为一谈——后者在 + // 精确 marker 仍在时是允许确认的。 + if status.BindingConflict { + return heldRestoreMarker(status, "派发台账的不可变绑定与本次计划冲突") + } + if done != nil { + if status.State != libraryrelease.RestoreDispatchMarkerConfirmed { + return heldRestoreMarker(status, "已完成 clean 的 effect 台账却不是 marker_confirmed") + } + // 终态:内容与世代由下面的 done 分支核对。 + } else { + switch status.State { + case libraryrelease.RestoreDispatchPrepared: + if status.Held { + return heldRestoreMarker(status, "派发绑定与不可变计划冲突") + } + if claimed != nil || finalize != nil { + return heldRestoreMarker(status, "prepared 台账却已有 claimed/finalize 证据") + } + observed, obsErr := t.observePlannedIndex(ctx, c) + if obsErr != nil { + return obsErr + } + if indexBytesEqual(observed, body) { + return heldRestoreMarker(status, "prepared 台账却已存在目标标记:协议证据矛盾") + } + continue + case libraryrelease.RestoreDispatchDispatching, libraryrelease.RestoreDispatchMarkerConfirmed: + observed, obsErr := t.observePlannedIndex(ctx, c) + if obsErr != nil { + return obsErr + } + if indexBytesEqual(observed, body) && observed.SeqNo != nil && observed.PrimaryTerm != nil { + continue // 只允许原确认分支继续,不重发 create + } + return heldRestoreMarker(status, "目标上缺少可归属的精确恢复标记") + default: + return heldRestoreMarker(status, "派发台账状态不可识别") + } + } + } + } + if done != nil { + observed, err := t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if done.Receipt == nil || !indexBytesEqual(observed, c.Before) || + !sameIndexGeneration(observed, done.Receipt.SeqNo, done.Receipt.PrimaryTerm) { + return fmt.Errorf("%w: 已标记 restored 的 effect 与目标现状不符", libraryrelease.ErrRestoreDispatchHeld) + } + continue + } + if intent == nil && claimed == nil && finalize == nil { + continue + } + observed, err := t.observePlannedIndex(ctx, c) + if err != nil { + return err + } + if intent != nil && indexBytesEqual(observed, body) { + continue // 旧标记已在目标上:按既有确认/CAS 规则处理,不派发新 create + } + return fmt.Errorf("%w: 既存恢复意图/证据没有新协议派发台账,无法证明未派发", libraryrelease.ErrRestoreDispatchHeld) + } + return nil +} + +// confirmDispatchedMarker 只在"marker 与冻结内容逐位相同且世代齐全"时记录回执。 +// 它不发送任何请求;确认失败即 held,绝不因为"看起来已经写好了"就继续 clean。 +func (t *ProductionLibraryTarget) confirmDispatchedMarker(ctx context.Context, c libraryrelease.IndexWrite, body json.RawMessage, observed indexWriteGuard) error { + if t.config.RestoreDispatch == nil || len(c.After) != 0 { + return nil + } + binding, err := t.restoreMarkerBinding(ctx, c, body) + if err != nil { + return err + } + status, found, err := t.config.RestoreDispatch.InspectRestoreMarker(ctx, binding) + if err != nil { + return err + } + if !found { + return fmt.Errorf("%w: 删除型恢复缺少派发台账,拒绝按外观继续", libraryrelease.ErrRestoreDispatchHeld) + } + if status.BindingConflict { + return heldRestoreMarker(status, "派发台账的不可变绑定与本次计划冲突") + } + if status.Held && status.State == libraryrelease.RestoreDispatchPrepared { + return heldRestoreMarker(status, "派发绑定与不可变计划冲突") + } + switch status.State { + case libraryrelease.RestoreDispatchPrepared: + // 还没派发:由调用方按 prepared 竞争许可。 + return nil + case libraryrelease.RestoreDispatchMarkerConfirmed: + return nil + case libraryrelease.RestoreDispatchDispatching: + if !indexBytesEqual(observed, body) || observed.SeqNo == nil || observed.PrimaryTerm == nil { + return heldRestoreMarker(status, "dispatching 结果未知且目标上没有精确标记") + } + receipt := indexReceipt{Index: c.Index, ID: c.ID, Result: "created", SeqNo: observed.SeqNo, PrimaryTerm: observed.PrimaryTerm} + raw, err := json.Marshal(receipt) + if err != nil { + return err + } + return t.config.RestoreDispatch.ConfirmRestoreMarker(ctx, binding, raw) + default: + return heldRestoreMarker(status, "派发台账状态不可识别") + } +} + +// dispatchRestoreMarkerCreate 是恢复期唯一获得发送许可的入口:preflight 与故障钩子 +// 都在 CAS 之前,Acquire 只在 dispatching 明确提交后返回许可。 +func (t *ProductionLibraryTarget) dispatchRestoreMarkerCreate(ctx context.Context, c libraryrelease.IndexWrite, body json.RawMessage) (indexReceipt, error) { + if t.config.RestoreDispatch == nil { + return indexReceipt{}, errors.New("恢复标记派发协议未接线:拒绝发送") + } + binding, err := t.restoreMarkerBinding(ctx, c, body) + if err != nil { + return indexReceipt{}, err + } + status, found, err := t.config.RestoreDispatch.InspectRestoreMarker(ctx, binding) + if err != nil { + return indexReceipt{}, err + } + if !found || status.State != libraryrelease.RestoreDispatchPrepared || status.Held { + return indexReceipt{}, heldRestoreMarker(status, "没有可竞争的 prepared 许可") + } + // 控制流故障注入必须在 CAS 之前:拒绝时状态仍是 prepared,可安全重试,零转发。 + if err := t.ds01TestRefusal(c); err != nil { + return indexReceipt{}, err + } + if err := t.refuseRestoreWrite(c); err != nil { + return indexReceipt{}, err + } + permit, acquireStatus, err := t.config.RestoreDispatch.AcquireRestoreMarker(ctx, binding) + if err != nil { + return indexReceipt{}, err + } + if permit == nil { + return indexReceipt{}, heldRestoreMarker(acquireStatus, "许可竞争未胜出") + } + if err := t.ds01TestHoldAfterCAS(ctx, c); err != nil { + return indexReceipt{}, err + } + receipt, err := t.sendRestoreMarkerOnce(ctx, c, body, binding, permit) + if err != nil { + return indexReceipt{}, err + } + raw, err := json.Marshal(receipt) + if err != nil { + return indexReceipt{}, err + } + // 回执来自这次唯一发送:必须落进台账才算确认。写失败时 marker 已在目标上, + // 下一进程走"精确 marker+世代"确认分支,不会重发 create。 + if err := t.config.RestoreDispatch.ConfirmRestoreMarker(ctx, binding, raw); err != nil { + return indexReceipt{}, fmt.Errorf("恢复标记已发送但确认未落库:%w", err) + } + return receipt, nil +} + +// sendRestoreMarkerOnce 是唯一的真实网络发送点:许可消费一次、请求不可被传输层重放。 +func (t *ProductionLibraryTarget) sendRestoreMarkerOnce(ctx context.Context, c libraryrelease.IndexWrite, body json.RawMessage, + binding libraryrelease.RestoreMarkerBinding, permit *libraryrelease.RestoreSendPermit) (indexReceipt, error) { + digest, err := binding.Digest() + if err != nil { + return indexReceipt{}, err + } + if err := permit.Consume(binding.Key, digest); err != nil { + return indexReceipt{}, err + } + method, path, payload, err := t.indexMutation(c, body, nil, nil, true) + if err != nil { + return indexReceipt{}, err + } + var receipt indexReceipt + if err := t.search.requestJSONOnce(ctx, method, path, payload, &receipt); err != nil { + return receipt, fmt.Errorf("restore marker outcome unknown: %w", err) + } + if err := validateIndexReceipt(c, len(body) > 0, receipt); err != nil { + return receipt, err + } + return receipt, nil +} + +// verifyRestoreEffectsClosed 是 Restore 收尾前的最后一道检查:以原 window 的权威台账 +// 全集为准(跨 plan),每个记录都必须是 marker_confirmed,且对应的 restored 文件证据 +// 存在。prepared/dispatching、计划外 effect、换 plan 别名、缺 restored 一律拒绝。 +func (t *ProductionLibraryTarget) verifyRestoreEffectsClosed(ctx context.Context) error { + if t.config.RestoreDispatch != nil { + records, err := t.config.RestoreDispatch.UnresolvedRestoreDispatches(ctx, + t.config.RestoreTargetIdentity, t.config.RestoreOperationID, t.config.RestoreWindowJobID) + if err != nil { + return fmt.Errorf("恢复收尾读不到权威派发台账:%w", err) + } + for _, record := range records { + if record.PlanDigest != t.activePlan.Digest { + return fmt.Errorf("%w: 收尾时原 window 仍有另一份计划的派发记录(plan=%s)", + libraryrelease.ErrRestoreDispatchHeld, record.PlanDigest) + } + if record.State != libraryrelease.RestoreDispatchMarkerConfirmed { + return fmt.Errorf("%w: 收尾前派发台账仍有未决 effect(index=%s doc=%s state=%s)", + libraryrelease.ErrRestoreDispatchHeld, record.Index, record.DocumentID, record.State) + } + c, ok := t.planEffect(record.Index, record.DocumentID) + if !ok { + return fmt.Errorf("%w: 收尾时存在计划外派发记录(index=%s doc=%s)", + libraryrelease.ErrRestoreDispatchHeld, record.Index, record.DocumentID) + } + done, err := t.loadIndexEffect(c, "restored") + if err != nil { + return err + } + if done == nil { + return fmt.Errorf("%w: 收尾前仍有未 clean 的 effect %s", libraryrelease.ErrRestoreDispatchHeld, c.ID) + } + // 收尾同样是**使用点**:绑定冲突即使状态看起来是 marker_confirmed 也必须拒绝。 + body, err := t.restoreIndexClaimBody(c) + if err != nil { + return err + } + binding, err := t.restoreMarkerBinding(ctx, c, body) + if err != nil { + return err + } + status, found, err := t.config.RestoreDispatch.InspectRestoreMarker(ctx, binding) + if err != nil { + return fmt.Errorf("恢复收尾读不到派发台账:%w", err) + } + if !found { + return fmt.Errorf("%w: 收尾时 effect %s 的派发台账消失了", libraryrelease.ErrRestoreDispatchHeld, c.ID) + } + if status.BindingConflict { + return heldRestoreMarker(status, "收尾时派发台账的不可变绑定与本次计划冲突") + } + if status.State != libraryrelease.RestoreDispatchMarkerConfirmed { + return fmt.Errorf("%w: 收尾时 effect %s 的派发状态是 %s", libraryrelease.ErrRestoreDispatchHeld, c.ID, status.State) + } + } + } + for _, c := range t.activePlan.Index { + if len(c.After) != 0 { + continue + } + intent, err := t.loadIndexEffect(c, "restore-mark-intent") + if err != nil { + return err + } + if intent == nil { + continue + } + done, err := t.loadIndexEffect(c, "restored") + if err != nil { + return err + } + if done == nil { + return fmt.Errorf("%w: 恢复收尾前仍有未决 effect %s", libraryrelease.ErrRestoreDispatchHeld, c.ID) + } + } + return nil +} + +// ds01TestRefusal 是正式 worker 全链验收的最小测试接缝:只有显式隔离运行 +// (KG_LIBRARY_TEST_ISOLATED=1)且指定了 effect 时才在 CAS 之前拒绝一次;生产默认 +// 全关,且每个进程只触发一次,重启后的 worker 不会重复拒绝。 +// ds01TestHoldAfterCAS 是 N1 的最小测试接缝:CAS 已提交、许可已拿到,但在真实发送 +// 之前挂起,让验收进程能观察到 durable dispatching 后终止执行者。生产默认全关。 +func (t *ProductionLibraryTarget) ds01TestHoldAfterCAS(ctx context.Context, c libraryrelease.IndexWrite) error { + if os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" || t.restoreHoldUsed { + return nil + } + spec := os.Getenv("KG_DS01_TEST_HOLD_AFTER_CAS") + if spec == "" || spec != c.Index+"/"+c.ID { + return nil + } + t.restoreHoldUsed = true + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(90 * time.Second): + return errors.New("injected DS01 hold after CAS expired") + } +} + +func (t *ProductionLibraryTarget) ds01TestRefusal(c libraryrelease.IndexWrite) error { + if os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" || t.restoreRefusalUsed { + return nil + } + spec := os.Getenv("KG_DS01_TEST_REFUSE_MARKER") + if spec == "" || spec != c.Index+"/"+c.ID { + return nil + } + t.restoreRefusalUsed = true + return errors.New("injected DS01 marker refusal before dispatch CAS") +} diff --git a/internal/releaseadapter/v071/library_legacy_index_test.go b/internal/releaseadapter/v071/library_legacy_index_test.go index 70f31c2..aa9b107 100644 --- a/internal/releaseadapter/v071/library_legacy_index_test.go +++ b/internal/releaseadapter/v071/library_legacy_index_test.go @@ -5,18 +5,19 @@ import ( "testing" ) -func TestLibraryCandidateLegacyChunkIndexCoverage(t *testing.T) { +// R3f: status and chunk type are source metadata, not a governance index +// requirement. The exact PG/ES sets are captured as-is; only question +// metadata/index identity remains independently checked. +func TestLibraryCandidateLegacyChunkKindsDoNotGateCapture(t *testing.T) { for _, tc := range []struct { - name, kind string - status int - indexed, valid bool + name, kind string + status int }{ - {"legacy text missing", "text", 0, false, false}, - {"legacy text indexed", "text", 0, true, true}, - {"legacy unknown type missing", "", 0, false, false}, - {"context parent not indexed", "parent_text", 0, false, true}, - {"stored parent not indexed", "parent_text", 1, false, true}, - {"indexed parent missing", "parent_text", 2, false, false}, + {"legacy text missing", "text", 0}, + {"legacy unknown type missing", "", 0}, + {"context parent not indexed", "parent_text", 0}, + {"stored parent not indexed", "parent_text", 1}, + {"indexed parent missing", "parent_text", 2}, } { t.Run(tc.name, func(t *testing.T) { pg, es, _ := libraryCandidateFixture() @@ -25,16 +26,10 @@ func TestLibraryCandidateLegacyChunkIndexCoverage(t *testing.T) { t.Fatal(err) } pg.Tables[1] = newTableSnapshot("chunks", []json.RawMessage{raw}) - if !tc.indexed { - es.Documents = nil - es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents) - } - err = validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es) - if tc.valid && err != nil { - t.Fatalf("valid chunk rejected: %v", err) - } - if !tc.valid && err == nil { - t.Fatal("missing legacy index escaped completeness validation") + es.Documents = nil + es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents) + if err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es); err != nil { + t.Fatalf("source shape without body index must be captured as-is: %v", err) } }) } diff --git a/internal/releaseadapter/v071/library_local_ids.go b/internal/releaseadapter/v071/library_local_ids.go new file mode 100644 index 0000000..ac9cfb7 --- /dev/null +++ b/internal/releaseadapter/v071/library_local_ids.go @@ -0,0 +1,176 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "sort" + "strconv" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// Compile local number requests without changing sequence state. Allocation is +// a separate, explicitly mutating phase after the backup and P0 are durable. +func (t *ProductionLibraryTarget) localIDRequests(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) ([]libraryrelease.LocalIDMapping, error) { + var result []libraryrelease.LocalIDMapping + seen := map[string]bool{} + for _, part := range manifest.Parts { + if part.Kind != "database" && part.Kind != "wiki" { + continue + } + contract, ok := migrationIdentityContracts[part.Name] + if !ok { + if part.Count != 0 { + return nil, fmt.Errorf("unknown table %s", part.Name) + } + continue + } + if contract.LocalColumn == "" { + continue + } + reader, err := archive.OpenPart(part) + if err != nil { + return nil, err + } + var rows []map[string]json.RawMessage + err = json.NewDecoder(reader).Decode(&rows) + reader.Close() + if err != nil { + return nil, err + } + for _, row := range rows { + raw, ok := row[contract.LocalColumn] + if !ok && contract.LocalColumn != "id" { + continue + } // older snapshots lacking the added column remain explicit legacy input + source, err := positiveBigint(raw) + if err != nil { + return nil, fmt.Errorf("%s.%s: %w", part.Name, contract.LocalColumn, err) + } + key := part.Name + "/" + source + if seen[key] { + return nil, fmt.Errorf("duplicate local identity %s", key) + } + seen[key] = true + result = append(result, libraryrelease.LocalIDMapping{Table: part.Name, Column: contract.LocalColumn, Source: source}) + } + } + sort.Slice(result, func(i, j int) bool { + if result[i].Table != result[j].Table { + return result[i].Table < result[j].Table + } + a, _ := strconv.ParseInt(result[i].Source, 10, 64) + b, _ := strconv.ParseInt(result[j].Source, 10, 64) + return a < b + }) + return result, nil +} + +func (t *ProductionLibraryTarget) allocateLocalIDs(ctx context.Context, set *libraryrelease.WriteSet) error { + // Preflight every sequence before consuming even one value. No setval and no + // rewind on failure: an unanchored allocation can leave holes, never aliases. + checked := map[string]bool{} + for _, mapping := range set.LocalIDs { + if checked[mapping.Table] { + continue + } + checked[mapping.Table] = true + contract := migrationIdentityContracts[mapping.Table] + var datatype, def string + err := t.pool.QueryRow(ctx, `SELECT format_type(a.atttypid,a.atttypmod),coalesce(pg_get_expr(d.adbin,d.adrelid),'') FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum WHERE n.nspname='public' AND c.relname=$1 AND a.attname=$2 AND NOT a.attisdropped`, mapping.Table, mapping.Column).Scan(&datatype, &def) + if err != nil || datatype != "bigint" || def != "nextval('"+contract.Sequence+"'::regclass)" { + return fmt.Errorf("local sequence schema mismatch: %s.%s", mapping.Table, mapping.Column) + } + var increment, maximum, cache int64 + var cycle bool + if err := t.pool.QueryRow(ctx, `SELECT seqincrement,seqmax,seqcache,seqcycle FROM pg_sequence WHERE seqrelid=to_regclass($1)`, contract.Sequence).Scan(&increment, &maximum, &cache, &cycle); err != nil { + return err + } + if increment != 1 || cycle || cache != 1 { + return errors.New("unsupported local sequence allocation policy") + } + var last, maxUsed int64 + var called bool + if err := t.pool.QueryRow(ctx, fmt.Sprintf(`SELECT last_value,is_called FROM %s`, contract.Sequence)).Scan(&last, &called); err != nil { + return err + } + if err := t.pool.QueryRow(ctx, fmt.Sprintf(`SELECT coalesce(max(%s),0) FROM %s`, mapping.Column, mapping.Table)).Scan(&maxUsed); err != nil { + return err + } + next := last + if called { + if last >= maximum { + return errors.New("local sequence exhausted") + } + next++ + } + count := int64(0) + for _, m := range set.LocalIDs { + if m.Table == mapping.Table { + count++ + } + } + if next <= maxUsed || count-1 > maximum-next { + return fmt.Errorf("local sequence behind occupied values or exhausted: %s", contract.Sequence) + } + } + raw, err := json.Marshal(set) + if err != nil { + return err + } + sum := sha256.Sum256(raw) + if err := persistImmutableJSON(filepath.Join(t.config.ArchiveRoot, "plans-p0", hex.EncodeToString(sum[:])+".json"), raw); err != nil { + return err + } + for i := range set.LocalIDs { + mapping := &set.LocalIDs[i] + contract := migrationIdentityContracts[mapping.Table] + var allocated int64 + if err := t.pool.QueryRow(ctx, `SELECT nextval($1::regclass)`, contract.Sequence).Scan(&allocated); err != nil { + return err + } + var occupied bool + if err := t.pool.QueryRow(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM %s WHERE %s=$1)`, mapping.Table, mapping.Column), allocated).Scan(&occupied); err != nil { + return err + } + if occupied { + return errors.New("allocated local identity already occupied; maintenance/fence lost") + } + mapping.Target = strconv.FormatInt(allocated, 10) + if contract.Kind == "local-bigint" { + set.Rows = append(set.Rows, libraryrelease.WriteSetRow{Table: mapping.Table, ID: mapping.Target}) + } + } + return nil +} + +func (t *ProductionLibraryTarget) mapLocalID(table string, row map[string]json.RawMessage) (bool, error) { + if t.activePlan == nil || t.activeSnapshot != t.activePlan.TargetSnapshotID || t.preserveChunkSequence { + return false, nil + } + contract := migrationIdentityContracts[table] + if contract.LocalColumn == "" { + return false, nil + } + raw, ok := row[contract.LocalColumn] + if !ok { + return false, nil + } + source, err := positiveBigint(raw) + if err != nil { + return false, err + } + for _, mapping := range t.activePlan.LocalIDs { + if mapping.Table == table && mapping.Column == contract.LocalColumn && mapping.Source == source { + row[contract.LocalColumn] = json.RawMessage(mapping.Target) + return true, nil + } + } + return false, fmt.Errorf("missing persisted local mapping: %s.%s", table, contract.LocalColumn) +} diff --git a/internal/releaseadapter/v071/library_memory_object_contract_test.go b/internal/releaseadapter/v071/library_memory_object_contract_test.go new file mode 100644 index 0000000..e6ef326 --- /dev/null +++ b/internal/releaseadapter/v071/library_memory_object_contract_test.go @@ -0,0 +1,59 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" +) + +// In-memory protocol model only; not evidence of any provider's atomicity. +func (s *memoryObjectStore) ConditionalCapability(context.Context) error { return nil } +func (s *memoryObjectStore) ObserveObject(_ context.Context, provider, path string) (objectObservation, error) { + key := objectKey(provider, path) + body, exists := s.objects[key] + if !exists { + return objectObservation{}, nil + } + sum := sha256.Sum256(body) + o := s.observations[key] + o.Exists = true + o.Bytes = int64(len(body)) + o.SHA256 = hex.EncodeToString(sum[:]) + o.ETag = o.SHA256 + if o.VersionID == "" { + o.VersionID = "seed" + } + return o, nil +} +func (s *memoryObjectStore) CreateObject(ctx context.Context, provider, path string, body io.Reader, size int64, owner string) error { + if s.failPut { + return errObjectWriteRejected + } + key := objectKey(provider, path) + if _, exists := s.objects[key]; exists { + return errObjectWriteRejected + } + if err := s.Put(ctx, provider, path, body, size); err != nil { + return err + } + if s.observations == nil { + s.observations = map[string]objectObservation{} + } + s.observations[key] = objectObservation{Owner: owner, VersionID: fmt.Sprint(len(s.puts))} + return nil +} +func (s *memoryObjectStore) RemoveObject(ctx context.Context, provider, path string, want objectObservation) error { + got, err := s.ObserveObject(ctx, provider, path) + if err != nil { + return err + } + if got != want || !got.Exists { + return errors.New("memory exact version mismatch") + } + delete(s.objects, objectKey(provider, path)) + delete(s.observations, objectKey(provider, path)) + return nil +} diff --git a/internal/releaseadapter/v071/library_natural_keys.go b/internal/releaseadapter/v071/library_natural_keys.go new file mode 100644 index 0000000..72359cb --- /dev/null +++ b/internal/releaseadapter/v071/library_natural_keys.go @@ -0,0 +1,132 @@ +package v071 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + + "github.com/jackc/pgx/v5" + "knowledge-governance/internal/librarysnapshot" +) + +type migrationUniqueKey struct { + Name string + Columns []string + Predicate string + NullsEqual bool + Expression bool +} + +// Preflight all catalog unique keys, including partial indexes. Source-local +// sequence keys are checked separately by the allocator, never compared as UUIDs. +func (t *ProductionLibraryTarget) preflightNaturalKeys(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error { + for _, part := range manifest.Parts { + if (part.Kind != "database" && part.Kind != "wiki") || part.Count == 0 { + continue + } + contract, known := migrationIdentityContracts[part.Name] + if !known { + return errors.New("unknown natural-key contract") + } + reader, err := archive.OpenPart(part) + if err != nil { + return err + } + var source []map[string]json.RawMessage + err = json.NewDecoder(reader).Decode(&source) + reader.Close() + if err != nil { + return err + } + for _, row := range source { + if err := t.retargetRow(part.Name, row); err != nil { + return err + } + } + raw, err := json.Marshal(source) + if err != nil { + return err + } + rows, err := t.pool.Query(ctx, `SELECT ic.relname,ARRAY(SELECT a.attname::text FROM unnest(i.indkey) WITH ORDINALITY k(attnum,ord) JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=k.attnum WHERE k.ord<=i.indnkeyatts ORDER BY k.ord),coalesce(pg_get_expr(i.indpred,i.indrelid),''),i.indnullsnotdistinct,i.indexprs IS NOT NULL FROM pg_index i JOIN pg_class c ON c.oid=i.indrelid JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_class ic ON ic.oid=i.indexrelid WHERE n.nspname='public' AND c.relname=$1 AND i.indisunique ORDER BY ic.relname`, part.Name) + if err != nil { + return err + } + var keys []migrationUniqueKey + for rows.Next() { + var key migrationUniqueKey + if err := rows.Scan(&key.Name, &key.Columns, &key.Predicate, &key.NullsEqual, &key.Expression); err != nil { + rows.Close() + return err + } + keys = append(keys, key) + } + rows.Close() + if err := rows.Err(); err != nil { + return err + } + table := pgx.Identifier{"public", part.Name}.Sanitize() + recordset := "jsonb_populate_recordset(NULL::" + table + ",$1::jsonb)" + for _, key := range keys { + if key.Expression || len(key.Columns) == 0 { + return fmt.Errorf("unreviewed unique expression: %s", key.Name) + } + skip := false + for _, column := range key.Columns { + if column == contract.LocalColumn { + skip = true + } + } + if skip { + continue + } + predicate := "true" + if key.Predicate != "" { + predicate = key.Predicate + } + cols, nonnull, join := []string{}, []string{}, []string{} + for _, column := range key.Columns { + q := pgx.Identifier{column}.Sanitize() + cols = append(cols, q) + nonnull = append(nonnull, q+" IS NOT NULL") + op := "=" + if key.NullsEqual { + op = "IS NOT DISTINCT FROM" + } + join = append(join, "s."+q+" "+op+" t."+q) + } + sourceFilter := predicate + if !key.NullsEqual { + sourceFilter += " AND " + strings.Join(nonnull, " AND ") + } + var conflict bool + query := "SELECT EXISTS(SELECT 1 FROM " + recordset + " s WHERE " + sourceFilter + " GROUP BY " + strings.Join(cols, ",") + " HAVING count(*)>1)" + if err := t.pool.QueryRow(ctx, query, raw).Scan(&conflict); err != nil { + return fmt.Errorf("source unique preflight %s: %w", key.Name, err) + } + if conflict { + return fmt.Errorf("source duplicates natural key %s", key.Name) + } + targetFilter := predicate + args := []any{raw} + if part.Name != "resources" { + scope := strings.ReplaceAll(strings.ReplaceAll(t.scopeWhere(part.Name), "$2", "$3"), "$1", "$2") + targetFilter += " AND NOT (" + scope + ")" + args = append(args, t.scope.TenantID, t.scope.KnowledgeBaseID) + } + query = "SELECT EXISTS(SELECT 1 FROM (SELECT * FROM " + recordset + " WHERE " + sourceFilter + ") s JOIN (SELECT * FROM " + table + " WHERE " + targetFilter + ") t ON " + strings.Join(join, " AND ") + ")" + // Equal resource ID is handled by immutable row/object reuse evidence. + if part.Name == "resources" { + query = strings.TrimSuffix(query, ")") + " WHERE s.id IS DISTINCT FROM t.id)" + } + if err := t.pool.QueryRow(ctx, query, args...).Scan(&conflict); err != nil { + return fmt.Errorf("target unique preflight %s: %w", key.Name, err) + } + if conflict { + return fmt.Errorf("target natural key conflict outside replace scope: %s", key.Name) + } + } + } + return nil +} diff --git a/internal/releaseadapter/v071/library_natural_keys_test.go b/internal/releaseadapter/v071/library_natural_keys_test.go new file mode 100644 index 0000000..8d66f38 --- /dev/null +++ b/internal/releaseadapter/v071/library_natural_keys_test.go @@ -0,0 +1,31 @@ +package v071 + +import ( + "knowledge-governance/internal/libraryrelease" + "testing" +) + +func TestContractNaturalResourceConflictPreflightIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, err := fx.pool.Exec(fx.ctx, `CREATE UNIQUE INDEX resources_handle_contract ON resources(handle)`); err != nil { + t.Fatal(err) + } + before := universeDump(t, fx.pool) + puts := fx.objects.puts.Load() + snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { + parts["resources"][0]["handle"] = wsHandleOther + parts["chunks"][0]["content"] = "resource://" + wsHandleOther + }) + target := fx.target(t) + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if result.State != "failed" || result.FailedAt != "" { + t.Fatalf("natural key collision reached writes: %+v", result) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("conflict changed PG: %s", diff) + } + if fx.objects.puts.Load() != puts { + t.Fatal("conflict wrote objects") + } +} diff --git a/internal/releaseadapter/v071/library_object_effects.go b/internal/releaseadapter/v071/library_object_effects.go new file mode 100644 index 0000000..2c3e121 --- /dev/null +++ b/internal/releaseadapter/v071/library_object_effects.go @@ -0,0 +1,254 @@ +package v071 + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +func (t *ProductionLibraryTarget) planObjects(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest, set *libraryrelease.WriteSet) error { + objects := map[string]librarysnapshot.Part{} + for _, p := range manifest.Parts { + if p.Kind == "resource" { + if _, exists := objects[p.Name]; exists { + return errors.New("duplicate object resource identity") + } + objects[p.Name] = p + } + } + if len(objects) == 0 { + return nil + } + store, ok := t.config.Objects.(conditionalObjectStore) + if !ok { + return errors.New("target lacks conditional object effects") + } + if err := store.ConditionalCapability(ctx); err != nil { + return err + } + seen := map[string]bool{} + for _, part := range manifest.Parts { + if part.Kind != "database" || part.Name != "resources" { + continue + } + reader, err := archive.OpenPart(part) + if err != nil { + return err + } + var rows []map[string]json.RawMessage + err = json.NewDecoder(reader).Decode(&rows) + reader.Close() + if err != nil { + return err + } + for _, row := range rows { + var id string + if err := json.Unmarshal(row["id"], &id); err != nil { + return err + } + blob, exists := objects[id] + if !exists { + return errors.New("resource has no bound object blob") + } + if err := t.retargetRow("resources", row); err != nil { + return err + } + obj := libraryrelease.ObjectWrite{ResourceID: id, SHA256: blob.SHA256, Bytes: blob.Bytes} + if json.Unmarshal(row["provider"], &obj.Provider) != nil || json.Unmarshal(row["physical_path"], &obj.Locator) != nil { + return errors.New("resource locator missing") + } + rest := strings.TrimPrefix(obj.Locator, "storage://") + parts := strings.SplitN(rest, "/", 2) + if rest == obj.Locator || len(parts) != 2 { + return errors.New("object needs explicit backend/bucket/key") + } + obj.BackendID = parts[0] + physical := strings.TrimPrefix(parts[1], obj.Provider+"://") + location := strings.SplitN(physical, "/", 2) + if physical == parts[1] || len(location) != 2 || location[0] == "" || location[1] == "" { + return errors.New("invalid physical object identity") + } + obj.Bucket, obj.Key = location[0], location[1] + // Backend aliases cannot make a shared physical key look independent. + key := obj.Provider + "/" + obj.Bucket + "/" + obj.Key + if seen[key] { + return errors.New("duplicate physical object destination") + } + seen[key] = true + token := sha256.Sum256([]byte(set.JobID + "\x00" + set.Target + "\x00" + set.BackupSnapshotID + "\x00" + set.TargetSnapshotID + "\x00" + key)) + obj.OwnerToken = hex.EncodeToString(token[:]) + observation, err := store.ObserveObject(ctx, obj.Provider, obj.Locator) + if err != nil { + return err + } + obj.Existing, obj.BeforeETag = observation.Exists, observation.ETag + obj.BeforeVersionID = observation.VersionID + if observation.Exists && (observation.SHA256 != obj.SHA256 || observation.Bytes != obj.Bytes) { + return errors.New("different existing object cannot be recoverably overwritten") + } + set.Objects = append(set.Objects, obj) + delete(objects, id) + } + } + if len(objects) != 0 { + return errors.New("object blob lacks resource identity") + } + return nil +} + +func (t *ProductionLibraryTarget) objectEffectPath(obj libraryrelease.ObjectWrite, phase string) string { + sum := sha256.Sum256([]byte(obj.Provider + "\x00" + obj.Bucket + "\x00" + obj.Key)) + return filepath.Join(t.config.ArchiveRoot, "effects", t.activePlan.Digest, "objects", hex.EncodeToString(sum[:]), phase+".json") +} + +func effectExists(path string) (bool, error) { + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, err + } + if !info.Mode().IsRegular() { + return false, errors.New("effect evidence is not a regular file") + } + return true, nil +} + +func (t *ProductionLibraryTarget) recordObjectEffect(obj libraryrelease.ObjectWrite, phase string, observation objectObservation) error { + raw, err := json.Marshal(struct { + Plan string `json:"plan"` + Object libraryrelease.ObjectWrite `json:"object"` + Observation objectObservation `json:"observation"` + }{t.activePlan.Digest, obj, observation}) + if err != nil { + return err + } + return persistImmutableJSON(t.objectEffectPath(obj, phase), raw) +} + +func matchesObject(obj libraryrelease.ObjectWrite, observed objectObservation, owned bool) bool { + return observed.Exists && observed.Bytes == obj.Bytes && observed.SHA256 == obj.SHA256 && (!owned || (observed.Owner == obj.OwnerToken && observed.VersionID != "" && observed.VersionID != "null")) +} + +func (t *ProductionLibraryTarget) applyPlannedObject(ctx context.Context, obj libraryrelease.ObjectWrite, body []byte) error { + store, ok := t.config.Objects.(conditionalObjectStore) + if !ok { + return errors.New("object effects capability missing") + } + if obj.Existing { + observed, err := store.ObserveObject(ctx, obj.Provider, obj.Locator) + if err != nil { + return err + } + if !matchesObject(obj, observed, false) || observed.ETag != obj.BeforeETag || observed.VersionID != obj.BeforeVersionID { + return errors.New("read-only object changed since plan") + } + return nil + } + intended, err := effectExists(t.objectEffectPath(obj, "create-intent")) + if err != nil { + return err + } + if !intended { + if err := t.recordObjectEffect(obj, "create-intent", objectObservation{}); err != nil { + return err + } + err = store.CreateObject(ctx, obj.Provider, obj.Locator, bytes.NewReader(body), obj.Bytes, obj.OwnerToken) + if errors.Is(err, errObjectWriteRejected) { + if e := t.recordObjectEffect(obj, "create-rejected", objectObservation{}); e != nil { + return e + } + return err + } + // Even 2xx is not a receipt: observe the exact physical target independently. + } + observed, observeErr := store.ObserveObject(ctx, obj.Provider, obj.Locator) + if observeErr != nil { + return observeErr + } + if !matchesObject(obj, observed, true) { + return errors.New("object create unknown or conflicting; do not replay/delete without ownership proof") + } + return t.recordObjectEffect(obj, "created", observed) +} + +func (t *ProductionLibraryTarget) restoreCreatedObjects(ctx context.Context) error { + if t.activePlan == nil { + return errors.New("object restoration requires adopted plan") + } + if len(t.activePlan.Objects) == 0 { + return nil + } + store, ok := t.config.Objects.(conditionalObjectStore) + if !ok { + return errors.New("object restoration capability missing") + } + for _, obj := range t.activePlan.Objects { + if obj.Existing { + continue + } + intent, err := effectExists(t.objectEffectPath(obj, "create-intent")) + if err != nil { + return err + } + if !intent { + continue + } + rejected, err := effectExists(t.objectEffectPath(obj, "create-rejected")) + if err != nil { + return err + } + if rejected { + continue + } + observed, err := store.ObserveObject(ctx, obj.Provider, obj.Locator) + if err != nil { + return err + } + created, err := effectExists(t.objectEffectPath(obj, "created")) + if err != nil { + return err + } + if !observed.Exists { + if !created { + return errors.New("unresolved create intent: absence is not proof no delayed write remains") + } + if err := t.recordObjectEffect(obj, "removed", objectObservation{}); err != nil { + return err + } + continue + } + if !matchesObject(obj, observed, true) { + return errors.New("created object now differs or has another owner; cleanup refused") + } + if err := t.recordObjectEffect(obj, "created", observed); err != nil { + return err + } + if err := t.recordObjectEffect(obj, "delete-intent", observed); err != nil { + return err + } + deleteErr := store.RemoveObject(ctx, obj.Provider, obj.Locator, observed) + after, err := store.ObserveObject(ctx, obj.Provider, obj.Locator) + if err != nil { + return err + } + if after.Exists { + return fmt.Errorf("conditional object cleanup not confirmed: %v", deleteErr) + } + if err := t.recordObjectEffect(obj, "removed", objectObservation{}); err != nil { + return err + } + } + return nil +} diff --git a/internal/releaseadapter/v071/library_object_effects_test.go b/internal/releaseadapter/v071/library_object_effects_test.go new file mode 100644 index 0000000..e6d9cd7 --- /dev/null +++ b/internal/releaseadapter/v071/library_object_effects_test.go @@ -0,0 +1,61 @@ +package v071 + +import ( + "context" + "errors" + "io" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +type contractFailWikiTarget struct{ *ProductionLibraryTarget } + +func (s *flakyStore) ConditionalCapability(ctx context.Context) error { + return s.s3.ConditionalCapability(ctx) +} +func (s *flakyStore) ObserveObject(ctx context.Context, provider, path string) (objectObservation, error) { + return s.s3.ObserveObject(ctx, provider, path) +} +func (s *flakyStore) RemoveObject(ctx context.Context, provider, path string, expected objectObservation) error { + return s.s3.RemoveObject(ctx, provider, path, expected) +} +func (s *flakyStore) CreateObject(ctx context.Context, provider, path string, reader io.Reader, size int64, owner string) error { + if s.failPut.Load() { + return errObjectWriteRejected + } + s.puts.Add(1) + return s.s3.CreateObject(ctx, provider, path, reader, size, owner) +} + +func (t contractFailWikiTarget) Apply(ctx context.Context, stage libraryrelease.Stage, snapshot string) error { + if stage == libraryrelease.StageWiki { + return errors.New("injected Wiki failure after object upload") + } + return t.ProductionLibraryTarget.Apply(ctx, stage, snapshot) +} + +func TestContractObjectCreatedThenFailureMustDisappearIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, fx.backups(t, target), nil) + if outcome.State != "rolled_back" { + t.Fatalf("rollback: %+v", outcome) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatal(diff) + } + path := wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-src") + if _, _, err := fx.objects.s3.Stat(fx.ctx, "minio", path); err == nil { + t.Fatal("PG rollback passed but exact created object remains") + } + for _, id := range []string{"res-target", "res-other", "res-shared", "res-orphan"} { + path := wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, id) + if n, _, err := fx.objects.s3.Stat(fx.ctx, "minio", path); err != nil || n != 8 { + t.Fatalf("pre-existing object changed: %s", id) + } + } +} diff --git a/internal/releaseadapter/v071/library_object_plan_binding.go b/internal/releaseadapter/v071/library_object_plan_binding.go new file mode 100644 index 0000000..99bae81 --- /dev/null +++ b/internal/releaseadapter/v071/library_object_plan_binding.go @@ -0,0 +1,49 @@ +package v071 + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +func validateObjectPlanBinding(set libraryrelease.WriteSet, source librarysnapshot.Manifest) error { + blobs := map[string]librarysnapshot.Part{} + for _, part := range source.Parts { + if part.Kind == "resource" { + if _, exists := blobs[part.Name]; exists { + return errors.New("duplicate source object blob") + } + blobs[part.Name] = part + } + } + if len(blobs) != len(set.Objects) { + return errors.New("object plan coverage differs from source") + } + seen := map[string]bool{} + for _, obj := range set.Objects { + part, ok := blobs[obj.ResourceID] + if !ok || obj.Bytes != part.Bytes || obj.SHA256 != part.SHA256 { + return errors.New("object plan bytes differ from bound source blob") + } + delete(blobs, obj.ResourceID) + if obj.Provider == "" || obj.BackendID == "" || obj.Bucket == "" || obj.Key == "" || obj.Locator != "storage://"+obj.BackendID+"/"+obj.Provider+"://"+obj.Bucket+"/"+obj.Key { + return errors.New("object plan physical identity incomplete") + } + key := obj.Provider + "/" + obj.Bucket + "/" + obj.Key + if seen[key] { + return errors.New("duplicate physical object in plan") + } + seen[key] = true + token := sha256.Sum256([]byte(set.JobID + "\x00" + set.Target + "\x00" + set.BackupSnapshotID + "\x00" + set.TargetSnapshotID + "\x00" + key)) + if obj.OwnerToken != hex.EncodeToString(token[:]) { + return errors.New("object ownership token not bound to job/target/backup/snapshot") + } + if obj.Existing && obj.BeforeETag == "" { + return errors.New("existing object lacks immutable before observation") + } + } + return nil +} diff --git a/internal/releaseadapter/v071/library_object_reconcile_test.go b/internal/releaseadapter/v071/library_object_reconcile_test.go new file mode 100644 index 0000000..cf846da --- /dev/null +++ b/internal/releaseadapter/v071/library_object_reconcile_test.go @@ -0,0 +1,130 @@ +package v071 + +import ( + "bytes" + "context" + "errors" + "io" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +func TestContractObjectConditionalPrimitivesIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + path := wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-orphan") + before, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", path) + if err != nil { + t.Fatal(err) + } + if err := fx.objects.s3.CreateObject(fx.ctx, "minio", path, bytes.NewReader([]byte("evil")), 4, strings.Repeat("a", 64)); err == nil { + t.Fatal("conditional create overwrote an existing object") + } + wrong := before + wrong.ETag = `"wrong-etag"` + if err := fx.objects.s3.RemoveObject(fx.ctx, "minio", path, wrong); err == nil { + t.Fatal("conditional delete accepted wrong ETag") + } + after, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", path) + if err != nil || before != after { + t.Fatalf("conditional primitives changed existing object: %v", err) + } + unsupported := *fx.objects.s3 + unsupported.provider = "oss" + if err := unsupported.ConditionalCapability(fx.ctx); err == nil { + t.Fatal("untested provider declared conditional compatibility") + } +} + +type contractAmbiguousStore struct { + *flakyStore + beforeSend bool + rejectDelete bool + calls int +} + +func (s *contractAmbiguousStore) CreateObject(ctx context.Context, provider, path string, body io.Reader, n int64, owner string) error { + s.calls++ + if !s.beforeSend { + if err := s.flakyStore.CreateObject(ctx, provider, path, body, n, owner); err != nil { + return err + } + } + return errors.New("injected response loss") +} +func (s *contractAmbiguousStore) RemoveObject(ctx context.Context, provider, path string, expected objectObservation) error { + if s.rejectDelete { + return errors.New("injected delete transport failure") + } + return s.flakyStore.RemoveObject(ctx, provider, path, expected) +} + +func TestContractObjectUnknownReconciliationIsolated(t *testing.T) { + for _, beforeSend := range []bool{false, true} { + name := "applied-response-lost" + if beforeSend { + name = "absent-unknown-held" + } + t.Run(name, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + ambiguous := &contractAmbiguousStore{flakyStore: fx.objects, beforeSend: beforeSend} + target.config.Objects = ambiguous + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + expected := "succeeded" + if beforeSend { + expected = "rollback_failed" + } + if outcome.State != expected || ambiguous.calls != 1 { + t.Fatalf("unknown outcome incorrectly handled: %+v calls=%d", outcome, ambiguous.calls) + } + next := fx.target(t) + next.config.Objects = ambiguous + if err := next.AdoptWriteSet(*outcome.Backup.WriteSet); err != nil { + t.Fatal(err) + } + if beforeSend { + if err := next.Restore(fx.ctx, outcome.Backup); err == nil { + t.Fatal("absent ambiguous write accepted as restored") + } + } else { + if err := next.Apply(fx.ctx, libraryrelease.StageResources, snapshot); err != nil { + t.Fatal(err) + } + if err := next.Restore(fx.ctx, outcome.Backup); err != nil { + t.Fatal(err) + } + } + if ambiguous.calls != 1 { + t.Fatal("ambiguous create was blindly retried after restart") + } + }) + } +} + +func TestContractObjectCleanupFailureReplayIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + target.config.Objects = &contractAmbiguousStore{flakyStore: fx.objects, rejectDelete: true} + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, fx.backups(t, target), nil) + if result.State != "rollback_failed" { + t.Fatalf("failed cleanup declared restored: %+v", result) + } + next := fx.target(t) + if err := next.Restore(fx.ctx, result.Backup); err != nil { + t.Fatal(err) + } + if err := next.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: result.Backup.SnapshotID}); err != nil { + t.Fatal(err) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatal(diff) + } +} diff --git a/internal/releaseadapter/v071/library_object_store.go b/internal/releaseadapter/v071/library_object_store.go new file mode 100644 index 0000000..9d9d7ca --- /dev/null +++ b/internal/releaseadapter/v071/library_object_store.go @@ -0,0 +1,133 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +type objectObservation struct { + VersionID string `json:"version_id,omitempty"` + Exists bool `json:"exists"` + ETag string `json:"etag,omitempty"` + SHA256 string `json:"sha256,omitempty"` + Bytes int64 `json:"bytes"` + Owner string `json:"owner,omitempty"` +} + +// No fallback to blind Put/Delete is allowed when conditional effects are absent. +type conditionalObjectStore interface { + ConditionalCapability(context.Context) error + ObserveObject(context.Context, string, string) (objectObservation, error) + CreateObject(context.Context, string, string, io.Reader, int64, string) error + RemoveObject(context.Context, string, string, objectObservation) error +} + +var errObjectWriteRejected = errors.New("object write definitively rejected before send") + +func (s *S3ObjectStore) ConditionalCapability(ctx context.Context) error { + if s.provider != "minio" && s.provider != "s3" { + return errors.New("object provider has no verified conditional create/version-delete adapter") + } + status, err := s.client.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(s.bucket)}) + if err != nil || string(status.Status) != "Enabled" { + return errors.New("object effects require verified bucket versioning; never enable a business bucket implicitly") + } + return nil +} + +// Bind the supplied logical locator to the configured physical bucket. Legacy +// Open/Put intentionally accept bare keys; the new contract does not infer them. +func (s *S3ObjectStore) conditionalKey(provider, locator string) (string, error) { + if provider != s.provider || !validObjectKey(locator) { + return "", errors.New("conditional object provider/locator mismatch") + } + rest := strings.TrimPrefix(locator, "storage://") + parts := strings.SplitN(rest, "/", 2) + if rest == locator || len(parts) != 2 || parts[0] == "" { + return "", errors.New("conditional object requires explicit backend") + } + expected := provider + "://" + s.bucket + "/" + if !strings.HasPrefix(parts[1], expected) { + return "", errors.New("conditional object bucket/provider mismatch") + } + key := strings.TrimPrefix(parts[1], expected) + if key == "" { + return "", errors.New("empty conditional object key") + } + return key, nil +} + +func (s *S3ObjectStore) ObserveObject(ctx context.Context, provider, locator string) (objectObservation, error) { + key, err := s.conditionalKey(provider, locator) + if err != nil { + return objectObservation{}, err + } + obj, err := s.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key)}) + if err != nil { + var response *smithyhttp.ResponseError + if errors.As(err, &response) && response.HTTPStatusCode() == 404 { + return objectObservation{}, nil + } + return objectObservation{}, errors.New("object observation unavailable") + } + defer obj.Body.Close() + if obj.ContentLength == nil || *obj.ContentLength < 0 || *obj.ContentLength > s.maxObjectBytes || obj.ETag == nil || *obj.ETag == "" { + return objectObservation{}, errors.New("incomplete object observation") + } + hash := sha256.New() + size, err := io.Copy(hash, io.LimitReader(obj.Body, s.maxObjectBytes+1)) + if err != nil || size != *obj.ContentLength { + return objectObservation{}, errors.New("object observation body incomplete") + } + return objectObservation{VersionID: aws.ToString(obj.VersionId), Exists: true, ETag: *obj.ETag, SHA256: hex.EncodeToString(hash.Sum(nil)), Bytes: size, Owner: obj.Metadata["kg-release-owner"]}, nil +} + +func (s *S3ObjectStore) CreateObject(ctx context.Context, provider, locator string, body io.Reader, size int64, owner string) error { + if err := s.ConditionalCapability(ctx); err != nil { + return err + } + key, err := s.conditionalKey(provider, locator) + if err != nil { + return err + } + if size < 0 || size > s.maxObjectBytes || len(owner) != 64 { + return errObjectWriteRejected + } + // A durable intent represents one network attempt. Automatic retries could + // remain in flight after compensation, so ambiguity is reconciled by reads. + _, err = s.client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key), Body: body, ContentLength: aws.Int64(size), IfNoneMatch: aws.String("*"), Metadata: map[string]string{"kg-release-owner": owner}}, func(o *s3.Options) { o.RetryMaxAttempts = 1 }) + if err != nil { + return errors.New("conditional object create outcome unknown") + } + return nil +} + +func (s *S3ObjectStore) RemoveObject(ctx context.Context, provider, locator string, expected objectObservation) error { + if err := s.ConditionalCapability(ctx); err != nil { + return err + } + key, err := s.conditionalKey(provider, locator) + if err != nil { + return err + } + if expected.ETag == "" || expected.VersionID == "" || expected.VersionID == "null" { + return errors.New("deletion requires an immutable object version") + } + before, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key), VersionId: aws.String(expected.VersionID)}) + if err != nil || aws.ToString(before.ETag) != expected.ETag || before.Metadata["kg-release-owner"] != expected.Owner { + return errors.New("exact object version no longer matches receipt") + } + _, err = s.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key), VersionId: aws.String(expected.VersionID)}, func(o *s3.Options) { o.RetryMaxAttempts = 1 }) + if err != nil { + return errors.New("conditional object delete outcome unknown") + } + return nil +} diff --git a/internal/releaseadapter/v071/library_object_version_fixture_test.go b/internal/releaseadapter/v071/library_object_version_fixture_test.go new file mode 100644 index 0000000..800a1ae --- /dev/null +++ b/internal/releaseadapter/v071/library_object_version_fixture_test.go @@ -0,0 +1,23 @@ +package v071 + +import ( + "context" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" + "strings" + "testing" +) + +func enableIsolatedObjectVersions(t *testing.T, ctx context.Context, store *S3ObjectStore) { + t.Helper() + if !strings.HasPrefix(store.bucket, "kg-library-test-") { + t.Fatal("versioning setup restricted to disposable fixture bucket") + } + if _, err := store.client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: aws.String(store.bucket), VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled}}); err != nil { + t.Fatal(err) + } + if err := store.ConditionalCapability(ctx); err != nil { + t.Fatal(err) + } +} diff --git a/internal/releaseadapter/v071/library_plan_binding.go b/internal/releaseadapter/v071/library_plan_binding.go new file mode 100644 index 0000000..5788f0c --- /dev/null +++ b/internal/releaseadapter/v071/library_plan_binding.go @@ -0,0 +1,72 @@ +package v071 + +import ( + "errors" + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// Consumption verifies the immutable source, not the half-written target. A +// correctly hashed sidecar alone does not prove complete mapping coverage. +func (t *ProductionLibraryTarget) validatePlanBindings(set libraryrelease.WriteSet) error { + if set.Version != libraryrelease.MigrationWriteSetVersion || set.ContractVersion != migrationIdentityContractVersion || len(set.SchemaDigest) != 64 { + return errors.New("legacy/incomplete plan is diagnostic-only; execution evidence missing") + } + archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024) + if err != nil { + return err + } + defer archive.Close() + source, err := archive.Load(set.TargetSnapshotID) + if err != nil { + return err + } + if set.ContractVersion != 0 && (source.TenantID != set.SourceTenantID || source.KnowledgeBaseID != set.SourceKnowledgeBaseID) { + return errors.New("plan source identity differs from bound manifest") + } + backup, err := archive.Load(set.BackupSnapshotID) + if err != nil { + return err + } + if backup.TenantID != set.TenantID || backup.KnowledgeBaseID != set.KnowledgeBaseID { + return errors.New("plan before-image identity differs from target") + } + if err := validateObjectPlanBinding(set, source); err != nil { + return err + } + if err := t.validateIndexPlanBinding(archive, source, backup, set); err != nil { + return err + } + requests, err := t.localIDRequests(archive, source) + if err != nil { + return err + } + if len(requests) != len(set.LocalIDs) { + return errors.New("plan local mapping coverage differs from source") + } + expected := map[string]bool{} + for _, r := range requests { + expected[r.Table+"/"+r.Column+"/"+r.Source] = true + } + wikiRows := map[string]bool{} + for _, row := range set.Rows { + if row.Table == "wiki_log_entries" { + wikiRows[row.ID] = !row.Existing + } + } + for _, m := range set.LocalIDs { + if !expected[m.Table+"/"+m.Column+"/"+m.Source] { + return errors.New("plan includes unknown local mapping") + } + if m.Table == "wiki_log_entries" { + if !wikiRows[m.Target] { + return errors.New("plan omits allocated Wiki write identity") + } + delete(wikiRows, m.Target) + } + } + if len(wikiRows) > 0 { + return errors.New("plan includes unmapped Wiki write identity") + } + return nil +} diff --git a/internal/releaseadapter/v071/library_production_target.go b/internal/releaseadapter/v071/library_production_target.go index 6a52d58..ae079a7 100644 --- a/internal/releaseadapter/v071/library_production_target.go +++ b/internal/releaseadapter/v071/library_production_target.go @@ -17,8 +17,11 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" + "knowledge-governance/internal/libraryprofile" "knowledge-governance/internal/libraryrelease" "knowledge-governance/internal/librarysnapshot" + "knowledge-governance/internal/objectgateway" + "knowledge-governance/internal/testbarrier" ) // 生产整库目标:真实读、真实写、真实校验、真实恢复。 @@ -56,6 +59,20 @@ type ProductionLibraryConfig struct { MaxDocuments int HTTPClient *http.Client Now func() time.Time + // 以下字段只用于 DS01 恢复标记派发协议:RestoreDispatch 为 nil 时该能力整体 + // fail closed(既不对旧证据放行,也不产生新证据)。身份来自本次真实 attempt + // 与原作业/计划绑定,不能由调用方临时编造。 + RestoreDispatch libraryrelease.RestoreMarkerGate + RestoreTargetIdentity string + RestoreScope string + RestoreInstance string + RestoreOperationID string + RestoreWindowJobID string + RestoreAttemptOwner string + RestoreAttemptEpoch int64 + // 恢复分发身份:只在恢复 worker 里非空;普通自动回滚为空。 + RestoreRecoveryJobID string + RestoreRecoveryOperationID string } func (config ProductionLibraryConfig) validate(scope ProductionScope) error { @@ -69,13 +86,22 @@ func (config ProductionLibraryConfig) validate(scope ProductionScope) error { return nil } -// 依赖顺序:插入按正序,删除按倒序。 -// 真实 Schema 有外键(resource_bindings.resource_id → resources.id), -// 所以父表 resources 必须排在子表 resource_bindings 之前。 -var productionLibraryTables = []string{ - "knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", - "resources", "resource_bindings", "wiki_folders", "wiki_pages", - "wiki_page_issues", "wiki_log_entries", +// productionLibraryTables 是 0.7.1 的知识域表集合(依赖顺序:插入按正序,删除按 +// 倒序;真实 Schema 有外键 resource_bindings.resource_id → resources.id,父表 +// resources 必须排在子表 resource_bindings 之前)。 +// +// 它**不是**本包整库读写的表清单来源:真实路径一律用 ResolveSchemaProfile 解析出的 +// Tables——0.9.0 没有 wiki_log_entries,任何一条固定清单的查询都会在真库上失败,而 +// "表不存在就跳过"又会让 0.7.1 少一张必需表也悄悄通过。这里只留给明确 74-only 的 +// 入口(编目、残留复核、0.7.1 夹具),定义直接取自 profile 声明,避免两份清单走偏。 +var productionLibraryTables = legacyKnowledgeTables() + +func legacyKnowledgeTables() []string { + profile, err := libraryprofile.For(libraryprofile.LegacyVersion) + if err != nil { + panic(err) + } + return append([]string(nil), profile.RequiredTables...) } type ProductionLibraryTarget struct { @@ -84,6 +110,11 @@ type ProductionLibraryTarget struct { scope ProductionScope search *SearchExporter now func() time.Time + // schema / tables 是目标库解析出的版本声明与"实际存在的知识域表"。写入、校验、 + // 清理、编目全部按它取数:0.9.0 缺 wiki_log_entries 时不得查询/删除该表, + // 而 0.7.1 少一张必需表必须失败,不能靠"表不存在就跳过"。 + schema SchemaProfile + tables []string // storageBackend / storageProvider 是本次写入使用的目标存储后端与提供方 // (写入与校验共用,缺一不可:只换桶不换提供方,目标取文件仍会走来源实例的路)。 storageBackend string @@ -94,6 +125,43 @@ type ProductionLibraryTarget struct { snapshotKB string // targetEmbeddingModel 是目标知识库绑定的 embedding 模型 id(文档行要换成它)。 targetEmbeddingModel string + // reusedResources 是"写前已存在、且已证明可复用"的资源身份:写入阶段跳过它们, + // 既不重写行也不重传对象。PlanWriteSet 与 Apply 在同一个作业里串行执行。 + reusedResources map[string]bool + // 回滚必须重放目标原始序列;普通发布由目标数据库分配本地序列。 + preserveChunkSequence bool + activePlan *libraryrelease.WriteSet + activeSnapshot string + // drillRestore 表示 activePlan 是受限演练恢复计划:索引按写前镜像重建, + // 对象只做只读字节核对(计划本身零对象写项)。发布恢复永不为 true。 + drillRestore bool + // restoreScope / restoreSourceSnapshot / restoreBackupSnapshot 在 Restore 进入时 + // 从**原持久锚点**冻结:scope 来自真实装配,来源快照与写前镜像来自本次 WriteSet + // 与原 backup 引用。它们不能由调用方在恢复中途改写,也不允许同一个快照既当 + // 来源又当 before-image。 + restoreScope string + restoreSourceSnapshot string + restoreBackupSnapshot string + // restoreFingerprint / restoreIndexUUID 是本次恢复冻结的实际目标身份。派发绑定 + // 每次重建时都实时重读并比较:同名重建的目标/索引不可能复用旧证明。 + restoreFingerprint string + restoreIndexUUID string + // targetIDs / mappingActive 是本作业的目标隔离映射;只对目标快照生效。 + targetIDs *targetIDMapper + mappingActive bool + // targetIDMode 来自持久计划(或本次新建计划)。只有它等于 scoped 契约时 + // 才允许映射:旧计划/写前镜像的 ID 已经是目标身份,重映射会写到别处。 + targetIDMode string + // restoreIntentFault 是一次性文件写失败注入点(生产恒为 nil):在 prepared 已提交、 + // mark-intent 尚未落盘处返回错误,用来复现"可补同内容"的窄故障区段。 + restoreIntentFault func(libraryrelease.IndexWrite) error + // restoreRefusalUsed / restoreHoldUsed 是测试专用接缝的一次性标记(生产恒为 false)。 + restoreRefusalUsed bool + restoreHoldUsed bool + // restoreMarkerFault 是一次性控制流故障注入点(生产恒为 nil):它在恢复标记的 + // 持久意图落盘之后、网络派发之前返回错误,用来区分"边界上确定没写进去"与 + // "写入结果未知"——前者重试时只凭世代证据重做,后者仍按 B19 永久 held。 + restoreMarkerFault func(libraryrelease.IndexWrite) error } // resolveStorageBackend 在目标库里找本次写入的存储后端。找不到就报错:宁可不写, @@ -162,7 +230,15 @@ func NewProductionLibraryTarget(ctx context.Context, config ProductionLibraryCon if now == nil { now = time.Now } - return &ProductionLibraryTarget{pool: pool, config: config, scope: scope, search: search, now: now}, nil + // 目标版本在装配时定型:未知版本/dirty/缺表在这里就失败,不能等到第一条写入 + // 才发现"目标其实没有这张表"。 + schema, err := ResolveSchemaProfile(ctx, pool, "publish target") + if err != nil { + pool.Close() + return nil, err + } + return &ProductionLibraryTarget{pool: pool, config: config, scope: scope, search: search, now: now, + schema: schema, tables: schema.Tables}, nil } func (t *ProductionLibraryTarget) Close() { t.pool.Close() } @@ -182,7 +258,7 @@ func (t *ProductionLibraryTarget) Identity() PostgresIdentity { func (t *ProductionLibraryTarget) Current(ctx context.Context) (libraryrelease.CurrentState, error) { state := libraryrelease.CurrentState{Counts: map[string]int64{}, Digests: map[string]string{}, CapturedAt: t.now().UTC()} - for _, table := range productionLibraryTables { + for _, table := range t.tables { count, digest, err := t.tableState(ctx, table) if err != nil { return libraryrelease.CurrentState{}, err @@ -202,10 +278,19 @@ func (t *ProductionLibraryTarget) Current(ctx context.Context) (libraryrelease.C return state, nil } -// scopeWhere 返回"这张表里属于本知识库的行"的过滤条件($1=tenant,$2=kb)。 +// scopeWhere 是 74-only 入口(残留复核、0.7.1 夹具)使用的固定表集合版本。 +func scopeWhere(table string) string { return scopeWhereFor(productionLibraryTables, table) } + +// scopeWhere 用本次目标解析出的表集合。 +func (t *ProductionLibraryTarget) scopeWhere(table string) string { + return scopeWhereFor(t.tables, table) +} + +// scopeWhereFor 返回"这张表里属于本知识库的行"的过滤条件($1=tenant,$2=kb)。 // 不同表的归属列不同:关系表与绑定表没有 knowledge_base_id,必须走父表判定, -// 否则要么删错、要么把别的知识库数据算进来。 -func scopeWhere(table string) string { +// 否则要么删错、要么把别的知识库数据算进来。表集合来自解析出的 profile: +// 0.9.0 的资源正文引用子查询不能提到不存在的 wiki_log_entries。 +func scopeWhereFor(tables []string, table string) string { switch table { case "knowledge_tag_relations": // 真实 WeKnora 的这张表只有 knowledge_id/tag_id/created_at, @@ -222,7 +307,7 @@ func scopeWhere(table string) string { // 两种归属都要算:显式绑定(knowledge/chunk)+ 被本库 chunk 正文以 // resource:// 引用(图片/附件常见,可能没有绑定行)。 // 与归档侧收集资源部件的规则保持一致,否则校验会把导入的资源算成"多余"。 - return `(EXISTS ( + return `resources.tenant_id=$1 AND (EXISTS ( SELECT 1 FROM resource_bindings b JOIN knowledges k ON k.id=b.owner_id AND k.tenant_id=b.tenant_id WHERE b.resource_id=resources.id AND b.tenant_id=$1 AND b.owner_type='knowledge' AND k.knowledge_base_id=$2 @@ -230,11 +315,7 @@ func scopeWhere(table string) string { SELECT 1 FROM resource_bindings b JOIN chunks c ON c.id=b.owner_id AND c.tenant_id=b.tenant_id WHERE b.resource_id=resources.id AND b.tenant_id=$1 AND b.owner_type='chunk' AND c.knowledge_base_id=$2) - OR EXISTS ( - SELECT 1 FROM chunks c - WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL - AND coalesce(resources.handle,'') <> '' - AND position('resource://'||resources.handle IN coalesce(c.content,'')) > 0))` + OR EXISTS (` + libraryResourceBodyReferenceSQL(tables, "c.tenant_id=$1 AND c.knowledge_base_id=$2") + `))` default: return "tenant_id=$1 AND knowledge_base_id=$2" } @@ -252,22 +333,67 @@ func identityExpr(table string) string { } func (t *ProductionLibraryTarget) tableState(ctx context.Context, table string) (int64, string, error) { - rows, err := t.pool.Query(ctx, fmt.Sprintf(`SELECT %s FROM %s WHERE %s ORDER BY 1`, - identityExpr(table), table, scopeWhere(table)), t.scope.TenantID, t.scope.KnowledgeBaseID) - if err != nil { - return 0, "", fmt.Errorf("读取生产 %s 失败", table) + identity := PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID} + var rows []json.RawMessage + if table == "resources" { + // F01: derive exact references once; do not run the per-resource body + // scan used by the legacy scope predicate. + exporter := PostgresExporter{db: t.pool} + var bodies, bindings []json.RawMessage + for _, name := range t.tables { + if name == "resources" { + continue + } + items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`, + name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID) + if err != nil { + return 0, "", fmt.Errorf("读取生产 %s 失败", table) + } + if name != "resource_bindings" && name != "knowledge_tag_relations" { + bodies = append(bodies, items...) + } + if name == "resource_bindings" { + bindings = items + } + } + items, err := scopedResourceRows(ctx, &exporter, identity, true, bodies, bindings) + if err != nil { + return 0, "", fmt.Errorf("读取生产 %s 失败: %w", table, err) + } + rows = items } - defer rows.Close() - ids := make([]string, 0, 64) - for rows.Next() { - var id string - if err := rows.Scan(&id); err != nil { + // Non-resource identities are plain text (UUID, doc id, numeric id, or a + // composite key), not JSON. Scanning them through queryRows would run + // canonicalJSON on text and fail on every non-empty table. + if table != "resources" { + rows, err := t.pool.Query(ctx, fmt.Sprintf(`SELECT %s FROM %s WHERE %s ORDER BY 1`, + "("+identityExpr(table)+")::text", table, t.scopeWhere(table)), identity.TenantID, identity.KnowledgeBaseID) + if err != nil { + return 0, "", fmt.Errorf("读取生产 %s 失败", table) + } + defer rows.Close() + ids := make([]string, 0, 64) + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return 0, "", err + } + ids = append(ids, id) + } + if err := rows.Err(); err != nil { return 0, "", err } - ids = append(ids, id) + return int64(len(ids)), digestIDs(ids), nil } - if err := rows.Err(); err != nil { - return 0, "", err + ids := make([]string, 0, len(rows)) + for _, raw := range rows { + var value struct { + ID string `json:"id"` + } + if err := json.Unmarshal(raw, &value); err != nil || value.ID == "" { + return 0, "", fmt.Errorf("读取生产 %s 身份失败", table) + } + ids = append(ids, value.ID) } return int64(len(ids)), digestIDs(ids), nil } @@ -279,6 +405,24 @@ func digestIDs(ids []string) string { // Apply 把一类数据从归档写进生产;database 与 wiki 走同一个知识域事务。 func (t *ProductionLibraryTarget) Apply(ctx context.Context, stage libraryrelease.Stage, snapshotID string) error { + if authorizer, ok := t.config.Objects.(interface{ EnsureObjectGrant(context.Context) error }); ok { + if e := authorizer.EnsureObjectGrant(ctx); e != nil { + return e + } + } + if t.activePlan != nil { + expected := t.activePlan.TargetSnapshotID + if t.preserveChunkSequence { + expected = t.activePlan.BackupSnapshotID + } + if snapshotID != expected { + return errors.New("apply snapshot differs from frozen execution plan") + } + } + if err := t.verifyPlanSchema(ctx); err != nil { + return err + } + t.activeSnapshot = snapshotID if err := t.resolveStorageBackend(ctx); err != nil { return err } @@ -292,9 +436,18 @@ func (t *ProductionLibraryTarget) Apply(ctx context.Context, stage libraryreleas if err != nil { return errors.New("预发布快照不可读") } + if err := requireSameProfile(manifest.Compatibility.SchemaVersion, t.schema, "publish"); err != nil { + return err + } if err := t.bindSnapshotScope(manifestScope{tenantID: manifest.TenantID, knowledgeBaseID: manifest.KnowledgeBaseID}); err != nil { return err } + t.disableTargetMapping() + if t.targetMappingApplies(snapshotID) { + if err := t.enableTargetMapping(archive, manifest); err != nil { + return err + } + } switch stage { case libraryrelease.StageDatabase, libraryrelease.StageWiki: kind := "database" @@ -326,8 +479,8 @@ func (t *ProductionLibraryTarget) importRows(ctx context.Context, archive *libra return errors.New("开启生产事务失败") } defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() - for index := len(productionLibraryTables) - 1; index >= 0; index-- { - table := productionLibraryTables[index] + for index := len(t.tables) - 1; index >= 0; index-- { + table := t.tables[index] if _, ok := parts[table]; !ok { continue } @@ -335,7 +488,7 @@ func (t *ProductionLibraryTarget) importRows(ctx context.Context, archive *libra return err } } - for _, table := range productionLibraryTables { + for _, table := range t.tables { part, ok := parts[table] if !ok { continue @@ -355,7 +508,7 @@ func (t *ProductionLibraryTarget) deleteScope(ctx context.Context, tx pgx.Tx, ta // 资源可能被多个知识库共享:这里不删,只做插入/更新。 return nil } - statement := fmt.Sprintf(`DELETE FROM %s WHERE %s`, table, scopeWhere(table)) + statement := fmt.Sprintf(`DELETE FROM %s WHERE %s`, table, t.scopeWhere(table)) if _, err := tx.Exec(ctx, statement, t.scope.TenantID, t.scope.KnowledgeBaseID); err != nil { return fmt.Errorf("清理生产 %s 失败", table) } @@ -383,11 +536,25 @@ func (t *ProductionLibraryTarget) insertRows(ctx context.Context, tx pgx.Tx, arc if len(row) == 0 { continue } + // 已证明与目标现状完全一致的资源:不重写这一行(连 updated_at 都不碰)。 + // 它在写集合里是 Existing+Reused,恢复清理也不会看它。 + if table == resourceReuseTableName && t.reusedResources != nil { + var identity string + if json.Unmarshal(row["id"], &identity) == nil && t.reusedResources[identity] { + continue + } + } // 行必须先映射到目标范围再落库:原样插入会把行写进来源租户/知识库, // 目标范围的删除、校验与恢复都看不见它们。 if err := t.retargetRow(table, row); err != nil { return err } + if _, err := t.mapLocalID(table, row); err != nil { + return err + } + if table == "chunks" && !t.preserveChunkSequence && t.activePlan == nil { + delete(row, "seq_id") + } if columns == nil { columns = make([]string, 0, len(row)) for key := range row { @@ -395,9 +562,19 @@ func (t *ProductionLibraryTarget) insertRows(ctx context.Context, tx pgx.Tx, arc } sort.Strings(columns) // 本库行先删后插:除 resources(可能被多个知识库共享)外不需要 upsert。 + // resources 的 upsert 必须限定"同租户":同 ID 属于别的租户时整行覆盖会把 + // 别人的文件改坏(跨范围 ID 冲突已由写集合预检拒绝,这里是最后一道闸)。 if table == "resources" { statement = fmt.Sprintf(`INSERT INTO %s SELECT * FROM jsonb_populate_record(NULL::%s, $1::jsonb) -ON CONFLICT (id) DO UPDATE SET %s`, table, table, updateAssignments(columns)) +ON CONFLICT (id) DO UPDATE SET %s WHERE %s.tenant_id = $2`, table, table, updateAssignments(columns), table) + } else if table == "chunks" && !t.preserveChunkSequence && t.activePlan == nil { + // Omitting the column (not inserting NULL) invokes the target default. + quoted := make([]string, len(columns)) + for i, column := range columns { + quoted[i] = pgx.Identifier{column}.Sanitize() + } + projection := strings.Join(quoted, ", ") + statement = fmt.Sprintf(`INSERT INTO chunks (%s) SELECT %s FROM jsonb_populate_record(NULL::chunks, $1::jsonb)`, projection, projection) } else { statement = fmt.Sprintf(`INSERT INTO %s SELECT * FROM jsonb_populate_record(NULL::%s, $1::jsonb)`, table, table) @@ -407,9 +584,19 @@ ON CONFLICT (id) DO UPDATE SET %s`, table, table, updateAssignments(columns)) if err != nil { return err } - if _, err := tx.Exec(ctx, statement, encoded); err != nil { + args := []any{encoded} + if table == "resources" { + args = append(args, t.scope.TenantID) + } + tag, err := tx.Exec(ctx, statement, args...) + if err != nil { return fmt.Errorf("写入生产 %s 失败: %w", table, err) } + if table == "resources" && tag.RowsAffected() != 1 { + var identity string + _ = json.Unmarshal(row["id"], &identity) + return fmt.Errorf("写入生产 resources 冲突:%s 属于其它租户,拒绝覆盖", identity) + } } return nil } @@ -437,7 +624,20 @@ type resourceLocation struct { // rowTransform 是"写入时对行做过的变换"的统一入口:校验要用同一份,否则摘要比的是 // 变换前的行、目标里是变换后的行,永远不一致。范围映射同样必须两边一致。 func (t *ProductionLibraryTarget) rowTransform(table string) func(map[string]json.RawMessage) error { - return func(row map[string]json.RawMessage) error { return t.retargetRow(table, row) } + return func(row map[string]json.RawMessage) error { + if err := t.retargetRow(table, row); err != nil { + return err + } + // seq_id is destination-local, not content identity. Full-universe + // rollback verification still compares the original value exactly. + if _, err := t.mapLocalID(table, row); err != nil { + return err + } + if table == "chunks" && !t.preserveChunkSequence && t.activePlan == nil { + delete(row, "seq_id") + } + return nil + } } func (t *ProductionLibraryTarget) importResources(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error { @@ -453,6 +653,11 @@ func (t *ProductionLibraryTarget) importResources(ctx context.Context, archive * if !ok || location.Path == "" { return fmt.Errorf("生产缺少资源 %s 的存储路径", part.Name) } + // 复用资源的对象字节已经在计划阶段逐字节比过:不再重传(重传只会改 + // 对象的写入时间,没有任何收益)。 + if t.reusedResources[part.Name] && t.activePlan == nil { + continue + } reader, err := archive.OpenPart(part) if err != nil { return err @@ -462,6 +667,42 @@ func (t *ProductionLibraryTarget) importResources(ctx context.Context, archive * if err != nil || int64(len(body)) != part.Bytes { return fmt.Errorf("资源 %s 字节与归档摘要不符", part.Name) } + if t.activePlan != nil { + if t.activeSnapshot == t.activePlan.BackupSnapshotID { + store, ok := t.config.Objects.(conditionalObjectStore) + if !ok { + return errors.New("rollback lacks conditional object observation") + } + observed, err := store.ObserveObject(ctx, location.Provider, location.Path) + if err != nil { + return err + } + if !observed.Exists || observed.SHA256 != part.SHA256 || observed.Bytes != part.Bytes { + return errors.New("before-image object changed; refusing blind restore overwrite") + } + continue + } + if t.activeSnapshot != t.activePlan.TargetSnapshotID { + return errors.New("object snapshot differs from plan") + } + found := false + for _, obj := range t.activePlan.Objects { + if obj.ResourceID == part.Name { + if obj.Locator != location.Path || obj.Provider != location.Provider || obj.SHA256 != part.SHA256 || obj.Bytes != part.Bytes { + return errors.New("object plan differs from resource/blob") + } + if err := t.applyPlannedObject(ctx, obj, body); err != nil { + return err + } + found = true + break + } + } + if !found { + return errors.New("resource omitted from immutable object plan") + } + continue + } if err := t.config.Objects.Put(ctx, location.Provider, location.Path, bytes.NewReader(body), int64(len(body))); err != nil { return fmt.Errorf("上传资源 %s 失败: %w", part.Name, err) } @@ -536,6 +777,12 @@ WHERE tenant_id=$1 AND id = ANY($2::text[])`, t.scope.TenantID, ids) } func (t *ProductionLibraryTarget) importIndex(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error { + if t.activePlan != nil && !t.drillRestore { + if t.preserveChunkSequence { + return t.restorePlannedIndex(ctx) + } + return t.applyPlannedIndex(ctx) + } for _, part := range manifest.Parts { if part.Kind != "index" { continue @@ -552,9 +799,22 @@ func (t *ProductionLibraryTarget) importIndex(ctx context.Context, archive *libr if err != nil { return err } + if t.mappingActive && t.targetIDs != nil { + for i := range documents { + mappedID, mappedSource, err := t.targetIDs.remapIndexDocument(documents[i].ID, documents[i].Source) + if err != nil { + return err + } + documents[i] = librarysnapshot.IndexDocument{ID: mappedID, Source: mappedSource} + } + } // 直接搬运原始文档与向量:不解析、不重新 Embedding。 - identity := SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID} - if err := t.search.BulkIndex(ctx, documents, identity); err != nil { + identity := SearchIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID, NoTenantField: !t.schema.IndexTenantField} + write := t.search.BulkIndex + if t.activePlan != nil { + write = t.search.BulkIndexGuarded + } + if err := write(ctx, documents, identity); err != nil { return err } // 快照里没有的文档必须从生产索引删掉,否则撤销只在数据库生效。 @@ -571,6 +831,7 @@ func (t *ProductionLibraryTarget) importIndex(ctx context.Context, archive *libr // Verify 用行数 + 身份集合摘要 + 索引条数核对生产与预发布快照是否一致。 func (t *ProductionLibraryTarget) Verify(ctx context.Context, expect libraryrelease.Expectation) error { + t.activeSnapshot = expect.SnapshotID if err := t.resolveStorageBackend(ctx); err != nil { return err } @@ -584,9 +845,18 @@ func (t *ProductionLibraryTarget) Verify(ctx context.Context, expect libraryrele if err != nil { return errors.New("预发布快照不可读") } + if err := requireSameProfile(manifest.Compatibility.SchemaVersion, t.schema, "publish verify"); err != nil { + return err + } if err := t.bindSnapshotScope(manifestScope{tenantID: manifest.TenantID, knowledgeBaseID: manifest.KnowledgeBaseID}); err != nil { return err } + t.disableTargetMapping() + if t.targetMappingApplies(expect.SnapshotID) { + if err := t.enableTargetMapping(archive, manifest); err != nil { + return err + } + } for _, part := range manifest.Parts { if part.Kind != "database" && part.Kind != "wiki" { continue @@ -598,7 +868,20 @@ func (t *ProductionLibraryTarget) Verify(ctx context.Context, expect libraryrele return err } } - wantCount, wantDigest, err := archivedTableState(archive, part) + wantCount, wantDigest, err := t.archivedTableState(archive, part) + if err == nil && part.Name == "wiki_log_entries" && t.activePlan != nil && t.activeSnapshot == t.activePlan.TargetSnapshotID && !t.preserveChunkSequence { + ids := []string{} + for _, mapping := range t.activePlan.LocalIDs { + if mapping.Table == part.Name { + ids = append(ids, mapping.Target) + } + } + if int64(len(ids)) != wantCount { + return errors.New("Wiki local mapping coverage mismatch") + } + sort.Strings(ids) + wantDigest = digestIDs(ids) + } if errors.Is(err, errMissingIdentity) { // 个别表(例如日志表)没有代理主键:身份集合无从比,但行数与逐行内容摘要仍然必须一致。 wantContentCount, wantContentDigest, columns, contentErr := archivedTableContent(archive, part, t.rowTransform(part.Name)) @@ -663,67 +946,6 @@ func (t *ProductionLibraryTarget) Verify(ctx context.Context, expect libraryrele return nil } -// dropOrphanResources 清掉"本次恢复后已无任何归属"的目标租户资源行。 -// -// 判据必须同时满足:属于目标租户、不在预备份快照里、没有任何 resource_binding、 -// 也没有任何分块正文以 resource:// 引用它。这样的行对目标应用完全不可见 -// (没有知识库能按它取到文件),只可能是失败写入留下的残渣。 -func (t *ProductionLibraryTarget) dropOrphanResources(ctx context.Context, backupSnapshotID string) error { - archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024) - if err != nil { - return errors.New("归档不可用") - } - defer archive.Close() - manifest, err := archive.Load(backupSnapshotID) - if err != nil { - return errors.New("预备份快照不可读") - } - kept := []string{} - for _, part := range manifest.Parts { - if part.Kind != "database" || part.Name != "resources" { - continue - } - ids, err := archivedResourceIDs(archive, part) - if err != nil { - return err - } - kept = append(kept, ids...) - } - rows, err := t.pool.Query(ctx, ` -SELECT r.id FROM resources AS r -WHERE r.tenant_id=$1 - AND NOT (r.id = ANY($2::text[])) - AND NOT EXISTS (SELECT 1 FROM resource_bindings b WHERE b.resource_id=r.id) - AND NOT EXISTS (SELECT 1 FROM chunks c WHERE c.tenant_id=r.tenant_id AND c.deleted_at IS NULL - AND coalesce(r.handle,'') <> '' - AND position('resource://'||r.handle IN coalesce(c.content,'')) > 0)`, - t.scope.TenantID, kept) - if err != nil { - return fmt.Errorf("查找目标残留资源失败: %w", err) - } - orphans := make([]string, 0, 8) - for rows.Next() { - var id string - if err := rows.Scan(&id); err != nil { - rows.Close() - return err - } - orphans = append(orphans, id) - } - rows.Close() - if err := rows.Err(); err != nil { - return err - } - if len(orphans) == 0 { - return nil - } - if _, err := t.pool.Exec(ctx, `DELETE FROM resources WHERE tenant_id=$1 AND id = ANY($2::text[])`, - t.scope.TenantID, orphans); err != nil { - return fmt.Errorf("清理目标残留资源失败: %w", err) - } - return nil -} - // archivedResourceState 只核对"归档里列出的这些资源"是否还在且未变。 func (t *ProductionLibraryTarget) archivedResourceState(ctx context.Context, ids []string) (int64, string, error) { rows, err := t.pool.Query(ctx, `SELECT id FROM resources WHERE id = ANY($1::text[]) ORDER BY id`, ids) @@ -800,46 +1022,369 @@ func archivedTableState(archive *librarysnapshot.Archive, part librarysnapshot.P } func archiveRowIdentity(table string, row map[string]json.RawMessage) string { - value := func(key string) string { - var text string - _ = json.Unmarshal(row[key], &text) - return text + identity, err := parseRowIdentity(table, row) + if err != nil { + return "" } - if table == "knowledge_tag_relations" { - knowledge, tag := value("knowledge_id"), value("tag_id") - if knowledge == "" || tag == "" { - return "" - } - return knowledge + ":" + tag - } - return value("id") + return identity.key() } -// Restore 用预备份把生产整库恢复回去:走同一条 Apply 路径,可重复执行。 -func (t *ProductionLibraryTarget) Restore(ctx context.Context, backup libraryrelease.BackupRef) error { - if backup.SnapshotID == "" { - return errors.New("恢复需要绑定的预备份快照") +// AdoptWriteSet 消费已持久化的写集合(接管/恢复路径)。 +// +// 只做一件事:把"这些 resources 已证明与目标现状逐字节一致"的决定装回执行目标, +// 让 Apply 的跳过逻辑生效。它**不重新计划**、不重新比较目标现状——那会把半写状态 +// 当成新基线,也把"共享对象没被重写"这句话变成谎话(F07)。 +// +// 校验从严:计划必须自校验通过、绑定同一目标 tenant/KB、绑定本次要写的那份快照; +// 任何一项不符都拒绝,因为错误的复用集合会导致该写的没写、或该跳的却重写。 +func (t *ProductionLibraryTarget) AdoptWriteSet(set libraryrelease.WriteSet) error { + if err := set.Verify(); err != nil { + return fmt.Errorf("写集合记录校验失败:%w", err) } - for _, stage := range libraryrelease.Stages() { - if err := t.Apply(ctx, stage, backup.SnapshotID); err != nil { - return fmt.Errorf("恢复阶段 %s 失败: %w", stage, err) + if set.IsRestoreDrill() { + // 演练计划只描述 canary 回放,不是发布执行计划;发布恢复入口不得消费它。 + return errors.New("演练恢复计划不能作为发布执行计划接管") + } + if set.TenantID != t.scope.TenantID || set.KnowledgeBaseID != t.scope.KnowledgeBaseID { + return fmt.Errorf("写集合绑定的是 %d/%s,与目标 %d/%s 不一致", + set.TenantID, set.KnowledgeBaseID, t.scope.TenantID, t.scope.KnowledgeBaseID) + } + reused := map[string]bool{} + for _, row := range set.Rows { + if row.Table != resourceReuseTableName || !row.Reused { + continue + } + if !row.Existing { + return fmt.Errorf("写集合把资源 %s 标成复用但写前不存在:拒绝按不可信的复用集合执行", row.ID) + } + reused[row.ID] = true + } + if set.ContractVersion != 0 && set.ContractVersion != migrationIdentityContractVersion { + return errors.New("unsupported migration identity contract") + } + t.targetIDMode = set.TargetIDMode + if t.targetIDMode == libraryrelease.TargetIDModeScoped { + // 新进程接管计划时没有内存里的映射器:按持久契约从目标快照重建, + // 否则 validatePlanBindings 会拿索引原 ID 去比映射后的计划而失败。 + archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024) + if err != nil { + return err + } + manifest, err := archive.Load(set.TargetSnapshotID) + if err != nil { + _ = archive.Close() + return err + } + err = t.enableTargetMapping(archive, manifest) + _ = archive.Close() + if err != nil { + return err } } - // resources 是多知识库共享表,回放阶段不删它:本次写入新增、恢复后已经 - // 没有任何归属的资源行会残留。它们对应用不可见,但属于"多写的"。 - if err := t.dropOrphanResources(ctx, backup.SnapshotID); err != nil { + if err := t.validatePlanBindings(set); err != nil { return err } - // 恢复工具把四个阶段都跑完不算恢复完成:整实例必须回到预备份时刻的样子。 - // 只比目标范围会把"写到范围外"的残留当成已恢复(真实事故:恢复后仍多 67 行)。 - if len(backup.Universe) > 0 { - after, err := universeFingerprint(ctx, t.pool) - if err != nil { - return fmt.Errorf("恢复后读取整库指纹失败: %w", err) + // Copy through JSON: the caller cannot mutate the adopted immutable plan. + raw, err := json.Marshal(set) + if err != nil { + return err + } + var adopted libraryrelease.WriteSet + if err := json.Unmarshal(raw, &adopted); err != nil { + return err + } + if binder, ok := t.config.Objects.(interface { + BindObjectPlan(libraryrelease.WriteSet) error + }); ok { + if err := binder.BindObjectPlan(adopted); err != nil { + return err } - if diff := universeDiff(backup.Universe, after); diff != "" { - return fmt.Errorf("恢复后目标与预备份时刻不一致:%s(很可能有写入逃出了预备份范围,不能当作已恢复)", diff) + } + t.activePlan = &adopted + t.reusedResources = reused + return nil +} + +// ValidateDrillWriteSet 只接受"恢复演练写的隔离 canary 行":表必须是 knowledge_tags、 +// 写前不存在、不是复用。任何其它行都说明这份写集合不是演练产生的,演练入口拒绝回放。 +func ValidateDrillWriteSet(set libraryrelease.WriteSet) error { + if len(set.Rows) == 0 { + return errors.New("演练写集合为空:没有可恢复的 canary") + } + for _, row := range set.Rows { + if row.Table != "knowledge_tags" || row.Existing || row.Reused || row.ID == "" { + return fmt.Errorf("演练写集合包含非 canary 行(表=%s id=%s existing=%v reused=%v):拒绝回放", + row.Table, row.ID, row.Existing, row.Reused) } } return nil } + +// PrepareDrillPlan 把演练台账升级为**受限可执行计划**:V2 执行信封 + 目标 schema +// 摘要 + 真实来源身份 + 当前 owned attempt 绑定,但对象/索引/本地映射写项必须为空。 +// +// 为什么必须在这里而不是在 Apply 里临时补:对象网关控制器只认治理库里 +// production_prebackup 证据登记的 writeset_digest;计划必须在 Seal/落盘/登记之前 +// 定型,否则控制器加载到的摘要是另一份形状。它只增加受限语义,不放宽任何发布校验。 +func (t *ProductionLibraryTarget) PrepareDrillPlan(ctx context.Context, set *libraryrelease.WriteSet) error { + if set == nil || set.JobID == "" { + return errors.New("演练恢复计划缺少作业身份") + } + if set.TenantID != t.scope.TenantID || set.KnowledgeBaseID != t.scope.KnowledgeBaseID { + return fmt.Errorf("演练恢复计划绑定的是 %d/%s,与目标 %d/%s 不一致", + set.TenantID, set.KnowledgeBaseID, t.scope.TenantID, t.scope.KnowledgeBaseID) + } + if err := set.ValidateRestoreBinding(set.BackupSnapshotID, t.scope.TenantID, t.scope.KnowledgeBaseID); err != nil { + return err + } + archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024) + if err != nil { + return errors.New("归档不可用") + } + source, err := archive.Load(set.TargetSnapshotID) + archive.Close() + if err != nil { + return errors.New("演练来源快照不可读") + } + if source.TenantID != t.scope.TenantID || source.KnowledgeBaseID != t.scope.KnowledgeBaseID { + return errors.New("演练来源快照不属于当前目标范围") + } + _, schemaDigest, err := t.migrationCatalog(ctx) + if err != nil { + return err + } + // 先清空任何发布写项:演练计划只允许 canary 行。 + set.Kind = libraryrelease.WriteSetKindRestoreDrill + set.Version = libraryrelease.MigrationWriteSetVersion + set.ContractVersion = migrationIdentityContractVersion + set.SourceTenantID, set.SourceKnowledgeBaseID = source.TenantID, source.KnowledgeBaseID + set.SchemaDigest = schemaDigest + set.Index, set.Objects, set.LocalIDs = nil, nil, nil + // 自动对象网关没有静态 grant:计划签发必须绑定当前 owned attempt, + // 网关控制器会再按治理库核一次(不靠调用方自证)。 + if claim, automatic := t.ownedAttempt(); automatic { + return validateDrillAttempt(claim, set.JobID) + } + return nil +} + +// ownedAttempt 返回本目标装配时冻结的对象网关 claim。只有 Automatic 网关需要它。 +func (t *ProductionLibraryTarget) ownedAttempt() (objectgateway.Claim, bool) { + if provider, ok := t.config.Objects.(interface { + OwnedAttemptClaim() (objectgateway.Claim, bool) + }); ok { + return provider.OwnedAttemptClaim() + } + return objectgateway.Claim{}, false +} + +// validateDrillAttempt 要求计划/回放绑定一个真实的作业代次,而不是调用方编造的身份。 +func validateDrillAttempt(claim objectgateway.Claim, jobID string) error { + if claim.JobID == "" || claim.JobID != jobID || claim.OperationID == "" || claim.Owner == "" || claim.AttemptEpoch < 1 { + return errors.New("演练恢复缺少当前 owned attempt 身份(job/operation/owner/epoch)") + } + return nil +} + +// validateDrillDispatch 证明这次演练的派发身份来自原窗口的真实 attempt 与恢复投递, +// 不是把 gate 置 nil 绕过 DS01。 +func (t *ProductionLibraryTarget) validateDrillDispatch(claim objectgateway.Claim, automatic bool) error { + config := t.config + if config.RestoreTargetIdentity == "" || config.RestoreScope == "" || config.RestoreInstance == "" || + config.RestoreOperationID == "" || config.RestoreWindowJobID == "" || config.RestoreAttemptOwner == "" || + config.RestoreAttemptEpoch < 1 || config.RestoreRecoveryJobID == "" || config.RestoreRecoveryOperationID == "" { + return errors.New("演练恢复缺少完整的派发身份(目标/scope/实例/原 operation/窗口/attempt/恢复作业)") + } + if automatic && (claim.JobID != config.RestoreWindowJobID || claim.OperationID != config.RestoreOperationID || + claim.Owner != config.RestoreAttemptOwner || claim.AttemptEpoch != config.RestoreAttemptEpoch || + claim.RecoveryJobID != config.RestoreRecoveryJobID || claim.RecoveryOperationID != config.RestoreRecoveryOperationID) { + return errors.New("演练恢复的派发身份与当前 owned attempt 不一致") + } + return nil +} + +// RestoreDrill 是恢复演练**限定范围**的安全恢复入口。 +// +// 为什么不是直接调用 Restore:Restore 的写集合是"发布执行计划"(v2 合同 + 索引/对象/ +// 本地 ID 映射 + 源快照清单全部行),演练只写过一行隔离 canary,按发布计划构造会伪造 +// 一份从未发生过的发布。这里保留同一份 DS01 身份合同(来源快照 ≠ 写前镜像、同一作业/ +// 目标/预备份)与同一批 Apply 原语:四个阶段都按写前镜像**整段回放**(先清 scope 再 +// 插入归档行),不是"只删 canary";回放后再用整实例指纹证明目标与预备份一致。 +// +// 自动对象网关保持启用:演练计划显式零对象写项,仍由控制器按当前 attempt/job/目标/ +// 写前镜像签发零写入许可;对象阶段只做只读字节核对,任何创建/删除都会被网关拒绝。 +// 有派发闸口的目标也不再把 gate 置 nil:必须携带原窗口 attempt + 恢复投递身份。 +func (t *ProductionLibraryTarget) RestoreDrill(ctx context.Context, backup libraryrelease.BackupRef) error { + if backup.SnapshotID == "" { + return errors.New("恢复需要绑定的预备份快照") + } + if backup.WriteSet == nil { + return errors.New("演练恢复缺少持久化的写集合记录") + } + if err := backup.WriteSet.Verify(); err != nil { + return fmt.Errorf("写集合记录校验失败,拒绝演练恢复:%w", err) + } + if err := backup.WriteSet.ValidateRestoreBinding(backup.SnapshotID, t.scope.TenantID, t.scope.KnowledgeBaseID); err != nil { + return err + } + if err := ValidateDrillWriteSet(*backup.WriteSet); err != nil { + return err + } + if !backup.WriteSet.IsRestoreDrill() { + return errors.New("演练恢复只接受受限恢复计划(restore-drill),拒绝发布执行计划") + } + claim, automatic := t.ownedAttempt() + if automatic { + if err := validateDrillAttempt(claim, backup.WriteSet.JobID); err != nil { + return err + } + } + if t.config.RestoreDispatch != nil { + if backup.WriteSet.Target != t.config.RestoreScope { + return fmt.Errorf("演练恢复计划 scope=%s,与派发身份 scope=%s 不一致", + backup.WriteSet.Target, t.config.RestoreScope) + } + if err := t.validateDrillDispatch(claim, automatic); err != nil { + return err + } + } + // 对象网关:冻结零对象计划。控制器仍按治理库核 attempt/job/目标/写前镜像; + // 没有冻结计划时 EnsureObjectGrant 会继续 fail closed。 + if binder, ok := t.config.Objects.(interface { + BindObjectPlan(libraryrelease.WriteSet) error + }); ok { + if err := binder.BindObjectPlan(*backup.WriteSet); err != nil { + return err + } + } + adopted := *backup.WriteSet + adopted.Rows = append([]libraryrelease.WriteSetRow(nil), backup.WriteSet.Rows...) + t.activePlan = &adopted + t.drillRestore = true + // DS01 准入必须在任何 PG/对象/索引写之前:原窗口若还有未决派发记录, + // 即使计划是零对象也要 held。 + if t.config.RestoreDispatch != nil { + if err := t.admitRestorePlan(ctx); err != nil { + return err + } + } + // 幂等:恢复收尾可能重放(上次恢复到一半崩溃)。这里不要求"目标当前仍与镜像不同"—— + // "写确实发生"由发起方在写入后的 drift 校验证明,而不是由重放入口猜。 + previous := t.preserveChunkSequence + t.preserveChunkSequence = true + defer func() { t.preserveChunkSequence = previous }() + for _, stage := range libraryrelease.Stages() { + if err := t.Apply(ctx, stage, backup.SnapshotID); err != nil { + return fmt.Errorf("演练恢复阶段 %s 失败: %w", stage, err) + } + } + // canary 是这次演练唯一新建的行:回放后必须精确消失(不是"整库看起来差不多")。 + for _, id := range backup.WriteSet.CreatedIDs("knowledge_tags") { + var exists bool + if err := t.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM knowledge_tags WHERE id=$1)`, id).Scan(&exists); err != nil { + return fmt.Errorf("读取演练 canary 残留失败: %w", err) + } + if exists { + return fmt.Errorf("演练恢复后 canary %s 仍在目标中", id) + } + } + after, err := universeFingerprint(ctx, t.pool) + if err != nil { + return fmt.Errorf("演练恢复后读取整库指纹失败: %w", err) + } + if diff := universeDiff(backup.WriteSet.Universe, after); diff != "" { + return fmt.Errorf("演练恢复后目标与预备份不一致:%s", diff) + } + return nil +} + +// Restore 用预备份把生产整库恢复回去:走同一条 Apply 路径,可重复执行。 +// +// 恢复必须带着"本次写集合 + 写前整实例证据"(写第一笔之前落盘、摘要登记在治理库)。 +// 缺它就直接失败:此刻目标已经变了,按现状推断"哪些是残渣"会删掉历史孤儿、 +// 同租户其它知识库暂未绑定的资源、被共享的资源——而预备份里没有这些行,删了回不来。 +func (t *ProductionLibraryTarget) Restore(ctx context.Context, backup libraryrelease.BackupRef) error { + if backup.SnapshotID == "" { + return errors.New("恢复需要绑定的预备份快照") + } + if backup.WriteSet == nil { + return errors.New("恢复缺少持久化的写集合记录(作业/目标/预备份绑定):拒绝按目标现状推断残渣,维护保持") + } + if err := backup.WriteSet.Verify(); err != nil { + return fmt.Errorf("写集合记录校验失败,拒绝恢复:%w", err) + } + if backup.WriteSet.IsRestoreDrill() { + return errors.New("演练恢复计划不能走发布恢复入口:请使用同作业的恢复演练路径") + } + // 身份合同与演练共用同一份判定(libraryrelease.WriteSet.ValidateRestoreBinding): + // 来源快照 ≠ 写前镜像、同一预备份、同一 tenant/KB,缺一不可。 + if err := backup.WriteSet.ValidateRestoreBinding(backup.SnapshotID, t.scope.TenantID, t.scope.KnowledgeBaseID); err != nil { + return err + } + // 恢复重放的是目标写前镜像,行里已经是目标原始 ID;再映射一次会写到别的身份上。 + t.disableTargetMapping() + t.restoreScope = t.config.RestoreScope + t.restoreSourceSnapshot = backup.WriteSet.TargetSnapshotID + t.restoreBackupSnapshot = backup.SnapshotID + t.restoreFingerprint, t.restoreIndexUUID = "", "" + if err := t.AdoptWriteSet(*backup.WriteSet); err != nil { + return err + } + if err := ensureRestorableResourceReferences(ctx, t.pool, t.tables, *backup.WriteSet); err != nil { + return err + } + if err := ensureNoResourceGrants(ctx, t.pool, backup.WriteSet.CreatedIDs("resources")); err != nil { + return err + } + // DS01:整份计划的未决派发准入必须在这里——在任何 PG/对象/索引写之前。 + // 否则会先回放 database/resources,最后才在 index 上说 held,目标已经半写。 + if err := t.admitRestorePlan(ctx); err != nil { + return err + } + previous := t.preserveChunkSequence + t.preserveChunkSequence = true + defer func() { t.preserveChunkSequence = previous }() + for _, stage := range libraryrelease.Stages() { + if err := t.Apply(ctx, stage, backup.SnapshotID); err != nil { + return fmt.Errorf("恢复阶段 %s 失败: %w", stage, err) + } + _ = testbarrier.Wait(ctx, "restore:"+string(stage), backup.WriteSet.JobID) + } + // resources 是多知识库共享表,回放阶段不删它。这里只清"写前不存在 ∧ 由本次写入 ∧ + // 不在本次恢复内容里"的精确身份,历史孤儿与其它知识库的资源一律不动。 + archiveForCleanup, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024) + if err != nil { + return errors.New("归档不可用") + } + restoredManifest, err := archiveForCleanup.Load(backup.SnapshotID) + if err != nil { + archiveForCleanup.Close() + return errors.New("预备份快照不可读") + } + restored, err := t.snapshotRowIdentities(archiveForCleanup, restoredManifest) + archiveForCleanup.Close() + if err != nil { + return err + } + if err := t.restoreCreatedObjects(ctx); err != nil { + return err + } + if err := t.clearJobCreatedRows(ctx, *backup.WriteSet, restored); err != nil { + return err + } + // 恢复工具把四个阶段都跑完不算恢复完成:整实例(含其它知识库的内容)必须回到 + // 预备份时刻的样子。没有证据就不许降级跳过——那等于把"未经校验"报成"已恢复"。 + after, err := universeFingerprint(ctx, t.pool) + if err != nil { + return fmt.Errorf("恢复后读取整库指纹失败: %w", err) + } + if diff := universeDiff(backup.WriteSet.Universe, after); diff != "" { + return fmt.Errorf("恢复后目标与预备份时刻不一致:%s(很可能有写入逃出了预备份范围,不能当作已恢复)", diff) + } + // 收尾前再拒绝一次未决 effect:任何残留的 dispatching/未 clean 的删除型恢复 + // 都不允许被报成"已恢复",也不允许随后释放维护窗口。 + if err := t.verifyRestoreEffectsClosed(ctx); err != nil { + return err + } + return nil +} diff --git a/internal/releaseadapter/v071/library_production_target_integration_test.go b/internal/releaseadapter/v071/library_production_target_integration_test.go index 51c8ed0..cffec5c 100644 --- a/internal/releaseadapter/v071/library_production_target_integration_test.go +++ b/internal/releaseadapter/v071/library_production_target_integration_test.go @@ -23,7 +23,8 @@ import ( "knowledge-governance/internal/librarysnapshot" ) -// 隔离集成验证:真实 PostgreSQL + 真实 Elasticsearch,不放桩。 +// 隔离集成验证:真实 PostgreSQL + Elasticsearch,Wiki与Verify不打桩。 +// fixtureObjectStore是静态对象模型;真实对象版本由MinIO隔离套件另验。 // 需要显式一次性隔离库与随机索引(与既有捕获集成测试同一套环境变量), // 默认 CI 不连接这些服务,因此在 test-scope.json 里声明为可选未运行。 func TestLibraryProductionTargetIsolated(t *testing.T) { @@ -108,6 +109,36 @@ func TestLibraryProductionTargetIsolated(t *testing.T) { t.Fatalf("target: %v", err) } defer target.Close() + // Capture the actual target, not the source snapshot disguised as a backup. + call("PUT", "/"+index+"/_doc/chunk-safe?refresh=true", + `{"tenant_id":10000,"knowledge_base_id":"kb-safe","knowledge_id":"doc-safe","chunk_id":"chunk-safe","source_id":"chunk-safe","content":"chunk","embedding":[0.1,0.2]}`, 201) + mapping, err := target.Search().MappingSHA256(ctx) + if err != nil { + t.Fatal(err) + } + backups, err := NewProductionBackupStore(ProductionBackupConfig{ + Pool: target.Pool(), Search: target.Search(), Objects: fixtureObjectStore{}, ArchiveRoot: archiveRoot, + Scope: "internal", Identity: target.Identity(), MaxDocuments: 100, + Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", EmbeddingDimension: 1024, IndexMappingSHA256: mapping}, + }) + if err != nil { + t.Fatal(err) + } + prepare := func(snapshot string) libraryrelease.BackupRef { + t.Helper() + current, err := target.Current(ctx) + if err != nil { + t.Fatal(err) + } + backup, err := backups.Prepare(ctx, snapshot, current) + if err != nil { + t.Fatal(err) + } + backup.WriteSet = planLedgerWithUniverse(t, target, snapshot, backup.SnapshotID, backup.Universe) + return backup + } + prepare(first) for _, stage := range []libraryrelease.Stage{libraryrelease.StageDatabase, libraryrelease.StageWiki, libraryrelease.StageIndex} { if err := target.Apply(ctx, stage, first); err != nil { @@ -125,6 +156,8 @@ func TestLibraryProductionTargetIsolated(t *testing.T) { t.Fatalf("chunks after first sync = %d, want 1", chunks) } + // A new intent needs its own frozen plan and real before-image. + secondBackup := prepare(second) // 第二个快照没有 chunk:撤销必须真的从生产消失,而不是"只增不减"。 for _, stage := range []libraryrelease.Stage{libraryrelease.StageDatabase, libraryrelease.StageWiki, libraryrelease.StageIndex} { if err := target.Apply(ctx, stage, second); err != nil { @@ -149,50 +182,29 @@ func TestLibraryProductionTargetIsolated(t *testing.T) { t.Fatalf("cross-scope rows must survive, got %d", others) } // 恢复:把第一个快照再应用一次,撤销的内容回来。 - if err := target.Restore(ctx, libraryrelease.BackupRef{ID: "backup", SnapshotID: first}); err != nil { + // 恢复必须带着写集合记录(生产路径在写第一笔之前就算好并落盘)。 + if err := target.Restore(ctx, secondBackup); err != nil { t.Fatalf("restore: %v", err) } - if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: first}); err != nil { - t.Fatalf("verify after restore: %v", err) + if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: secondBackup.SnapshotID}); err != nil { + t.Fatalf("verify after restore to second job before-image: %v", err) } - // 独立预备份:从真实生产当前状态导出成归档版本,再用它做恢复演练。 - mapping, err := target.Search().MappingSHA256(ctx) - if err != nil { - t.Fatalf("mapping: %v", err) - } - // 预备份与发布快照放在同一个归档根(生产上就是 LIBRARY_ARCHIVE_ROOT): - // 恢复时按快照 ID 回放,不依赖"备份路径"这种第二套寻址。 - backupRoot := archiveRoot - backups, err := NewProductionBackupStore(ProductionBackupConfig{ - Pool: target.Pool(), Search: target.Search(), Objects: fixtureObjectStore{}, ArchiveRoot: backupRoot, - Scope: "internal", Identity: target.Identity(), MaxDocuments: 100, - Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, - RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", - EmbeddingDimension: 1024, IndexMappingSHA256: mapping}, - }) - if err != nil { - t.Fatalf("backup store: %v", err) - } - current, err := target.Current(ctx) - if err != nil { - t.Fatalf("current: %v", err) - } - backup, err := backups.Prepare(ctx, first, current) - if err != nil { - t.Fatalf("prepare backup: %v", err) - } - if backup.SnapshotID == "" || backup.Bytes <= 0 { - t.Fatalf("backup must carry a snapshot and bytes: %+v", backup) - } + // Freeze repair evidence before fault injection, never from damaged state. + backup := prepare(first) // 故障注入:直接破坏生产状态,校验必须失败,恢复后必须通过。 - if _, err := pool.Exec(ctx, `DELETE FROM chunks WHERE id='chunk-safe'`); err != nil { + deleted, err := pool.Exec(ctx, `DELETE FROM chunks WHERE id=$1`, expectedTargetID(10000, "kb-safe", "chunks", "chunk-safe")) + if err != nil { t.Fatal(err) } + if deleted.RowsAffected() != 1 { + t.Fatalf("fault injection deleted %d rows, want 1", deleted.RowsAffected()) + } if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: first}); err == nil { t.Fatal("verify must detect a missing chunk row") } + if err := target.Restore(ctx, backup); err != nil { t.Fatalf("restore from backup: %v", err) } @@ -298,7 +310,7 @@ func TestLibraryReleaseRunIsolated(t *testing.T) { t.Fatal(err) } now := time.Now().UTC() - request := libraryrelease.Request{Target: "internal", SnapshotID: snapshotID, + request := libraryrelease.Request{JobID: "job-e2e-isolated", Target: "internal", SnapshotID: snapshotID, ParamsDigest: "digest-e2e", Now: now, Grant: libraryrelease.Grant{Target: "internal", SnapshotID: snapshotID, ParamsDigest: "digest-e2e", ExpiresAt: now.Add(10 * time.Minute), AuthorizedBy: "acceptance"}} @@ -314,6 +326,13 @@ func TestLibraryReleaseRunIsolated(t *testing.T) { type fixtureObjectStore struct{} +// Static read-only object model, not evidence of any provider's versioning. +// These tests never mutate objects; the real-MinIO suites exercise that path. +func (fixtureObjectStore) ObserveObject(context.Context, string, string) (objectObservation, error) { + sum := sha256.Sum256([]byte("12345678")) + return objectObservation{Exists: true, VersionID: "fixture-static-v1", SHA256: hex.EncodeToString(sum[:]), Bytes: 8}, nil +} + // Open 返回与夹具资源行 size=8 一致的字节,供预备份读取对象。 func (fixtureObjectStore) Open(context.Context, string, string) (io.ReadCloser, error) { return io.NopCloser(strings.NewReader("12345678")), nil @@ -397,9 +416,10 @@ func sealTargetFixture(t *testing.T, archive *librarysnapshot.Archive, scope str // memoryObjectStore 是"真实字节"的资源存储替身:Put/Open/Stat/Copy 都按摘要核对, // 可以强制写入失败,用来复现"资源阶段失败"这一半写场景。 type memoryObjectStore struct { - objects map[string][]byte - failPut bool - puts []string + objects map[string][]byte + failPut bool + puts []string + observations map[string]objectObservation } func newMemoryObjectStore(objects map[string][]byte) *memoryObjectStore { @@ -561,7 +581,7 @@ func TestLibraryCrossScopeSyncRollbackLeavesNoResidueIsolated(t *testing.T) { t.Fatalf("backup store: %v", err) } now := time.Now().UTC() - request := libraryrelease.Request{Target: "internal", SnapshotID: snapshotID, + request := libraryrelease.Request{JobID: "job-cross-scope", Target: "internal", SnapshotID: snapshotID, ParamsDigest: "digest-cross-scope", Now: now, Grant: libraryrelease.Grant{Target: "internal", SnapshotID: snapshotID, ParamsDigest: "digest-cross-scope", ExpiresAt: now.Add(10 * time.Minute), AuthorizedBy: "acceptance"}} @@ -624,6 +644,7 @@ func TestLibraryCrossScopeSyncRollbackLeavesNoResidueIsolated(t *testing.T) { // 2) 同样的跨范围同步,资源能写 → 行必须落在目标范围,资源定位符指向目标存储。 store.failPut = false + request.JobID = "job-cross-scope-next-intent" succeed := libraryrelease.Run(ctx, request, target, backups, nil) if succeed.State != "succeeded" { t.Fatalf("second run outcome = %+v", succeed) @@ -633,14 +654,15 @@ func TestLibraryCrossScopeSyncRollbackLeavesNoResidueIsolated(t *testing.T) { } var knowledgeKB, chunkKB, provider, locator string var tenant int64 - if err := pool.QueryRow(ctx, `SELECT tenant_id, knowledge_base_id FROM knowledges WHERE id='doc-source'`). + if err := pool.QueryRow(ctx, `SELECT tenant_id, knowledge_base_id FROM knowledges WHERE id=$1`, + expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", "doc-source")). Scan(&tenant, &knowledgeKB); err != nil { t.Fatalf("source document must exist in the target scope: %v", err) } if tenant != 10001 || knowledgeKB != "kb-target" { t.Fatalf("cross-scope row landed at %d/%s", tenant, knowledgeKB) } - if err := pool.QueryRow(ctx, `SELECT knowledge_base_id FROM chunks WHERE id='chunk-source'`).Scan(&chunkKB); err != nil { + if err := pool.QueryRow(ctx, `SELECT knowledge_base_id FROM chunks WHERE id=$1`, expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", "chunk-source")).Scan(&chunkKB); err != nil { t.Fatal(err) } if chunkKB != "kb-target" { @@ -729,3 +751,29 @@ func sealCrossScopeFixture(t *testing.T, archive *librarysnapshot.Archive, sourc } func formatTenant(tenant uint64) string { return strconv.FormatUint(tenant, 10) } + +// planLedgerFor 给"直接调 Apply 再 Restore"的用例造一份真实写集合: +// 生产路径由 libraryrelease.Run 在写第一笔之前完成同样的动作。 +func planLedgerFor(t *testing.T, target *ProductionLibraryTarget, snapshotID, backupID string) *libraryrelease.WriteSet { + t.Helper() + return planLedgerWithUniverse(t, target, snapshotID, backupID, nil) +} + +func planLedgerWithUniverse(t *testing.T, target *ProductionLibraryTarget, snapshotID, backupID string, + universe map[string]libraryrelease.TableFingerprint) *libraryrelease.WriteSet { + t.Helper() + ctx := context.Background() + if universe == nil { + computed, err := universeFingerprint(ctx, target.Pool()) + if err != nil { + t.Fatalf("whole-instance fingerprint: %v", err) + } + universe = computed + } + set, err := target.PlanWriteSet(ctx, libraryrelease.WriteSetPlan{JobID: "job-test-" + snapshotID[:8], + Target: "internal", BackupSnapshotID: backupID, TargetSnapshotID: snapshotID, Universe: universe}) + if err != nil { + t.Fatalf("plan write set: %v", err) + } + return &set +} diff --git a/internal/releaseadapter/v071/library_production_target_v090_integration_test.go b/internal/releaseadapter/v071/library_production_target_v090_integration_test.go new file mode 100644 index 0000000..fdfa7c0 --- /dev/null +++ b/internal/releaseadapter/v071/library_production_target_v090_integration_test.go @@ -0,0 +1,411 @@ +package v071 + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "strconv" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// 0.9.0 整库发布目标的隔离夹具身份。来源=0.9.0 测试实例,目标=另一租户/知识库, +// 这样"资源定位符换桶/后端/租户段"与"行改写目标范围"都被真实覆盖。 +const ( + v090TargetTenant = 10001 + v090TargetKB = "kb-v090-prod" + v090TargetBackend = "backend-v090-target" + v090TargetBucket = "kg-v090-target-bucket" + v090SourceBackend = "backend-v090-source" + // 来源定位符是目标应用真实使用的形状:storage:///:///。 + v090SourceLocator = "storage://backend-v090-source/oss://kg-v090-source-bucket/weknora/10000/rs-v090-1/kn.bin" +) + +// v090ObjectBytes 按"提供方|路径"供字节,既能给封存读来源对象,也能给目标写回。 +type v090ObjectBytes map[string][]byte + +func (o v090ObjectBytes) Open(_ context.Context, provider, physicalPath string) (io.ReadCloser, error) { + content, ok := o[provider+"|"+physicalPath] + if !ok { + return nil, errors.New("fixture object missing: " + provider + "|" + physicalPath) + } + return io.NopCloser(bytes.NewReader(content)), nil +} + +// TestV090ProductionTargetPublishIsolated 是 0.9.0(schema 134)**发布写入路径**的 +// 端到端证据:真实导出 → 真实封存 → 真实 ProductionLibraryTarget 写进干净 134 目标 +// → 逐表核对 → 用写前镜像恢复回滚 → 再核对回到写前状态。 +// +// 这里不允许打桩 PG/索引/对象:134 与 74 的差别(没有 wiki_log_entries、chunks 多 +// NOT NULL 列、seq_id 由目标序列分配)只有在真 schema 上才会暴露。因此默认 CI 跳过, +// 在 scripts/test-scope.json 里声明为可选未运行,并写明理由。 +func TestV090ProductionTargetPublishIsolated(t *testing.T) { + base := os.Getenv("KG_LIBRARY_TEST_ELASTIC_URL") + if os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" || base == "" { + t.Skip("requires isolated PG plus ES opt-in (KG_LIBRARY_TEST_ISOLATED=1, KG_LIBRARY_TEST_ELASTIC_URL)") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + + src := v090Pool(t, "KG_V090_SOURCE_DSN") + dst := v090Pool(t, "KG_V090_TARGET_DSN") + identity := seedV090(t, ctx, src) + // 资源行必须带目标实例真实可解析的定位符,否则"换桶/换后端"这条改写没有被覆盖。 + if _, err := src.Exec(ctx, `UPDATE resources SET provider='oss', storage_backend_id=$2, + physical_path=$3, location_hash=$4 WHERE id=$1`, + v090Resource, v090SourceBackend, v090SourceLocator, resourceLocationHash(v090SourceLocator)); err != nil { + t.Fatalf("retarget source resource locator: %v", err) + } + + source, err := ExportLibrary(ctx, src, identity) + if err != nil { + t.Fatalf("export 0.9.0 library: %v", err) + } + if source.SchemaVersion != 134 || source.Profile != "v090" { + t.Fatalf("snapshot must record the 0.9.0 profile, got %d/%q", source.SchemaVersion, source.Profile) + } + if tablePresent(source, "wiki_log_entries") { + t.Fatal("0.9.0 export must not produce a wiki_log_entries table") + } + + token := make([]byte, 8) + if _, err := rand.Read(token); err != nil { + t.Fatal(err) + } + index := "kg_v090_publish_" + hex.EncodeToString(token) + client := &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }} + call := func(method, path, body string, want int) { + t.Helper() + request, err := http.NewRequestWithContext(ctx, method, base+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", "application/json") + response, err := client.Do(request) + if err != nil { + t.Fatalf("fixture HTTP: %v", err) + } + defer response.Body.Close() + if response.StatusCode != want { + t.Fatalf("fixture %s %s => %d, want %d", method, path, response.StatusCode, want) + } + } + call("PUT", "/"+index, `{"mappings":{"properties":{"tenant_id":{"type":"long"},"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"chunk_id":{"type":"keyword"},"content":{"type":"text"},"embedding":{"type":"dense_vector","dims":2}}}}`, 200) + defer func() { + call("DELETE", "/"+index, "", 200) + call("HEAD", "/"+index, "", 404) + }() + exporter, err := NewSearchExporter(SearchExporterConfig{BaseURL: base, Index: index, PageSize: 100, HTTPClient: client}) + if err != nil { + t.Fatalf("search exporter: %v", err) + } + mappingSHA, err := exporter.MappingSHA256(ctx) + if err != nil { + t.Fatalf("index mapping digest: %v", err) + } + + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + archive, err := librarysnapshot.Open(root, 64<<20) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + objectBytes := []byte("fixture-object-bytes") + objects := v090ObjectBytes{"oss|" + v090SourceLocator: objectBytes} + contract := librarysnapshot.Compatibility{ + WeKnoraVersion: "v0.9.0", SchemaVersion: 134, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "bge-m3", + EmbeddingDimension: 1024, IndexMappingSHA256: mappingSHA, + } + sealed, err := ArchiveLibraryCandidate(ctx, archive, "internal", identity, contract, source, + v090PublishIndexSnapshot(t, source, mappingSHA), objects, time.Now().UTC()) + if err != nil { + t.Fatalf("seal 0.9.0 archive: %v", err) + } + manifest, err := archive.Load(sealed) + if err != nil { + t.Fatalf("load sealed manifest: %v", err) + } + for _, part := range manifest.Parts { + if part.Name == "wiki_log_entries" { + t.Fatal("0.9.0 archive must not contain a wiki_log_entries part") + } + } + + // 目标库:干净 134 schema + KB/模型绑定 + 目标存储后端(桶名用于解析定位符)。 + if err := seedV090Target(t, ctx, dst); err != nil { + t.Fatalf("seed target binding: %v", err) + } + store := newMemoryObjectStore(nil) + target, err := NewProductionLibraryTarget(ctx, ProductionLibraryConfig{ + Postgres: os.Getenv("KG_V090_TARGET_DSN"), SearchURL: base, SearchIndex: index, + Objects: store, ObjectsReader: store, ArchiveRoot: root, + ObjectsBucket: v090TargetBucket, MaxDocuments: 100, HTTPClient: client, + }, ProductionScope{TenantID: v090TargetTenant, KnowledgeBaseID: v090TargetKB}) + if err != nil { + t.Fatalf("target: %v", err) + } + defer target.Close() + + backups, err := NewProductionBackupStore(ProductionBackupConfig{ + Pool: target.Pool(), Search: target.Search(), Objects: store, ArchiveRoot: root, + Scope: "internal", Identity: target.Identity(), MaxDocuments: 100, Compatibility: contract, + }) + if err != nil { + t.Fatalf("backup store: %v", err) + } + + // 现状:真实 Current() 必须在 134 上可用,且不得去查 0.9.0 里不存在的 wiki_log_entries。 + before, err := target.Current(ctx) + if err != nil { + t.Fatalf("current target state on 0.9.0: %v", err) + } + if _, present := before.Counts["wiki_log_entries"]; present { + t.Fatalf("0.9.0 target state must not include wiki_log_entries: %+v", before.Counts) + } + backup, err := backups.Prepare(ctx, sealed, before) + if err != nil { + t.Fatalf("prepare before-image: %v", err) + } + backup.WriteSet = planLedgerWithUniverse(t, target, sealed, backup.SnapshotID, backup.Universe) + + for _, stage := range libraryrelease.Stages() { + if err := target.Apply(ctx, stage, sealed); err != nil { + t.Fatalf("apply %s on 0.9.0 target: %v", stage, err) + } + } + if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: sealed}); err != nil { + t.Fatalf("verify after 0.9.0 publish: %v", err) + } + + assertV090Published(t, ctx, dst, target, source) + + // 跨版本必须拒绝,并且错误同时点名两个版本号。用另一个没有冻结计划的目标实例: + // 已接管写集合的执行目标会先被"快照与计划不符"挡住,那不是版本闸门。 + legacy := sealTargetFixture(t, archive, "internal", []string{"doc-safe"}, []string{"chunk-safe"}, "wiki-safe") + legacyTarget, err := NewProductionLibraryTarget(ctx, ProductionLibraryConfig{ + Postgres: os.Getenv("KG_V090_TARGET_DSN"), SearchURL: base, SearchIndex: index, + Objects: store, ObjectsReader: store, ArchiveRoot: root, + ObjectsBucket: v090TargetBucket, MaxDocuments: 100, HTTPClient: client, + }, ProductionScope{TenantID: v090TargetTenant, KnowledgeBaseID: v090TargetKB}) + if err != nil { + t.Fatalf("legacy target: %v", err) + } + defer legacyTarget.Close() + err = legacyTarget.Apply(ctx, libraryrelease.StageDatabase, legacy) + if err == nil || !strings.Contains(err.Error(), "74") || !strings.Contains(err.Error(), "134") { + t.Fatalf("cross-version publish must be refused naming both versions, got %v", err) + } + if err := legacyTarget.Verify(ctx, libraryrelease.Expectation{SnapshotID: legacy}); err == nil || + !strings.Contains(err.Error(), "74") || !strings.Contains(err.Error(), "134") { + t.Fatalf("cross-version verify must be refused naming both versions, got %v", err) + } + + // 写前镜像恢复:目标必须回到写之前的样子(0.9.0 表集合)。 + if err := target.Restore(ctx, backup); err != nil { + t.Fatalf("restore from before-image: %v", err) + } + if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: backup.SnapshotID}); err != nil { + t.Fatalf("verify after restore: %v", err) + } + for _, table := range []string{"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations", + "wiki_pages", "wiki_folders", "wiki_page_issues"} { + statement := `SELECT count(*) FROM ` + table + ` WHERE tenant_id=$1 AND knowledge_base_id=$2` + args := []any{v090TargetTenant, v090TargetKB} + if table == "knowledge_tag_relations" { + // 关系表没有租户/知识库列:归属只能走父表。 + statement = `SELECT count(*) FROM knowledge_tag_relations r WHERE r.knowledge_id IN + (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)` + } + var count int64 + if err := dst.QueryRow(ctx, statement, args...).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 0 { + t.Fatalf("rollback left %d rows in %s", count, table) + } + } + var restoredResource int64 + if err := dst.QueryRow(ctx, `SELECT count(*) FROM resources WHERE tenant_id=$1`, v090TargetTenant).Scan(&restoredResource); err != nil { + t.Fatal(err) + } + if restoredResource != 0 { + t.Fatalf("rollback left %d published resources in the target tenant", restoredResource) + } + t.Logf("v0.9.0 publish verified: snapshot=%s backup=%s bytes=%d", sealed, backup.SnapshotID, backup.Bytes) +} + +// assertV090Published 逐表核对目标与来源内容一致(身份列走目标隔离映射,不作为内容比对)。 +func assertV090Published(t *testing.T, ctx context.Context, dst *pgxpool.Pool, target *ProductionLibraryTarget, source PostgresSnapshot) { + t.Helper() + wantChunks := int64(source.Table("chunks").RowCount) + var chunks int64 + if err := dst.QueryRow(ctx, `SELECT count(*) FROM chunks WHERE tenant_id=$1 AND knowledge_base_id=$2`, + v090TargetTenant, v090TargetKB).Scan(&chunks); err != nil { + t.Fatal(err) + } + if chunks != wantChunks || chunks < 2 { + t.Fatalf("chunks in target = %d, want %d", chunks, wantChunks) + } + // 目标隔离映射:写入的是目标身份,不是来源身份。 + for _, chunkID := range []string{v090ChunkOne, v090ChunkTwo} { + var content string + if err := dst.QueryRow(ctx, `SELECT content FROM chunks WHERE id=$1`, + expectedTargetID(v090TargetTenant, v090TargetKB, "chunks", chunkID)).Scan(&content); err != nil { + t.Fatalf("mapped chunk %s missing: %v", chunkID, err) + } + if content == "" { + t.Fatalf("mapped chunk %s has empty content", chunkID) + } + } + // 0.9.0 新增 NOT NULL 列走目标默认值;seq_id 由目标序列分配(来源值不得搬过来)。 + var defaults, assigned int64 + if err := dst.QueryRow(ctx, `SELECT count(*) FROM chunks WHERE tenant_id=$1 AND knowledge_base_id=$2 + AND source_content IS NOT NULL AND content_revision IS NOT NULL AND index_status IS NOT NULL + AND context_header IS NOT NULL AND last_editor_id IS NOT NULL AND seq_id IS NOT NULL`, + v090TargetTenant, v090TargetKB).Scan(&defaults); err != nil { + t.Fatal(err) + } + if defaults != wantChunks { + t.Fatalf("0.9.0 NOT NULL columns unsatisfied on %d/%d chunks", defaults, wantChunks) + } + if err := dst.QueryRow(ctx, `SELECT count(DISTINCT seq_id) FROM chunks WHERE tenant_id=$1 AND knowledge_base_id=$2`, + v090TargetTenant, v090TargetKB).Scan(&assigned); err != nil { + t.Fatal(err) + } + if assigned != wantChunks { + t.Fatalf("target seq_id must be assigned per chunk, got %d distinct for %d chunks", assigned, wantChunks) + } + + // Wiki 必须非空:空表通过等于没验证 wiki 部件。 + var pages int64 + var content, slug string + if err := dst.QueryRow(ctx, `SELECT count(*) FROM wiki_pages WHERE tenant_id=$1 AND knowledge_base_id=$2`, + v090TargetTenant, v090TargetKB).Scan(&pages); err != nil { + t.Fatal(err) + } + if pages != 1 { + t.Fatalf("wiki_pages in target = %d, want 1", pages) + } + if err := dst.QueryRow(ctx, `SELECT content, slug FROM wiki_pages WHERE id=$1`, + expectedTargetID(v090TargetTenant, v090TargetKB, "wiki_pages", v090Page)).Scan(&content, &slug); err != nil { + t.Fatalf("published wiki page missing: %v", err) + } + if content != "wiki 正文" || slug != "fixture-page" { + t.Fatalf("wiki page content changed: content=%q slug=%q", content, slug) + } + + var tags int64 + if err := dst.QueryRow(ctx, `SELECT count(*) FROM knowledge_tags WHERE tenant_id=$1 AND knowledge_base_id=$2 AND name='夹具标签'`, + v090TargetTenant, v090TargetKB).Scan(&tags); err != nil { + t.Fatal(err) + } + if tags != 1 { + t.Fatalf("knowledge_tags in target = %d, want 1", tags) + } + + var title, model string + if err := dst.QueryRow(ctx, `SELECT title, embedding_model_id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2`, + v090TargetTenant, v090TargetKB).Scan(&title, &model); err != nil { + t.Fatalf("published knowledge missing: %v", err) + } + if title != "0.9.0 夹具" || model != "bge-m3-v090" { + t.Fatalf("knowledge content changed: title=%q model=%q", title, model) + } + + // 资源必须指向目标桶/后端,且定位符哈希按最终路径重算。 + wantLocator := "storage://" + v090TargetBackend + "/minio://" + v090TargetBucket + "/" + + strconv.FormatUint(v090TargetTenant, 10) + "/" + v090Resource + "/kn.bin" + var provider, backend, locator, locationHash string + var size int64 + if err := dst.QueryRow(ctx, `SELECT provider, coalesce(storage_backend_id,''), physical_path, location_hash, size + FROM resources WHERE tenant_id=$1`, v090TargetTenant). + Scan(&provider, &backend, &locator, &locationHash, &size); err != nil { + t.Fatalf("published resource missing: %v", err) + } + if provider != "minio" || backend != v090TargetBackend { + t.Fatalf("resource must point at the target backend: provider=%q backend=%q", provider, backend) + } + if locator != wantLocator { + t.Fatalf("resource locator not retargeted:\n got %s\nwant %s", locator, wantLocator) + } + if locationHash != resourceLocationHash(wantLocator) { + t.Fatalf("resource location_hash must hash the target locator") + } + if size != int64(len("fixture-object-bytes")) { + t.Fatalf("resource size changed: %d", size) + } + // 目标对象存储里必须真的有这份字节(写入阶段按目标定位符上传)。 + if _, err := target.Objects().Open(ctx, provider, locator); err != nil { + t.Fatalf("published object unreadable in target store: %v", err) + } +} + +// v090PublishIndexSnapshot 按导出分块合成索引快照:这批文档走的是与线上同一套 +// 映射/摘要校验,不能凭空绕过。 +func v090PublishIndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA string) SearchSnapshot { + t.Helper() + var documents []SearchDocument + for _, raw := range pg.Table("chunks").Rows { + var chunk struct { + ID string `json:"id"` + TenantID uint64 `json:"tenant_id"` + KnowledgeBaseID string `json:"knowledge_base_id"` + KnowledgeID string `json:"knowledge_id"` + Content string `json:"content"` + } + if err := json.Unmarshal(raw, &chunk); err != nil { + t.Fatalf("decode chunk: %v", err) + } + source, err := json.Marshal(map[string]any{ + "chunk_id": chunk.ID, "tenant_id": chunk.TenantID, + "knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID, + "content": chunk.Content, "source_id": chunk.ID, "source_type": 0, + "embedding": []float64{0.1, 0.2}, + }) + if err != nil { + t.Fatalf("encode index document: %v", err) + } + documents = append(documents, SearchDocument{ID: "doc-" + chunk.ID, Source: source}) + } + digest, err := searchDocumentsDigest(documents) + if err != nil { + t.Fatalf("index digest: %v", err) + } + return SearchSnapshot{Documents: documents, MappingSHA256: mappingSHA, DocumentsSHA256: digest} +} + +// seedV090Target 在目标库造 KB/模型绑定与目标存储后端:发布写的是内容行,不是 KB 定义。 +func seedV090Target(t *testing.T, ctx context.Context, db *pgxpool.Pool) error { + t.Helper() + for _, statement := range []string{ + `INSERT INTO models(id,tenant_id,name,type,source,parameters) + VALUES ('bge-m3-v090',$1,'bge-m3','embedding','local','{"embedding_parameters":{"dimension":1024}}'::jsonb)`, + `INSERT INTO knowledge_bases(id,name,tenant_id,embedding_model_id,summary_model_id,indexing_strategy) + VALUES ('` + v090TargetKB + `','v090 publish target',$1,'bge-m3-v090','bge-m3-v090','{"graph_enabled":false}'::jsonb)`, + `INSERT INTO storage_backends(id,tenant_id,name,provider,config) + VALUES ('` + v090TargetBackend + `',$1,'v090 target','minio','{"bucket_name":"` + v090TargetBucket + `"}'::jsonb)`, + } { + if _, err := db.Exec(ctx, strings.ReplaceAll(statement, "$1", strconv.Itoa(v090TargetTenant))); err != nil { + return err + } + } + return nil +} diff --git a/internal/releaseadapter/v071/library_profile_v090_integration_test.go b/internal/releaseadapter/v071/library_profile_v090_integration_test.go new file mode 100644 index 0000000..05956ee --- /dev/null +++ b/internal/releaseadapter/v071/library_profile_v090_integration_test.go @@ -0,0 +1,182 @@ +package v071 + +import ( + "context" + "encoding/json" + "os" + "sort" + "strings" + "testing" + "time" + + "knowledge-governance/internal/librarysnapshot" +) + +// v090MappingDigest 读真实抓下来的 0.9.0 映射(KG_V090_MAPPING_JSON)。 +func v090MappingDigest(t *testing.T) string { + t.Helper() + path := os.Getenv("KG_V090_MAPPING_JSON") + if path == "" { + t.Skip("requires KG_V090_MAPPING_JSON pointing at the captured 0.9.0 index mapping") + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read KG_V090_MAPPING_JSON: %v", err) + } + digest, err := IndexMappingDigest(raw) + if err != nil { + t.Fatalf("mapping digest: %v", err) + } + return digest +} + +// TestV090LibraryRoundTripIsolated 走完整 0.9.0 往返: +// 导出 → 封存(真实 manifest 校验)→ 导入干净 134 schema → 再导出逐行比对。 +func TestV090LibraryRoundTripIsolated(t *testing.T) { + ctx := context.Background() + src := v090Pool(t, "KG_V090_SOURCE_DSN") + identity := seedV090(t, ctx, src) + mappingSHA := v090MappingDigest(t) + + source, err := ExportLibrary(ctx, src, identity) + if err != nil { + t.Fatalf("export 0.9.0 library: %v", err) + } + if source.SchemaVersion != 134 || source.Profile != "v090" { + t.Fatalf("snapshot must record the 0.9.0 profile, got %d/%q", source.SchemaVersion, source.Profile) + } + // 0.9.0 没有 wiki_log_entries:不允许出现该表,也不允许空 Wiki 冒充通过。 + if tablePresent(source, "wiki_log_entries") { + t.Fatal("0.9.0 export must not produce a wiki_log_entries table") + } + if source.Table("wiki_pages").RowCount < 1 || source.Table("wiki_folders").RowCount < 1 { + t.Fatalf("wiki parts must be non-empty: pages=%d folders=%d", + source.Table("wiki_pages").RowCount, source.Table("wiki_folders").RowCount) + } + if source.Table("chunks").RowCount < 2 || source.Table("knowledges").RowCount != 1 { + t.Fatalf("unexpected fixture shape: chunks=%d knowledges=%d", + source.Table("chunks").RowCount, source.Table("knowledges").RowCount) + } + + es := v090IndexSnapshot(t, source, mappingSHA) + root := t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + archive, err := librarysnapshot.Open(root, 64<<20) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + contract := librarysnapshot.Compatibility{ + WeKnoraVersion: "v0.9.0", SchemaVersion: 134, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "bge-m3", + EmbeddingDimension: 1024, IndexMappingSHA256: mappingSHA, + } + sealed, err := ArchiveLibraryCandidate(ctx, archive, "internal", identity, contract, source, es, + v090Objects{"fixture/kn-v090.bin": []byte("fixture-object-bytes")}, time.Now().UTC()) + if err != nil { + t.Fatalf("seal 0.9.0 archive: %v", err) + } + manifest, err := archive.Load(sealed) + if err != nil { + t.Fatalf("load sealed manifest: %v", err) + } + if manifest.Compatibility.SchemaVersion != 134 || manifest.Compatibility.WeKnoraVersion != "v0.9.0" { + t.Fatalf("manifest must record the 0.9.0 profile, got %+v", manifest.Compatibility) + } + for _, part := range manifest.Parts { + if part.Kind == "wiki" && part.Name == "wiki_log_entries" { + t.Fatal("0.9.0 archive must not contain a wiki_log_entries part") + } + } + + dst := v090Pool(t, "KG_V090_TARGET_DSN") + if err := seedV090Binding(t, ctx, dst); err != nil { + t.Fatalf("seed target binding: %v", err) + } + importer, err := NewPostgresImporter(dst) + if err != nil { + t.Fatal(err) + } + document := PostgresIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: v090Knowledge} + if err := importer.Replace(ctx, document, source); err != nil { + t.Fatalf("import 0.9.0 snapshot: %v", err) + } + reloaded, err := ExportLibrary(ctx, dst, identity) + if err != nil { + t.Fatalf("re-export imported library: %v", err) + } + compareSnapshotContent(t, source, reloaded) + + // 0.9.0 新增的 NOT NULL 列在导入后必须仍是合法值,且 seq_id 由目标序列分配。 + var defaults int + if err := dst.QueryRow(ctx, `SELECT count(*) FROM chunks + WHERE source_content IS NOT NULL AND content_revision IS NOT NULL + AND index_status IS NOT NULL AND context_header IS NOT NULL + AND last_editor_id IS NOT NULL AND seq_id IS NOT NULL`).Scan(&defaults); err != nil { + t.Fatal(err) + } + if defaults != source.Table("chunks").RowCount { + t.Fatalf("0.9.0 NOT NULL columns must be satisfied on every imported chunk: got %d want %d", + defaults, source.Table("chunks").RowCount) + } + var distinctSeq int + if err := dst.QueryRow(ctx, `SELECT count(DISTINCT seq_id) FROM chunks`).Scan(&distinctSeq); err != nil { + t.Fatal(err) + } + if distinctSeq != source.Table("chunks").RowCount { + t.Fatalf("target chunk seq_id must be assigned, got %d distinct", distinctSeq) + } + + // 跨版本必须拒绝:0.7.1 归档不能落到 0.9.0 目标。 + crossVersion := source + crossVersion.SchemaVersion = 74 + crossVersion.Profile = "v071" + err = importer.Replace(ctx, document, crossVersion) + if err == nil || !strings.Contains(err.Error(), "74") || !strings.Contains(err.Error(), "134") { + t.Fatalf("cross-version import must be refused with both versions named, got %v", err) + } +} + +// compareSnapshotContent 逐表逐行比对"共有列"的规范化内容。 +// chunks.seq_id 是库级序列值、不是文档内容,导入时由目标分配,故排除比对。 +func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) { + t.Helper() + if len(source.Tables) != len(target.Tables) { + t.Fatalf("table set changed across round trip: %d -> %d", len(source.Tables), len(target.Tables)) + } + for _, table := range source.Tables { + want := tableDigests(t, table.Name, table.Rows) + got := tableDigests(t, table.Name, target.Table(table.Name).Rows) + if table.RowCount != target.Table(table.Name).RowCount || len(want) != len(got) { + t.Fatalf("%s row count changed: %d -> %d", table.Name, len(want), len(got)) + } + for index := range want { + if want[index] != got[index] { + t.Fatalf("%s row %d content changed across round trip", table.Name, index) + } + } + } +} + +func tableDigests(t *testing.T, name string, rows []json.RawMessage) []string { + t.Helper() + digests := make([]string, 0, len(rows)) + for _, raw := range rows { + var row map[string]json.RawMessage + if err := json.Unmarshal(raw, &row); err != nil { + t.Fatalf("decode %s row: %v", name, err) + } + if name == "chunks" { + delete(row, "seq_id") + } + digest, err := canonicalRowDigest(row) + if err != nil { + t.Fatalf("digest %s row: %v", name, err) + } + digests = append(digests, digest) + } + sort.Strings(digests) + return digests +} diff --git a/internal/releaseadapter/v071/library_question_index_test.go b/internal/releaseadapter/v071/library_question_index_test.go index 217efe2..a1afd6a 100644 --- a/internal/releaseadapter/v071/library_question_index_test.go +++ b/internal/releaseadapter/v071/library_question_index_test.go @@ -32,10 +32,10 @@ func TestLibraryCandidateGeneratedQuestionIndex(t *testing.T) { } es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents) err := validateLibraryCandidate(PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, pg, es) - if mode == "complete" && err != nil { + if (mode == "complete" || mode == "missing-body") && err != nil { t.Fatalf("valid persisted question rejected: %v", err) } - if mode != "complete" && err == nil { + if mode != "complete" && mode != "missing-body" && err == nil { t.Fatal("incomplete or inconsistent question index accepted") } }) diff --git a/internal/releaseadapter/v071/library_reference_closure.go b/internal/releaseadapter/v071/library_reference_closure.go new file mode 100644 index 0000000..b23007f --- /dev/null +++ b/internal/releaseadapter/v071/library_reference_closure.go @@ -0,0 +1,151 @@ +package v071 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "regexp" + "sort" + "strings" + + "github.com/jackc/pgx/v5" + "knowledge-governance/internal/libraryprofile" + "knowledge-governance/internal/librarysnapshot" +) + +type libraryClosureReader interface { + QueryRow(context.Context, string, ...any) pgx.Row +} + +// Check edges before JOIN-based export can erase a scoped orphan. Either parent +// can establish scope; an edge is not safe merely because its other parent is absent. +func verifyLibraryRelationalClosure(ctx context.Context, db libraryClosureReader, identity PostgresIdentity, includeDeleted bool) error { + var invalid bool + err := db.QueryRow(ctx, `/* library-relational-closure */ SELECT + EXISTS(SELECT 1 FROM chunks c LEFT JOIN knowledges k ON k.id=c.knowledge_id + WHERE c.tenant_id=$1 AND c.knowledge_base_id=$2 AND ($3 OR c.deleted_at IS NULL) + AND (k.id IS NULL OR k.tenant_id IS DISTINCT FROM c.tenant_id OR k.knowledge_base_id IS DISTINCT FROM c.knowledge_base_id OR (NOT $3 AND k.deleted_at IS NOT NULL))) + OR EXISTS(SELECT 1 FROM knowledge_tag_relations r LEFT JOIN knowledges k ON k.id=r.knowledge_id LEFT JOIN knowledge_tags t ON t.id=r.tag_id + WHERE ((k.tenant_id=$1 AND k.knowledge_base_id=$2 AND ($3 OR k.deleted_at IS NULL)) OR (t.tenant_id=$1 AND t.knowledge_base_id=$2 AND ($3 OR t.deleted_at IS NULL))) + AND (k.id IS NULL OR t.id IS NULL OR k.tenant_id IS DISTINCT FROM t.tenant_id OR k.knowledge_base_id IS DISTINCT FROM t.knowledge_base_id OR (NOT $3 AND (k.deleted_at IS NOT NULL OR t.deleted_at IS NOT NULL)))) + OR EXISTS(SELECT 1 FROM resource_bindings b WHERE b.tenant_id=$1 + AND (EXISTS(SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$1 AND k.knowledge_base_id=$2 AND ($3 OR k.deleted_at IS NULL)) OR EXISTS(SELECT 1 FROM chunks c WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND ($3 OR c.deleted_at IS NULL))) + AND (b.owner_type NOT IN ('knowledge','chunk') OR b.owner_type IS NULL))`, identity.TenantID, identity.KnowledgeBaseID, includeDeleted).Scan(&invalid) + if err != nil { + return fmt.Errorf("read library reference closure: %w", err) + } + if invalid { + return errors.New("unresolved or cross-parent library relationship") + } + return nil +} + +func verifyLibraryResourceOwners(ctx context.Context, db libraryClosureReader, ids []string) error { + var invalid bool + err := db.QueryRow(ctx, `/* library-resource-owner-closure */ SELECT EXISTS( + SELECT 1 FROM resource_bindings b JOIN resources r ON r.id=b.resource_id WHERE r.id=ANY($1::text[]) AND ( + b.tenant_id IS DISTINCT FROM r.tenant_id OR b.owner_type IS NULL OR NOT ( + (b.owner_type='knowledge' AND EXISTS(SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=b.tenant_id)) OR + (b.owner_type='chunk' AND EXISTS(SELECT 1 FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE c.id=b.owner_id AND c.tenant_id=b.tenant_id)))))`, ids).Scan(&invalid) + if err != nil { + return fmt.Errorf("read referenced resource owners: %w", err) + } + if invalid { + return errors.New("referenced resource has unknown or unresolved owner") + } + return nil +} + +var libraryResourceToken = regexp.MustCompile(`resource://([A-Za-z0-9_-]*)`) + +// Decode JSON before scanning string leaves (including nested metadata). The +// v071 reader accepts exactly 22 URL-safe characters, not URI query/path suffixes. +// Opaque escaped/encoded representations are refused rather than silently omitted. +func libraryResourceHandles(rows []json.RawMessage) ([]string, error) { + seen := map[string]bool{} + var visit func(any) error + visit = func(value any) error { + switch v := value.(type) { + case map[string]any: + for _, x := range v { + if e := visit(x); e != nil { + return e + } + } + case []any: + for _, x := range v { + if e := visit(x); e != nil { + return e + } + } + case string: + rest := v + for strings.Contains(rest, "resource:") { + start := strings.Index(rest, "resource:") + rest = rest[start:] + match := libraryResourceToken.FindStringSubmatchIndex(rest) + if match == nil || match[0] != 0 || match[3]-match[2] != 22 { + return errors.New("unsupported resource reference representation") + } + if match[1] < len(rest) && strings.ContainsRune("/?#=%\\", rune(rest[match[1]])) { + return errors.New("unsupported resource reference suffix") + } + seen[rest[match[2]:match[3]]] = true + rest = rest[match[1]:] + } + } + return nil + } + for _, raw := range rows { + var value any + decoder := json.NewDecoder(strings.NewReader(string(raw))) + decoder.UseNumber() + if e := decoder.Decode(&value); e != nil { + return nil, e + } + if e := visit(value); e != nil { + return nil, e + } + } + handles := make([]string, 0, len(seen)) + for handle := range seen { + handles = append(handles, handle) + } + sort.Strings(handles) + return handles, nil +} + +// Revalidate frozen source content at the actual planning boundary. A sealed +// manifest proves bytes, not that every row has a parent or a supported owner. +func validateArchivedLibraryClosure(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error { + // 快照的 schema 契约来自 manifest:不带上版本号,重建出来的快照就是"版本未知", + // 而未知版本按 0.7.1 校验——0.9.0 的归档会被要求提供它根本没有的 wiki_log_entries。 + pg := PostgresSnapshot{SchemaVersion: manifest.Compatibility.SchemaVersion} + if profile, err := libraryprofile.For(pg.SchemaVersion); err == nil { + pg.Profile = profile.Name + } + es := SearchSnapshot{MappingSHA256: manifest.Compatibility.IndexMappingSHA256} + for _, part := range manifest.Parts { + if part.Kind != "database" && part.Kind != "wiki" && part.Kind != "index" { + continue + } + reader, e := archive.OpenPart(part) + if e != nil { + return e + } + if part.Kind == "index" { + e = json.NewDecoder(reader).Decode(&es.Documents) + } else { + var rows []json.RawMessage + e = json.NewDecoder(reader).Decode(&rows) + pg.Tables = append(pg.Tables, newTableSnapshot(part.Name, rows)) + } + reader.Close() + if e != nil { + return e + } + } + es.DocumentsSHA256, _ = searchDocumentsDigest(es.Documents) + return validateLibraryCandidate(PostgresIdentity{TenantID: manifest.TenantID, KnowledgeBaseID: manifest.KnowledgeBaseID}, pg, es) +} diff --git a/internal/releaseadapter/v071/library_residue.go b/internal/releaseadapter/v071/library_residue.go index b692c38..f3c7d0d 100644 --- a/internal/releaseadapter/v071/library_residue.go +++ b/internal/releaseadapter/v071/library_residue.go @@ -152,8 +152,8 @@ func (t *ProductionLibraryTarget) ClearForeignScope(ctx context.Context, source return report, nil } // 删除顺序:子表先、父表后(resource_bindings → resources,chunks → knowledges)。 - for index := len(productionLibraryTables) - 1; index >= 0; index-- { - table := productionLibraryTables[index] + for index := len(t.tables) - 1; index >= 0; index-- { + table := t.tables[index] ids, ok := identities[table] if !ok || len(ids) == 0 { continue @@ -216,7 +216,7 @@ func (t *ProductionLibraryTarget) legacyResourceRow(row map[string]json.RawMessa // VerifyResidueCleared 复核清理结果:来源身份不再存在、其它租户的解释得清、 // 且(可选)目标内容与预备份完全一致。 func (t *ProductionLibraryTarget) VerifyResidueCleared(ctx context.Context, source ProductionScope) error { - for _, table := range productionLibraryTables { + for _, table := range t.tables { if !tableHasTenant(table) { continue } @@ -240,7 +240,7 @@ func (t *ProductionLibraryTarget) VerifyResidueCleared(ctx context.Context, sour // ForeignScopes 列出目标里所有"不是目标租户"的租户,用于人工确认没有别的泄漏。 func (t *ProductionLibraryTarget) ForeignScopes(ctx context.Context) (map[string]string, error) { foreign := map[string]string{} - for _, table := range productionLibraryTables { + for _, table := range t.tables { if !tableHasTenant(table) { continue } @@ -272,7 +272,7 @@ func (t *ProductionLibraryTarget) foreignScopeRows(ctx context.Context, table st if !tableHasTenant(table) { return nil, nil } - statement := fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`, table, table, scopeWhere(table)) + statement := fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`, table, table, t.scopeWhere(table)) arguments := []any{source.TenantID, source.KnowledgeBaseID} if table == "resources" || table == "resource_bindings" { statement = fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE tenant_id=$1`, table, table) diff --git a/internal/releaseadapter/v071/library_resource_fk.go b/internal/releaseadapter/v071/library_resource_fk.go new file mode 100644 index 0000000..a512b17 --- /dev/null +++ b/internal/releaseadapter/v071/library_resource_fk.go @@ -0,0 +1,34 @@ +package v071 + +import ( + "context" + "errors" + "github.com/jackc/pgx/v5" +) + +type resourceGrantQuery interface { + QueryRow(context.Context, string, ...any) pgx.Row +} + +// Grants are an external FK, not part of the migration archive. Deleting a +// resource would silently cascade a capability owned outside this operation. +func ensureNoResourceGrants(ctx context.Context, q resourceGrantQuery, ids []string) error { + if len(ids) == 0 { + return nil + } + var present bool + if err := q.QueryRow(ctx, `SELECT to_regclass('public.resource_access_grants') IS NOT NULL`).Scan(&present); err != nil { + return err + } + if !present { + return nil + } + var referenced bool + if err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM public.resource_access_grants WHERE resource_id=ANY($1::text[]))`, ids).Scan(&referenced); err != nil { + return err + } + if referenced { + return errors.New("created resource has external access grants; refusing cascade and object deletion") + } + return nil +} diff --git a/internal/releaseadapter/v071/library_resource_fk_test.go b/internal/releaseadapter/v071/library_resource_fk_test.go new file mode 100644 index 0000000..7d9a708 --- /dev/null +++ b/internal/releaseadapter/v071/library_resource_fk_test.go @@ -0,0 +1,65 @@ +package v071 + +import ( + "knowledge-governance/internal/libraryrelease" + "testing" +) + +func TestContractResourceGrantHoldsRestoreBeforeObjectDeleteIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, err := fx.pool.Exec(fx.ctx, `CREATE TABLE resource_access_grants(id text PRIMARY KEY,resource_id text NOT NULL REFERENCES resources(id) ON DELETE CASCADE)`); err != nil { + t.Fatal(err) + } + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "succeeded" { + t.Fatalf("publication: %+v", outcome) + } + if _, err := fx.pool.Exec(fx.ctx, `INSERT INTO resource_access_grants VALUES('after-publication','res-src')`); err != nil { + t.Fatal(err) + } + before := universeDump(t, fx.pool) + exactBefore := r10State(t, fx) + if err := target.Restore(fx.ctx, outcome.Backup); err == nil { + t.Fatal("external grant allowed destructive restore") + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("grant-protected restore changed PG: %s", diff) + } + r10Unchanged(t, fx, exactBefore) + var grantCount int + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM resource_access_grants WHERE id='after-publication'`).Scan(&grantCount); err != nil || grantCount != 1 { + t.Fatal("grant changed across held restore", err) + } + r10Save(t, "grant-readback", grantCount) + for _, object := range outcome.Backup.WriteSet.Objects { + if object.ResourceID == "res-src" { + got, err := fx.objects.s3.ObserveObject(fx.ctx, object.Provider, object.Locator) + if err != nil || !got.Exists || got.SHA256 != object.SHA256 { + t.Fatalf("grant-protected object lost: %v", err) + } + } + } +} + +func TestContractResourceGrantBlocksCreatedResourceCleanupIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, err := fx.pool.Exec(fx.ctx, `CREATE TABLE resource_access_grants(id text PRIMARY KEY,resource_id text NOT NULL REFERENCES resources(id) ON DELETE CASCADE); INSERT INTO resources(id,tenant_id,handle) VALUES('protected-created',10001,'GrantProtectedResource'); INSERT INTO resource_access_grants VALUES('foreign-grant','protected-created')`); err != nil { + t.Fatal(err) + } + set := libraryrelease.WriteSet{Rows: []libraryrelease.WriteSetRow{{Table: "resources", ID: "protected-created"}}} + target := fx.target(t) + if err := target.clearJobCreatedRows(fx.ctx, set, map[string]map[string]bool{}); err == nil { + t.Error("cleanup cascaded external grant instead of holding recovery") + } + var grants, resources int + if err := fx.pool.QueryRow(fx.ctx, `SELECT (SELECT count(*) FROM resource_access_grants WHERE id='foreign-grant'),(SELECT count(*) FROM resources WHERE id='protected-created')`).Scan(&grants, &resources); err != nil { + t.Fatal(err) + } + if grants != 1 || resources != 1 { + t.Fatalf("external FK protection lost: grants=%d resources=%d", grants, resources) + } +} diff --git a/internal/releaseadapter/v071/library_resource_references.go b/internal/releaseadapter/v071/library_resource_references.go new file mode 100644 index 0000000..c90a29d --- /dev/null +++ b/internal/releaseadapter/v071/library_resource_references.go @@ -0,0 +1,77 @@ +package v071 + +import ( + "context" + "errors" + "fmt" + "strings" + + "knowledge-governance/internal/libraryrelease" +) + +// Keep capture/verification and deletion protection on the same set of bodies. +// predicate is an internal SQL fragment, never caller-supplied content; tables comes +// from the resolved schema profile (0.9.0 has no wiki_log_entries to scan). +func libraryResourceBodyReferenceSQL(tables []string, predicate string) string { + queries := []string{} + for _, table := range tables { + if table == "resources" || table == "resource_bindings" || table == "knowledge_tag_relations" { + continue + } + queries = append(queries, fmt.Sprintf(`SELECT 1 FROM %s c WHERE (%s) AND coalesce(resources.handle,'')<>'' AND position('resource://'||resources.handle IN to_jsonb(c)::text)>0`, table, predicate)) + } + return strings.Join(queries, " UNION ALL ") +} + +// This must precede *all* restore mutations, including ES and object deletes. +// A created row is not permission to invalidate a later out-of-plan reader. +func ensureRestorableResourceReferences(ctx context.Context, q libraryClosureReader, tables []string, set libraryrelease.WriteSet) error { + ids := set.CreatedIDs("resources") + if len(ids) == 0 { + return nil + } + if e := verifyLibraryResourceOwners(ctx, q, ids); e != nil { + return e + } + bindings := []string{} + for _, row := range set.Rows { + if row.Table == "resource_bindings" { + bindings = append(bindings, row.ID) + } + } + var referenced bool + err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM resource_bindings b WHERE b.resource_id=ANY($1::text[]) AND + (NOT(b.id=ANY($2::text[])) OR b.tenant_id IS DISTINCT FROM $3 OR NOT ( + (b.owner_type='knowledge' AND EXISTS(SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$3 AND k.knowledge_base_id=$4)) OR + (b.owner_type='chunk' AND EXISTS(SELECT 1 FROM chunks c WHERE c.id=b.owner_id AND c.tenant_id=$3 AND c.knowledge_base_id=$4)))))`, ids, bindings, set.TenantID, set.KnowledgeBaseID).Scan(&referenced) + if err != nil { + return err + } + if referenced { + return errors.New("created resource has out-of-plan bindings; restore held before writes") + } + bodySQL := libraryResourceBodyReferenceSQL(tables, "c.tenant_id IS DISTINCT FROM $2 OR c.knowledge_base_id IS DISTINCT FROM $3") + err = q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM resources WHERE id=ANY($1::text[]) AND EXISTS (`+bodySQL+`))`, ids, set.TenantID, set.KnowledgeBaseID).Scan(&referenced) + if err != nil { + return err + } + if referenced { + return errors.New("created resource has foreign body/metadata references; restore held before writes") + } + return nil +} + +// Recheck under the already-held resource parent locks. This does not claim +// cross-store isolation from uncontrolled writers; deployed exclusivity is separate. +func ensureCreatedResourcesUnreferenced(ctx context.Context, q libraryClosureReader, tables, ids []string) error { + var referenced bool + err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM resources WHERE id=ANY($1::text[]) AND + (EXISTS(SELECT 1 FROM resource_bindings b WHERE b.resource_id=resources.id) OR EXISTS (`+libraryResourceBodyReferenceSQL(tables, "TRUE")+`)))`, ids).Scan(&referenced) + if err != nil { + return err + } + if referenced { + return errors.New("created resource is still referenced; refusing row deletion") + } + return nil +} diff --git a/internal/releaseadapter/v071/library_resource_scope_f01_test.go b/internal/releaseadapter/v071/library_resource_scope_f01_test.go new file mode 100644 index 0000000..ee8bc83 --- /dev/null +++ b/internal/releaseadapter/v071/library_resource_scope_f01_test.go @@ -0,0 +1,123 @@ +package v071 + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// F01 regression: a small target library inside a large tenant must resolve +// resources from exact binding ids + body handles, not by scanning every +// tenant resource with a per-row body predicate. The fixture has one active +// target document/chunk (plus one deleted and one foreign-tenant row), not the +// historical 4/38 target; the 20,000 unrelated resources are the scale input. +// The old predicate is kept only as an oracle for equality and timing. +func TestLibraryResourceClosureIsBoundedByTargetReferences(t *testing.T) { + dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database") + } + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + t.Fatal("isolated database required") + } + ctx := context.Background() + db, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err = db.Exec(ctx, `DROP SCHEMA public CASCADE; CREATE SCHEMA public`); err != nil { + t.Fatal(err) + } + if _, err = db.Exec(ctx, libraryTestSchema); err != nil { + t.Fatal(err) + } + if _, err = db.Exec(ctx, `CREATE INDEX resources_handle_f01 ON resources(handle); CREATE INDEX resources_pkey_f01 ON resources(id);`); err != nil { + t.Fatal(err) + } + const unrelated = 20000 + if _, err = db.Exec(ctx, `INSERT INTO resources(id,handle,tenant_id,physical_path,deleted_at) + SELECT 'unrelated-'||i, lpad(i::text,22,'0'), 10000, 'unrelated/'||i, NULL FROM generate_series(1,$1) i`, unrelated); err != nil { + t.Fatal(err) + } + // A body-only reference must still be found without a binding row. + if _, err = db.Exec(ctx, `INSERT INTO resources(id,handle,tenant_id,physical_path,deleted_at) + VALUES ('res-body','BBBBBBBBBBBBBBBBBBBBBB',10000,'body.txt',NULL); + UPDATE chunks SET content='see resource://BBBBBBBBBBBBBBBBBBBBBB' WHERE id='chunk-safe'`); err != nil { + t.Fatal(err) + } + identity := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"} + + start := time.Now() + oldRows, err := db.Query(ctx, fmt.Sprintf(`SELECT to_jsonb(resources)::text FROM resources WHERE %s`, scopeWhere("resources")), + identity.TenantID, identity.KnowledgeBaseID) + if err != nil { + t.Fatal(err) + } + oldIDs := []string{} + for oldRows.Next() { + var raw string + if err := oldRows.Scan(&raw); err != nil { + oldRows.Close() + t.Fatal(err) + } + var row struct { + ID string `json:"id"` + } + if err := json.Unmarshal([]byte(raw), &row); err != nil { + oldRows.Close() + t.Fatal(err) + } + oldIDs = append(oldIDs, row.ID) + } + oldRows.Close() + oldElapsed := time.Since(start) + + start = time.Now() + snapshot, err := ExportLibrary(ctx, db, identity) + if err != nil { + t.Fatal(err) + } + newElapsed := time.Since(start) + newIDs := []string{} + for _, raw := range snapshot.Table("resources").Rows { + var row struct { + ID string `json:"id"` + } + if err := json.Unmarshal(raw, &row); err != nil { + t.Fatal(err) + } + newIDs = append(newIDs, row.ID) + } + if fmt.Sprint(oldIDs) != fmt.Sprint(newIDs) { + t.Fatalf("resource closure changed: old=%v new=%v", oldIDs, newIDs) + } + var bodies []json.RawMessage + for _, table := range snapshot.Tables { + bodies = append(bodies, table.Rows...) + } + handles, handleErr := libraryResourceHandles(bodies) + t.Logf("old_ids=%v new_ids=%v handles=%v handle_err=%v", oldIDs, newIDs, handles, handleErr) + if len(newIDs) != 2 { + t.Fatalf("expected bound + body-only resources, got %v", newIDs) + } + var activeDocs, activeChunks int + if err := db.QueryRow(ctx, `SELECT count(*) FROM knowledges WHERE tenant_id=10000 AND knowledge_base_id='kb-safe' AND deleted_at IS NULL`).Scan(&activeDocs); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(ctx, `SELECT count(*) FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id WHERE k.tenant_id=10000 AND k.knowledge_base_id='kb-safe' AND k.deleted_at IS NULL AND c.deleted_at IS NULL`).Scan(&activeChunks); err != nil { + t.Fatal(err) + } + t.Logf("target_docs=%d target_chunks=%d unrelated_resources=%d old_scan=%s new_export=%s resources=%v", + activeDocs, activeChunks, unrelated, oldElapsed, newElapsed, newIDs) + if newElapsed >= oldElapsed { + t.Fatalf("F01 path did not improve: old=%s new=%s", oldElapsed, newElapsed) + } +} diff --git a/internal/releaseadapter/v071/library_restore_target_identity.go b/internal/releaseadapter/v071/library_restore_target_identity.go new file mode 100644 index 0000000..dcb2789 --- /dev/null +++ b/internal/releaseadapter/v071/library_restore_target_identity.go @@ -0,0 +1,56 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" +) + +// 恢复派发只接受"实际目标"的身份:租户/KB、目标库(服务器+库名)、索引名与索引 +// UUID、对象桶。它们用于识别"同名但被重建/替换"的目标,让旧绑定无法复用;它们不是 +// 历史未发送的证明,也不构成 ES 端 fence。 +func (t *ProductionLibraryTarget) observeRestoreTarget(ctx context.Context) (string, string, error) { + if t.pool == nil || t.search == nil { + return "", "", errors.New("restore dispatch requires a live target") + } + var database, address string + var port int + if err := t.pool.QueryRow(ctx, + `SELECT current_database(), COALESCE(host(inet_server_addr()), ''), COALESCE(inet_server_port(), 0)`). + Scan(&database, &address, &port); err != nil { + return "", "", fmt.Errorf("read target database identity: %w", err) + } + if database == "" { + return "", "", errors.New("target database identity is empty") + } + indexUUID, err := t.search.IndexUUID(ctx) + if err != nil { + return "", "", fmt.Errorf("read target index uuid: %w", err) + } + joined := strings.Join([]string{ + "v1", fmt.Sprintf("%d", t.scope.TenantID), t.scope.KnowledgeBaseID, + database, address, fmt.Sprintf("%d", port), t.config.SearchIndex, indexUUID, t.config.ObjectsBucket, + }, "\x00") + sum := sha256.Sum256([]byte(joined)) + return hex.EncodeToString(sum[:]), indexUUID, nil +} + +// frozenRestoreTarget 在一个 Restore 调用内冻结实际目标身份;后续每次重建绑定都 +// 重新观察并与冻结值比较。目标/索引在恢复中途被替换时立即失败,而不是继续用旧绑定。 +func (t *ProductionLibraryTarget) frozenRestoreTarget(ctx context.Context) (string, string, error) { + fingerprint, indexUUID, err := t.observeRestoreTarget(ctx) + if err != nil { + return "", "", err + } + if t.restoreFingerprint == "" { + t.restoreFingerprint, t.restoreIndexUUID = fingerprint, indexUUID + return fingerprint, indexUUID, nil + } + if fingerprint != t.restoreFingerprint || indexUUID != t.restoreIndexUUID { + return "", "", fmt.Errorf("%w: 目标/索引身份在恢复过程中发生变化", ErrProductionTargetUnconfigured) + } + return t.restoreFingerprint, t.restoreIndexUUID, nil +} diff --git a/internal/releaseadapter/v071/library_reuse.go b/internal/releaseadapter/v071/library_reuse.go new file mode 100644 index 0000000..53236bf --- /dev/null +++ b/internal/releaseadapter/v071/library_reuse.go @@ -0,0 +1,458 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "time" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// 资源复用证据:目标里已经有这个资源 ID、但它不在预备份范围内时,唯一安全的 +// 处理是证明"本次要写的那一行/那一份对象字节,已经原样存在于目标里"。 +// +// 为什么不能按"没人引用"推断归属:历史孤儿、同租户另一个知识库暂未绑定的资源 +// 同样没人引用;按它放行等于允许覆盖别人的数据。这里的证据必须同时满足三件事: +// 1. 有可审计的持久来源(治理库里这个目标成功同步过的快照或它自己的预备份, +// 且同一资源行内容一致); +// 2. 整行内容(除易变时间戳外)与本次写入将要落地的行完全一致; +// 3. 该资源的对象字节与本次快照归档摘要一致。 +// +// 证据独立落盘(reuse/.json),摘要写进写集合行;它不冒充历史写集合—— +// 那两次没有 writeset 的成功作业依然没有 writeset。 + +const ( + reuseDirName = "reuse" + reuseEvidenceVersion = 1 + reuseEvidenceNoPrior = 3 + resourceReuseTableName = "resources" +) + +// reuseObject 是一个资源对象的字节证据:归档摘要 + 目标现状必须匹配。 +type reuseObject struct { + Name string `json:"name"` + Path string `json:"path"` + Bytes int64 `json:"bytes"` + SHA256 string `json:"sha256"` +} + +// ResourceReuseEvidence 是"这一行可以复用"的完整证据文档。 +// Digest 覆盖除自己以外的全部内容:被改动就对不上写集合行里的摘要。 +type ResourceReuseEvidence struct { + Version int `json:"version"` + JobID string `json:"job_id"` + Target string `json:"target"` + TenantID uint64 `json:"tenant_id"` + KnowledgeBaseID string `json:"knowledge_base_id"` + SourceTenantID uint64 `json:"source_tenant_id"` + SourceKnowledgeBaseID string `json:"source_knowledge_base_id"` + TargetSnapshotID string `json:"target_snapshot_id"` + ResourceID string `json:"resource_id"` + // ArchivedRowDigest 是来源快照里那一行(不含易变时间戳)的摘要。 + ArchivedRowDigest string `json:"archived_row_digest"` + // RetargetedRowDigest 是同一行按本次目标范围/存储改写后的摘要。 + RetargetedRowDigest string `json:"retargeted_row_digest"` + // TargetRowDigest 是目标现状按归档列投影后的摘要:必须与上一条一致。 + TargetRowDigest string `json:"target_row_digest"` + // ProvenanceJobID / ProvenanceSnapshotID 指向一次**已成功**的同步作业及 + // 它当时写入目标的快照;ProvenanceRowDigest 是那份快照里同一行的摘要。 + ProvenanceJobID string `json:"provenance_job_id"` + ProvenanceSnapshotID string `json:"provenance_snapshot_id"` + ProvenanceKind string `json:"provenance_kind"` + ProvenanceRowDigest string `json:"provenance_row_digest"` + Objects []reuseObject `json:"objects,omitempty"` + CreatedAt time.Time `json:"created_at"` + Digest string `json:"digest"` +} + +func reusePath(archiveRoot, digest string) string { + return filepath.Join(archiveRoot, reuseDirName, digest+".json") +} + +// Seal 规范化并写入摘要;字段顺序由 json.Marshal 的结构体顺序固定。 +func (e *ResourceReuseEvidence) Seal() error { + copied := *e + copied.Digest = "" + raw, err := json.Marshal(copied) + if err != nil { + return fmt.Errorf("编码复用证据失败: %w", err) + } + sum := sha256.Sum256(raw) + e.Digest = hex.EncodeToString(sum[:]) + return nil +} + +// Verify 校验版本、必备身份与摘要;缺任何一项都不许拿它去放行覆盖。 +func (e *ResourceReuseEvidence) Verify() error { + if e.Version != reuseEvidenceVersion && e.Version != 2 && e.Version != reuseEvidenceNoPrior { + return fmt.Errorf("复用证据版本 %d 不受支持(当前 %d)", e.Version, reuseEvidenceVersion) + } + if e.JobID == "" || e.Target == "" || e.TargetSnapshotID == "" || e.ResourceID == "" { + return errors.New("复用证据缺少作业/目标/快照/资源身份") + } + // v3:目标首次复用,本目标没有历史成功同步/预备份来源。归属改由 + // “目标行 == 本次映射行”与“对象字节 == 归档对象”证明,不再要求 provenance。 + // v1/v2 仍必须是完整历史来源,旧证据语义不变。 + if e.Version != reuseEvidenceNoPrior && + (e.ProvenanceJobID == "" || e.ProvenanceSnapshotID == "" || e.ProvenanceKind == "") { + return errors.New("复用证据缺少作业/目标/快照/来源身份") + } + if e.TenantID == 0 || e.KnowledgeBaseID == "" || e.SourceTenantID == 0 || e.SourceKnowledgeBaseID == "" { + return errors.New("复用证据缺少范围身份") + } + // 三份行摘要必须一致:来源行、映射后的行、目标现状是同一份内容。 + if e.RetargetedRowDigest == "" || e.TargetRowDigest != e.RetargetedRowDigest { + return errors.New("复用证据里目标行与本次要写的行不一致") + } + if e.Version == 1 && e.ProvenanceRowDigest != e.ArchivedRowDigest { + return errors.New("复用证据里的来源行与本次快照行不一致") + } + if e.Version == 2 && (e.ProvenanceKind != libraryrelease.PriorSnapshotPrebackup || e.ProvenanceRowDigest != e.RetargetedRowDigest) { + return errors.New("prebackup reuse proof differs from target projection") + } + if e.Version == reuseEvidenceNoPrior && (e.ProvenanceJobID != "" || e.ProvenanceSnapshotID != "" || e.ProvenanceKind != "" || + len(e.Objects) == 0) { + return errors.New("无历史来源的复用证据不能夹带历史身份,且必须有对象字节证据") + } + copied := *e + copied.Digest = "" + raw, err := json.Marshal(copied) + if err != nil { + return err + } + sum := sha256.Sum256(raw) + if hex.EncodeToString(sum[:]) != e.Digest { + return errors.New("复用证据摘要不符(内容被改动或截断)") + } + return nil +} + +// PersistReuseEvidence 按内容寻址落盘(只读、幂等)。同摘要已存在时校验后直接返回。 +func PersistReuseEvidence(archiveRoot string, evidence *ResourceReuseEvidence) (string, error) { + if evidence.Digest == "" { + if err := evidence.Seal(); err != nil { + return "", err + } + } + if evidence.Digest == "" { + return "", errors.New("复用证据没有摘要,拒绝落盘") + } + if err := evidence.Verify(); err != nil { + return "", err + } + raw, err := json.Marshal(*evidence) + if err != nil { + return "", err + } + path := reusePath(archiveRoot, evidence.Digest) + if err := persistImmutableJSON(path, raw); err != nil { + return "", err + } + return path, nil +} + +// LoadReuseEvidence 取回并校验证据;摘要或绑定对不上就失败。 +func LoadReuseEvidence(archiveRoot, digest string) (*ResourceReuseEvidence, error) { + if digest == "" { + return nil, errors.New("没有复用证据摘要") + } + raw, err := os.ReadFile(reusePath(archiveRoot, digest)) + if err != nil { + return nil, fmt.Errorf("复用证据缺失(%s)", digest) + } + var evidence ResourceReuseEvidence + if err := json.Unmarshal(raw, &evidence); err != nil { + return nil, errors.New("复用证据不可解析") + } + if err := evidence.Verify(); err != nil { + return nil, err + } + if evidence.Digest != digest { + return nil, errors.New("复用证据摘要不符") + } + return &evidence, nil +} + +// archivedRowByID 从归档部件里读出指定身份的行(原样,不改写)。 +func archivedRowByID(archive *librarysnapshot.Archive, part librarysnapshot.Part, id string) (map[string]json.RawMessage, error) { + reader, err := archive.OpenPart(part) + if err != nil { + return nil, fmt.Errorf("读取归档 %s 失败", part.Name) + } + defer reader.Close() + decoder := json.NewDecoder(reader) + token, err := decoder.Token() + if err != nil || token != json.Delim('[') { + return nil, fmt.Errorf("归档 %s 不是行数组", part.Name) + } + for decoder.More() { + var row map[string]json.RawMessage + if err := decoder.Decode(&row); err != nil { + return nil, fmt.Errorf("解析归档 %s 行失败", part.Name) + } + var identity string + if json.Unmarshal(row["id"], &identity) == nil && identity == id { + return row, nil + } + } + return nil, nil +} + +// targetResourceRow 读出目标里这一行;不存在返回 nil。 +func (t *ProductionLibraryTarget) targetResourceRow(ctx context.Context, id string) (map[string]json.RawMessage, error) { + var raw map[string]json.RawMessage + err := t.pool.QueryRow(ctx, `SELECT to_jsonb(r) FROM resources r WHERE r.id=$1 AND r.tenant_id=$2`, + id, t.scope.TenantID).Scan(&raw) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + return nil, fmt.Errorf("读取目标资源 %s 失败", id) + } + return raw, nil +} + +// cloneRow 复制一行,避免改写归档缓存/调用方数据。 +func cloneRow(row map[string]json.RawMessage) map[string]json.RawMessage { + copied := make(map[string]json.RawMessage, len(row)) + for key, value := range row { + copied[key] = value + } + return copied +} + +// projectRow 只保留给定列集合里的列:目标行比归档多出的默认列不参与比对。 +func projectRow(row map[string]json.RawMessage, columns map[string]bool) map[string]json.RawMessage { + projected := make(map[string]json.RawMessage, len(columns)) + for key := range columns { + if value, ok := row[key]; ok { + projected[key] = value + } + } + return projected +} + +// targetObjectSHA256 读取目标对象的实际字节并返回大小与摘要。 +func (t *ProductionLibraryTarget) targetObjectSHA256(ctx context.Context, provider, path string) (int64, string, error) { + if t.config.ObjectsReader == nil { + return 0, "", errors.New("缺少目标对象读取器,无法证明对象字节一致") + } + reader, err := t.config.ObjectsReader.Open(ctx, provider, path) + if err != nil { + return 0, "", err + } + defer reader.Close() + hash := sha256.New() + size, err := io.Copy(hash, reader) + if err != nil { + return 0, "", err + } + return size, hex.EncodeToString(hash.Sum(nil)), nil +} + +// resourceLocatorField 解析改写后的资源行里的定位符与提供方(与写入/校验同一口径)。 +func resourceLocatorField(row map[string]json.RawMessage) (provider, path string, err error) { + if err := json.Unmarshal(row["provider"], &provider); err != nil { + return "", "", errors.New("资源行提供方不可解析") + } + if err := json.Unmarshal(row["physical_path"], &path); err != nil || path == "" { + return "", "", errors.New("资源行定位符不可解析") + } + return provider, path, nil +} + +// provenanceFor 在"这个目标的持久来源"里找同一资源的同一行内容: +// - 成功同步过的快照(说明这个目标先前就把这行写进去过); +// - 这个目标自己的预备份(说明这行本来就是本目标历史状态的一部分)。 +// +// 找不到就说明归属无法证明:即使目标里那行看起来一模一样,也不能覆盖/复用。 +func provenanceFor(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest, targetSnapshotID, + id, archivedDigest string, prior []libraryrelease.PriorSnapshot) (libraryrelease.PriorSnapshot, string, error) { + for _, candidate := range prior { + if candidate.JobID == "" || candidate.SnapshotID == "" { + continue + } + if candidate.SnapshotID == targetSnapshotID { + // 本次要写的快照本身就是一次成功同步写进目标的那一份。 + return candidate, archivedDigest, nil + } + priorManifest, err := archive.Load(candidate.SnapshotID) + if err != nil { + // 来源快照不可读不能当作"没有来源":那会把不可审计变成静默放行。 + return libraryrelease.PriorSnapshot{}, "", fmt.Errorf("复用来源快照 %s 不可读", candidate.SnapshotID) + } + if priorManifest.TenantID != manifest.TenantID || priorManifest.KnowledgeBaseID != manifest.KnowledgeBaseID { + continue + } + var part librarysnapshot.Part + found := false + for _, item := range priorManifest.Parts { + if item.Kind == "database" && item.Name == resourceReuseTableName { + part, found = item, true + break + } + } + if !found { + continue + } + row, err := archivedRowByID(archive, part, id) + if err != nil { + return libraryrelease.PriorSnapshot{}, "", err + } + if row == nil { + continue + } + digest, err := canonicalRowDigest(row) + if err != nil { + return libraryrelease.PriorSnapshot{}, "", err + } + if digest != archivedDigest { + continue + } + return candidate, digest, nil + } + return libraryrelease.PriorSnapshot{}, "", nil +} + +// planReusableResource 是资源冲突的唯一放行路径:内容相同 + 字节相同 + 来源可审计。 +// 返回写集合行(Existing + Reused)并把它登记到本次目标,写入阶段据此跳过这一行。 +func (t *ProductionLibraryTarget) planReusableResource(ctx context.Context, archive *librarysnapshot.Archive, + manifest librarysnapshot.Manifest, part librarysnapshot.Part, id, owner string, + plan libraryrelease.WriteSetPlan) (libraryrelease.WriteSetRow, error) { + archived, err := archivedRowByID(archive, part, id) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + if archived == nil { + return libraryrelease.WriteSetRow{}, fmt.Errorf("资源 %s 在快照 %s 的 resources 部件里找不到", id, plan.TargetSnapshotID) + } + archivedDigest, err := canonicalRowDigest(archived) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + columns := map[string]bool{} + for key := range archived { + columns[key] = true + } + retargeted := cloneRow(archived) + if err := t.retargetRow(resourceReuseTableName, retargeted); err != nil { + return libraryrelease.WriteSetRow{}, err + } + retargetedDigest, err := canonicalRowDigest(retargeted) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + existing, err := t.targetResourceRow(ctx, id) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + if existing == nil { + return libraryrelease.WriteSetRow{}, fmt.Errorf("资源 %s 在目标里已不存在,不能复用", id) + } + targetDigest, err := canonicalRowDigest(projectRow(existing, columns)) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + if targetDigest != retargetedDigest { + return libraryrelease.WriteSetRow{}, fmt.Errorf( + "资源 ID 冲突:%s 已存在于目标租户但内容与本次快照不一致(目标 %s / 本次 %s),拒绝覆盖", + id, shortDigest(targetDigest), shortDigest(retargetedDigest)) + } + provenance, provenanceDigest, err := provenanceFor(archive, manifest, plan.TargetSnapshotID, id, archivedDigest, plan.PriorSnapshots) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + evidenceVersion := reuseEvidenceVersion + backupIDs, backupErr := archivedSnapshotResourceIDs(archive, plan.BackupSnapshotID) + if backupErr != nil { + return libraryrelease.WriteSetRow{}, backupErr + } + if backupIDs[id] { + baseline, err := archive.Load(plan.BackupSnapshotID) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + if baseline.TenantID != t.scope.TenantID || baseline.KnowledgeBaseID != t.scope.KnowledgeBaseID { + return libraryrelease.WriteSetRow{}, errors.New("resource prebackup scope mismatch") + } + for _, p := range baseline.Parts { + if p.Kind != "database" || p.Name != "resources" { + continue + } + row, err := archivedRowByID(archive, p, id) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + digest, err := canonicalRowDigest(projectRow(row, columns)) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + if digest != retargetedDigest { + return libraryrelease.WriteSetRow{}, errors.New("shared resource differs from immutable before-image") + } + provenance = libraryrelease.PriorSnapshot{JobID: plan.JobID, SnapshotID: plan.BackupSnapshotID, Kind: libraryrelease.PriorSnapshotPrebackup} + provenanceDigest = digest + evidenceVersion = 2 + } + } + if provenance.JobID == "" { + // 用户批准:首次同步不要求本目标历史归属。行内容一致已在上方核对; + // 下面仍逐对象核对实际字节,任一不一致即拒绝,且不删/不改旧库资源与绑定。 + evidenceVersion = reuseEvidenceNoPrior + } + provider, path, err := resourceLocatorField(retargeted) + if err != nil { + return libraryrelease.WriteSetRow{}, err + } + objects := make([]reuseObject, 0, 2) + for _, item := range manifest.Parts { + if item.Kind != "resource" || item.Name != id { + continue + } + size, digest, err := t.targetObjectSHA256(ctx, provider, path) + if err != nil { + return libraryrelease.WriteSetRow{}, fmt.Errorf("资源 %s 的对象读不到,无法证明字节一致:%w", id, err) + } + if size != item.Bytes || digest != item.SHA256 { + return libraryrelease.WriteSetRow{}, fmt.Errorf( + "资源 ID 冲突:%s 的目标对象字节与本次快照不一致(%d/%d 字节),拒绝覆盖", + id, size, item.Bytes) + } + objects = append(objects, reuseObject{Name: item.Name, Path: path, Bytes: size, SHA256: digest}) + } + evidence := &ResourceReuseEvidence{ + Version: evidenceVersion, JobID: plan.JobID, Target: plan.Target, + TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID, + SourceTenantID: manifest.TenantID, SourceKnowledgeBaseID: manifest.KnowledgeBaseID, + TargetSnapshotID: plan.TargetSnapshotID, ResourceID: id, + ArchivedRowDigest: archivedDigest, RetargetedRowDigest: retargetedDigest, TargetRowDigest: targetDigest, + ProvenanceJobID: provenance.JobID, ProvenanceSnapshotID: provenance.SnapshotID, ProvenanceKind: provenance.Kind, + ProvenanceRowDigest: provenanceDigest, Objects: objects, CreatedAt: t.now().UTC(), + } + if _, err := PersistReuseEvidence(t.config.ArchiveRoot, evidence); err != nil { + return libraryrelease.WriteSetRow{}, fmt.Errorf("复用证据无法落盘,拒绝放行覆盖:%w", err) + } + if t.reusedResources == nil { + t.reusedResources = map[string]bool{} + } + t.reusedResources[id] = true + return libraryrelease.WriteSetRow{Table: resourceReuseTableName, ID: id, Existing: true, + Owner: owner, Reused: true, ReuseEvidence: evidence.Digest}, nil +} + +func shortDigest(digest string) string { + if len(digest) > 12 { + return digest[:12] + } + return digest +} diff --git a/internal/releaseadapter/v071/library_reuse_integration_test.go b/internal/releaseadapter/v071/library_reuse_integration_test.go new file mode 100644 index 0000000..1589a39 --- /dev/null +++ b/internal/releaseadapter/v071/library_reuse_integration_test.go @@ -0,0 +1,388 @@ +package v071 + +import ( + "reflect" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/libraryrelease" +) + +// 这一组用例覆盖真实缺陷现场:同步 A 成功 → 手工恢复 B(对象保留、资源行不删) +// → 再同步 A。旧预检把"恢复保留下来的、本目标自己上次写进去的资源"判成 +// "其它知识库的同 ID 冲突",整个同步在写第一笔之前被拒。 +// +// 复用的放行条件必须是可审计的证据,而不是"目标里没人引用": +// - 目标现状那一行与本次要写的行逐列相同(除易变时间戳); +// - 该资源的对象字节与本次快照归档摘要一致; +// - 治理库里存在"这个目标成功同步过、且含有同一行内容"的快照/作业。 +// 缺任何一条都必须继续拒绝,且拒绝发生在写入之前。 + +const ( + wsHandleNew = "gggggggggggggggggggggg" + // resNewBody 是"A 的下一次发布"新增资源的内容;与 res-src 的 "12345678" 不同, + // 这样"本次真新建"和"证明可复用"在同一份写集合里能同时被观察到。 + resNewBody = "87654321" +) + +// reusePriors 是治理库会给出的来源清单:一次成功同步 + 它产生的预备份。 +func reusePriors(syncJobID, syncSnapshotID string, prebackups ...string) []libraryrelease.PriorSnapshot { + priors := []libraryrelease.PriorSnapshot{{JobID: syncJobID, SnapshotID: syncSnapshotID, Kind: libraryrelease.PriorSnapshotSync}} + for _, snapshot := range prebackups { + priors = append(priors, libraryrelease.PriorSnapshot{JobID: syncJobID, SnapshotID: snapshot, + Kind: libraryrelease.PriorSnapshotPrebackup}) + } + return priors +} + +func requestForWithPrior(snapshotID, jobID string, prior []libraryrelease.PriorSnapshot) libraryrelease.Request { + request := requestFor(snapshotID) + request.JobID = jobID + request.PriorSnapshots = prior + return request +} + +// syncThenRestore 造出现场:同步 A 成功,然后按生产恢复作业的方式恢复到 A 的 +// 预备份(再走一次 Run:新的预备份 + 它自己的写集合)。恢复不删 resources 表, +// 所以 A 写进去的资源会作为"没人引用的行"留在目标里——正是本次缺陷的前提。 +func syncThenRestore(t *testing.T, fx *writeSetFixture, snapshotID string) (*ProductionLibraryTarget, + *ProductionBackupStore, libraryrelease.Outcome, []libraryrelease.PriorSnapshot) { + t.Helper() + target := fx.target(t) + backups := fx.backups(t, target) + first := libraryrelease.Run(fx.ctx, requestForWithPrior(snapshotID, "job-sync-a", nil), target, backups, nil) + if first.State != "succeeded" { + t.Fatalf("首次同步 A 必须成功:%+v", first) + } + if first.Backup.WriteSet == nil { + t.Fatal("首次同步必须落盘写集合") + } + // 恢复作业同样只认已登记来源:它自己刚拍的那份预备份就是本目标的历史状态。 + restore := libraryrelease.Run(fx.ctx, requestForWithPrior(first.Backup.SnapshotID, "job-restore-b", + reusePriors(first.Backup.WriteSet.JobID, snapshotID, first.Backup.SnapshotID)), target, backups, nil) + if restore.State != "succeeded" { + t.Fatalf("手工恢复 B 必须成功:%+v", restore) + } + var bindings int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM resource_bindings WHERE resource_id='res-src'`).Scan(&bindings); err != nil { + t.Fatal(err) + } + if bindings != 0 { + t.Fatalf("恢复后 res-src 不应还有绑定行(现场前提):%d", bindings) + } + return target, backups, first, reusePriors(first.Backup.WriteSet.JobID, snapshotID, first.Backup.SnapshotID) +} + +// resourceFingerprint 取 PG 行的 xmin 与整行 JSON:xmin 不变才能证明"没有重写这一行"。 +func resourceFingerprint(t *testing.T, pool *pgxpool.Pool, id string) (string, string) { + t.Helper() + var xmin, row string + if err := pool.QueryRow(t.Context(), `SELECT xmin::text, to_jsonb(r)::text FROM resources r WHERE id=$1`, id). + Scan(&xmin, &row); err != nil { + t.Fatalf("读取资源 %s: %v", id, err) + } + return xmin, row +} + +func resourceRowOf(t *testing.T, pool *pgxpool.Pool, id string) string { + t.Helper() + var row string + if err := pool.QueryRow(t.Context(), `SELECT to_jsonb(r)::text FROM resources r WHERE id=$1`, id).Scan(&row); err != nil { + t.Fatalf("读取资源 %s: %v", id, err) + } + return row +} + +func TestLibraryResyncAfterRestoreReusesProvenResourcesIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshotID := sealSourceSnapshot(t, fx, nil) + target, backups, first, priors := syncThenRestore(t, fx, snapshotID) + + beforeXmin, beforeRow := resourceFingerprint(t, fx.pool, "res-src") + // B10:no-op 复用不允许重写对象——精确版本与字节都必须原样。 + reusedObjectPath := wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-src") + objectBeforeReuse, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", reusedObjectPath) + if err != nil || !objectBeforeReuse.Exists { + t.Fatalf("复用对象不存在:%+v %v", objectBeforeReuse, err) + } + orphanBefore := resourceRowOf(t, fx.pool, "res-orphan") + otherBefore := resourceRowOf(t, fx.pool, "res-other") + sharedBefore := resourceRowOf(t, fx.pool, "res-shared") + foreignBefore := resourceRowOf(t, fx.pool, "res-foreign") + + outcome := libraryrelease.Run(fx.ctx, requestForWithPrior(snapshotID, "job-sync-a-again", priors), + target, backups, nil) + if outcome.State != "succeeded" { + t.Fatalf("恢复后再次同步 A 必须完成:%+v", outcome) + } + if outcome.Backup.WriteSet == nil { + t.Fatal("写集合必须落盘") + } + ledger, err := LoadWriteSet(fx.archiveRoot, outcome.Backup.WriteSet.Digest) + if err != nil { + t.Fatalf("写集合记录取不回来:%v", err) + } + reused := ledger.ReusedIDs("resources") + if len(reused) != 1 || reused[0] != "res-src" { + t.Fatalf("复用资源 = %v,want [res-src]", reused) + } + if created := ledger.CreatedIDs("resources"); len(created) != 0 { + t.Fatalf("复用资源不能被记成本次新建(恢复会删掉它):%v", created) + } + var reuseRow libraryrelease.WriteSetRow + for _, row := range ledger.Rows { + if row.Table == "resources" && row.ID == "res-src" { + reuseRow = row + } + } + if !reuseRow.Existing || !reuseRow.Reused || reuseRow.ReuseEvidence == "" { + t.Fatalf("复用行必须带证据摘要并标记为写前已存在:%+v", reuseRow) + } + evidence, err := LoadReuseEvidence(fx.archiveRoot, reuseRow.ReuseEvidence) + if err != nil { + t.Fatalf("复用证据取不回来:%v", err) + } + if evidence.ProvenanceSnapshotID != snapshotID || evidence.ProvenanceJobID != first.Backup.WriteSet.JobID { + t.Fatalf("复用证据没有指向前一次成功同步:%+v", evidence) + } + if evidence.TargetRowDigest != evidence.RetargetedRowDigest || evidence.ProvenanceRowDigest != evidence.ArchivedRowDigest { + t.Fatalf("复用证据的行摘要不一致:%+v", evidence) + } + if len(evidence.Objects) != 1 || evidence.Objects[0].SHA256 == "" { + t.Fatalf("复用证据必须逐个记录对象字节:%+v", evidence.Objects) + } + + // 复用不许改原行:xmin 与整行 JSON 都必须原样。 + afterXmin, afterRow := resourceFingerprint(t, fx.pool, "res-src") + if afterXmin != beforeXmin { + t.Fatalf("复用资源被重写了:xmin %s -> %s", beforeXmin, afterXmin) + } + if afterRow != beforeRow { + t.Fatalf("复用资源内容变了:\n%s\n->\n%s", beforeRow, afterRow) + } + objectAfterReuse, err := fx.objects.s3.ObserveObject(fx.ctx, "minio", reusedObjectPath) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(objectBeforeReuse, objectAfterReuse) { + t.Fatalf("no-op 复用改写了对象版本:%+v -> %+v", objectBeforeReuse, objectAfterReuse) + } + // 历史孤儿/其它知识库/共享/外租户资源一律不许被覆盖。 + for id, want := range map[string]string{"res-orphan": orphanBefore, "res-other": otherBefore, + "res-shared": sharedBefore, "res-foreign": foreignBefore} { + if got := resourceRowOf(t, fx.pool, id); got != want { + t.Fatalf("资源 %s 被改动:\n%s\n->\n%s", id, want, got) + } + } +} + +func TestLibraryResyncAfterRestoreReusesTargetRowWithoutProvenanceIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshotID := sealSourceSnapshot(t, fx, nil) + target, backups, first, _ := syncThenRestore(t, fx, snapshotID) + beforeXmin, beforeRow := resourceFingerprint(t, fx.pool, "res-src") + + // 用户批准:没有本目标历史来源也可以复用,条件退回到“目标行与本次映射行逐列一致 + // + 对象字节与归档一致”。这里的 res-src 是上一次同步写进目标、恢复后留下的行。 + noSource := []libraryrelease.PriorSnapshot{{JobID: first.Backup.WriteSet.JobID, + SnapshotID: first.Backup.SnapshotID, Kind: libraryrelease.PriorSnapshotPrebackup}} + outcome := libraryrelease.Run(fx.ctx, requestForWithPrior(snapshotID, "job-sync-no-provenance", noSource), target, backups, nil) + if outcome.State != "succeeded" { + t.Fatalf("无本目标历史来源、但行与字节一致时必须复用成功:%+v", outcome) + } + if xmin, row := resourceFingerprint(t, fx.pool, "res-src"); xmin != beforeXmin || row != beforeRow { + t.Fatalf("复用不得改写共享资源行:\n%s\n->\n%s", beforeRow, row) + } +} + +func TestLibraryResyncAfterRestoreRejectsReuseWhenContentDiffersIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshotID := sealSourceSnapshot(t, fx, nil) + target, backups, _, priors := syncThenRestore(t, fx, snapshotID) + // 同 ID 同租户,但内容被改过(这里改大小,等价于"另一份文件占了这个 ID")。 + if _, err := fx.pool.Exec(fx.ctx, `UPDATE resources SET size=size+1 WHERE id='res-src'`); err != nil { + t.Fatal(err) + } + changed := resourceRowOf(t, fx.pool, "res-src") + before := universeDump(t, fx.pool) + outcome := libraryrelease.Run(fx.ctx, requestForWithPrior(snapshotID, "job-sync-content-diff", priors), target, backups, nil) + if outcome.State != "failed" { + t.Fatalf("内容不一致必须拒绝:%+v", outcome) + } + if !strings.Contains(outcome.Error, "res-src") || !strings.Contains(outcome.Error, "内容") { + t.Fatalf("拒绝原因必须点名内容不一致:%s", outcome.Error) + } + if resourceRowOf(t, fx.pool, "res-src") != changed { + t.Fatal("被拒绝的同步不许改目标资源") + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("被拒绝的同步不许动目标:%s", diff) + } +} + +// 同租户、同 ID、同内容,来源快照属于另一个知识库:历史归属不再参与放行, +// 但仍必须以“目标行逐列一致 + 对象字节一致”为前提,且不得改写旧库行。 +// 若内容或字节不同,下面的负例必须继续拒绝。 +func TestLibraryReuseAcrossSourceScopeKeepsTargetRowsIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshotID := sealSourceSnapshot(t, fx, nil) + target, backups, _, priors := syncThenRestore(t, fx, snapshotID) + otherSource := sealSourceSnapshotScope(t, fx, wsSourceTenant+1, "kb-source-other", nil, nil) + before := universeDump(t, fx.pool) + outcome := libraryrelease.Run(fx.ctx, requestForWithPrior(otherSource, "job-sync-other-source", priors), target, backups, nil) + if outcome.State != "succeeded" { + t.Fatalf("同内容同字节的跨来源复用应被允许:%+v", outcome) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff == "" { + // 允许成功但必须有实际导入结果;目标已有行可能被保留,不能空跑成功。 + t.Fatal("复用后目标应出现新的导入结果") + } +} + +// 显式注入晚期 Wiki 故障:database/resources 已提交,回滚只清"本次真新建", +// 复用资源与历史孤儿原内容完整保留(xmin 也不变)。 +func TestLibraryHalfWriteRollbackKeepsReusedResourcesIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshotID := sealSourceSnapshot(t, fx, nil) + target, backups, _, priors := syncThenRestore(t, fx, snapshotID) + reuseXmin, reuseRow := resourceFingerprint(t, fx.pool, "res-src") + orphanBefore := resourceRowOf(t, fx.pool, "res-orphan") + + next := sealSourceSnapshotScope(t, fx, wsSourceTenant, wsSourceKB, + func(parts map[string][]map[string]any) { + parts["chunks"] = append(parts["chunks"], map[string]any{"id": "chunk-src-2", "tenant_id": wsSourceTenant, + "knowledge_base_id": wsSourceKB, "knowledge_id": "doc-src", "content": "新增正文 resource://" + wsHandleNew}) + parts["resources"] = append(parts["resources"], map[string]any{"id": "res-new", "handle": wsHandleNew, + "tenant_id": wsSourceTenant, "storage_backend_id": "backend-source", "provider": "oss", + "physical_path": wsLocator("backend-source", "oss", "source-bucket", wsSourceTenant, "res-new"), + "size": int64(len(resNewBody))}) + parts["resource_bindings"] = append(parts["resource_bindings"], map[string]any{"id": "bind-src-2", + "resource_id": "res-new", "tenant_id": wsSourceTenant, "owner_type": "chunk", + "owner_id": "chunk-src-2", "relation": "attachment"}) + + }, map[string]string{"res-new": resNewBody}) + + outcome := libraryrelease.Run(fx.ctx, requestForWithPrior(next, "job-sync-half-write", priors), contractFailWikiTarget{target}, backups, nil) + if outcome.State != "rolled_back" { + t.Fatalf("wiki 半写必须回滚:%+v", outcome) + } + if outcome.FailedAt != libraryrelease.StageWiki { + t.Fatalf("failed_at = %s, want wiki", outcome.FailedAt) + } + ledger := outcome.Backup.WriteSet + if ledger == nil { + t.Fatal("半写作业必须留下写集合") + } + if created := ledger.CreatedIDs("resources"); len(created) != 1 || created[0] != "res-new" { + t.Fatalf("本次真新建的资源 = %v,want [res-new]", created) + } + if reused := ledger.ReusedIDs("resources"); len(reused) != 1 || reused[0] != "res-src" { + t.Fatalf("复用资源 = %v,want [res-src]", reused) + } + // 本次真新建的清干净。 + var residue int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM resources WHERE id='res-new'`).Scan(&residue); err != nil { + t.Fatal(err) + } + if residue != 0 { + t.Fatal("回滚后本次新建的资源必须被清理") + } + // 复用资源与历史孤儿原内容(含 xmin)保留。 + afterXmin, afterRow := resourceFingerprint(t, fx.pool, "res-src") + if afterXmin != reuseXmin || afterRow != reuseRow { + t.Fatalf("回滚动了复用资源:xmin %s->%s\n%s\n->\n%s", reuseXmin, afterXmin, reuseRow, afterRow) + } + if resourceRowOf(t, fx.pool, "res-orphan") != orphanBefore { + t.Fatal("回滚动了历史孤儿资源") + } + if err := target.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: outcome.Backup.SnapshotID}); err != nil { + t.Fatalf("回滚必须与预备份一致:%v", err) + } +} + +// 新目标库首次同步:本目标没有任何历史成功同步/预备份来源,但同 tenant 的 +// 另一个知识库已经绑定了一个 ID、整行内容与对象字节都完全相同的资源。 +// 用户已批准取消"必须有本目标历史来源"这一自加门槛;仍须保留旧库行/绑定/对象, +// 且内容不同或字节不同必须继续拒绝。 +func TestLibraryFirstSyncReusesResourceOwnedByOtherKBIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + // 同 tenant 另一个 KB 的文档 + 资源 + 绑定;res-src 与源快照同 ID 同内容。 + otherDoc := "doc-first-other" + statements := []string{ + `INSERT INTO knowledges VALUES('` + otherDoc + `',10001,'` + wsOtherKB + `','completed',0,'',NULL)`, + `INSERT INTO resources VALUES('res-src','` + wsHandleSource + `',10001,'` + wsLocator("backend-target", "minio", wsBucket, 10001, "res-src") + `',NULL,'minio',8,'backend-target')`, + `INSERT INTO resource_bindings VALUES('bind-first-other',10001,'res-src','knowledge','` + otherDoc + `',NULL)`, + } + for _, statement := range statements { + if _, err := fx.pool.Exec(fx.ctx, statement); err != nil { + t.Fatalf("seed other-KB resource: %v\n%s", err, statement) + } + } + if err := fx.objects.s3.Put(fx.ctx, "minio", wsLocator("backend-target", "minio", wsBucket, 10001, "res-src"), + strings.NewReader("12345678"), 8); err != nil { + t.Fatal(err) + } + beforeXmin, beforeRow := resourceFingerprint(t, fx.pool, "res-src") + snapshotID := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + outcome := libraryrelease.Run(fx.ctx, requestForWithPrior(snapshotID, "job-first-no-provenance", nil), target, backups, nil) + if outcome.State != "succeeded" { + t.Fatalf("首次同步必须完成(无本目标历史来源,但同 tenant 同内容资源可复用):%+v", outcome) + } + if xmin, row := resourceFingerprint(t, fx.pool, "res-src"); xmin != beforeXmin || row != beforeRow { + t.Fatalf("复用不得改写共享资源行:\n%s\n->\n%s", beforeRow, row) + } + var binding int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM resource_bindings WHERE id='bind-first-other' AND resource_id='res-src'`).Scan(&binding); err != nil || binding != 1 { + t.Fatalf("旧库绑定必须保留:%d %v", binding, err) + } + var targetDocs int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE knowledge_base_id=$1 AND id<>$2`, + wsTargetKB, otherDoc).Scan(&targetDocs); err != nil || targetDocs == 0 { + t.Fatalf("目标 KB 必须完成导入:%d %v", targetDocs, err) + } +} + +// 首次同步复用仍必须核对实际对象字节:行投影一致、但目标对象字节不同 -> 拒绝, +// 且不得改写资源行/绑定或留下写入。 +func TestLibraryFirstSyncRejectsReuseWhenObjectBytesDifferIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + otherDoc := "doc-byte-other" + statements := []string{ + `INSERT INTO knowledges VALUES('` + otherDoc + `',10001,'` + wsOtherKB + `','completed',0,'',NULL)`, + `INSERT INTO resources VALUES('res-src','` + wsHandleSource + `',10001,'` + wsLocator("backend-target", "minio", wsBucket, 10001, "res-src") + `',NULL,'minio',8,'backend-target')`, + `INSERT INTO resource_bindings VALUES('bind-byte-other',10001,'res-src','knowledge','` + otherDoc + `',NULL)`, + } + for _, statement := range statements { + if _, err := fx.pool.Exec(fx.ctx, statement); err != nil { + t.Fatalf("seed: %v", err) + } + } + if err := fx.objects.s3.Put(fx.ctx, "minio", wsLocator("backend-target", "minio", wsBucket, 10001, "res-src"), + strings.NewReader("87654321"), 8); err != nil { + t.Fatal(err) + } + beforeXmin, beforeRow := resourceFingerprint(t, fx.pool, "res-src") + before := universeDump(t, fx.pool) + snapshotID := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + outcome := libraryrelease.Run(fx.ctx, requestForWithPrior(snapshotID, "job-byte-diff", nil), target, backups, nil) + if outcome.State != "failed" || !strings.Contains(outcome.Error, "字节") { + t.Fatalf("对象字节不同必须拒绝:%+v", outcome) + } + if xmin, row := resourceFingerprint(t, fx.pool, "res-src"); xmin != beforeXmin || row != beforeRow { + t.Fatal("拒绝时不得改写共享资源行") + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("拒绝时不得写入目标:%s", diff) + } +} diff --git a/internal/releaseadapter/v071/library_schema_contract.go b/internal/releaseadapter/v071/library_schema_contract.go new file mode 100644 index 0000000..f7b5308 --- /dev/null +++ b/internal/releaseadapter/v071/library_schema_contract.go @@ -0,0 +1,243 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + + "github.com/jackc/pgx/v5" + "knowledge-governance/internal/libraryprofile" + "knowledge-governance/internal/librarysnapshot" +) + +type migrationCatalog map[string]json.RawMessage + +// Catalog capture is read-only. Sequence *definitions*, not mutable last_value, +// belong in the fingerprint; allocating a number must not look like DDL drift. +func (t *ProductionLibraryTarget) migrationCatalog(ctx context.Context) (migrationCatalog, string, error) { + tx, err := t.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}) + if err != nil { + return nil, "", err + } + defer tx.Rollback(context.WithoutCancel(ctx)) + catalog, digest, err := captureMigrationCatalogFor(ctx, tx, t.tables) + if err != nil { + return nil, "", err + } + if err := tx.Commit(ctx); err != nil { + return nil, "", err + } + return catalog, digest, nil +} + +// captureMigrationCatalog 是 0.7.1(既有表集合)的入口,行为保持不变。 +func captureMigrationCatalog(ctx context.Context, tx pgx.Tx) (migrationCatalog, string, error) { + return captureMigrationCatalogFor(ctx, tx, productionLibraryTables) +} + +// captureMigrationCatalogFor 按 profile 解析出的表集合取定义:0.9.0 没有 +// wiki_log_entries,用固定清单会让整库编目在第一张不存在的表上失败。 +// Source rows and their definitions must come from the same read-only transaction. +func captureMigrationCatalogFor(ctx context.Context, tx pgx.Tx, tables []string) (migrationCatalog, string, error) { + queries := map[string]string{ + "columns": `SELECT c.relname AS table_name,a.attname AS column_name,format_type(a.atttypid,a.atttypmod) AS type,a.attnotnull AS not_null,a.attidentity AS identity,a.attgenerated AS generated,coalesce(pg_get_expr(d.adbin,d.adrelid),'') AS default_expr FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum WHERE n.nspname='public' AND c.relname=ANY($1) AND a.attnum>0 AND NOT a.attisdropped ORDER BY c.relname,a.attnum`, + "constraints": `SELECT ns.nspname AS namespace,c.relname AS table_name,x.conname AS name,x.contype AS type,pg_get_constraintdef(x.oid) AS definition,coalesce(r.relname,'') AS referenced_table,coalesce(rns.nspname,'') AS referenced_namespace FROM pg_constraint x JOIN pg_class c ON c.oid=x.conrelid JOIN pg_namespace ns ON ns.oid=c.relnamespace LEFT JOIN pg_class r ON r.oid=x.confrelid LEFT JOIN pg_namespace rns ON rns.oid=r.relnamespace WHERE (ns.nspname='public' AND c.relname=ANY($1)) OR (rns.nspname='public' AND r.relname=ANY($1)) ORDER BY ns.nspname,c.relname,x.conname`, + "indexes": `SELECT c.relname AS table_name,ic.relname AS name,i.indisunique AS unique_index,i.indisvalid AS valid,pg_get_indexdef(i.indexrelid) AS definition,coalesce(pg_get_expr(i.indpred,i.indrelid),'') AS predicate FROM pg_index i JOIN pg_class c ON c.oid=i.indrelid JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_class ic ON ic.oid=i.indexrelid WHERE n.nspname='public' AND c.relname=ANY($1) ORDER BY c.relname,ic.relname`, + "triggers": `SELECT c.relname AS table_name,g.tgname AS name,pg_get_triggerdef(g.oid) AS definition FROM pg_trigger g JOIN pg_class c ON c.oid=g.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=ANY($1) AND NOT g.tgisinternal ORDER BY c.relname,g.tgname`, + "relations": `SELECT c.relname AS table_name,c.relkind::text AS kind,c.relispartition AS partition,c.relrowsecurity AS row_security,EXISTS(SELECT 1 FROM pg_inherits i WHERE i.inhrelid=c.oid OR i.inhparent=c.oid) AS inherits FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=ANY($1) ORDER BY c.relname`, + "sequences": `SELECT c.relname AS table_name,a.attname AS column_name,coalesce(s.seqrelid::regclass::text,'') AS sequence,s.seqstart,s.seqincrement,s.seqmin,s.seqmax,s.seqcache,s.seqcycle,coalesce(own.deptype::text,'') AS ownership FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum LEFT JOIN pg_depend dep ON dep.classid='pg_attrdef'::regclass AND dep.objid=d.oid AND dep.refclassid='pg_class'::regclass AND EXISTS(SELECT 1 FROM pg_sequence sq WHERE sq.seqrelid=dep.refobjid) LEFT JOIN pg_depend own ON own.refclassid='pg_class'::regclass AND own.refobjid=c.oid AND own.refobjsubid=a.attnum AND own.classid='pg_class'::regclass AND own.deptype IN ('a','i') AND EXISTS(SELECT 1 FROM pg_sequence sq WHERE sq.seqrelid=own.objid) LEFT JOIN pg_sequence s ON s.seqrelid=coalesce(dep.refobjid,own.objid) WHERE n.nspname='public' AND c.relname=ANY($1) AND a.attnum>0 AND NOT a.attisdropped AND (s.seqrelid IS NOT NULL OR a.attname='seq_id' OR (c.relname='wiki_log_entries' AND a.attname='id')) ORDER BY c.relname,a.attname,s.seqrelid`, + } + catalog := migrationCatalog{} + for key, query := range queries { + var raw []byte + if err := tx.QueryRow(ctx, "SELECT coalesce(jsonb_agg(to_jsonb(q)),'[]'::jsonb) FROM ("+query+") q", tables).Scan(&raw); err != nil { + return nil, "", fmt.Errorf("capture migration catalog %s: %w", key, err) + } + catalog[key] = raw + } + raw, err := json.Marshal(catalog) + if err != nil { + return nil, "", err + } + hash := sha256.Sum256(raw) + return catalog, hex.EncodeToString(hash[:]), nil +} + +func validateMigrationCatalog(catalog migrationCatalog) error { + profile, err := libraryprofile.For(libraryprofile.LegacyVersion) + if err != nil { + return err + } + return validateMigrationCatalogFor(catalog, productionLibraryTables, profile) +} + +func validateMigrationCatalogFor(catalog migrationCatalog, tables []string, profile libraryprofile.Profile) error { + var triggers []struct { + Table string `json:"table_name"` + Name string `json:"name"` + Definition string `json:"definition"` + } + if err := json.Unmarshal(catalog["triggers"], &triggers); err != nil { + return err + } + // 触发器 = 写一行还会改别的表。只接受 profile 里逐字核对过的定义, + // 且它们必须真实存在:消失了说明这也不是我们审过的那份 schema。 + reviewed := map[string]bool{} + for _, definition := range profile.ReviewedTriggers { + reviewed[definition] = true + } + seen := map[string]bool{} + for _, trigger := range triggers { + if !reviewed[trigger.Definition] { + return fmt.Errorf("unreviewed migration trigger %s on %s", trigger.Name, trigger.Table) + } + seen[trigger.Definition] = true + } + for definition := range reviewed { + if !seen[definition] { + return errors.New("reviewed migration trigger is missing from this schema version") + } + } + var relations []struct { + Table string `json:"table_name"` + Kind string `json:"kind"` + Partition bool `json:"partition"` + RLS bool `json:"row_security"` + Inherits bool `json:"inherits"` + } + if err := json.Unmarshal(catalog["relations"], &relations); err != nil { + return err + } + if len(relations) != len(tables) { + return errors.New("incomplete migration table catalog") + } + for _, r := range relations { + if r.Kind != "r" || r.Partition || r.RLS || r.Inherits { + return fmt.Errorf("unsupported migration relation: %s", r.Table) + } + } + var constraints []struct { + Namespace string `json:"namespace"` + Table string `json:"table_name"` + Type string `json:"type"` + Referenced string `json:"referenced_table"` + ReferencedNamespace string `json:"referenced_namespace"` + Definition string `json:"definition"` + } + if err := json.Unmarshal(catalog["constraints"], &constraints); err != nil { + return err + } + for _, c := range constraints { + if c.Type != "f" { + continue + } + // Internal-table membership does not prove the referenced identity survives + // local-number remapping. v071 has exactly these reviewed FK contracts. + if !(c.Namespace == "public" && c.ReferencedNamespace == "public" && + (c.Table == "resource_bindings" || c.Table == "resource_access_grants") && c.Referenced == "resources" && + c.Definition == "FOREIGN KEY (resource_id) REFERENCES resources(id) ON DELETE CASCADE") { + return fmt.Errorf("unreviewed incoming migration FK: %s.%s", c.Namespace, c.Table) + } + } + return nil +} + +func (t *ProductionLibraryTarget) preflightMigrationCatalog(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) (string, error) { + catalog, digest, err := t.migrationCatalog(ctx) + if err != nil { + return "", err + } + if err := validateMigrationCatalogFor(catalog, t.tables, t.schema.Profile); err != nil { + return "", err + } + var columns []struct { + Table string `json:"table_name"` + Column string `json:"column_name"` + Type string `json:"type"` + Generated string `json:"generated"` + Identity string `json:"identity"` + } + if err := json.Unmarshal(catalog["columns"], &columns); err != nil { + return "", err + } + allowed := map[string]map[string]string{} + for _, c := range columns { + if c.Generated != "" || c.Identity != "" { + return "", fmt.Errorf("unsupported generated/identity column: %s.%s", c.Table, c.Column) + } + if allowed[c.Table] == nil { + allowed[c.Table] = map[string]string{} + } + allowed[c.Table][c.Column] = c.Type + } + for _, part := range manifest.Parts { + if part.Kind == "schema" { + if part.Name != "migration-catalog" || part.SHA256 != digest { + return "", errors.New("captured source/target schema catalog mismatch") + } + reader, err := archive.OpenPart(part) + if err != nil { + return "", err + } + reader.Close() + continue + } + if part.Kind != "database" && part.Kind != "wiki" { + continue + } + reader, err := archive.OpenPart(part) + if err != nil { + return "", err + } + var rows []map[string]json.RawMessage + err = json.NewDecoder(reader).Decode(&rows) + reader.Close() + if err != nil { + return "", err + } + contract := migrationIdentityContracts[part.Name] + for _, row := range rows { + for name := range row { + if _, ok := allowed[part.Name][name]; !ok { + return "", fmt.Errorf("source column absent from target contract: %s.%s", part.Name, name) + } + } + if contract.LocalColumn != "" && allowed[part.Name][contract.LocalColumn] != "" { + if allowed[part.Name][contract.LocalColumn] != "bigint" { + return "", fmt.Errorf("local column type mismatch: %s.%s", part.Name, contract.LocalColumn) + } + if _, err := positiveBigint(row[contract.LocalColumn]); err != nil { + return "", fmt.Errorf("missing/invalid source local number: %s.%s", part.Name, contract.LocalColumn) + } + } + } + } + raw, err := json.Marshal(catalog) + if err != nil { + return "", err + } + if err := persistImmutableJSON(t.config.ArchiveRoot+"/catalogs/"+digest+".json", raw); err != nil { + return "", err + } + return digest, nil +} + +func (t *ProductionLibraryTarget) verifyPlanSchema(ctx context.Context) error { + if t.activePlan == nil { + return nil + } + if t.activePlan.SchemaDigest == "" { + return errors.New("persisted execution plan lacks schema fingerprint") + } + _, digest, err := t.migrationCatalog(ctx) + if err != nil { + return err + } + if digest != t.activePlan.SchemaDigest { + return errors.New("target schema changed after immutable plan") + } + return nil +} diff --git a/internal/releaseadapter/v071/library_schema_contract_test.go b/internal/releaseadapter/v071/library_schema_contract_test.go new file mode 100644 index 0000000..56f091c --- /dev/null +++ b/internal/releaseadapter/v071/library_schema_contract_test.go @@ -0,0 +1,32 @@ +package v071 + +import ( + "knowledge-governance/internal/libraryrelease" + "testing" +) + +func TestContractUnknownSchemaEffectsRefusedIsolated(t *testing.T) { + for _, kind := range []string{"trigger", "incoming-cascade"} { + t.Run(kind, func(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + sql := `CREATE FUNCTION unexpected_hook() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END $$; CREATE TRIGGER unexpected_write BEFORE INSERT ON chunks FOR EACH ROW EXECUTE FUNCTION unexpected_hook()` + if kind == "incoming-cascade" { + sql = `CREATE TABLE unrelated_audit(id text, knowledge_id text REFERENCES knowledges(id) ON DELETE CASCADE); INSERT INTO unrelated_audit VALUES('protected','doc-target')` + } + if _, err := fx.pool.Exec(fx.ctx, sql); err != nil { + t.Fatal(err) + } + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + result := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if result.State != "failed" || result.FailedAt != "" { + t.Fatalf("unreviewed schema must refuse before writes: %+v", result) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("schema refusal changed rows: %s", diff) + } + }) + } +} diff --git a/internal/releaseadapter/v071/library_schema_sequence_test.go b/internal/releaseadapter/v071/library_schema_sequence_test.go new file mode 100644 index 0000000..18f095e --- /dev/null +++ b/internal/releaseadapter/v071/library_schema_sequence_test.go @@ -0,0 +1,28 @@ +package v071 + +import ( + "knowledge-governance/internal/libraryrelease" + "testing" +) + +// Real v0.7.1 chunks/tag sequences are referenced by defaults but not OWNED BY. +// pg_get_serial_sequence alone silently loses their policy from the schema seal. +func TestContractUnownedSequencePolicyIsFrozenIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, err := fx.pool.Exec(fx.ctx, `CREATE SEQUENCE chunks_seq_id_seq; ALTER TABLE chunks ADD COLUMN seq_id bigint NOT NULL DEFAULT nextval('chunks_seq_id_seq')`); err != nil { + t.Fatal(err) + } + snapshot := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { parts["chunks"][0]["seq_id"] = 1 }) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), target, fx.backups(t, target), nil) + if outcome.State != "succeeded" { + t.Fatalf("valid unowned sequence could not publish: %+v", outcome) + } + if _, err := fx.pool.Exec(fx.ctx, `ALTER SEQUENCE chunks_seq_id_seq INCREMENT BY 2`); err != nil { + t.Fatal(err) + } + if err := target.verifyPlanSchema(fx.ctx); err == nil { + t.Fatal("unowned local sequence policy drift escaped frozen schema") + } +} diff --git a/internal/releaseadapter/v071/library_scope_hash_test.go b/internal/releaseadapter/v071/library_scope_hash_test.go new file mode 100644 index 0000000..fe137cf --- /dev/null +++ b/internal/releaseadapter/v071/library_scope_hash_test.go @@ -0,0 +1,64 @@ +package v071 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "testing" +) + +// F08:整库搬运改了 physical_path 就必须重算 location_hash。 +// +// oracle 用 crypto/sha256 **自己复算**,不调用被测实现里的 resourceLocationHash: +// 写入与校验共用同一个转换函数时,自比永远成立,错误会被自己的自洽掩盖。 +func TestResourceRetargetRecomputesLocationHash(t *testing.T) { + old := "storage://source-backend/minio://source-bucket/10001/file.pdf" + hash := sha256.Sum256([]byte(old)) + raw, _ := json.Marshal(map[string]any{"id": "resource-one", "tenant_id": 10001, + "physical_path": old, "location_hash": hex.EncodeToString(hash[:]), + "provider": "minio", "storage_backend_id": "source-backend"}) + var row map[string]json.RawMessage + if err := json.Unmarshal(raw, &row); err != nil { + t.Fatal(err) + } + target := &ProductionLibraryTarget{ + config: ProductionLibraryConfig{ObjectsBucket: "target-bucket"}, + scope: ProductionScope{TenantID: 10002, KnowledgeBaseID: "target-kb"}, + storageBackend: "target-backend", storageProvider: "minio", + snapshotTenant: 10001, snapshotKB: "source-kb", + } + if err := target.retargetRow("resources", row); err != nil { + t.Fatal(err) + } + var path, got string + _ = json.Unmarshal(row["physical_path"], &path) + _ = json.Unmarshal(row["location_hash"], &got) + if path == old { + t.Fatal("夹具没有改写定位符:这条断言就没有意义") + } + want := sha256.Sum256([]byte(path)) + if got != hex.EncodeToString(want[:]) { + t.Fatalf("改路径后 location_hash 仍是旧值:path=%s got=%s want=%s", path, got, hex.EncodeToString(want[:])) + } + // 反例:跨桶/跨租户组合下同样成立(桶段与租户段都参与最终路径)。 + for _, tc := range []struct{ name, bucket, backend string }{ + {"跨桶", "another-bucket", "target-backend"}, + {"跨后端", "target-bucket", "backend-2"}, + } { + var other map[string]json.RawMessage + _ = json.Unmarshal(raw, &other) + next := *target + next.config.ObjectsBucket = tc.bucket + next.storageBackend = tc.backend + if err := next.retargetRow("resources", other); err != nil { + t.Fatalf("%s:%v", tc.name, err) + } + var moved, movedHash string + _ = json.Unmarshal(other["physical_path"], &moved) + _ = json.Unmarshal(other["location_hash"], &movedHash) + sum := sha256.Sum256([]byte(moved)) + if movedHash != hex.EncodeToString(sum[:]) { + t.Fatalf("%s:location_hash 与最终路径不一致:path=%s got=%s", tc.name, moved, movedHash) + } + } +} diff --git a/internal/releaseadapter/v071/library_scope_probe.go b/internal/releaseadapter/v071/library_scope_probe.go index d25ec8e..ce11d83 100644 --- a/internal/releaseadapter/v071/library_scope_probe.go +++ b/internal/releaseadapter/v071/library_scope_probe.go @@ -17,10 +17,14 @@ func ScopeContentCounts(ctx context.Context, pool *pgxpool.Pool, identity Produc if pool == nil || identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) { return nil, errors.New("invalid scope identity") } - counts := make(map[string]int64, len(productionLibraryTables)) - for _, table := range productionLibraryTables { + profile, err := ResolveSchemaProfile(ctx, pool, "scope content probe") + if err != nil { + return nil, err + } + counts := make(map[string]int64, len(profile.Tables)) + for _, table := range profile.Tables { var count int64 - if err := pool.QueryRow(ctx, fmt.Sprintf(`SELECT count(*) FROM %s WHERE %s`, table, scopeWhere(table)), + if err := pool.QueryRow(ctx, fmt.Sprintf(`SELECT count(*) FROM %s WHERE %s`, table, scopeWhereFor(profile.Tables, table)), identity.TenantID, identity.KnowledgeBaseID).Scan(&count); err != nil { return nil, fmt.Errorf("count %s: %w", table, err) } diff --git a/internal/releaseadapter/v071/library_scope_remap.go b/internal/releaseadapter/v071/library_scope_remap.go index 23fe813..17effcb 100644 --- a/internal/releaseadapter/v071/library_scope_remap.go +++ b/internal/releaseadapter/v071/library_scope_remap.go @@ -2,6 +2,8 @@ package v071 import ( "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -49,6 +51,11 @@ type manifestScope struct { // 换成目标身份,资源行还要把定位符、存储后端、提供方换成目标实例自己的值。 func (t *ProductionLibraryTarget) retargetRow(table string, row map[string]json.RawMessage) error { if !tableHasTenant(table) { + // 关系表没有 tenant/kb 列,但它的两个分量都是身份:范围改写跳过它时, + // 身份映射仍必须执行,否则写集合/写入会出现未映射元组。 + if t.mappingActive && t.targetIDs != nil { + return t.targetIDs.remapRow(table, row) + } return nil } if err := t.retargetTenantField(row); err != nil { @@ -63,7 +70,14 @@ func (t *ProductionLibraryTarget) retargetRow(table string, row map[string]json. return t.rewriteResourceIdentity(row) } if table == "knowledges" { - return t.retargetEmbeddingModelField(row) + if err := t.retargetEmbeddingModelField(row); err != nil { + return err + } + } + // 身份与引用最后换:前面的范围/资源/模型改写都按来源身份读字段, + // 先换 ID 会让它们找不到要改的列。 + if t.mappingActive && t.targetIDs != nil { + return t.targetIDs.remapRow(table, row) } return nil } @@ -169,6 +183,17 @@ func (t *ProductionLibraryTarget) rewriteResourceIdentity(row map[string]json.Ra } row["physical_path"] = encoded } + // location_hash 的契约是 sha256(最终 physical_path),不是"来源路径的哈希"。 + // 旧实现只换路径不重算哈希:目标行声明的是一个不存在的定位符,去重/按路径定位 + // 都会失效;而写入与校验复用同一个转换函数,内部自比根本发现不了(F08)。 + // 这里在同一个转换里重算,校验侧另有独立 oracle(测试里直接用 crypto/sha256 复算)。 + if _, ok := row["location_hash"]; ok { + encoded, err := json.Marshal(resourceLocationHash(rewritten)) + if err != nil { + return errors.New("编码目标定位符哈希失败") + } + row["location_hash"] = encoded + } if t.storageBackend != "" { if _, ok := row["storage_backend_id"]; ok { encoded, err := json.Marshal(t.storageBackend) @@ -190,6 +215,15 @@ func (t *ProductionLibraryTarget) rewriteResourceIdentity(row map[string]json.Ra return nil } +// resourceLocationHash 是 `location_hash` 契约的**唯一实现**:sha256(最终 physical_path)。 +// +// 全库搬运(本文件)与文档级导入(postgres_import.go)必须用同一个函数: +// 两条路径各写一份,迟早只改一边,而目标实例正是按这个哈希去重/定位资源的。 +func resourceLocationHash(physicalPath string) string { + sum := sha256.Sum256([]byte(physicalPath)) + return hex.EncodeToString(sum[:]) +} + // retargetLocator 把 "storage:///:///" 整体换成目标 // 实例的真实取值:后端 id、scheme/提供方、桶名,以及对象键里的租户段。 // 桶名为空表示目标没有配置对象存储(测试夹具),此时不动定位符。 diff --git a/internal/releaseadapter/v071/library_structured_references.go b/internal/releaseadapter/v071/library_structured_references.go new file mode 100644 index 0000000..6692d13 --- /dev/null +++ b/internal/releaseadapter/v071/library_structured_references.go @@ -0,0 +1,169 @@ +package v071 + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +// This is the finite v071 structured-reference contract, not a heuristic that +// treats arbitrary text/numbers as IDs. Historical log refs are display facts. +func validateLibraryStructuredReferences(pg PostgresSnapshot) error { + type row map[string]json.RawMessage + tables := map[string]map[string]row{} + for _, table := range pg.Tables { + tables[table.Name] = map[string]row{} + for _, raw := range table.Rows { + var r row + if e := json.Unmarshal(raw, &r); e != nil { + return e + } + var id string + json.Unmarshal(r["id"], &id) + if id == "" { + id = string(r["id"]) + } + tables[table.Name][id] = r + } + } + text := func(r row, key string) (string, error) { + v := bytes.TrimSpace(r[key]) + if len(v) == 0 || bytes.Equal(v, []byte("null")) { + return "", nil + } + var out string + if e := json.Unmarshal(v, &out); e != nil { + return "", fmt.Errorf("unsupported reference %s", key) + } + return out, nil + } + ref := func(r row, key, table string, sameKnowledge bool) error { + v, e := text(r, key) + if e != nil || v == "" { + return e + } + parent, ok := tables[table][v] + if !ok { + return fmt.Errorf("unresolved %s reference to %s", key, table) + } + if sameKnowledge { + a, _ := text(r, "knowledge_id") + b, _ := text(parent, "knowledge_id") + if a != b { + return fmt.Errorf("cross-parent %s reference", key) + } + } + return nil + } + refs := func(r row, key, table string, legacyTitle bool) error { + raw := bytes.TrimSpace(r[key]) + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + return nil + } + var ids []string + if e := json.Unmarshal(raw, &ids); e != nil { + return fmt.Errorf("unsupported %s reference representation", key) + } + for _, id := range ids { + if legacyTitle { + id = strings.SplitN(id, "|", 2)[0] + } + if _, ok := tables[table][id]; !ok { + return fmt.Errorf("unresolved %s reference to %s", key, table) + } + } + return nil + } + for _, r := range tables["chunks"] { + for _, key := range []string{"pre_chunk_id", "next_chunk_id", "parent_chunk_id"} { + if e := ref(r, key, "chunks", true); e != nil { + return e + } + } + if e := ref(r, "tag_id", "knowledge_tags", false); e != nil { + return e + } + for _, key := range []string{"relation_chunks", "indirect_relation_chunks"} { + if e := refs(r, key, "chunks", false); e != nil { + return e + } + } + } + for _, r := range tables["wiki_folders"] { + if e := ref(r, "parent_id", "wiki_folders", false); e != nil { + return e + } + } + // Parent edges must be acyclic; pre/next chunk adjacency is intentionally not + // run through this check because a normal bidirectional adjacency is a cycle. + for _, kind := range []struct{ table, key string }{{"wiki_folders", "parent_id"}, {"chunks", "parent_chunk_id"}} { + for id := range tables[kind.table] { + seen := map[string]bool{} + for id != "" { + if seen[id] { + return fmt.Errorf("cyclic %s reference", kind.key) + } + seen[id] = true + next, e := text(tables[kind.table][id], kind.key) + if e != nil { + return e + } + id = next + } + } + } + for _, r := range tables["wiki_pages"] { + if e := ref(r, "folder_id", "wiki_folders", false); e != nil { + return e + } + if e := refs(r, "source_refs", "knowledges", true); e != nil { + return e + } + if e := refs(r, "chunk_refs", "chunks", false); e != nil { + return e + } + } + for _, r := range tables["wiki_log_entries"] { + raw := bytes.TrimSpace(r["pages_affected"]) + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + continue + } + var items []json.RawMessage + if e := json.Unmarshal(raw, &items); e != nil { + return fmt.Errorf("unsupported Wiki log pages_affected") + } + shape := "" + for _, item := range items { + var slug string + if json.Unmarshal(item, &slug) == nil { + if shape == "object" { + return fmt.Errorf("mixed Wiki log reference representations") + } + shape = "string" + continue + } + var object map[string]json.RawMessage + if e := json.Unmarshal(item, &object); e != nil || object == nil { + return fmt.Errorf("unsupported Wiki log page reference") + } + if shape == "string" { + return fmt.Errorf("mixed Wiki log reference representations") + } + shape = "object" + if e := json.Unmarshal(object["slug"], &slug); e != nil { + return fmt.Errorf("Wiki log reference lacks string slug") + } + for key, value := range object { + if key != "slug" && key != "title" { + return fmt.Errorf("unreviewed Wiki log reference field: %s", key) + } + var s string + if e := json.Unmarshal(value, &s); e != nil { + return fmt.Errorf("unsupported Wiki log reference %s", key) + } + } + } + } + return nil +} diff --git a/internal/releaseadapter/v071/library_table_state_text_id_test.go b/internal/releaseadapter/v071/library_table_state_text_id_test.go new file mode 100644 index 0000000..3924555 --- /dev/null +++ b/internal/releaseadapter/v071/library_table_state_text_id_test.go @@ -0,0 +1,58 @@ +package v071 + +import ( + "context" + "os" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// F01/F02 regression: tableState reads normal text identities (doc id, UUID, +// composite relation key, numeric local id) without treating them as JSON. +// The fixture is session-local temp tables; it never writes a persistent table. +func TestTableStateReadsTextIdentities(t *testing.T) { + dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database") + } + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") { + t.Fatal("isolated database required") + } + cfg.MaxConns = 1 + cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp" + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "10000" + ctx := context.Background() + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + _, err = pool.Exec(ctx, ` +CREATE TEMP TABLE knowledges(id text,tenant_id bigint,knowledge_base_id text); +CREATE TEMP TABLE knowledge_tag_relations(knowledge_id text,tag_id text); +CREATE TEMP TABLE wiki_log_entries(id bigint,tenant_id bigint,knowledge_base_id text); +INSERT INTO knowledges VALUES ('doc-parent',10000,'kb-parent'), + ('f643a7e7-bbb9-4209-9033-fca7f76f011b',10000,'kb-parent'); +INSERT INTO knowledge_tag_relations VALUES ('doc-parent','tag-parent'), + ('f643a7e7-bbb9-4209-9033-fca7f76f011b','tag-two'); +INSERT INTO wiki_log_entries VALUES (1,10000,'kb-parent'),(2,10000,'kb-parent');`) + if err != nil { + t.Fatal(err) + } + target := &ProductionLibraryTarget{pool: pool, scope: ProductionScope{TenantID: 10000, KnowledgeBaseID: "kb-parent"}} + for _, fixture := range []struct { + table string + count int64 + }{{"knowledges", 2}, {"knowledge_tag_relations", 2}, {"wiki_log_entries", 2}} { + count, _, err := target.tableState(ctx, fixture.table) + if err != nil { + t.Fatalf("%s plain identity rejected: %v", fixture.table, err) + } + if count != fixture.count { + t.Fatalf("%s count=%d want=%d", fixture.table, count, fixture.count) + } + } +} diff --git a/internal/releaseadapter/v071/library_target_contract.go b/internal/releaseadapter/v071/library_target_contract.go new file mode 100644 index 0000000..98ad8b9 --- /dev/null +++ b/internal/releaseadapter/v071/library_target_contract.go @@ -0,0 +1,166 @@ +package v071 + +import ( + "context" + "errors" + "fmt" + "strings" + + "knowledge-governance/internal/librarysnapshot" +) + +// LiveTargetContract 是目标知识库**此刻**的模型/索引/schema 契约。 +// +// 为什么要单独读:旧实现直接拿"要发布的那份来源快照的 compatibility"当生产预备份的 +// 合同,于是"目标是什么模型"从来没被问过。后果是目标拿到 A 生成的向量、知识行却声明 +// 是 B——同维不同模型在 mapping 判据下完全通过(F17)。 +type LiveTargetContract struct { + SchemaVersion int + Dirty bool + EmbeddingModel string + EmbeddingDimension int + EngineType string + IndexName string + MappingSHA256 string + // ModelBound 表示 knowledge_bases → models 的 join 命中:false 时维度不可知, + // 不能凭"看起来是同一维"放行。 + ModelBound bool +} + +// liveTargetContractSQL 用 LEFT JOIN 读模型:模型行缺失时仍然拿到 KB 声明的模型 id, +// 这样"没绑模型/绑了但不可读"能被明确拒绝,而不是在发布中途才炸。 +const liveTargetContractSQL = ` +SELECT COALESCE(migration.version, 0), + COALESCE(migration.dirty, false), + COALESCE(model.name, ''), + COALESCE(NULLIF(model.parameters->'embedding_parameters'->>'dimension', '')::INTEGER, 0), + (model.id IS NOT NULL), + COALESCE(knowledge_base.embedding_model_id, ''), + COALESCE(vector_store.engine_type, ''), + COALESCE(vector_store.index_config->>'index_name', '') +FROM knowledge_bases AS knowledge_base +LEFT JOIN models AS model + ON model.id = knowledge_base.embedding_model_id AND model.deleted_at IS NULL +LEFT JOIN schema_migrations AS migration ON TRUE +LEFT JOIN vector_stores AS vector_store + ON vector_store.id = knowledge_base.vector_store_id AND vector_store.deleted_at IS NULL +WHERE knowledge_base.id = $1 AND knowledge_base.tenant_id = $2 AND knowledge_base.deleted_at IS NULL +` + +// LiveTargetContract 读目标知识库的实时契约。读不到就直接失败——**不许**回退到 +// 来源快照的声明:那正是"用来源兼容性冒充目标合同"的老毛病。 +func (t *ProductionLibraryTarget) LiveTargetContract(ctx context.Context) (LiveTargetContract, error) { + if t.pool == nil { + return LiveTargetContract{}, errors.New("目标数据库未接线:无法核对实时模型契约") + } + var ( + contract LiveTargetContract + declared string + indexName string + ) + if err := t.pool.QueryRow(ctx, liveTargetContractSQL, t.scope.KnowledgeBaseID, t.scope.TenantID).Scan( + &contract.SchemaVersion, &contract.Dirty, &contract.EmbeddingModel, &contract.EmbeddingDimension, + &contract.ModelBound, &declared, &contract.EngineType, &indexName); err != nil { + return LiveTargetContract{}, fmt.Errorf("读不到目标知识库 %s 的实时契约:%w", t.scope.KnowledgeBaseID, err) + } + if !contract.ModelBound && declared != "" { + // KB 声明了模型但模型行不可读(未迁移/已删):维度未知,不能证明兼容。 + contract.EmbeddingModel = declared + } + contract.IndexName = indexName + if t.search != nil { + if mapping, mapErr := t.search.MappingSHA256(ctx); mapErr == nil { + contract.MappingSHA256 = mapping + } + } + return contract, nil +} + +// VerifySourceAgainstTarget 判断"来源快照的向量能不能直接搬进这个目标"。 +// +// 只允许**等价模型**:名字一致、维度一致。名字不同即使维度相同也拒绝——向量是在 +// 模型 A 的语义空间里算出来的,搬进声明模型 B 的行里,检索结果会静默变错,而这 +// 种错误不会被任何"行数/摘要"校验发现(本模块不重算 embedding,也不许假装等价)。 +func VerifySourceAgainstTarget(source librarysnapshot.Compatibility, live LiveTargetContract) error { + if live.Dirty { + return errors.New("目标 schema 处于 dirty 状态:拒绝在该目标上写入") + } + if source.SchemaVersion != 0 && live.SchemaVersion != 0 && source.SchemaVersion != live.SchemaVersion { + return fmt.Errorf("目标 schema 版本 %d 与来源快照声明 %d 不一致:拒绝搬运", + live.SchemaVersion, source.SchemaVersion) + } + if !live.ModelBound || live.EmbeddingDimension < 1 || strings.TrimSpace(live.EmbeddingModel) == "" { + return errors.New("目标知识库没有可读的 embedding 模型绑定(模型行缺失或维度未知):" + + "无法证明向量可迁移,先在目标上绑定模型") + } + if source.EmbeddingModel != "" && live.EmbeddingModel != "" && source.EmbeddingModel != live.EmbeddingModel { + return fmt.Errorf("来源 embedding 模型 %q 与目标实时模型 %q 不同:不重算 embedding 就不能声称兼容", + source.EmbeddingModel, live.EmbeddingModel) + } + if source.EmbeddingDimension > 0 && source.EmbeddingDimension != live.EmbeddingDimension { + return fmt.Errorf("来源向量维度 %d 与目标模型维度 %d 不一致", + source.EmbeddingDimension, live.EmbeddingDimension) + } + return nil +} + +// ContractFromLive 用目标实时状态构造预备份合同:新备份声明的是"目标现在是什么", +// 不是"要发布的来源是什么"。 +func ContractFromLive(source librarysnapshot.Compatibility, live LiveTargetContract) librarysnapshot.Compatibility { + contract := source + contract.SchemaVersion = live.SchemaVersion + contract.EmbeddingModel = live.EmbeddingModel + contract.EmbeddingDimension = live.EmbeddingDimension + if live.EngineType != "" { + contract.RetrieverEngine = live.EngineType + } + if live.MappingSHA256 != "" { + contract.IndexMappingSHA256 = live.MappingSHA256 + } + return contract +} + +// graphEnabledSQL 只读知识库自己的索引策略:图谱开关是 KB 的声明,不是部署的推测值。 +const graphEnabledSQL = ` +SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean, false) +FROM knowledge_bases +WHERE id = $1 AND tenant_id = $2 AND deleted_at IS NULL +` + +// GraphEnabled 回答"这个目标知识库是否开启了图谱索引"。 +// +// 为什么要挡在发布之前:发布链路只搬 PostgreSQL / Elasticsearch / 对象存储, +// 从不动 Neo4j。目标开图谱时,写进去的文档与图谱会静默不一致——没有任何 +// 行数/摘要校验能发现"图谱还是旧的"。这里只读、只拒绝,不修改目标配置, +// 也不扩写图谱迁移。 +// +// 读不到(库/行不可读、值无法解析)按未知处理:未知即拒绝。 +func (t *ProductionLibraryTarget) GraphEnabled(ctx context.Context) (bool, error) { + if t.pool == nil { + return false, errors.New("目标数据库未接线:无法确认图谱开关") + } + var enabled bool + if err := t.pool.QueryRow(ctx, graphEnabledSQL, t.scope.KnowledgeBaseID, t.scope.TenantID).Scan(&enabled); err != nil { + return false, fmt.Errorf("读不到目标知识库 %s 的图谱开关:%w", t.scope.KnowledgeBaseID, err) + } + return enabled, nil +} + +// verifyTargetGraphGate 把"读到开 / 读到关 / 读不到"换算成发布是否允许。 +// 纯函数:决定逻辑必须能被单测固定,而不是只能靠连真库才看得到。 +func verifyTargetGraphGate(enabled bool, readErr error) error { + if readErr != nil { + return fmt.Errorf("目标图谱开关未知,拒绝发布:%w", readErr) + } + if enabled { + return errors.New("目标知识库开启了图谱索引(graph_enabled=true):发布链路只写 PostgreSQL/Elasticsearch/对象存储," + + "不会同步 Neo4j,写进去的内容会与图谱静默不一致;拒绝发布(在目标侧关闭图谱或先提供图谱迁移)") + } + return nil +} + +// VerifyGraphGate 是发布装配处调用的门禁入口(读实时开关 + 换算成允许/拒绝)。 +func (t *ProductionLibraryTarget) VerifyGraphGate(ctx context.Context) error { + enabled, err := t.GraphEnabled(ctx) + return verifyTargetGraphGate(enabled, err) +} diff --git a/internal/releaseadapter/v071/library_target_contract_test.go b/internal/releaseadapter/v071/library_target_contract_test.go new file mode 100644 index 0000000..0610b55 --- /dev/null +++ b/internal/releaseadapter/v071/library_target_contract_test.go @@ -0,0 +1,53 @@ +package v071 + +import ( + "strings" + "testing" + + "knowledge-governance/internal/librarysnapshot" +) + +// F17:目标实时模型契约必须核,且"同维不同模型"不许放行。 +func TestVerifySourceAgainstTargetRejectsDifferentModel(t *testing.T) { + source := librarysnapshot.Compatibility{SchemaVersion: 71, EmbeddingModel: "model-a", EmbeddingDimension: 1024} + live := LiveTargetContract{SchemaVersion: 71, EmbeddingModel: "model-b", EmbeddingDimension: 1024, ModelBound: true} + if err := VerifySourceAgainstTarget(source, live); err == nil { + t.Fatal("同维不同模型必须拒绝:向量空间不同,行声明与向量会对不上") + } + // 等价模型(同名字同维度)放行。 + live.EmbeddingModel = "model-a" + if err := VerifySourceAgainstTarget(source, live); err != nil { + t.Fatalf("等价模型应放行:%v", err) + } + // 维度不同必须拒绝。 + live.EmbeddingDimension = 768 + if err := VerifySourceAgainstTarget(source, live); err == nil { + t.Fatal("维度不同必须拒绝") + } + // 目标模型行缺失(维度未知)也必须拒绝:不能靠"看起来同维"猜。 + live = LiveTargetContract{SchemaVersion: 71, EmbeddingModel: "model-a", ModelBound: false} + if err := VerifySourceAgainstTarget(source, live); err == nil { + t.Fatal("目标模型不可读时必须拒绝,而不是按来源声明放行") + } + // dirty schema 直接拒绝。 + if err := VerifySourceAgainstTarget(source, LiveTargetContract{SchemaVersion: 71, Dirty: true, + EmbeddingModel: "model-a", EmbeddingDimension: 1024, ModelBound: true}); err == nil { + t.Fatal("dirty schema 必须拒绝") + } +} + +// 预备份合同必须来自目标实况:不能把来源声明当目标声明。 +func TestContractFromLiveUsesTargetState(t *testing.T) { + source := librarysnapshot.Compatibility{WeKnoraVersion: "0.7.1", SchemaVersion: 71, + EmbeddingModel: "model-a", EmbeddingDimension: 1024, RetrieverEngine: "elasticsearch_v8", + IndexMappingSHA256: strings.Repeat("a", 64)} + live := LiveTargetContract{SchemaVersion: 71, EmbeddingModel: "model-b", EmbeddingDimension: 1024, + EngineType: "elasticsearch", MappingSHA256: strings.Repeat("b", 64), ModelBound: true} + got := ContractFromLive(source, live) + if got.EmbeddingModel != "model-b" || got.IndexMappingSHA256 != strings.Repeat("b", 64) { + t.Fatalf("预备份合同必须取目标实况:%+v", got) + } + if got.WeKnoraVersion != source.WeKnoraVersion { + t.Fatalf("数据格式版本仍来自来源快照:%+v", got) + } +} diff --git a/internal/releaseadapter/v071/library_target_ids.go b/internal/releaseadapter/v071/library_target_ids.go new file mode 100644 index 0000000..ee05e6e --- /dev/null +++ b/internal/releaseadapter/v071/library_target_ids.go @@ -0,0 +1,496 @@ +package v071 + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "sort" + "strconv" + "strings" + + "knowledge-governance/internal/librarysnapshot" +) + +// 目标隔离 ID 映射。 +// +// 为什么必须映射:同一实例里可以存在多个知识库,源库的 UUID 主键被原样写进第二个 +// 目标库时会与旧库的行撞主键(父证据:2 knowledges / 2 chunks / 23 wiki_pages / +// 17 wiki_folders 已存在于旧 KB),而写入前的"跨范围冲突"检查会(正确地)拒绝。 +// 关掉检查等于让两个库共享身份,删除/恢复/校验都会互相误伤。 +// +// 因此身份必须由"目标范围 + 表 + 源身份"确定性派生: +// - 同一目标重复同步/重试/跨版本 → 同一 ID(幂等、可恢复); +// - 不同目标 KB、不同表 → 不同 ID(隔离); +// - 源归档字节不变,映射只存在于目标侧派生视图。 +// +// 资源表(resources)是多知识库共享的字节载体,ID 不重映射,沿用既有复用/归属证明; +// 绑定行的 owner_id 与自身 id 则按目标映射。 +type targetIDMapper struct { + tenant uint64 + kb string + ids map[string]string + reverse map[string]string + known map[string]map[string]bool + owner map[string]string + sequence int + + // 不重映射的表:资源行是跨库共享对象,改了 ID 就等于复制一份字节, + // 现有复用契约要求"内容相同 + 来源可审计"才复用,不能靠换 ID 绕过。 + skip map[string]bool +} + +const targetIDNamespace = "knowledge-governance/target-identity/v1" + +var errUnmappedTargetReference = errors.New("unmapped target reference") + +func newTargetIDMapper(tenant uint64, kb string, _ any) *targetIDMapper { + return &targetIDMapper{ + tenant: tenant, kb: kb, + ids: map[string]string{}, reverse: map[string]string{}, + known: map[string]map[string]bool{}, owner: map[string]string{}, + skip: map[string]bool{"resources": true}, + } +} + +func (m *targetIDMapper) mapID(table, source string) string { + if source == "" || m.skip[table] { + return source + } + key := table + "\x00" + source + if mapped, ok := m.ids[key]; ok { + return mapped + } + sum := sha256.Sum256([]byte(targetIDNamespace + "\x00" + strconv.FormatUint(m.tenant, 10) + "\x00" + m.kb + "\x00" + table + "\x00" + source)) + var raw [16]byte + copy(raw[:], sum[:16]) + raw[6] = raw[6]&0x0f | 0x50 // version 5 semantics: name-based, deterministic + raw[8] = raw[8]&0x3f | 0x80 // RFC 4122 variant + mapped := fmt.Sprintf("%x-%x-%x-%x-%x", raw[0:4], raw[4:6], raw[6:8], raw[8:10], raw[10:16]) + if previous, exists := m.reverse[table+"\x00"+mapped]; exists && previous != source { + // 位移后的 SHA-256 也撞同一张表是密码学事件;宁可停住也不静默合并两个身份。 + panic("target id collision for " + table) + } + m.ids[key] = mapped + m.reverse[table+"\x00"+mapped] = source + m.sequence++ + return mapped +} + +func (m *targetIDMapper) registerSourceID(table, id string) { + if id == "" || m.skip[table] { + return + } + // 本地自增主键(如 wiki_log_entries.id)不是跨库身份:既不能当引用匹配, + // 也不能参与"残留源 ID"判断,否则普通整数列会被误报。 + if contract, ok := migrationIdentityContracts[table]; ok && (contract.Kind == "local-bigint" || contract.Kind == "tuple") { + // 本地自增/复合元组都不是可被别的表引用的实体身份: + // 关系表的两个分量必须由 knowledges/knowledge_tags 自己登记。 + return + } + if m.known[table] == nil { + m.known[table] = map[string]bool{} + } + m.known[table][id] = true + if _, exists := m.owner[id]; !exists { + m.owner[id] = table + } +} + +// remapRow 只改"身份与引用"字段;正文、向量、顺序、重复项一律原样保留。 +func (m *targetIDMapper) remapRow(table string, row map[string]json.RawMessage) error { + if m.skip[table] { + return nil + } + switch table { + case "knowledges": + if err := m.remapScalar(row, "id", table); err != nil { + return err + } + case "chunks": + if err := m.remapScalar(row, "id", table); err != nil { + return err + } + if err := m.remapScalar(row, "knowledge_id", "knowledges"); err != nil { + return err + } + if err := m.remapScalar(row, "tag_id", "knowledge_tags"); err != nil { + return err + } + for _, column := range []string{"parent_chunk_id", "pre_chunk_id", "next_chunk_id"} { + if err := m.remapScalar(row, column, "chunks"); err != nil { + return err + } + } + for _, column := range []string{"relation_chunks", "indirect_relation_chunks"} { + // 这两列是"分块引用":目标表由字段语义决定(chunks),不由字符串 + // 在别的表里也出现来决定;跨表同 ID 是合法数据,不是歧义。 + if err := m.remapJSONExact(row, column, "chunks"); err != nil { + return err + } + } + case "knowledge_tags": + if err := m.remapScalar(row, "id", table); err != nil { + return err + } + case "knowledge_tag_relations": + if err := m.remapScalar(row, "knowledge_id", "knowledges"); err != nil { + return err + } + if err := m.remapScalar(row, "tag_id", "knowledge_tags"); err != nil { + return err + } + case "wiki_folders": + if err := m.remapScalar(row, "id", table); err != nil { + return err + } + if err := m.remapScalar(row, "parent_id", table); err != nil { + return err + } + case "wiki_pages": + if err := m.remapScalar(row, "id", table); err != nil { + return err + } + if err := m.remapScalar(row, "folder_id", "wiki_folders"); err != nil { + return err + } + if err := m.remapRefArray(row, "chunk_refs", "chunks"); err != nil { + return err + } + if err := m.remapSourceRefs(row); err != nil { + return err + } + case "wiki_page_issues": + if err := m.remapScalar(row, "id", table); err != nil { + return err + } + if err := m.remapRefArray(row, "suspected_knowledge_ids", "knowledges"); err != nil { + return err + } + for _, column := range []string{"page_id", "knowledge_id", "chunk_id"} { + if err := m.remapScalar(row, column, m.tableFor(column)); err != nil { + return err + } + } + case "wiki_log_entries": + // id 是目标本地的 bigint,由既有 LocalIDs 分配;历史日志可能引用已删除文档, + // 这类引用只做"已知才换",不能当作悬挂拒绝(否则整库同步被历史日志卡死)。 + m.remapScalarIfKnown(row, "knowledge_id", "knowledges") + if err := m.remapScalar(row, "page_id", "wiki_pages"); err != nil { + return err + } + case "resource_bindings": + if err := m.remapScalar(row, "id", table); err != nil { + return err + } + var ownerType string + if raw, ok := row["owner_type"]; ok { + _ = json.Unmarshal(raw, &ownerType) + } + switch ownerType { + case "knowledge": + if err := m.remapScalar(row, "owner_id", "knowledges"); err != nil { + return err + } + case "chunk": + if err := m.remapScalar(row, "owner_id", "chunks"); err != nil { + return err + } + default: + return fmt.Errorf("resource_bindings: unknown owner_type %q", ownerType) + } + // resource_id 不映射:资源是共享字节,绑定只换归属。 + } + return m.rejectUnmapped(table, row) +} + +func (m *targetIDMapper) tableFor(column string) string { + switch column { + case "page_id": + return "wiki_pages" + case "knowledge_id": + return "knowledges" + case "chunk_id": + return "chunks" + } + return column +} + +func (m *targetIDMapper) remapScalar(row map[string]json.RawMessage, column, table string) error { + raw, ok := row[column] + if !ok { + return nil + } + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return fmt.Errorf("%s: unreadable %s", table, column) + } + if value == "" { + return nil + } + if !m.known[table][value] { + return fmt.Errorf("%w: %s.%s=%s", errUnmappedTargetReference, table, column, value) + } + encoded, _ := json.Marshal(m.mapID(table, value)) + row[column] = encoded + return nil +} + +func (m *targetIDMapper) remapScalarIfKnown(row map[string]json.RawMessage, column, table string) { + raw, ok := row[column] + if !ok { + return + } + var value string + if err := json.Unmarshal(raw, &value); err != nil || value == "" || !m.known[table][value] { + return + } + encoded, _ := json.Marshal(m.mapID(table, value)) + row[column] = encoded +} + +func (m *targetIDMapper) remapRefArray(row map[string]json.RawMessage, column, table string) error { + raw, ok := row[column] + if !ok { + return nil + } + var values []string + if err := json.Unmarshal(raw, &values); err != nil { + return nil + } + for i, value := range values { + if !m.known[table][value] { + return fmt.Errorf("%w: %s.%s=%s", errUnmappedTargetReference, table, column, value) + } + values[i] = m.mapID(table, value) + } + encoded, _ := json.Marshal(values) + row[column] = encoded + return nil +} + +func (m *targetIDMapper) remapSourceRefs(row map[string]json.RawMessage) error { + raw, ok := row["source_refs"] + if !ok { + return nil + } + var refs []string + if err := json.Unmarshal(raw, &refs); err != nil { + return nil + } + for i, ref := range refs { + id, suffix := ref, "" + if cut := strings.IndexByte(ref, '|'); cut >= 0 { + id, suffix = ref[:cut], ref[cut:] + } + if !m.known["knowledges"][id] { + return fmt.Errorf("%w: wiki_pages.source_refs=%s", errUnmappedTargetReference, id) + } + refs[i] = m.mapID("knowledges", id) + suffix + } + encoded, _ := json.Marshal(refs) + row["source_refs"] = encoded + return nil +} + +// remapJSONExact 只在指定 JSON 列里替换"整体等于已知身份"的字符串; +// 不做子串替换(正文里出现同形状文本不是引用)。 +func (m *targetIDMapper) remapJSONExact(row map[string]json.RawMessage, column, table string) error { + raw, ok := row[column] + if !ok { + return nil + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() // >2^53 的整数必须原样保留,不能经 float64 + var value any + if err := decoder.Decode(&value); err != nil { + return fmt.Errorf("%s.%s 不可解析", table, column) + } + changed := false + var walk func(any) (any, error) + walk = func(v any) (any, error) { + switch typed := v.(type) { + case string: + if m.known[table][typed] { + changed = true + return m.mapID(table, typed), nil + } + for other, ids := range m.known { + if other == table || m.skip[other] { + continue + } + if ids[typed] { + return nil, fmt.Errorf("%w: %s.%s references %s entity %s", errUnmappedTargetReference, table, column, other, typed) + } + } + return typed, nil + case []any: + for i := range typed { + mapped, err := walk(typed[i]) + if err != nil { + return nil, err + } + typed[i] = mapped + } + return typed, nil + case map[string]any: + for key := range typed { + mapped, err := walk(typed[key]) + if err != nil { + return nil, err + } + typed[key] = mapped + } + return typed, nil + } + return v, nil + } + mapped, err := walk(value) + if err != nil { + return err + } + if !changed { + return nil + } + encoded, err := json.Marshal(mapped) + if err != nil { + return err + } + row[column] = encoded + return nil +} + +// rejectUnmapped 保证"改写后不再残留任何已知源身份",并拒绝无法判定归属的悬挂引用。 +func (m *targetIDMapper) rejectUnmapped(table string, row map[string]json.RawMessage) error { + body := map[string]bool{"content": true, "summary": true, "description": true, "physical_path": true, + "pages_affected": true, "slug": true, "metadata": true, "page_metadata": true, "title": true, "aliases": true, "in_links": true, "out_links": true} + for column, raw := range row { + if body[column] { + continue + } + if leftover := m.findKnown(string(raw)); leftover != "" { + return fmt.Errorf("%w: %s.%s still references source id %s", errUnmappedTargetReference, table, column, leftover) + } + } + return nil +} + +func rawStrings(row map[string]json.RawMessage) []string { + out := make([]string, 0, len(row)) + for _, raw := range row { + out = append(out, string(raw)) + } + return out +} + +func (m *targetIDMapper) findKnown(value string) string { + if table, ok := m.owner[value]; ok && !m.skip[table] { + return value + } + // JSON 字符串里嵌着的 id 也要查(只查完整 id 子串,不做模糊匹配)。 + for id, table := range m.owner { + if m.skip[table] || len(id) < 16 || !strings.Contains(value, id) { + continue + } + // 允许 it 出现在正文类字段里的情况已由 rejectUnmapped 排除;这里只对 + // 明确带引用的字段生效,因此命中即说明漏改。 + return id + } + return "" +} + +func (m *targetIDMapper) remapIndexDocument(id string, source json.RawMessage) (string, json.RawMessage, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(source, &fields); err != nil { + return "", nil, errors.New("index document source is not an object") + } + for column, table := range map[string]string{ + "chunk_id": "chunks", "knowledge_id": "knowledges", "tag_id": "knowledge_tags", + } { + raw, ok := fields[column] + if !ok { + continue + } + var value string + if err := json.Unmarshal(raw, &value); err != nil || value == "" { + continue + } + if !m.known[table][value] { + return "", nil, fmt.Errorf("%w: index %s=%s", errUnmappedTargetReference, column, value) + } + encoded, _ := json.Marshal(m.mapID(table, value)) + fields[column] = encoded + } + // source_id 在不同索引器版本里既可能是 chunk id,也可能是外部文档 id: + // 只有能确定是分块/文档身份时才映射,opaque 外部 id 原样保留。 + if raw, ok := fields["source_id"]; ok { + var value string + if json.Unmarshal(raw, &value) == nil && value != "" { + switch { + case m.known["chunks"][value]: + encoded, _ := json.Marshal(m.mapID("chunks", value)) + fields["source_id"] = encoded + case m.known["knowledges"][value]: + encoded, _ := json.Marshal(m.mapID("knowledges", value)) + fields["source_id"] = encoded + } + } + } + encoded, err := json.Marshal(fields) + if err != nil { + return "", nil, err + } + return m.mapID("index_chunks", id), encoded, nil +} + +// targetIDMapperFromArchive 从目标快照里登记源身份,供引用映射与残留检查使用。 +func targetIDMapperFromArchive(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest, tenant uint64, kb string) (*targetIDMapper, error) { + mapper := newTargetIDMapper(tenant, kb, nil) + for _, part := range manifest.Parts { + switch part.Kind { + case "database", "wiki": + reader, err := archive.OpenPart(part) + if err != nil { + return nil, err + } + var rows []map[string]json.RawMessage + err = json.NewDecoder(reader).Decode(&rows) + reader.Close() + if err != nil { + return nil, err + } + for _, row := range rows { + if identity, err := parseRowIdentity(part.Name, row); err == nil { + for _, value := range identity.Values { + mapper.registerSourceID(part.Name, value) + } + } + // 引用值不登记为"实体存在":悬挂引用必须由主键表缺行来暴露。 + } + case "index": + // 索引文档的 chunk_id/knowledge_id 同样只是引用,不能反过来证明实体存在。 + reader, err := archive.OpenPart(part) + if err != nil { + return nil, err + } + documents, err := librarysnapshot.ReadIndexDocuments(reader) + reader.Close() + if err != nil { + return nil, err + } + _ = documents + } + } + return mapper, nil +} + +// sortedSourceIDs 只用于稳定报告/调试,不参与映射。 +func (m *targetIDMapper) sortedSourceIDs() []string { + out := make([]string, 0, len(m.ids)) + for key := range m.ids { + out = append(out, strings.ReplaceAll(key, "\x00", "/")) + } + sort.Strings(out) + return out +} diff --git a/internal/releaseadapter/v071/library_target_ids_integration_test.go b/internal/releaseadapter/v071/library_target_ids_integration_test.go new file mode 100644 index 0000000..ab7d40a --- /dev/null +++ b/internal/releaseadapter/v071/library_target_ids_integration_test.go @@ -0,0 +1,171 @@ +package v071 + +import ( + "context" + "strings" + "testing" + + "knowledge-governance/internal/librarysnapshot" + + "knowledge-governance/internal/libraryrelease" +) + +// 同一隔离实例里已有旧库占用源快照的原始 UUID;目标换成另一个空知识库。 +// 必须 Plan→Apply→Verify 成功、旧库逐字节保留,失败路径恢复目标 before-image。 +func TestTargetIDMappingPlanApplyVerifyRestoreIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + ctx := fx.ctx + // 旧库占用与来源快照相同的身份(真实缺陷:原实现按原 ID 写入会撞主键/被归属检查拒绝)。 + oldRows := []string{ + `INSERT INTO knowledges VALUES('doc-src',10001,'` + wsOtherKB + `','completed',0,'',NULL)`, + `INSERT INTO chunks VALUES('chunk-src',10001,'` + wsOtherKB + `','doc-src','旧库正文',NULL)`, + `INSERT INTO wiki_pages VALUES('wiki-src',10001,'` + wsOtherKB + `','legacy-page','旧库 wiki',NULL,'published')`, + } + for _, statement := range oldRows { + if _, err := fx.pool.Exec(ctx, statement); err != nil { + t.Fatalf("seed old kb: %v\n%s", err, statement) + } + } + before := universeDump(t, fx.pool) + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + current, err := target.Current(ctx) + if err != nil { + t.Fatal(err) + } + backup, err := backups.Prepare(ctx, snapshot, current) + if err != nil { + t.Fatal(err) + } + set, err := target.PlanWriteSet(ctx, libraryrelease.WriteSetPlan{JobID: "target-id-map-job", Target: "internal", + BackupSnapshotID: backup.SnapshotID, TargetSnapshotID: snapshot, Universe: backup.Universe}) + if err != nil { + t.Fatalf("plan against a database that already owns the source ids: %v", err) + } + for _, row := range set.Rows { + if row.ID == "doc-src" || row.ID == "chunk-src" || row.ID == "wiki-src" { + t.Fatalf("plan still carries source identity %s for %s", row.ID, row.Table) + } + } + for _, stage := range []libraryrelease.Stage{libraryrelease.StageDatabase, libraryrelease.StageWiki, + libraryrelease.StageResources, libraryrelease.StageIndex} { + if err := target.Apply(ctx, stage, snapshot); err != nil { + t.Fatalf("apply %s: %v", stage, err) + } + } + if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshot}); err != nil { + t.Fatalf("verify: %v", err) + } + // 旧库原行必须原样存在(内容与 ID 都不变)。 + for _, check := range []struct{ query, want string }{ + {`SELECT content FROM chunks WHERE id='chunk-src' AND knowledge_base_id='` + wsOtherKB + `'`, "旧库正文"}, + {`SELECT content FROM wiki_pages WHERE id='wiki-src' AND knowledge_base_id='` + wsOtherKB + `'`, "旧库 wiki"}, + } { + var got string + if err := fx.pool.QueryRow(ctx, check.query).Scan(&got); err != nil || got != check.want { + t.Fatalf("old kb row changed/lost (%s): %q %v", check.query, got, err) + } + } + // 新目标里必须是映射后的身份,不能出现源 UUID。 + var sourceIDs int64 + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND id IN ('doc-src','chunk-src')`, + wsTargetTenant, wsTargetKB).Scan(&sourceIDs); err != nil { + t.Fatal(err) + } + if sourceIDs != 0 { + t.Fatalf("source ids leaked into the new target: %d", sourceIDs) + } + var mapped int64 + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND id<>'doc-src'`, + wsTargetTenant, wsTargetKB).Scan(&mapped); err != nil { + t.Fatal(err) + } + if mapped == 0 { + t.Fatal("no mapped knowledge row written") + } + // 第二次同步(全新 target 实例、只靠持久计划)不重复、不冲突。 + second := fx.target(t) + if err := second.AdoptWriteSet(set); err != nil { + t.Fatalf("adopt persisted plan: %v", err) + } + if err := second.Apply(ctx, libraryrelease.StageDatabase, snapshot); err != nil { + t.Fatalf("second apply: %v", err) + } + var duplicated int64 + if err := fx.pool.QueryRow(ctx, `SELECT count(*) FROM chunks WHERE tenant_id=$1 AND knowledge_base_id=$2`, + wsTargetTenant, wsTargetKB).Scan(&duplicated); err != nil { + t.Fatal(err) + } + if duplicated != 1 { + t.Fatalf("repeat sync duplicated target chunks: %d", duplicated) + } + // 失败恢复:按持久写集合回放目标 before-image,旧库不变、残留为 0。 + ref := backup + ref.WriteSet = &set + if err := target.Restore(context.WithoutCancel(ctx), ref); err != nil { + t.Fatalf("restore: %v", err) + } + if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: backup.SnapshotID}); err != nil { + t.Fatalf("verify restored before-image: %v", err) + } + after := universeDump(t, fx.pool) + if diff := diffUniverse(before, after); diff != "" { + t.Fatalf("restore did not return to before-image: %s", diff) + } + t.Logf("plan rows=%d index=%d objects=%d; old kb preserved; restore exact", len(set.Rows), len(set.Index), len(set.Objects)) +} + +// 映射后的目标 ID 若真被另一个库占用,仍必须拒绝(不能只取消旧冲突预期)。 +func TestTargetIDMappedIdentityCollisionStillRejectedIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + mapped := expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", "doc-src") + if _, err := fx.pool.Exec(fx.ctx, `INSERT INTO knowledges VALUES($1,10001,$2,'completed',0,'',NULL)`, mapped, wsOtherKB); err != nil { + t.Fatal(err) + } + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatal(err) + } + backup, err := fx.backups(t, target).Prepare(fx.ctx, snapshot, current) + if err != nil { + t.Fatal(err) + } + if _, err := target.PlanWriteSet(fx.ctx, libraryrelease.WriteSetPlan{JobID: "mapped-collision", Target: "internal", + BackupSnapshotID: backup.SnapshotID, TargetSnapshotID: snapshot, Universe: backup.Universe}); err == nil { + t.Fatal("mapped identity occupied by another KB was accepted") + } +} + +// 旧空 mode 计划没有映射契约:真实写入路径必须按原 ID 落库并因此与旧库冲突, +// 证明新进程不会给历史计划隐式重映射。 +func TestLegacyPlanWithoutModeDoesNotRemapIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + if _, err := fx.pool.Exec(fx.ctx, `INSERT INTO knowledges VALUES('doc-src',10001,$1,'completed',0,'',NULL)`, wsOtherKB); err != nil { + t.Fatal(err) + } + snapshot := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + archive, err := librarysnapshot.Open(fx.archiveRoot, 256*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + manifest, err := archive.Load(snapshot) + if err != nil { + t.Fatal(err) + } + target.disableTargetMapping() + if err := target.bindSnapshotScope(manifestScope{tenantID: manifest.TenantID, knowledgeBaseID: manifest.KnowledgeBaseID}); err != nil { + t.Fatal(err) + } + err = target.importRows(context.Background(), archive, manifest, "database") + if err == nil || !strings.Contains(strings.ToLower(err.Error()), "duplicate") && !strings.Contains(err.Error(), "冲突") { + t.Fatalf("legacy path must write original ids and fail on the old-kb collision, got %v", err) + } +} diff --git a/internal/releaseadapter/v071/library_target_ids_test.go b/internal/releaseadapter/v071/library_target_ids_test.go new file mode 100644 index 0000000..1359086 --- /dev/null +++ b/internal/releaseadapter/v071/library_target_ids_test.go @@ -0,0 +1,263 @@ +package v071 + +import ( + "encoding/json" + "strings" + "testing" + + "knowledge-governance/internal/libraryrelease" +) + +// 目标隔离映射的行为契约:同源对象在不同目标 KB 必须得到不同 ID;同一目标 +// 跨作业/跨版本稳定;引用字段与身份字段一起换,正文不得被改。 +func TestTargetIDMapperIsScopedAndStable(t *testing.T) { + a := newTargetIDMapper(10000, "kb-a", nil) + b := newTargetIDMapper(10000, "kb-b", nil) + first := a.mapID("chunks", "0d25c09c-5af7-4cee-8b6e-a0b129caeb63") + if first == "0d25c09c-5af7-4cee-8b6e-a0b129caeb63" { + t.Fatalf("mapping returned the source id unchanged") + } + if len(first) != 36 || strings.Count(first, "-") != 4 { + t.Fatalf("mapped id is not uuid-shaped: %q", first) + } + if again := a.mapID("chunks", "0d25c09c-5af7-4cee-8b6e-a0b129caeb63"); again != first { + t.Fatalf("mapping is not deterministic: %q != %q", first, again) + } + if other := b.mapID("chunks", "0d25c09c-5af7-4cee-8b6e-a0b129caeb63"); other == first { + t.Fatalf("different target KB produced the same id") + } + if cross := a.mapID("wiki_pages", "0d25c09c-5af7-4cee-8b6e-a0b129caeb63"); cross == first { + t.Fatalf("different tables collided on one id") + } +} + +func rawTargetRow(t *testing.T, v any) map[string]json.RawMessage { + t.Helper() + encoded, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + var row map[string]json.RawMessage + if err := json.Unmarshal(encoded, &row); err != nil { + t.Fatal(err) + } + return row +} + +func TestTargetIDMapperRewritesChunkReferences(t *testing.T) { + m := newTargetIDMapper(10000, "kb-a", nil) + chunk := "11111111-1111-4111-8111-111111111111" + m.registerSourceID("chunks", chunk) + know := "22222222-2222-4222-8222-222222222222" + m.registerSourceID("knowledges", know) + parent := "33333333-3333-4333-8333-333333333333" + m.registerSourceID("chunks", parent) + row := rawTargetRow(t, map[string]any{ + "id": chunk, "knowledge_id": know, "parent_chunk_id": parent, + "pre_chunk_id": parent, "next_chunk_id": parent, + "relation_chunks": []string{parent}, + "indirect_relation_chunks": []any{map[string]any{"id": parent}}, + "metadata": map[string]any{"source_chunk": parent}, + "content": "正文里出现 " + parent + " 也不能被改", + }) + if err := m.remapRow("chunks", row); err != nil { + t.Fatal(err) + } + if got := jsonString(t, row["id"]); got != m.mapID("chunks", chunk) { + t.Fatalf("chunk id not remapped: %s", got) + } + if got := jsonString(t, row["knowledge_id"]); got != m.mapID("knowledges", know) { + t.Fatalf("knowledge_id not remapped: %s", got) + } + if got := jsonString(t, row["parent_chunk_id"]); got != m.mapID("chunks", parent) { + t.Fatalf("parent_chunk_id not remapped: %s", got) + } + var content string + _ = json.Unmarshal(row["content"], &content) + if content != "正文里出现 "+parent+" 也不能被改" { + t.Fatalf("content was rewritten: %q", content) + } + var rel []string + _ = json.Unmarshal(row["relation_chunks"], &rel) + if rel[0] != m.mapID("chunks", parent) { + t.Fatalf("relation_chunks not remapped: %v", rel) + } + var meta map[string]any + _ = json.Unmarshal(row["metadata"], &meta) + if meta["source_chunk"] != parent { + t.Fatalf("non-reference metadata payload must stay byte-identical: %v", meta) + } +} + +func TestTargetIDMapperRewritesWikiRefsPreservingShape(t *testing.T) { + m := newTargetIDMapper(10000, "kb-a", nil) + c1 := "44444444-4444-4444-8444-444444444444" + m.registerSourceID("chunks", c1) + c2 := "55555555-5555-4555-8555-555555555555" + m.registerSourceID("chunks", c2) + k := "66666666-6666-4666-8666-666666666666" + m.registerSourceID("knowledges", k) + m.registerSourceID("wiki_pages", "77777777-7777-4777-8777-777777777777") + m.registerSourceID("wiki_folders", "88888888-8888-4888-8888-888888888888") + row := rawTargetRow(t, map[string]any{ + "id": "77777777-7777-4777-8777-777777777777", "folder_id": "88888888-8888-4888-8888-888888888888", + "chunk_refs": []string{c1, c1, c2}, + "source_refs": []string{k + "|文档", k}, + "content": "body", "title": "t", + }) + if err := m.remapRow("wiki_pages", row); err != nil { + t.Fatal(err) + } + var refs []string + _ = json.Unmarshal(row["chunk_refs"], &refs) + if len(refs) != 3 || refs[0] != m.mapID("chunks", c1) || refs[1] != refs[0] || refs[2] != m.mapID("chunks", c2) { + t.Fatalf("chunk_refs shape/order/dupes not preserved: %v", refs) + } + var src []string + _ = json.Unmarshal(row["source_refs"], &src) + if src[0] != m.mapID("knowledges", k)+"|文档" || src[1] != m.mapID("knowledges", k) { + t.Fatalf("source_refs not remapped: %v", src) + } + var content string + _ = json.Unmarshal(row["content"], &content) + if content != "body" { + t.Fatal("wiki body changed") + } +} + +func TestTargetIDMapperKeepsSharedResourceIdentity(t *testing.T) { + m := newTargetIDMapper(10000, "kb-a", nil) + res := "99999999-9999-4999-8999-999999999999" + m.registerSourceID("resource_bindings", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb") + know := "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" + m.registerSourceID("knowledges", know) + row := rawTargetRow(t, map[string]any{"id": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "resource_id": res, "owner_id": know, "owner_type": "knowledge"}) + if err := m.remapRow("resource_bindings", row); err != nil { + t.Fatal(err) + } + if got := jsonString(t, row["resource_id"]); got != res { + t.Fatalf("shared resource id must not be remapped: %s", got) + } + if got := jsonString(t, row["owner_id"]); got != m.mapID("knowledges", know) { + t.Fatalf("owner_id not remapped: %s", got) + } +} + +func TestTargetIDMapperRejectsUnmappedReference(t *testing.T) { + m := newTargetIDMapper(10000, "kb-a", nil) + m.registerSourceID("chunks", "cccccccc-cccc-4ccc-8ccc-cccccccccccc") + row := rawTargetRow(t, map[string]any{"id": "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "chunk_refs": []string{"eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"}}) + if err := m.remapRow("wiki_pages", row); err == nil { + t.Fatal("unmapped dangling reference was accepted") + } +} + +func TestTargetIndexDocumentMapping(t *testing.T) { + m := newTargetIDMapper(10000, "kb-a", nil) + chunk := "12121212-1212-4212-8212-121212121212" + m.registerSourceID("chunks", chunk) + doc := []byte(`{"chunk_id":"` + chunk + `","knowledge_base_id":"old","content":"c"}`) + id, source, err := m.remapIndexDocument("doc-1", doc) + if err != nil { + t.Fatal(err) + } + if id == "doc-1" { + t.Fatal("index document id not remapped") + } + var out map[string]any + if err := json.Unmarshal(source, &out); err != nil { + t.Fatal(err) + } + if out["chunk_id"] != m.mapID("chunks", chunk) { + t.Fatalf("index chunk_id not remapped: %v", out["chunk_id"]) + } + if out["content"] != "c" { + t.Fatal("index content changed") + } +} + +func TestTargetIDMapperRewritesRelationTuple(t *testing.T) { + m := newTargetIDMapper(10000, "kb-a", nil) + know := "13131313-1313-4131-8131-131313131313" + tag := "14141414-1414-4141-8141-141414141414" + m.registerSourceID("knowledges", know) + m.registerSourceID("knowledge_tags", tag) + row := rawTargetRow(t, map[string]any{"knowledge_id": know, "tag_id": tag}) + if err := m.remapRow("knowledge_tag_relations", row); err != nil { + t.Fatal(err) + } + if jsonString(t, row["knowledge_id"]) != m.mapID("knowledges", know) || jsonString(t, row["tag_id"]) != m.mapID("knowledge_tags", tag) { + t.Fatal("relation tuple not remapped") + } +} + +func TestTargetMappingOnlyAppliesToTargetSnapshot(t *testing.T) { + plan := &libraryrelease.WriteSet{TargetSnapshotID: "target-seal", BackupSnapshotID: "backup-seal"} + target := &ProductionLibraryTarget{activePlan: plan, targetIDMode: libraryrelease.TargetIDModeScoped} + if !target.targetMappingApplies("target-seal") { + t.Fatal("target snapshot must be mapped") + } + if target.targetMappingApplies("backup-seal") { + t.Fatal("backup/before-image must not be mapped") + } + target.preserveChunkSequence = true + if target.targetMappingApplies("target-seal") { + t.Fatal("restore replay must not be mapped") + } + target.preserveChunkSequence = false + target.targetIDMode = "" + if target.targetMappingApplies("target-seal") { + t.Fatal("legacy plan without target id mode must not be mapped") + } +} + +func TestTargetIDMapperPreservesLargeNumbersAndRejectsAmbiguity(t *testing.T) { + m := newTargetIDMapper(10000, "kb-a", nil) + chunk := "15151515-1515-4515-8515-151515151515" + m.registerSourceID("chunks", chunk) + // 同列还有 9007199254740993(>2^53):必须逐字节保留。 + row := rawTargetRow(t, map[string]any{"id": "16161616-1616-4616-8616-161616161616", + "relation_chunks": json.RawMessage(`["` + chunk + `",9007199254740993]`)}) + m.registerSourceID("chunks", "16161616-1616-4616-8616-161616161616") + if err := m.remapRow("chunks", row); err != nil { + t.Fatal(err) + } + if got := string(row["relation_chunks"]); got != `["`+m.mapID("chunks", chunk)+`",9007199254740993]` { + t.Fatalf("relation payload not preserved: %s", got) + } + // 同一字符串 ID 同时出现在两张表:不能 first-table-wins 猜映射。 + same := "17171717-1717-4717-8717-171717171717" + m.registerSourceID("chunks", same) + m.registerSourceID("knowledges", same) + m.registerSourceID("chunks", "18181818-1818-4818-8818-181818181818") + shared := rawTargetRow(t, map[string]any{"id": "18181818-1818-4818-8818-181818181818", + "relation_chunks": []string{same}}) + if err := m.remapRow("chunks", shared); err != nil { + t.Fatalf("typed chunk reference rejected for cross-table same id: %v", err) + } + if got := string(shared["relation_chunks"]); got != `["`+m.mapID("chunks", same)+`"]` { + t.Fatalf("relation must resolve by field semantics: %s", got) + } +} + +func TestTargetIDMapperDoesNotInventEntitiesFromReferences(t *testing.T) { + // 引用值不能反向登记为实体:wiki page 的 chunk_refs 指向一个不存在的主键。 + m := newTargetIDMapper(10000, "kb-a", nil) + m.registerSourceID("wiki_pages", "19191919-1919-4919-8919-191919191919") + row := rawTargetRow(t, map[string]any{"id": "19191919-1919-4919-8919-191919191919", + "chunk_refs": []string{"20202020-2020-4020-8020-202020202020"}}) + if err := m.remapRow("wiki_pages", row); err == nil { + t.Fatal("dangling chunk_ref was accepted") + } +} + +func jsonString(t *testing.T, raw json.RawMessage) string { + t.Helper() + var s string + if err := json.Unmarshal(raw, &s); err != nil { + t.Fatalf("not a string: %s", raw) + } + return s +} diff --git a/internal/releaseadapter/v071/library_target_path.go b/internal/releaseadapter/v071/library_target_path.go new file mode 100644 index 0000000..34eb995 --- /dev/null +++ b/internal/releaseadapter/v071/library_target_path.go @@ -0,0 +1,116 @@ +package v071 + +import ( + "encoding/json" + "errors" + "fmt" + "sort" + + "knowledge-governance/internal/libraryrelease" + + "knowledge-governance/internal/librarysnapshot" +) + +// enableTargetMapping 为目标快照构建一次映射器。源身份集合来自归档本身, +// 因此引用字段的"未登记即悬挂"判断与真实数据一致,不靠猜测。 +func (t *ProductionLibraryTarget) enableTargetMapping(archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error { + if t.scope.TenantID == 0 || t.scope.KnowledgeBaseID == "" { + return errors.New("目标范围身份不完整,拒绝生成目标 ID 映射") + } + mapper, err := targetIDMapperFromArchive(archive, manifest, t.scope.TenantID, t.scope.KnowledgeBaseID) + if err != nil { + return fmt.Errorf("构建目标 ID 映射失败: %w", err) + } + t.targetIDs = mapper + t.mappingActive = true + return nil +} + +func (t *ProductionLibraryTarget) disableTargetMapping() { + t.targetIDs = nil + t.mappingActive = false +} + +// targetMappingApplies 只在"把目标快照写进目标"时启用映射; +// 备份/恢复快照里的 ID 是目标自己的既有身份,二次映射会把恢复写坏。 +func (t *ProductionLibraryTarget) targetMappingApplies(snapshotID string) bool { + // 只有持久计划显式声明 scoped 契约时才映射。空 mode 是历史计划: + // 它登记的就是原身份,重映射会把恢复/重试写到别的 ID 上。 + if t.targetIDMode != libraryrelease.TargetIDModeScoped || t.preserveChunkSequence || snapshotID == "" { + return false + } + if t.activePlan == nil { + return false + } + return snapshotID == t.activePlan.TargetSnapshotID +} + +// archivedRowIdentitiesFor 返回写入后的目标身份集合(映射开启时)或归档原身份。 +func (t *ProductionLibraryTarget) archivedRowIdentitiesFor(archive *librarysnapshot.Archive, part librarysnapshot.Part) ([]string, error) { + if !t.mappingActive { + return archivedRowIdentities(archive, part) + } + reader, err := archive.OpenPart(part) + if err != nil { + return nil, err + } + defer reader.Close() + decoder := json.NewDecoder(reader) + token, err := decoder.Token() + if err != nil || token != json.Delim('[') { + return nil, errors.New("归档部件不是行数组") + } + transform := t.rowTransform(part.Name) + ids := make([]string, 0, 64) + for decoder.More() { + var row map[string]json.RawMessage + if err := decoder.Decode(&row); err != nil { + return nil, err + } + if err := transform(row); err != nil { + return nil, err + } + identity, err := parseRowIdentity(part.Name, row) + if err != nil { + return nil, err + } + ids = append(ids, identity.key()) + } + return ids, nil +} + +// archivedTableState 是 archivedTableState 的目标映射版本:身份摘要按写入后的 +// ID 计算,否则"写对了"也会被判成与快照不一致。 +func (t *ProductionLibraryTarget) archivedTableState(archive *librarysnapshot.Archive, part librarysnapshot.Part) (int64, string, error) { + if !t.mappingActive { + return archivedTableState(archive, part) + } + ids, err := t.archivedRowIdentitiesFor(archive, part) + if err != nil { + if errors.Is(err, errMissingIdentity) { + return 0, "", err + } + return 0, "", err + } + sort.Strings(ids) + return int64(len(ids)), digestIDs(ids), nil +} + +// remapIndexMap 把目标快照索引文档的物理 ID 与引用换成目标身份。 +func (t *ProductionLibraryTarget) remapIndexMap(documents map[string]json.RawMessage) (map[string]json.RawMessage, error) { + if !t.mappingActive { + return documents, nil + } + out := make(map[string]json.RawMessage, len(documents)) + for id, source := range documents { + mappedID, mappedSource, err := t.targetIDs.remapIndexDocument(id, source) + if err != nil { + return nil, err + } + if _, exists := out[mappedID]; exists { + return nil, errors.New("index target id collision") + } + out[mappedID] = mappedSource + } + return out, nil +} diff --git a/internal/releaseadapter/v071/library_target_probe.go b/internal/releaseadapter/v071/library_target_probe.go new file mode 100644 index 0000000..29a5425 --- /dev/null +++ b/internal/releaseadapter/v071/library_target_probe.go @@ -0,0 +1,43 @@ +package v071 + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// ProbeTargetIdentity 只读地探测"这个 DSN + 知识库"此刻在目标里是什么。 +// +// 用途是执行域准入(R4):worker 注册整库发布 handler 之前必须拿到**目标实况**, +// 而不是回声自己的配置。这里复用与发布路径同一份 SQL(liveTargetContractSQL), +// 避免"准入读一份、发布读另一份"的分叉。探测连接短命、只读、失败即返回错误。 +func ProbeTargetIdentity(ctx context.Context, dsn string, tenantID uint64, knowledgeBaseID string) (LiveTargetContract, error) { + if dsn == "" || tenantID == 0 || knowledgeBaseID == "" { + return LiveTargetContract{}, errors.New("probe requires dsn, tenant and knowledge base") + } + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + return LiveTargetContract{}, fmt.Errorf("connect target for probe: %w", err) + } + defer pool.Close() + probeCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + var ( + contract LiveTargetContract + declared string + indexName string + ) + if err := pool.QueryRow(probeCtx, liveTargetContractSQL, knowledgeBaseID, tenantID).Scan( + &contract.SchemaVersion, &contract.Dirty, &contract.EmbeddingModel, &contract.EmbeddingDimension, + &contract.ModelBound, &declared, &contract.EngineType, &indexName); err != nil { + return LiveTargetContract{}, fmt.Errorf("read target identity: %w", err) + } + if !contract.ModelBound && declared != "" { + contract.EmbeddingModel = declared + } + contract.IndexName = indexName + return contract, nil +} diff --git a/internal/releaseadapter/v071/library_target_real_seal_test.go b/internal/releaseadapter/v071/library_target_real_seal_test.go new file mode 100644 index 0000000..e6c8515 --- /dev/null +++ b/internal/releaseadapter/v071/library_target_real_seal_test.go @@ -0,0 +1,205 @@ +package v071 + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "sort" + "testing" + + "knowledge-governance/internal/librarysnapshot" +) + +// 用真实封存做离线转换闭包证明:不依赖人工精简 fixture。 +// 只读归档;不写数据库/对象存储,不联网。 +func TestRealSealTargetMappingClosure(t *testing.T) { + root := os.Getenv("KG_LIBRARY_ARCHIVE_ROOT") + if root == "" { + root = filepath.Join(os.Getenv("HOME"), ".local/share/knowledge-governance/library") + } + const seal = "2c6db552d3b2119dc8e3c6d7c39cb4993a47396ca5bb4e38cfd05e947126c4a8" + if _, err := os.Stat(filepath.Join(root, "versions", seal+".json")); err != nil { + t.Skip("real seal not present on this host") + } + archive, err := librarysnapshot.Open(root, 256*1024*1024) + if err != nil { + t.Fatalf("open archive: %v", err) + } + defer archive.Close() + manifest, err := archive.Load(seal) + if err != nil { + t.Fatalf("load seal: %v", err) + } + target := &ProductionLibraryTarget{} + target.scope.TenantID = 10000 + target.scope.KnowledgeBaseID = "a8e9c8ad-411c-4c53-8421-599d29e9b179" + target.snapshotTenant = manifest.TenantID + target.snapshotKB = manifest.KnowledgeBaseID + if err := target.enableTargetMapping(archive, manifest); err != nil { + t.Fatalf("enable mapping: %v", err) + } + mapper := target.targetIDs + t.Logf("mapping_active=%v known_chunks=%d known_know=%d known_pages=%d", target.mappingActive, len(mapper.known["chunks"]), len(mapper.known["knowledges"]), len(mapper.known["wiki_pages"])) + other := newTargetIDMapper(10000, "kb-other-target", nil) + mappedChunks := map[string]bool{} + mappedKnowledge := map[string]bool{} + counts := map[string]int{} + for _, part := range manifest.Parts { + if part.Kind != "database" && part.Kind != "wiki" { + continue + } + reader, err := archive.OpenPart(part) + if err != nil { + t.Fatal(err) + } + var rows []map[string]json.RawMessage + err = json.NewDecoder(reader).Decode(&rows) + reader.Close() + if err != nil { + t.Fatal(err) + } + transform := target.rowTransform(part.Name) + for _, row := range rows { + var sourceID string + if raw, ok := row["id"]; ok { + _ = json.Unmarshal(raw, &sourceID) + } + if err := transform(row); err != nil { + t.Fatalf("%s row %s: %v", part.Name, sourceID, err) + } + counts[part.Name]++ + var mappedID string + if raw, ok := row["id"]; ok { + _ = json.Unmarshal(raw, &mappedID) + } + switch part.Name { + case "chunks": + if mappedID == sourceID { + t.Fatalf("chunk id was not remapped: %s", sourceID) + } + if other.mapID("chunks", sourceID) == mappedID { + t.Fatalf("different target reused mapped chunk id") + } + mappedChunks[mappedID] = true + case "knowledges": + mappedKnowledge[mappedID] = true + case "resources": + if mappedID != sourceID { + t.Fatalf("shared resource id must be preserved: %s -> %s", sourceID, mappedID) + } + case "wiki_log_entries": + // id 是目标本地 bigint,映射器不得改动其类型或值。 + var number json.Number + if err := json.Unmarshal(row["id"], &number); err != nil { + t.Fatalf("log id must stay numeric: %s", row["id"]) + } + } + } + } + // 引用闭包:所有 chunk_refs / source_refs 必须落在映射后的同库身份里。 + for _, part := range manifest.Parts { + if part.Kind != "wiki" || part.Name != "wiki_pages" { + continue + } + reader, _ := archive.OpenPart(part) + var rows []map[string]json.RawMessage + _ = json.NewDecoder(reader).Decode(&rows) + reader.Close() + transform := target.rowTransform("wiki_pages") + for _, row := range rows { + if err := transform(row); err != nil { + t.Fatal(err) + } + var refs, sources []string + _ = json.Unmarshal(row["chunk_refs"], &refs) + _ = json.Unmarshal(row["source_refs"], &sources) + for _, ref := range refs { + if !mappedChunks[ref] { + t.Fatalf("chunk ref %s is not a mapped live chunk", ref) + } + } + for _, ref := range sources { + id := ref + if i := len(ref) - len("|"); i > 0 { + // "id|title" 形式:只比较前段 + for j := 0; j < len(ref); j++ { + if ref[j] == '|' { + id = ref[:j] + break + } + } + } + if !mappedKnowledge[id] { + t.Fatalf("source ref %s is not a mapped knowledge", id) + } + } + } + } + // 索引文档:ID/引用都换到目标身份,正文与向量字段不动。 + for _, part := range manifest.Parts { + if part.Kind != "index" { + continue + } + reader, _ := archive.OpenPart(part) + docs, err := librarysnapshot.ReadIndexDocuments(reader) + reader.Close() + if err != nil { + t.Fatal(err) + } + for _, document := range docs { + mappedID, source, err := mapper.remapIndexDocument(document.ID, document.Source) + if err != nil { + t.Fatal(err) + } + if mappedID == document.ID { + t.Fatal("index doc id not remapped") + } + var fields map[string]any + if err := json.Unmarshal(source, &fields); err != nil { + t.Fatal(err) + } + chunkID, _ := fields["chunk_id"].(string) + if !mappedChunks[chunkID] { + t.Fatalf("index chunk_id %s not in mapped chunk set", chunkID) + } + } + } + // 写集合身份必须用映射后的 ID:同一目标重复计算结果一致,且与源身份不同。 + for _, part := range manifest.Parts { + if part.Kind != "database" && part.Kind != "wiki" { + continue + } + if part.Name != "chunks" && part.Name != "knowledges" && part.Name != "wiki_pages" { + continue + } + first, err := target.archivedRowIdentitiesFor(archive, part) + if err != nil { + t.Fatalf("%s identities: %v", part.Name, err) + } + second, err := target.archivedRowIdentitiesFor(archive, part) + if err != nil { + t.Fatal(err) + } + sort.Strings(first) + sort.Strings(second) + if len(first) != len(second) { + t.Fatalf("%s identity count changed between runs", part.Name) + } + for i := range first { + if first[i] != second[i] { + t.Fatalf("%s identity is not deterministic", part.Name) + } + } + } + want := map[string]int{"knowledges": 4, "chunks": 38, "wiki_pages": 31, "wiki_folders": 21, "wiki_log_entries": 11} + for table, n := range want { + if counts[table] != n { + t.Fatalf("%s rows=%d want %d", table, counts[table], n) + } + } + if _, err := os.Stat(filepath.Join(root, "versions", seal+".json")); err != nil { + t.Fatal(errors.New("archive changed during test")) + } + t.Logf("mapped rows=%v chunks=%d knowledges=%d", counts, len(mappedChunks), len(mappedKnowledge)) +} diff --git a/internal/releaseadapter/v071/library_universe.go b/internal/releaseadapter/v071/library_universe.go index 4abf5fb..5674e7f 100644 --- a/internal/releaseadapter/v071/library_universe.go +++ b/internal/releaseadapter/v071/library_universe.go @@ -13,19 +13,29 @@ import ( "knowledge-governance/internal/librarysnapshot" ) -// universeFingerprint 是"整实例"的知识域指纹:不限租户/知识库的行数 + 身份集合摘要。 +// universeFingerprint 是"整实例"的知识域指纹:不限租户/知识库的行数与**逐行内容**摘要。 // // 为什么不能只比目标范围:恢复只按目标范围删除/回放,写到范围外的残留它看不见 // (真实事故:作业报"已恢复到预备份",目标却多出 4 文件 / 38 分块 / 21 资源 / -// 4 绑定)。整实例指纹让"多写了什么"必然暴露,同时也能证明恢复没有误删别的 -// 知识库的行。 +// 4 绑定)。整实例指纹让"多写了什么"必然暴露,同时也能证明恢复没有误删、误改 +// 别的知识库的行。 +// +// 为什么必须是内容而不是身份集合:只比 id 集合时,"另一个知识库的同 ID 行被覆盖 +// 写坏"(资源表的 ON CONFLICT 就会这样)在指纹上完全看不出来——数量、身份都一样。 +// 因此摘要取自每行 to_jsonb 的 md5,再按身份排序聚合。 func universeFingerprint(ctx context.Context, pool *pgxpool.Pool) (map[string]libraryrelease.TableFingerprint, error) { - result := make(map[string]libraryrelease.TableFingerprint, len(productionLibraryTables)) - for _, table := range productionLibraryTables { + // 表集合来自目标库自己的 profile:0.9.0 没有 wiki_log_entries,按 0.7.1 的固定 + // 清单取指纹会在第一张不存在的表上失败,而"跳过缺表"又会让 0.7.1 少表蒙混过去。 + schema, err := ResolveSchemaProfile(ctx, pool, "whole-instance fingerprint") + if err != nil { + return nil, err + } + result := make(map[string]libraryrelease.TableFingerprint, len(schema.Tables)) + for _, table := range schema.Tables { identity := identityExpr(table) statement := fmt.Sprintf( - `SELECT count(*), coalesce(md5(string_agg((%s)::text, E'\n' ORDER BY (%s)::text)), '') FROM %s`, - identity, identity, table) + `SELECT count(*), coalesce(md5(string_agg(md5(to_jsonb(x)::text), E'\n' ORDER BY (%s)::text)), '') FROM %s AS x`, + identity, table) var fingerprint libraryrelease.TableFingerprint if err := pool.QueryRow(ctx, statement).Scan(&fingerprint.Count, &fingerprint.Digest); err != nil { return nil, fmt.Errorf("读取整库 %s 指纹失败: %w", table, err) @@ -53,11 +63,17 @@ func archivedRowIdentities(archive *librarysnapshot.Archive, part librarysnapsho if err := decoder.Decode(&row); err != nil { return nil, err } - identity := archiveRowIdentity(part.Name, row) - if identity == "" { - continue + identity, err := parseRowIdentity(part.Name, row) + if err != nil { + return nil, err } - ids = append(ids, identity) + key := identity.key() + for _, previous := range ids { + if previous == key { + return nil, fmt.Errorf("duplicate %s identity", part.Name) + } + } + ids = append(ids, key) } return ids, nil } @@ -105,6 +121,11 @@ func (t *ProductionLibraryTarget) assertNoSourceScopeRows(ctx context.Context, a if !tableHasTenant(part.Name) { continue } + // DB-local source numbers have no target-global ownership meaning. + // The mapped target values are checked by the typed content verifier. + if part.Name == "wiki_log_entries" && t.activePlan != nil && t.activeSnapshot == t.activePlan.TargetSnapshotID { + continue + } ids, err := archivedRowIdentities(archive, part) if err != nil { return err @@ -112,9 +133,23 @@ func (t *ProductionLibraryTarget) assertNoSourceScopeRows(ctx context.Context, a if len(ids) == 0 { continue } - statement := fmt.Sprintf(`SELECT count(*) FROM %s WHERE tenant_id=$1 AND id = ANY($2::text[])`, part.Name) + // Shared tables have no KB column. Equal tenant identity is not + // evidence of leakage; their ownership is checked by the plan. + if !tablesWithKB[part.Name] && t.snapshotTenant == t.scope.TenantID { + continue + } + cast := "text" + if part.Name == "wiki_log_entries" { + cast = "bigint" + } + statement := fmt.Sprintf(`SELECT count(*) FROM %s WHERE tenant_id=$1 AND id = ANY($2::%s[])`, part.Name, cast) + args := []any{t.snapshotTenant, ids} + if tablesWithKB[part.Name] { + statement += " AND knowledge_base_id=$3" + args = append(args, t.snapshotKB) + } var count int64 - if err := t.pool.QueryRow(ctx, statement, t.snapshotTenant, ids).Scan(&count); err != nil { + if err := t.pool.QueryRow(ctx, statement, args...).Scan(&count); err != nil { return fmt.Errorf("检查目标 %s 的来源范围残留失败: %w", part.Name, err) } if count > 0 { diff --git a/internal/releaseadapter/v071/library_verify_content.go b/internal/releaseadapter/v071/library_verify_content.go index d458246..3e7668e 100644 --- a/internal/releaseadapter/v071/library_verify_content.go +++ b/internal/releaseadapter/v071/library_verify_content.go @@ -1,6 +1,7 @@ package v071 import ( + "bytes" "context" "crypto/sha256" "encoding/hex" @@ -22,7 +23,6 @@ var contentVolatileFields = map[string]bool{ "created_at": true, "updated_at": true, "processed_at": true, - "expires_at": true, } func canonicalRowDigest(raw map[string]json.RawMessage) (string, error) { @@ -32,7 +32,9 @@ func canonicalRowDigest(raw map[string]json.RawMessage) (string, error) { continue } var decoded any - if err := json.Unmarshal(value, &decoded); err != nil { + decoder := json.NewDecoder(bytes.NewReader(value)) + decoder.UseNumber() + if err := decoder.Decode(&decoded); err != nil { return "", fmt.Errorf("decode column %s: %w", key, err) } normalized[key] = decoded @@ -66,22 +68,52 @@ func joinLines(items []string) string { // 归档没有的列(生产默认值/后续新增列)不参与比对,避免"我们没管的列"造成假失败, // 但归档里有的每一列都必须逐字一致。 func (t *ProductionLibraryTarget) productionTableContent(ctx context.Context, table string, columns map[string]bool) (int64, string, error) { - // 不加表别名:scopeWhere(resources) 里引用了 resources.id,别名会让它失效。 - rows, err := t.pool.Query(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`, table, table, scopeWhere(table)), - t.scope.TenantID, t.scope.KnowledgeBaseID) - if err != nil { - return 0, "", fmt.Errorf("读取生产 %s 内容失败: %w", table, err) + identity := PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID} + exporter := PostgresExporter{db: t.pool} + var rows []json.RawMessage + if table == "resources" { + // F01: verification must use the same bounded reference set as capture; + // the legacy per-resource body scan made post-sync verification minutes + // long on a small target inside a large tenant. + var bodies, bindings []json.RawMessage + for _, name := range t.tables { + if name == "resources" { + continue + } + items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`, + name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID) + if err != nil { + return 0, "", fmt.Errorf("读取生产 %s 内容失败: %w", table, err) + } + if name != "resource_bindings" && name != "knowledge_tag_relations" { + bodies = append(bodies, items...) + } + if name == "resource_bindings" { + bindings = items + } + } + items, err := scopedResourceRows(ctx, &exporter, identity, true, bodies, bindings) + if err != nil { + return 0, "", fmt.Errorf("读取生产 %s 内容失败: %w", table, err) + } + rows = items + } else { + items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`, table, table, t.scopeWhere(table)), + identity.TenantID, identity.KnowledgeBaseID) + if err != nil { + return 0, "", fmt.Errorf("读取生产 %s 内容失败: %w", table, err) + } + rows = items } - defer rows.Close() - digests := make([]string, 0, 64) - for rows.Next() { - var raw map[string]json.RawMessage - if err := rows.Scan(&raw); err != nil { + digests := make([]string, 0, len(rows)) + for _, raw := range rows { + var value map[string]json.RawMessage + if err := json.Unmarshal(raw, &value); err != nil { return 0, "", err } projected := make(map[string]json.RawMessage, len(columns)) for key := range columns { - if value, ok := raw[key]; ok { + if value, ok := value[key]; ok { projected[key] = value } } @@ -91,9 +123,6 @@ func (t *ProductionLibraryTarget) productionTableContent(ctx context.Context, ta } digests = append(digests, digest) } - if err := rows.Err(); err != nil { - return 0, "", err - } return int64(len(digests)), combineRowDigests(digests), nil } @@ -136,26 +165,29 @@ func archivedTableContent(archive *librarysnapshot.Archive, part librarysnapshot } // orphanIndexDocuments 找出"索引里有、生产分块里没有"的文档(按 chunk_id 关联)。 -func (t *ProductionLibraryTarget) orphanIndexDocuments(ctx context.Context, documents []SearchDocument) []string { +func (t *ProductionLibraryTarget) orphanIndexDocuments(ctx context.Context, documents []SearchDocument) ([]string, error) { if len(documents) == 0 { - return nil + return nil, nil } // 按文档归属判断而不是按 chunk_id:真实 WeKnora 是父子分块, // 索引里的子块 ID 本来就不在 chunks 表里,按 chunk_id 判会误报孤儿。 rows, err := t.pool.Query(ctx, `SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND deleted_at IS NULL`, t.scope.TenantID, t.scope.KnowledgeBaseID) if err != nil { - return nil + return nil, err } defer rows.Close() known := map[string]bool{} for rows.Next() { var id string if err := rows.Scan(&id); err != nil { - return nil + return nil, err } known[id] = true } + if err := rows.Err(); err != nil { + return nil, err + } orphans := make([]string, 0, 4) for _, document := range documents { var source struct { @@ -163,13 +195,13 @@ func (t *ProductionLibraryTarget) orphanIndexDocuments(ctx context.Context, docu KnowledgeID string `json:"knowledge_id"` } if json.Unmarshal(document.Source, &source) != nil || source.KnowledgeID == "" { - continue + return nil, errors.New("index document has invalid or missing knowledge_id") } if !known[source.KnowledgeID] { orphans = append(orphans, document.ID) } } - return orphans + return orphans, nil } // firstIndexDifference 返回第一处不一致的文档 ID 与字段,便于定位。 @@ -227,6 +259,15 @@ func (t *ProductionLibraryTarget) verifyIndexDigest(ctx context.Context, archive if err != nil { return err } + if t.mappingActive && t.targetIDs != nil { + for i := range documents { + mappedID, mappedSource, err := t.targetIDs.remapIndexDocument(documents[i].ID, documents[i].Source) + if err != nil { + return err + } + documents[i] = librarysnapshot.IndexDocument{ID: mappedID, Source: mappedSource} + } + } archived := make([]SearchDocument, 0, len(documents)) for _, document := range documents { // 写入时 BulK Index 会把 tenant_id/knowledge_base_id 覆盖成本目标的身份, @@ -235,7 +276,11 @@ func (t *ProductionLibraryTarget) verifyIndexDigest(ctx context.Context, archive if err := json.Unmarshal(document.Source, &source); err != nil { return errors.New("归档索引文档不是对象") } - source["tenant_id"], _ = json.Marshal(t.scope.TenantID) + // 0.9.0 的分块文档只有 knowledge_base_id(索引里没有 tenant_id), + // 规范化必须按目标 profile 来,否则"写对了"也会被判成生产缺少字段。 + if t.schema.IndexTenantField { + source["tenant_id"], _ = json.Marshal(t.scope.TenantID) + } source["knowledge_base_id"], _ = json.Marshal(t.scope.KnowledgeBaseID) encoded, err := json.Marshal(source) if err != nil { @@ -247,6 +292,9 @@ func (t *ProductionLibraryTarget) verifyIndexDigest(ctx context.Context, archive } archived = append(archived, SearchDocument{ID: document.ID, Source: canonical}) } + // 目标 ID 映射会改变文档 ID 的排序位置;摘要按 ID 排序后的集合计算, + // 否则少一个/多一个的差异会被误报成"数量一致但摘要不同"。 + sort.Slice(archived, func(i, j int) bool { return archived[i].ID < archived[j].ID }) wantDigest, err := searchDocumentsDigest(archived) if err != nil { return err @@ -258,7 +306,11 @@ func (t *ProductionLibraryTarget) verifyIndexDigest(ctx context.Context, archive } // 孤儿向量:索引里有、数据库分块里没有的文档必须报出来。 // 只比"归档 vs 生产"会漏掉两边一致但都错的情况。 - if orphans := t.orphanIndexDocuments(ctx, snapshot.Documents); len(orphans) > 0 { + orphans, orphanErr := t.orphanIndexDocuments(ctx, snapshot.Documents) + if orphanErr != nil { + return fmt.Errorf("index ownership verification failed: %w", orphanErr) + } + if len(orphans) > 0 { return fmt.Errorf("生产索引存在 %d 条孤儿文档(所属文档已不在数据库),首个 %s", len(orphans), orphans[0]) } if len(snapshot.Documents) != len(archived) || snapshot.DocumentsSHA256 != wantDigest { diff --git a/internal/releaseadapter/v071/library_writeset.go b/internal/releaseadapter/v071/library_writeset.go new file mode 100644 index 0000000..0631123 --- /dev/null +++ b/internal/releaseadapter/v071/library_writeset.go @@ -0,0 +1,471 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// 写集合台账:一次发布的"明确写集合 + 写前存在状态 + 预备份时刻整实例证据"。 +// +// 为什么必须是持久记录而不是恢复时现算: +// 恢复发生在写失败之后,目标已经变了。此刻按"目标里没人引用的资源就是残渣"去删, +// 会连历史孤儿、同租户其它知识库暂未绑定的资源一起删掉——而预备份里没有这些行, +// 删了就是不可恢复的数据丢失(真实缺陷)。唯一可靠的口径是写之前就记下 +// "这次要写哪些精确 ID、哪些写前就已存在",恢复只删"写前不存在 ∧ 由本次写入"的那些。 + +// writeSetDirName 是台账在归档根下的固定目录,与快照同级:同一块持久卷, +// 重启后按摘要直接取回。 +const writeSetDirName = "writesets" + +func writeSetPath(archiveRoot, digest string) string { + return filepath.Join(archiveRoot, writeSetDirName, digest+".json") +} + +// PersistWriteSet 把台账按内容寻址落盘(文件名即 sha256),随后只读。 +// 幂等:同摘要文件已存在且内容一致就直接返回;内容不一致说明摘要被占用,必须失败。 +func PersistWriteSet(archiveRoot string, set *libraryrelease.WriteSet) (string, error) { + if set.Digest == "" { + if err := set.Seal(); err != nil { + return "", err + } + } + if len(set.Universe) == 0 { + return "", errors.New("写集合缺少整实例内容证据,拒绝落盘") + } + canonical, err := set.CanonicalBytes() + if err != nil { + return "", err + } + sum := sha256.Sum256(canonical) + digest := hex.EncodeToString(sum[:]) + if digest != set.Digest { + return "", errors.New("写集合摘要与内容不符,拒绝落盘") + } + raw, err := json.Marshal(*set) + if err != nil { + return "", fmt.Errorf("编码写集合失败: %w", err) + } + path := writeSetPath(archiveRoot, digest) + if err := persistImmutableJSON(path, raw); err != nil { + return "", err + } + return path, nil +} + +// LoadWriteSet 按摘要取回台账:文件名、字节摘要、内容摘要三者必须一致。 +// 任何一步不符都返回错误——治理库里的引用指向的就是这个摘要。 +func LoadWriteSet(archiveRoot, digest string) (*libraryrelease.WriteSet, error) { + if digest == "" { + return nil, errors.New("没有写集合摘要,无法取回记录") + } + path := writeSetPath(archiveRoot, digest) + raw, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("写集合记录缺失(%s)", digest) + } + var set libraryrelease.WriteSet + if err := json.Unmarshal(raw, &set); err != nil { + return nil, errors.New("写集合记录不可解析") + } + if err := set.Verify(); err != nil { + return nil, err + } + if set.Digest != digest { + return nil, errors.New("写集合记录摘要不符") + } + return &set, nil +} + +// PlanWriteSet 在写第一笔之前算出"这次明确要写什么",拒绝跨范围 ID 冲突, +// 并把台账落盘。返回的记录已 Seal 过;调用方负责把摘要登记到治理库。 +func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan libraryrelease.WriteSetPlan) (libraryrelease.WriteSet, error) { + if plan.JobID == "" || plan.BackupSnapshotID == "" || plan.TargetSnapshotID == "" { + return libraryrelease.WriteSet{}, errors.New("写集合缺少作业/预备份/快照身份") + } + if len(plan.Universe) == 0 { + return libraryrelease.WriteSet{}, errors.New("预备份没有整实例内容证据,拒绝在没有保护证据的情况下写目标") + } + // 资源复用的"整行内容"必须按写入时的同一套范围/存储改写来比,所以先把目标 + // 存储后端解析出来;解析不到就等于写不出可解析的定位符,直接拒绝。 + if err := t.resolveStorageBackend(ctx); err != nil { + return libraryrelease.WriteSet{}, err + } + // 每次预检都从空集开始:同一进程里复用目标对象时,上一次作业的"可复用" + // 判断不能泄漏到这一次。 + t.reusedResources = map[string]bool{} + archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024) + if err != nil { + return libraryrelease.WriteSet{}, errors.New("归档不可用") + } + defer archive.Close() + manifest, err := archive.Load(plan.TargetSnapshotID) + if err != nil { + return libraryrelease.WriteSet{}, errors.New("要同步的快照不可读") + } + if err := t.bindSnapshotScope(manifestScope{tenantID: manifest.TenantID, knowledgeBaseID: manifest.KnowledgeBaseID}); err != nil { + return libraryrelease.WriteSet{}, err + } + // 新计划必须从计划阶段就使用目标隔离身份:后面的归属检查、索引计划、 + // 写集合登记与 Apply/Verify 都要看到同一套 ID。 + if err := t.enableTargetMapping(archive, manifest); err != nil { + return libraryrelease.WriteSet{}, err + } + t.targetIDMode = libraryrelease.TargetIDModeScoped + if err := validateArchivedLibraryClosure(archive, manifest); err != nil { + return libraryrelease.WriteSet{}, err + } + if err := verifyLibraryRelationalClosure(ctx, t.pool, PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, true); err != nil { + return libraryrelease.WriteSet{}, err + } + schemaDigest, err := t.preflightMigrationCatalog(ctx, archive, manifest) + if err != nil { + return libraryrelease.WriteSet{}, err + } + backupResources, err := archivedSnapshotResourceIDs(archive, plan.BackupSnapshotID) + if err != nil { + return libraryrelease.WriteSet{}, err + } + resourceIDs := make([]string, 0, len(backupResources)) + for id := range backupResources { + resourceIDs = append(resourceIDs, id) + } + for _, part := range manifest.Parts { + if part.Kind == "resource" { + resourceIDs = append(resourceIDs, part.Name) + } + } + if err := verifyLibraryResourceOwners(ctx, t.pool, resourceIDs); err != nil { + return libraryrelease.WriteSet{}, err + } + set := libraryrelease.WriteSet{SchemaDigest: schemaDigest, Version: libraryrelease.MigrationWriteSetVersion, ContractVersion: migrationIdentityContractVersion, + SourceTenantID: manifest.TenantID, SourceKnowledgeBaseID: manifest.KnowledgeBaseID, JobID: plan.JobID, Target: plan.Target, + TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID, + BackupSnapshotID: plan.BackupSnapshotID, TargetSnapshotID: plan.TargetSnapshotID, + CreatedAt: t.now().UTC(), Universe: plan.Universe, TargetIDMode: libraryrelease.TargetIDModeScoped} + for _, part := range manifest.Parts { + if part.Kind != "database" && part.Kind != "wiki" { + continue + } + ids, err := t.archivedRowIdentitiesFor(archive, part) + if err != nil { + return libraryrelease.WriteSet{}, err + } + if len(ids) == 0 { + continue + } + if part.Name == "wiki_log_entries" { + continue + } // source IDs are local; target IDs are assigned below + owners, err := t.existingRowOwners(ctx, part.Name, ids) + if err != nil { + return libraryrelease.WriteSet{}, err + } + for _, id := range ids { + owner, exists := owners[id] + if !exists { + set.Rows = append(set.Rows, libraryrelease.WriteSetRow{Table: part.Name, ID: id}) + continue + } + if part.Name == resourceReuseTableName { + // 资源不在预备份范围,但可能正是这个目标上一次成功同步写进去、 + // 又被恢复保留下来的那份内容。只有"内容/字节相同 + 来源可审计" + // 才允许复用(不重写、不清理);否则按跨范围冲突拒绝。 + if err := t.assertResourceTenant(id, owner); err != nil { + return libraryrelease.WriteSet{}, err + } + row, reuseErr := t.planReusableResource(ctx, archive, manifest, part, id, owner, plan) + if reuseErr != nil { + return libraryrelease.WriteSet{}, reuseErr + } + set.Rows = append(set.Rows, row) + continue + } + if err := t.assertWriteSetOwnership(part.Name, id, owner, backupResources); err != nil { + return libraryrelease.WriteSet{}, err + } + set.Rows = append(set.Rows, libraryrelease.WriteSetRow{Table: part.Name, ID: id, Existing: true, Owner: owner}) + } + } + if err := t.preflightArchiveIndex(ctx, archive, manifest); err != nil { + return libraryrelease.WriteSet{}, err + } + if err := t.preflightNaturalKeys(ctx, archive, manifest); err != nil { + return libraryrelease.WriteSet{}, err + } + if err := t.planIndex(ctx, archive, manifest, &set); err != nil { + return libraryrelease.WriteSet{}, err + } + if err := t.planObjects(ctx, archive, manifest, &set); err != nil { + return libraryrelease.WriteSet{}, err + } + set.LocalIDs, err = t.localIDRequests(archive, manifest) + if err != nil { + return libraryrelease.WriteSet{}, err + } + if err := t.allocateLocalIDs(ctx, &set); err != nil { + return libraryrelease.WriteSet{}, err + } + if err := set.Seal(); err != nil { + return libraryrelease.WriteSet{}, err + } + if _, err := PersistWriteSet(t.config.ArchiveRoot, &set); err != nil { + return libraryrelease.WriteSet{}, err + } + if err := t.AdoptWriteSet(set); err != nil { + return libraryrelease.WriteSet{}, err + } + return set, nil +} + +// archivedSnapshotResourceIDs 读一份快照里"属于目标自己的资源身份"。 +// 资源表被多个知识库共享,只有在这份预备份里的资源行才允许被覆盖写。 +func archivedSnapshotResourceIDs(archive *librarysnapshot.Archive, snapshotID string) (map[string]bool, error) { + ids := map[string]bool{} + if snapshotID == "" { + return ids, nil + } + manifest, err := archive.Load(snapshotID) + if err != nil { + return nil, errors.New("预备份快照不可读") + } + for _, part := range manifest.Parts { + if part.Kind != "database" || part.Name != "resources" { + continue + } + values, err := archivedResourceIDs(archive, part) + if err != nil { + return nil, err + } + for _, id := range values { + ids[id] = true + } + } + return ids, nil +} + +// existingRowOwners 读出这些身份在目标里的写前归属("/")。 +// 没有 id 列的关系表按父表 knowledges 判归属。 +func (t *ProductionLibraryTarget) existingRowOwners(ctx context.Context, table string, ids []string) (map[string]string, error) { + owners := map[string]string{} + if _, ok := migrationIdentityContracts[table]; !ok { + return nil, fmt.Errorf("unknown migration table %s", table) + } + if table == "knowledge_tag_relations" { + knowledgeIDs, tagIDs := make([]string, 0, len(ids)), make([]string, 0, len(ids)) + for _, id := range ids { + parts := strings.Split(id, ":") + if len(parts) != 2 || !validSearchIdentifier(parts[0]) || !validSearchIdentifier(parts[1]) { + return nil, errors.New("invalid relation tuple") + } + knowledgeIDs = append(knowledgeIDs, parts[0]) + tagIDs = append(tagIDs, parts[1]) + } + rows, err := t.pool.Query(ctx, ` +SELECT r.knowledge_id, coalesce(r.tag_id,''), coalesce(k.tenant_id,0), coalesce(k.knowledge_base_id,'') +FROM knowledge_tag_relations r LEFT JOIN knowledges k ON k.id=r.knowledge_id +WHERE (r.knowledge_id,r.tag_id) IN (SELECT * FROM unnest($1::text[],$2::text[]))`, knowledgeIDs, tagIDs) + if err != nil { + return nil, fmt.Errorf("读取目标 %s 归属失败", table) + } + defer rows.Close() + for rows.Next() { + var knowledge, tag, kb string + var tenant uint64 + if err := rows.Scan(&knowledge, &tag, &tenant, &kb); err != nil { + return nil, err + } + owners[knowledge+":"+tag] = fmt.Sprintf("%d/%s", tenant, kb) + } + return owners, rows.Err() + } + statement := fmt.Sprintf(`SELECT id, tenant_id, coalesce(knowledge_base_id,'') FROM %s WHERE id = ANY($1::text[])`, table) + if table == "resource_bindings" { + // 绑定表没有 knowledge_base_id:归属只能走父表,否则"同租户"就会被当成"自己的"。 + statement = `SELECT b.id, b.tenant_id, + coalesce(k.knowledge_base_id, c.knowledge_base_id, '') +FROM resource_bindings b +LEFT JOIN knowledges k ON b.owner_type='knowledge' AND k.id=b.owner_id +LEFT JOIN chunks c ON b.owner_type='chunk' AND c.id=b.owner_id +WHERE b.id = ANY($1::text[])` + } else if !tablesWithKB[table] { + statement = fmt.Sprintf(`SELECT id, tenant_id, '' FROM %s WHERE id = ANY($1::text[])`, table) + } + if table == "wiki_log_entries" { + statement = `SELECT id::text, tenant_id, coalesce(knowledge_base_id,'') FROM wiki_log_entries WHERE id = ANY($1::bigint[])` + } + rows, err := t.pool.Query(ctx, statement, ids) + if err != nil { + return nil, fmt.Errorf("读取目标 %s 归属失败", table) + } + defer rows.Close() + for rows.Next() { + var id, kb string + var tenant uint64 + if err := rows.Scan(&id, &tenant, &kb); err != nil { + return nil, err + } + owners[id] = fmt.Sprintf("%d/%s", tenant, kb) + } + return owners, rows.Err() +} + +// assertResourceTenant 只检查"同 ID 是否属于别的租户":resources 没有 +// knowledge_base_id,同租户不等于同知识库,范围问题交给后续的复用证明。 +func (t *ProductionLibraryTarget) assertResourceTenant(id, owner string) error { + if owner != fmt.Sprintf("%d/", t.scope.TenantID) { + return fmt.Errorf("资源 ID 冲突:%s 已属于租户/范围 %s,拒绝覆盖", id, owner) + } + return nil +} + +// assertWriteSetOwnership 是跨范围 ID 冲突的预检:同 ID 已经是别人的行时, +// 写入会改掉别人的数据(resources 尤其危险:ON CONFLICT 会整行覆盖)。 +// 宁可整次拒绝,也不许"覆盖一下看起来也能跑"。 +func (t *ProductionLibraryTarget) assertWriteSetOwnership(table, id, owner string, backupResources map[string]bool) error { + target := fmt.Sprintf("%d/%s", t.scope.TenantID, t.scope.KnowledgeBaseID) + if table == "resources" { + // 资源只有租户:同租户不等于同知识库,必须落在预备份范围内才算自己的。 + if err := t.assertResourceTenant(id, owner); err != nil { + return err + } + if !backupResources[id] { + return fmt.Errorf("资源 ID 冲突:%s 存在于目标租户但不在预备份范围内(属于其它知识库),拒绝覆盖", id) + } + return nil + } + if owner != target && owner != fmt.Sprintf("%d/", t.scope.TenantID) { + return fmt.Errorf("%s ID 冲突:%s 已属于 %s,拒绝写入", table, id, owner) + } + return nil +} + +// clearJobCreatedRows 只删"写前不存在 ∧ 由本次写入 ∧ 不在恢复快照里"的精确身份, +// 并且对资源额外要求它仍然没有任何绑定/正文引用(作业失败期间被别的知识库接管 +// 使用的资源不能删)。 +// +// 为什么要减掉"快照里的身份":这份台账可能是为另一次动作算的(例如手工从某份 +// 预备份修复目标)。只要这一行就是恢复要回到的内容,它就不是残渣——按台账删掉 +// 等于把刚恢复的行再删一次。 +func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set libraryrelease.WriteSet, + restored map[string]map[string]bool) error { + tx, err := t.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(context.WithoutCancel(ctx)) + + // 子表先删:resource_bindings → chunks/knowledges、wiki 子表 → wiki 页 → 资源。 + for _, table := range []string{"resource_bindings", "chunks", "knowledges", "knowledge_tag_relations", + "wiki_page_issues", "wiki_log_entries", "wiki_pages", "wiki_folders", "knowledge_tags", "resources"} { + ids := make([]string, 0, 8) + for _, id := range set.CreatedIDs(table) { + if restored[table][id] { + continue + } + ids = append(ids, id) + } + if len(ids) == 0 { + continue + } + statement := fmt.Sprintf(`DELETE FROM %s WHERE (%s)::text = ANY($1::text[])`, table, identityExpr(table)) + if table == "resources" { + // Lock parent keys through grant check and delete; a concurrent FK insert + // must wait rather than race the protection query and be cascaded away. + locked, err := tx.Query(ctx, `SELECT id FROM resources WHERE id=ANY($1::text[]) FOR UPDATE`, ids) + if err != nil { + return err + } + for locked.Next() { + var id string + if err = locked.Scan(&id); err != nil { + locked.Close() + return err + } + } + locked.Close() + if err = locked.Err(); err != nil { + return err + } + if err = ensureNoResourceGrants(ctx, tx, ids); err != nil { + return err + } + + if err := ensureCreatedResourcesUnreferenced(ctx, tx, t.tables, ids); err != nil { + return err + } + } + if _, err := tx.Exec(ctx, statement, ids); err != nil { + return fmt.Errorf("清理本次新增的 %s 失败: %w", table, err) + } + } + // 复核:本次新建的行一个都不许剩。资源若因"被引用"而保留,那说明恢复没回到 + // 预备份状态,必须报出来让维护保持,而不是静默放过。 + leftovers := make([]string, 0, 4) + for _, table := range t.tables { + ids := make([]string, 0, 8) + for _, id := range set.CreatedIDs(table) { + if restored[table][id] { + continue + } + ids = append(ids, id) + } + if len(ids) == 0 { + continue + } + statement := fmt.Sprintf(`SELECT (%s)::text FROM %s WHERE (%s)::text = ANY($1::text[])`, + identityExpr(table), table, identityExpr(table)) + rows, err := tx.Query(ctx, statement, ids) + if err != nil { + return fmt.Errorf("复核本次新增的 %s 失败: %w", table, err) + } + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + rows.Close() + return err + } + leftovers = append(leftovers, table+"/"+id) + } + rows.Close() + if err := rows.Err(); err != nil { + return err + } + } + if len(leftovers) > 0 { + sort.Strings(leftovers) + return fmt.Errorf("恢复后仍留下本次写入的 %d 行(%v):目标未回到预备份状态,不能当作已恢复", + len(leftovers), leftovers) + } + return tx.Commit(ctx) +} + +// snapshotRowIdentities 读出"恢复要用这份快照"的全部行身份(按表)。 +func (t *ProductionLibraryTarget) snapshotRowIdentities(archive *librarysnapshot.Archive, + manifest librarysnapshot.Manifest) (map[string]map[string]bool, error) { + identities := map[string]map[string]bool{} + for _, part := range manifest.Parts { + if part.Kind != "database" && part.Kind != "wiki" { + continue + } + ids, err := archivedRowIdentities(archive, part) + if err != nil { + return nil, err + } + identities[part.Name] = map[string]bool{} + for _, id := range ids { + identities[part.Name][id] = true + } + } + return identities, nil +} diff --git a/internal/releaseadapter/v071/library_writeset_integration_test.go b/internal/releaseadapter/v071/library_writeset_integration_test.go new file mode 100644 index 0000000..130946b --- /dev/null +++ b/internal/releaseadapter/v071/library_writeset_integration_test.go @@ -0,0 +1,793 @@ +package v071 + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "sort" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "knowledge-governance/internal/libraryrelease" + "knowledge-governance/internal/librarysnapshot" +) + +// 这一组用例验证的是"失败恢复不许误删目标自己的数据"。 +// +// 资源用真实对象存储(MinIO/S3),PostgreSQL 与 Elasticsearch 也是真服务: +// 只有"写失败"是按需注入的(flakyStore),业务不变量不靠桩对象成立。 +// +// 为什么必须真实对象存储:旧实现按"目标租户里没有绑定、也没被正文引用"清理资源行, +// 它在内存桩上与真实存储上表现一样(都会删),但资源字节/定位符的改写只有在真实 +// bucket 上才能证明"恢复后仍是同一份内容"。桩只用于单元级。 + +type writeSetFixture struct { + embeddingDimension int + ctx context.Context + pool *pgxpool.Pool + client *http.Client + searchBase string + index string + archiveRoot string + objects *flakyStore + bucket string +} + +const ( + wsTargetTenant = 10001 + wsTargetKB = "kb-target" + wsOtherKB = "kb-other" + wsSourceTenant = 10002 + wsSourceKB = "kb-source" + wsForeignTnt = 20000 + + wsHandleTarget = "aaaaaaaaaaaaaaaaaaaaaa" + wsHandleShared = "bbbbbbbbbbbbbbbbbbbbbb" + wsHandleOther = "cccccccccccccccccccccc" + wsHandleOrphan = "dddddddddddddddddddddd" + wsHandleSource = "eeeeeeeeeeeeeeeeeeeeee" + wsHandleForeign = "ffffffffffffffffffffff" +) + +// A per-run bucket isolates object writes even when the S3 service is shared. +var wsBucket = func() string { + if bucket := os.Getenv("KG_LIBRARY_TEST_S3_BUCKET"); strings.HasPrefix(bucket, "kg-library-test-") { + return bucket + } + return "kg-wire-test-bucket" +}() + +func wsLocator(backend, provider, bucket string, tenant uint64, id string) string { + return fmt.Sprintf("storage://%s/%s://%s/%d/%s/a.png", backend, provider, bucket, tenant, id) +} + +// flakyStore 在真实 S3 之上按需注入写失败:只让"新对象上传"失败, +// 已存在的对象仍可覆盖(恢复要把预备份里的对象重新写回去,那条路径不能被注入打坏)。 +// Open/Stat/Copy 全部透传。 +type flakyStore struct { + s3 *S3ObjectStore + failPut atomic.Bool + // failPath 是注入失败的定位符片段:只让"这次要新增的那一个资源"上传失败, + // 恢复要把预备份里的对象重新写回去,那条路径不能被注入打坏。 + failPath string + puts atomic.Int64 +} + +func (s *flakyStore) Put(ctx context.Context, provider, path string, reader io.Reader, size int64) error { + if s.failPut.Load() && (s.failPath == "" || strings.Contains(path, s.failPath)) { + return errors.New("注入的对象写入失败") + } + s.puts.Add(1) + return s.s3.Put(ctx, provider, path, reader, size) +} + +func (s *flakyStore) Stat(ctx context.Context, provider, path string) (int64, string, error) { + return s.s3.Stat(ctx, provider, path) +} + +func (s *flakyStore) Copy(ctx context.Context, provider, source, target string) error { + return s.s3.Copy(ctx, provider, source, target) +} + +func (s *flakyStore) Open(ctx context.Context, provider, path string) (io.ReadCloser, error) { + return s.s3.Open(ctx, provider, path) +} + +func openWriteSetFixture(t *testing.T) *writeSetFixture { + t.Helper() + return openWriteSetFixtureWith(t, writeSetFixtureOptions{reset: true}) +} + +// writeSetFixtureOptions 让"被杀掉的子进程"复用父进程已经建好的现场: +// 不重建 schema、不新建索引,也不换归档根(写集合与预备份都落在那一个根下)。 +type writeSetFixtureOptions struct { + embeddingDimension int + reset bool + archiveRoot string + index string + // ddl 非空时替换最小夹具 schema:DS-02 冻结 bundle 用同一份 DDL 初始化两个隔离目标。 + ddl []string +} + +func openWriteSetFixtureWith(t *testing.T, options writeSetFixtureOptions) *writeSetFixture { + if options.embeddingDimension == 0 { + options.embeddingDimension = 2 + } + t.Helper() + dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL") + base := os.Getenv("KG_LIBRARY_TEST_ELASTIC_URL") + endpoint := os.Getenv("KG_LIBRARY_TEST_S3_ENDPOINT") + access, secret := os.Getenv("KG_LIBRARY_TEST_S3_ACCESS_KEY"), os.Getenv("KG_LIBRARY_TEST_S3_SECRET_KEY") + if dsn == "" || base == "" || endpoint == "" || access == "" || secret == "" || + os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + t.Skip("requires isolated PG, ES and object storage opt-in") + } + cfg, err := pgxpool.ParseConfig(dsn) + if options.reset { + previousBucket := wsBucket + var namespace [8]byte + if _, err := rand.Read(namespace[:]); err != nil { + t.Fatal(err) + } + wsBucket = "kg-library-test-" + hex.EncodeToString(namespace[:]) + t.Cleanup(func() { wsBucket = previousBucket }) + t.Setenv("KG_LIBRARY_TEST_S3_BUCKET", wsBucket) + t.Logf("isolated object namespace=%s", wsBucket) + } + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") { + t.Fatal("isolated database required") + } + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute) + t.Cleanup(cancel) + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatalf("open isolated PG: %v", err) + } + t.Cleanup(pool.Close) + if options.reset { + if _, err := pool.Exec(ctx, `DROP SCHEMA public CASCADE; CREATE SCHEMA public`); err != nil { + t.Fatalf("reset isolated schema: %v", err) + } + } + // 冻结 bundle 自带完整 DDL 时,不叠加最小夹具(否则两个目标的 schema 又不同)。 + if len(options.ddl) > 0 { + for _, statement := range options.ddl { + statement = strings.ReplaceAll(statement, "%BUCKET%", wsBucket) + if _, err := pool.Exec(ctx, statement); err != nil { + t.Fatalf("bundle schema: %v\n%s", err, statement) + } + } + } + schemaStatements := []string{ + libraryTestSchema, + // 清掉共用夹具里的示例行:本文件只用自己造的目标/其它租户数据, + // 免得"目标非空"被别的用例的行弄成不确定。 + `DELETE FROM knowledges; DELETE FROM chunks; DELETE FROM knowledge_tags; + DELETE FROM knowledge_tag_relations; DELETE FROM resources; + DELETE FROM resource_bindings; DELETE FROM wiki_pages; DELETE FROM wiki_folders; + DELETE FROM wiki_page_issues; DELETE FROM wiki_log_entries`, + `ALTER TABLE wiki_pages ADD COLUMN status text DEFAULT 'published'`, + `ALTER TABLE knowledge_tag_relations ADD COLUMN tenant_id bigint`, + `ALTER TABLE resources ADD COLUMN provider text, ADD COLUMN size bigint, ADD COLUMN storage_backend_id text`, + `ALTER TABLE resources ADD PRIMARY KEY (id)`, + `ALTER TABLE resource_bindings ADD COLUMN relation text`, + `CREATE UNIQUE INDEX wiki_pages_scope_slug ON wiki_pages(tenant_id, knowledge_base_id, slug)`, + `CREATE TABLE storage_backends(id text PRIMARY KEY, tenant_id bigint, provider text, config jsonb, created_at timestamptz)`, + `INSERT INTO storage_backends VALUES('backend-target',10001,'minio','{"bucket_name":"` + wsBucket + `"}',now())`, + `INSERT INTO knowledge_bases VALUES('` + wsTargetKB + `',10001,'{}',NULL),('` + wsOtherKB + `',10001,'{}',NULL),('` + wsSourceKB + `',10002,'{}',NULL)`, + } + if options.reset && len(options.ddl) == 0 { + for _, statement := range schemaStatements { + if _, err := pool.Exec(ctx, statement); err != nil { + t.Fatalf("fixture schema: %v", err) + } + } + } + + token := make([]byte, 8) + if _, err := rand.Read(token); err != nil { + t.Fatal(err) + } + index := "kg_library_test_" + hex.EncodeToString(token) + if options.index != "" { + index = options.index + } else if registered := os.Getenv("KG_R38_INDEX"); registered != "" { + // 隔离运行器在创建前登记了唯一索引;夹具必须消费它,否则 wrapper 清理的是 + // 一个从未被使用的名字(真索引只能靠 t.Cleanup,进程提前退出就漏掉)。 + index = registered + } + // Register each disposable namespace before its first ES/object mutation. + r10Save(t, "namespace", map[string]string{"bucket": wsBucket, "index": index}) + client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }} + call := func(method, path, body string, want int) { + t.Helper() + request, err := http.NewRequestWithContext(ctx, method, base+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", "application/json") + response, err := client.Do(request) + if err != nil { + t.Fatalf("fixture HTTP: %v", err) + } + defer response.Body.Close() + if response.StatusCode != want { + t.Fatalf("fixture %s %s => %d, want %d", method, path, response.StatusCode, want) + } + } + if options.reset { + call("PUT", "/"+index, `{"mappings":{"properties":{"tenant_id":{"type":"long"},"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"chunk_id":{"type":"keyword"},"content":{"type":"text"},"embedding":{"type":"dense_vector","dims":`+strconv.Itoa(options.embeddingDimension)+`}}}}`, 200) + } + if options.reset { + t.Cleanup(func() { + // 保留 UI 验收现场时不删索引:父要能对着真实目标点恢复。 + if os.Getenv("KG_R8_KEEP_SCENE") == "1" { + return + } + call("DELETE", "/"+index, "", 200) + call("HEAD", "/"+index, "", 404) + }) + } + + root := options.archiveRoot + if root == "" { + root = t.TempDir() + if err := os.Chmod(root, 0700); err != nil { + t.Fatal(err) + } + } + store, err := NewS3ObjectStore(S3ObjectStoreConfig{Provider: "minio", Endpoint: endpoint, + Region: "us-east-1", AccessKeyID: access, SecretAccessKey: secret, Bucket: wsBucket, + ForcePathStyle: true, MaxObjectBytes: 64 * 1024 * 1024}) + if err != nil { + t.Fatalf("object store: %v", err) + } + if err := store.EnsureBucket(ctx); err != nil { + t.Fatalf("ensure bucket: %v", err) + } + if options.reset { + enableIsolatedObjectVersions(t, ctx, store) + } + return &writeSetFixture{embeddingDimension: options.embeddingDimension, ctx: ctx, pool: pool, client: client, searchBase: base, index: index, + archiveRoot: root, objects: &flakyStore{s3: store}, bucket: wsBucket} +} + +// seedTargetData 造"目标本来就有数据"的现场:目标自己的行、同租户另一个知识库的行(含资源)、 +// 被两个知识库共享的资源、一个历史孤儿资源、另一个租户的行。 +func seedTargetData(t *testing.T, fx *writeSetFixture) { + t.Helper() + ctx := fx.ctx + locator := func(backend string, tenant uint64, id string) string { + return wsLocator(backend, "minio", wsBucket, tenant, id) + } + for _, object := range []struct { + tenant uint64 + id string + }{ + {10001, "res-target"}, {10001, "res-shared"}, {10001, "res-other"}, + {10001, "res-orphan"}, {20000, "res-foreign"}, + } { + path := locator("backend-target", object.tenant, object.id) + if err := fx.objects.s3.Put(ctx, "minio", path, bytes.NewReader([]byte("12345678")), 8); err != nil { + t.Fatalf("seed object %s: %v", object.id, err) + } + } + statements := []string{ + // 目标自己:文档 + 分块(正文引用目标资源)+ 资源 + 绑定 + Wiki。 + `INSERT INTO knowledges VALUES('doc-target',10001,'` + wsTargetKB + `','completed',0,'',NULL)`, + `INSERT INTO chunks VALUES('chunk-target',10001,'` + wsTargetKB + `','doc-target','图:resource://` + wsHandleTarget + `',NULL)`, + `INSERT INTO resources VALUES('res-target','` + wsHandleTarget + `',10001,'` + locator("backend-target", 10001, "res-target") + `',NULL,'minio',8,'backend-target')`, + `INSERT INTO resource_bindings VALUES('bind-target',10001,'res-target','knowledge','doc-target',NULL)`, + `INSERT INTO wiki_pages VALUES('wiki-target',10001,'` + wsTargetKB + `','index','目标 wiki',NULL,'published')`, + // 同租户另一个知识库:数据与资源都必须原样保留。 + `INSERT INTO knowledges VALUES('doc-other',10001,'` + wsOtherKB + `','completed',0,'',NULL)`, + `INSERT INTO chunks VALUES('chunk-other',10001,'` + wsOtherKB + `','doc-other','别的知识库正文',NULL)`, + `INSERT INTO resources VALUES('res-other','` + wsHandleOther + `',10001,'` + locator("backend-target", 10001, "res-other") + `',NULL,'minio',8,'backend-target')`, + `INSERT INTO resource_bindings VALUES('bind-other',10001,'res-other','knowledge','doc-other',NULL)`, + // 共享资源:同时被目标知识库与另一个知识库绑定。 + `INSERT INTO resources VALUES('res-shared','` + wsHandleShared + `',10001,'` + locator("backend-target", 10001, "res-shared") + `',NULL,'minio',8,'backend-target')`, + `INSERT INTO resource_bindings VALUES('bind-shared-target',10001,'res-shared','knowledge','doc-target',NULL)`, + `INSERT INTO resource_bindings VALUES('bind-shared-other',10001,'res-shared','knowledge','doc-other',NULL)`, + // 历史孤儿:没有任何绑定、也没有正文引用。它不是这次作业写的,绝不能被删。 + `INSERT INTO resources VALUES('res-orphan','` + wsHandleOrphan + `',10001,'` + locator("backend-target", 10001, "res-orphan") + `',NULL,'minio',8,'backend-target')`, + // 另一个租户的行。 + `INSERT INTO knowledges VALUES('doc-foreign',20000,'kb-foreign','completed',0,'',NULL)`, + `INSERT INTO chunks VALUES('chunk-foreign',20000,'kb-foreign','doc-foreign','外部正文',NULL)`, + `INSERT INTO resources VALUES('res-foreign','` + wsHandleForeign + `',20000,'` + locator("backend-target", 20000, "res-foreign") + `',NULL,'minio',8,'backend-target')`, + `INSERT INTO resource_bindings VALUES('bind-foreign',20000,'res-foreign','knowledge','doc-foreign',NULL)`, + } + for _, statement := range statements { + if _, err := fx.pool.Exec(ctx, statement); err != nil { + t.Fatalf("seed target: %v\n%s", err, statement) + } + } + // 目标索引自洽:目标分块必须有对应文档,否则预备份会(正确地)拒绝。 + fx.indexDoc(t, "chunk-target", wsTargetTenant, wsTargetKB, "doc-target", "图:"+wsHandleTarget) +} + +func (fx *writeSetFixture) embeddingJSON() []byte { + n := fx.embeddingDimension + if n == 0 { + n = 2 + } + v := make([]float64, n) + v[0] = 0.1 + v[1] = 0.2 + b, _ := json.Marshal(v) + return b +} +func (fx *writeSetFixture) indexDoc(t *testing.T, id string, tenant uint64, kb, knowledge, content string) { + t.Helper() + body := fmt.Sprintf(`{"tenant_id":%d,"knowledge_base_id":%q,"knowledge_id":%q,"chunk_id":%q,"source_id":%q,"content":%q,"embedding":%s}`, + tenant, kb, knowledge, id, id, content, fx.embeddingJSON()) + request, err := http.NewRequestWithContext(fx.ctx, "PUT", fmt.Sprintf("%s/%s/_doc/%s?refresh=true", fx.searchBase, fx.index, id), + strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", "application/json") + response, err := fx.client.Do(request) + if err != nil { + t.Fatalf("index doc: %v", err) + } + defer response.Body.Close() + if response.StatusCode != 201 && response.StatusCode != 200 { + t.Fatalf("index doc %s => %d", id, response.StatusCode) + } +} + +// sealSourceSnapshot 造一份"来源范围与目标不同"的整库快照。 +func sealSourceSnapshot(t *testing.T, fx *writeSetFixture, tweak func(parts map[string][]map[string]any)) string { + t.Helper() + return sealSourceSnapshotScope(t, fx, wsSourceTenant, wsSourceKB, tweak, nil) +} + +// sealSourceSnapshotScope 允许指定来源范围/附加对象:来源快照的身份决定 +// "同一资源行是否属于同一个来源",复用证据必须按它区分。 +func sealSourceSnapshotScope(t *testing.T, fx *writeSetFixture, sourceTenant uint64, sourceKB string, + tweak func(parts map[string][]map[string]any), extraObjects map[string]string) string { + t.Helper() + archive, err := librarysnapshot.Open(fx.archiveRoot, 128*1024*1024) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + encode := func(value any) []byte { + encoded, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return encoded + } + parts := map[string][]map[string]any{ + "knowledges": {{"id": "doc-src", "tenant_id": sourceTenant, "knowledge_base_id": sourceKB, + "parse_status": "completed", "pending_subtasks_count": 0, "file_path": ""}}, + "chunks": {{"id": "chunk-src", "tenant_id": sourceTenant, "knowledge_base_id": sourceKB, + "knowledge_id": "doc-src", "content": "来源正文 resource://" + wsHandleSource}}, + "knowledge_tags": {}, + "knowledge_tag_relations": {}, + "resources": {{"id": "res-src", "handle": wsHandleSource, "tenant_id": sourceTenant, + "storage_backend_id": "backend-source", "provider": "oss", + "physical_path": wsLocator("backend-source", "oss", "source-bucket", sourceTenant, "res-src"), + "size": int64(8)}}, + "resource_bindings": {{"id": "bind-src", "resource_id": "res-src", "tenant_id": sourceTenant, + "owner_type": "knowledge", "owner_id": "doc-src", "relation": "attachment"}}, + "wiki_folders": {}, + "wiki_pages": {{"id": "wiki-src", "tenant_id": sourceTenant, "knowledge_base_id": sourceKB, "slug": "index", "content": "来源 wiki"}}, + "wiki_page_issues": {}, + "wiki_log_entries": {}, + } + if tweak != nil { + tweak(parts) + } + kinds := map[string]string{"knowledges": "database", "chunks": "database", "knowledge_tags": "database", + "knowledge_tag_relations": "database", "resources": "database", "resource_bindings": "database", + "wiki_folders": "wiki", "wiki_pages": "wiki", "wiki_page_issues": "wiki", "wiki_log_entries": "wiki"} + manifestParts := make([]librarysnapshot.Part, 0, 14) + names := make([]string, 0, len(parts)) + for name := range parts { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + part, err := archive.Put(bytes.NewReader(encode(parts[name]))) + if err != nil { + t.Fatal(err) + } + part.Kind, part.Name, part.Count = kinds[name], name, int64(len(parts[name])) + manifestParts = append(manifestParts, part) + } + resourcePart, err := archive.Put(bytes.NewReader([]byte("12345678"))) + if err != nil { + t.Fatal(err) + } + resourcePart.Kind, resourcePart.Name, resourcePart.Count = "resource", "res-src", 1 + manifestParts = append(manifestParts, resourcePart) + extraNames := make([]string, 0, len(extraObjects)) + for name := range extraObjects { + extraNames = append(extraNames, name) + } + sort.Strings(extraNames) + for _, name := range extraNames { + part, err := archive.Put(bytes.NewReader([]byte(extraObjects[name]))) + if err != nil { + t.Fatal(err) + } + part.Kind, part.Name, part.Count = "resource", name, 1 + manifestParts = append(manifestParts, part) + } + // 索引文档按快照里的分块逐条生成:多一个分块就必须多一条向量,否则 + // 校验会把"写入正确"判成索引缺文档。 + indexRows := make([]map[string]any, 0, len(parts["chunks"])) + for _, chunk := range parts["chunks"] { + id, _ := chunk["id"].(string) + knowledge, _ := chunk["knowledge_id"].(string) + content, _ := chunk["content"].(string) + indexRows = append(indexRows, map[string]any{"id": id, "source": map[string]any{ + "tenant_id": sourceTenant, "knowledge_base_id": sourceKB, "knowledge_id": knowledge, + "chunk_id": id, "source_id": id, "content": content, "embedding": json.RawMessage(fx.embeddingJSON())}}) + } + indexPart, err := archive.Put(bytes.NewReader(encode(indexRows))) + if err != nil { + t.Fatal(err) + } + indexPart.Kind, indexPart.Name, indexPart.Count = "index", "chunks", int64(len(indexRows)) + manifestParts = append(manifestParts, indexPart) + manifest := librarysnapshot.Manifest{ValidationPolicy: librarysnapshot.ArtifactAcceptancePolicy, + Format: librarysnapshot.Format, Scope: "internal", TenantID: sourceTenant, KnowledgeBaseID: sourceKB, + CreatedAt: time.Now().UTC(), Parts: manifestParts, + Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", + EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("a", 64)}} + id, err := archive.Seal(manifest) + if err != nil { + t.Fatalf("seal source snapshot: %v", err) + } + return id +} + +func (fx *writeSetFixture) target(t *testing.T) *ProductionLibraryTarget { + t.Helper() + target, err := NewProductionLibraryTarget(fx.ctx, ProductionLibraryConfig{ + Postgres: os.Getenv("KG_LIBRARY_TEST_DATABASE_URL"), SearchURL: fx.searchBase, SearchIndex: fx.index, + Objects: fx.objects, ObjectsReader: fx.objects, ArchiveRoot: fx.archiveRoot, + ObjectsBucket: fx.bucket, MaxDocuments: 100, HTTPClient: fx.client, + }, ProductionScope{TenantID: wsTargetTenant, KnowledgeBaseID: wsTargetKB}) + if err != nil { + t.Fatalf("target: %v", err) + } + t.Cleanup(target.Close) + return target +} + +func (fx *writeSetFixture) backups(t *testing.T, target *ProductionLibraryTarget) *ProductionBackupStore { + t.Helper() + mapping, err := target.Search().MappingSHA256(fx.ctx) + if err != nil { + t.Fatal(err) + } + backups, err := NewProductionBackupStore(ProductionBackupConfig{ + Pool: target.Pool(), Search: target.Search(), Objects: fx.objects, ArchiveRoot: fx.archiveRoot, + Scope: "internal", Identity: target.Identity(), MaxDocuments: 100, + Compatibility: librarysnapshot.Compatibility{WeKnoraVersion: "v0.7.1", SchemaVersion: 74, + RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "text-embedding-v4", + EmbeddingDimension: 1024, IndexMappingSHA256: mapping}, + }) + if err != nil { + t.Fatalf("backup store: %v", err) + } + return backups +} + +// universeDump 是"整实例逐行字节"快照:任何一行被删/被改写都会体现在这里。 +func universeDump(t *testing.T, pool *pgxpool.Pool) map[string][]string { + t.Helper() + dump := map[string][]string{} + for _, table := range productionLibraryTables { + rows, err := pool.Query(context.Background(), fmt.Sprintf(`SELECT to_jsonb(x)::text FROM %s AS x ORDER BY 1`, table)) + if err != nil { + t.Fatalf("dump %s: %v", table, err) + } + values := make([]string, 0, 32) + for rows.Next() { + var raw string + if err := rows.Scan(&raw); err != nil { + rows.Close() + t.Fatalf("dump scan %s: %v", table, err) + } + values = append(values, raw) + } + rows.Close() + if err := rows.Err(); err != nil { + t.Fatalf("dump %s: %v", table, err) + } + dump[table] = values + } + return dump +} + +func diffUniverse(before, after map[string][]string) string { + tables := make([]string, 0, len(before)) + for table := range before { + tables = append(tables, table) + } + sort.Strings(tables) + for _, table := range tables { + if len(before[table]) != len(after[table]) { + return fmt.Sprintf("%s 行数 %d -> %d", table, len(before[table]), len(after[table])) + } + for index := range before[table] { + if before[table][index] != after[table][index] { + return fmt.Sprintf("%s 第 %d 行内容变了:%s", table, index, after[table][index]) + } + } + } + return "" +} + +func requestFor(snapshotID string) libraryrelease.Request { + now := time.Now().UTC() + return libraryrelease.Request{JobID: "job-writeset-acceptance", Target: "internal", SnapshotID: snapshotID, + ParamsDigest: "digest-writeset", Now: now, + Grant: libraryrelease.Grant{Target: "internal", SnapshotID: snapshotID, ParamsDigest: "digest-writeset", + ExpiresAt: now.Add(10 * time.Minute), AuthorizedBy: "acceptance"}} +} + +// 场景:目标非空(目标自己的文档/分块/资源/Wiki)、同租户里还有另一个知识库的数据与资源、 +// 一份被两个知识库共享的资源、一个历史孤儿资源、另一个租户的数据;来源快照属于另一个 +// 租户/知识库;资源阶段写失败 → 必须回滚,且"目标原有数据逐行字节不变、本次残留为 0"。 +func TestLibraryRollbackKeepsPreExistingTargetDataIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + snapshotID := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + + fx.objects.failPath = "/res-src/" + fx.objects.failPut.Store(true) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshotID), target, backups, nil) + fx.objects.failPut.Store(false) + if outcome.State != "rolled_back" { + t.Fatalf("outcome = %+v", outcome) + } + if outcome.FailedAt != libraryrelease.StageResources { + t.Fatalf("failed_at = %s, want resources", outcome.FailedAt) + } + t.Logf("rollback=%s backup=%s ledger=%s", outcome.Rollback, outcome.Backup.SnapshotID, + outcome.Backup.WriteSet.Digest) + after := universeDump(t, fx.pool) + if diff := diffUniverse(before, after); diff != "" { + t.Fatalf("回滚后目标数据被改动:%s", diff) + } + // 历史孤儿不是本次写的:它必须还在(旧实现按"目标租户里没人引用"清理,会删掉它)。 + var orphan string + if err := fx.pool.QueryRow(fx.ctx, `SELECT physical_path FROM resources WHERE id='res-orphan'`).Scan(&orphan); err != nil { + t.Fatalf("历史孤儿资源被删了(恢复把'没人引用的目标租户资源'当成本次残渣):%v", err) + } + var sourceScope int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2`, + wsSourceTenant, wsSourceKB).Scan(&sourceScope); err != nil { + t.Fatal(err) + } + if sourceScope != 0 { + t.Fatalf("回滚后仍有 %d 行来源范围文档", sourceScope) + } + var residue int64 + if err := fx.pool.QueryRow(fx.ctx, `SELECT count(*) FROM resources WHERE id='res-src'`).Scan(&residue); err != nil { + t.Fatal(err) + } + if residue != 0 { + t.Fatalf("本次同步新增的资源行未被清理") + } + if err := target.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: outcome.Backup.SnapshotID}); err != nil { + t.Fatalf("回滚必须与预备份一致:%v", err) + } + // 写集合必须已落盘、可校验,并且明确区分"本次新建"与"写前已存在"。 + if outcome.Backup.WriteSet == nil || outcome.Backup.WriteSet.Digest == "" { + t.Fatalf("预备份必须带着已落盘的写集合:%+v", outcome.Backup) + } + ledger, err := LoadWriteSet(fx.archiveRoot, outcome.Backup.WriteSet.Digest) + if err != nil { + t.Fatalf("写集合记录取不回来:%v", err) + } + createdResources := ledger.CreatedIDs("resources") + if len(createdResources) != 1 || createdResources[0] != "res-src" { + t.Fatalf("写集合里本次新建的资源 = %v,want [res-src]", createdResources) + } + // 写集合只允许包含"这次要写"的来源身份;目标自己的资源(含共享/历史孤儿/ + // 其它知识库的资源)一个都不许出现,否则恢复就会按它去删。 + created := map[string]bool{} + for _, id := range ledger.CreatedIDs("resources") { + created[id] = true + } + for _, id := range []string{"res-target", "res-shared", "res-orphan", "res-other", "res-foreign"} { + if created[id] { + t.Fatalf("写集合把目标原有的资源 %s 当成本次新建(恢复会删掉它):%v", id, created) + } + } + if ledger.JobID != "job-writeset-acceptance" || ledger.BackupSnapshotID != outcome.Backup.SnapshotID { + t.Fatalf("写集合没有绑定作业/预备份:%+v", ledger) + } + if ledger.UniverseDigest() == "" { + t.Fatal("写集合必须带整实例内容证据") + } +} + +// 场景:恢复只拿到"快照 id"(worker 重启后的真实形状)→ 没有持久化写集合就不许恢复, +// 更不能把校验降级成"跳过整实例比对"。 +func TestLibraryRestoreRefusesWithoutWriteSetRecordIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshotID := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + fx.objects.failPath = "/res-src/" + fx.objects.failPut.Store(true) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshotID), target, backups, nil) + fx.objects.failPut.Store(false) + if outcome.State != "rolled_back" { + t.Fatalf("outcome = %+v", outcome) + } + before := universeDump(t, fx.pool) + // 丢掉内存里的写集合:只按快照 id 恢复(这就是 fixedBackupStore 的形状)。 + if err := target.Restore(fx.ctx, libraryrelease.BackupRef{ID: "backup-" + outcome.Backup.SnapshotID, + SnapshotID: outcome.Backup.SnapshotID}); err == nil { + t.Fatal("缺少持久化写集合记录时恢复必须失败(不许把校验降级成静默跳过)") + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("被拒绝的恢复不许动目标:%s", diff) + } +} + +// 场景:来源快照里的资源 ID 已被另一个租户占用 → 必须在写第一笔之前拒绝, +// 不能 ON CONFLICT 改写别人的行。 +func TestLibraryPreflightRejectsCrossScopeIDConflictIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + // 另一个租户里已经有一条同 ID 的资源行。 + if _, err := fx.pool.Exec(fx.ctx, `INSERT INTO resources VALUES('res-src','`+wsHandleForeign+`',20000,'`+ + wsLocator("backend-foreign", "oss", "foreign-bucket", 20000, "res-src")+`',NULL,'oss',4,'backend-foreign')`); err != nil { + t.Fatal(err) + } + before := universeDump(t, fx.pool) + snapshotID := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshotID), target, backups, nil) + if outcome.State != "failed" { + t.Fatalf("outcome = %+v", outcome) + } + if outcome.FailedAt != "" { + t.Fatalf("冲突必须在任何阶段写入之前被拒绝,failed_at = %s", outcome.FailedAt) + } + if !strings.Contains(outcome.Error, "冲突") || !strings.Contains(outcome.Error, "res-src") { + t.Fatalf("拒绝原因必须点名冲突的资源 ID:%s", outcome.Error) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("冲突预检失败后目标被改动:%s", diff) + } + t.Logf("conflict rejected before write: %s", outcome.Error) +} + +// 场景:wiki 阶段半写失败(resources 已成功上传、database 已提交)→ 回滚必须把 +// 本次新增的资源也清掉,目标原有数据逐行不变。 +func TestLibraryDuplicateSlugRejectedBeforeWriteIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + // 重复 slug 保留为写前拒绝负例;晚期故障由独立用例注入。 + snapshotID := sealSourceSnapshot(t, fx, func(parts map[string][]map[string]any) { + parts["wiki_pages"] = []map[string]any{ + {"id": "wiki-src", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "slug": "index", "content": "来源 wiki"}, + {"id": "wiki-src-2", "tenant_id": wsSourceTenant, "knowledge_base_id": wsSourceKB, "slug": "index", "content": "重复 slug"}, + } + }) + target := fx.target(t) + backups := fx.backups(t, target) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshotID), target, backups, nil) + if outcome.State != "failed" || !strings.Contains(outcome.Error, "source duplicates natural key") { + t.Fatalf("outcome = %+v", outcome) + } + if outcome.FailedAt != "" { + t.Fatalf("failed_at = %s, want wiki", outcome.FailedAt) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("wiki 阶段半写回滚后目标数据被改动:%s", diff) + } + if fx.objects.puts.Load() != 0 { + t.Fatal("duplicate slug reached object write") + } +} + +func TestLibraryWikiStageHalfWriteRollbackIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + snapshotID := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshotID), contractFailWikiTarget{target}, fx.backups(t, target), nil) + if outcome.State != "rolled_back" || outcome.FailedAt != libraryrelease.StageWiki { + t.Fatalf("late failure: %+v", outcome) + } + if fx.objects.puts.Load() == 0 { + t.Fatal("late failure never reached real object write") + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatal(diff) + } + observed, err := fx.objects.ObserveObject(fx.ctx, "minio", wsLocator("backend-target", "minio", wsBucket, wsTargetTenant, "res-src")) + if err != nil || observed.Exists { + t.Fatalf("created object residue: %+v %v", observed, err) + } +} + +// 场景:写集合记录被删除/篡改 → 恢复必须失败并保持维护,不能"看不见记录就当没写过"。 +func TestLibraryWriteSetRecordTamperRefusesRestoreIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + snapshotID := sealSourceSnapshot(t, fx, nil) + target := fx.target(t) + backups := fx.backups(t, target) + fx.objects.failPath = "/res-src/" + fx.objects.failPut.Store(true) + outcome := libraryrelease.Run(fx.ctx, requestFor(snapshotID), target, backups, nil) + fx.objects.failPut.Store(false) + if outcome.State != "rolled_back" || outcome.Backup.WriteSet == nil { + t.Fatalf("outcome = %+v", outcome) + } + digest := outcome.Backup.WriteSet.Digest + path := writeSetPath(fx.archiveRoot, digest) + + // 1) 记录被篡改:同一个文件改一个字段 → 取回必须失败(摘要对不上)。 + original, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + tampered := bytes.Replace(original, []byte(`"tenant_id":10001`), []byte(`"tenant_id":10002`), 1) + if bytes.Equal(tampered, original) { + t.Fatalf("篡改夹具没生效:%s", original) + } + if err := os.Chmod(path, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, tampered, 0600); err != nil { + t.Fatal(err) + } + if _, err := LoadWriteSet(fx.archiveRoot, digest); err == nil { + t.Fatal("写集合被篡改后取回必须失败") + } + // 内存里带着被篡改的记录去恢复,同样必须失败。 + bad := *outcome.Backup.WriteSet + bad.TenantID = 10002 + if err := target.Restore(fx.ctx, libraryrelease.BackupRef{ID: outcome.Backup.ID, + SnapshotID: outcome.Backup.SnapshotID, WriteSet: &bad}); err == nil { + t.Fatal("写集合内容与摘要不符时恢复必须失败") + } + + // 2) 记录被删除:恢复必须失败并保持维护(不是静默跳过校验)。 + if err := os.WriteFile(path, original, 0600); err != nil { + t.Fatal(err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if _, err := LoadWriteSet(fx.archiveRoot, digest); err == nil { + t.Fatal("写集合记录被删除后取回必须失败") + } + t.Logf("tampered/removed ledger refused, digest=%s", digest) +} diff --git a/internal/releaseadapter/v071/library_writeset_kill_test.go b/internal/releaseadapter/v071/library_writeset_kill_test.go new file mode 100644 index 0000000..ca9f620 --- /dev/null +++ b/internal/releaseadapter/v071/library_writeset_kill_test.go @@ -0,0 +1,201 @@ +package v071 + +import ( + "context" + "encoding/json" + "io" + "os" + "os/exec" + "strings" + "syscall" + "testing" + "time" + + "knowledge-governance/internal/libraryrelease" +) + +// 真杀进程的接管验证:子进程在 resources 阶段被 SIGKILL(模拟 worker 被杀), +// 已经提交的 database 阶段与"写集合 + 预备份"记录留在盘上;父进程作为"重启后的 +// worker"只按持久记录恢复。 +// +// 说明边界:杀的是**发布路径的进程**(本文件的 helper),不是治理栈里的 worker 容器; +// 队列/UI 侧的接管由父负责页面验收。这里证明的是"进程没了之后,恢复只用盘上的 +// 写集合与整实例证据,并且删不到目标原有数据"。 + +const ( + killChildEnv = "KG_WRITESET_KILL_CHILD" + killStateEnv = "KG_WRITESET_KILL_STATE" + killJournalEnv = "KG_WRITESET_KILL_JOURNAL" +) + +// killHelperState 是子进程写下的"治理库记录"替身:真实系统里这两项分别落在 +// library_jobs.snapshot_id 与 library_versions.evidence.writeset_digest。 +type killHelperState struct { + JobID string `json:"job_id"` + BackupSnapshotID string `json:"backup_snapshot_id"` + TargetSnapshotID string `json:"target_snapshot_id"` + WriteSetDigest string `json:"writeset_digest"` +} + +func TestWriteSetKillHelper(t *testing.T) { + if os.Getenv(killChildEnv) != "1" { + t.Skip("helper process only") + } + // 子进程复用父进程的现场:不重建 schema/索引,写集合与预备份仍落在同一个归档根。 + fx := openWriteSetFixtureWith(t, writeSetFixtureOptions{archiveRoot: os.Getenv(killJournalEnv + "_ARCHIVE"), + index: os.Getenv(killJournalEnv + "_INDEX")}) + state := os.Getenv(killStateEnv) + journal := os.Getenv(killJournalEnv) + snapshotID := os.Getenv("KG_WRITESET_KILL_SNAPSHOT") + target := fx.target(t) + backups := fx.backups(t, target) + current, err := target.Current(fx.ctx) + if err != nil { + t.Fatalf("current: %v", err) + } + backup, err := backups.Prepare(fx.ctx, snapshotID, current) + if err != nil { + t.Fatalf("prepare backup: %v", err) + } + set, err := target.PlanWriteSet(fx.ctx, libraryrelease.WriteSetPlan{JobID: "job-kill", Target: "internal", + BackupSnapshotID: backup.SnapshotID, TargetSnapshotID: snapshotID, Universe: backup.Universe}) + if err != nil { + t.Fatalf("plan write set: %v", err) + } + record, err := json.Marshal(killHelperState{JobID: set.JobID, BackupSnapshotID: backup.SnapshotID, + TargetSnapshotID: snapshotID, WriteSetDigest: set.Digest}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(state, record, 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(journal, []byte(fx.archiveRoot), 0600); err != nil { + t.Fatal(err) + } + if err := target.Apply(fx.ctx, libraryrelease.StageDatabase, snapshotID); err != nil { + t.Fatalf("apply database: %v", err) + } + // resources 阶段:第一笔上传就把自己杀掉(真 SIGKILL,没有 defer、没有收尾)。 + dying := &killOnPutStore{inner: fx.objects.s3} + target.config.Objects = dying + if err := target.Apply(fx.ctx, libraryrelease.StageResources, snapshotID); err != nil { + t.Fatalf("apply resources: %v", err) + } + t.Fatal("helper should have been killed during the resources stage") +} + +// killOnPutStore 在第一次上传时直接 SIGKILL 自己:模拟进程被外部杀掉。 +type killOnPutStore struct { + inner *S3ObjectStore +} + +func (s *killOnPutStore) Put(ctx context.Context, provider, path string, body io.Reader, size int64) error { + return s.inner.Put(ctx, provider, path, body, size) +} +func (s *killOnPutStore) ConditionalCapability(ctx context.Context) error { + return s.inner.ConditionalCapability(ctx) +} +func (s *killOnPutStore) ObserveObject(ctx context.Context, provider, path string) (objectObservation, error) { + return s.inner.ObserveObject(ctx, provider, path) +} +func (s *killOnPutStore) RemoveObject(ctx context.Context, provider, path string, expected objectObservation) error { + return s.inner.RemoveObject(ctx, provider, path, expected) +} +func (s *killOnPutStore) CreateObject(ctx context.Context, provider, path string, body io.Reader, size int64, owner string) error { + if err := s.inner.CreateObject(ctx, provider, path, body, size, owner); err != nil { + return err + } + if err := syscall.Kill(os.Getpid(), syscall.SIGKILL); err != nil { + return err + } + select {} +} + +func (s *killOnPutStore) Stat(ctx context.Context, provider, path string) (int64, string, error) { + return s.inner.Stat(ctx, provider, path) +} + +func (s *killOnPutStore) Copy(ctx context.Context, provider, source, target string) error { + return s.inner.Copy(ctx, provider, source, target) +} + +func TestLibraryKillWorkerThenResumeRecoversWriteSetIsolated(t *testing.T) { + fx := openWriteSetFixture(t) + seedTargetData(t, fx) + before := universeDump(t, fx.pool) + snapshotID := sealSourceSnapshot(t, fx, nil) + + statePath := t.TempDir() + "/kill.json" + journalPath := t.TempDir() + "/journal.txt" + command := exec.Command(os.Args[0], "-test.run=TestWriteSetKillHelper", "-test.v") + command.Env = append(os.Environ(), killChildEnv+"=1", killStateEnv+"="+statePath, + killJournalEnv+"="+journalPath, killJournalEnv+"_ARCHIVE="+fx.archiveRoot, + killJournalEnv+"_INDEX="+fx.index, "KG_WRITESET_KILL_SNAPSHOT="+snapshotID) + output, err := command.CombinedOutput() + if err == nil { + t.Fatalf("helper must be killed, it exited cleanly: %s", output) + } + exitErr, ok := err.(*exec.ExitError) + if !ok { + t.Fatalf("helper failed to run: %v\n%s", err, output) + } + status, ok := exitErr.Sys().(syscall.WaitStatus) + if !ok || !status.Signaled() || status.Signal() != syscall.SIGKILL { + t.Fatalf("helper must die from SIGKILL, got %v\n%s", err, output) + } + t.Logf("helper killed by %s (half-written target)", status.Signal()) + + raw, err := os.ReadFile(statePath) + if err != nil { + t.Fatalf("child did not persist the job record: %v", err) + } + var record killHelperState + if err := json.Unmarshal(raw, &record); err != nil { + t.Fatal(err) + } + if record.WriteSetDigest == "" || record.BackupSnapshotID == "" { + t.Fatalf("child must persist writeset digest + backup snapshot: %+v", record) + } + journalRoot, err := os.ReadFile(journalPath) + if err != nil { + t.Fatal(err) + } + if strings.TrimSpace(string(journalRoot)) != fx.archiveRoot { + t.Fatalf("journal root mismatch: %q", journalRoot) + } + + // 重启后的 worker:新连接、新目标对象,只拿盘上的记录。 + resumedTarget := fx.target(t) + ledger, err := LoadWriteSet(fx.archiveRoot, record.WriteSetDigest) + if err != nil { + t.Fatalf("重启后取回写集合失败:%v", err) + } + if ledger.JobID != record.JobID || ledger.BackupSnapshotID != record.BackupSnapshotID || + ledger.TargetSnapshotID != record.TargetSnapshotID { + t.Fatalf("写集合与作业记录不一致:%+v vs %+v", ledger, record) + } + if err := resumedTarget.Restore(fx.ctx, libraryrelease.BackupRef{ID: "backup-" + record.BackupSnapshotID, + SnapshotID: record.BackupSnapshotID, WriteSet: ledger}); err != nil { + t.Fatalf("接管恢复失败:%v", err) + } + if diff := diffUniverse(before, universeDump(t, fx.pool)); diff != "" { + t.Fatalf("接管恢复后目标数据被改动:%s", diff) + } + if err := resumedTarget.Verify(fx.ctx, libraryrelease.Expectation{SnapshotID: record.BackupSnapshotID}); err != nil { + t.Fatalf("接管恢复后必须与预备份一致:%v", err) + } + t.Logf("resumed after SIGKILL: job=%s backup=%s ledger=%s", record.JobID, record.BackupSnapshotID, record.WriteSetDigest) + + // 负例:记录被移除 → 恢复必须失败(维护保持),而不是"看不见就当没写过"。 + if err := os.Chmod(writeSetPath(fx.archiveRoot, record.WriteSetDigest), 0600); err != nil { + t.Fatal(err) + } + if err := os.Remove(writeSetPath(fx.archiveRoot, record.WriteSetDigest)); err != nil { + t.Fatal(err) + } + if _, err := LoadWriteSet(fx.archiveRoot, record.WriteSetDigest); err == nil { + t.Fatal("写集合被移除后必须取不回来") + } + _ = time.Now() +} diff --git a/internal/releaseadapter/v071/object_import.go b/internal/releaseadapter/v071/object_import.go index a439a6f..0a042be 100644 --- a/internal/releaseadapter/v071/object_import.go +++ b/internal/releaseadapter/v071/object_import.go @@ -1,7 +1,6 @@ package v071 import ( - "bytes" "context" "errors" "io" @@ -47,57 +46,19 @@ func NewObjectImporter(store ObjectStore, config TargetObjectConfig) (*ObjectImp return &ObjectImporter{store: store, config: config}, nil } -func (importer *ObjectImporter) Stage(ctx context.Context, releaseRevision string, snapshot ObjectSnapshot) (ObjectStage, error) { - if !validSearchIdentifier(releaseRevision) || !validLowerSHA256(snapshot.SHA256) || snapshot.SHA256 != objectSnapshotDigest(snapshot.Objects) { - return ObjectStage{}, errors.New("invalid object import snapshot") - } - var total int64 - stage := ObjectStage{ReleaseRevision: releaseRevision, Provider: importer.config.Provider, Objects: make([]StagedObject, 0, len(snapshot.Objects))} - for _, object := range snapshot.Objects { - if !validSearchIdentifier(object.ResourceID) || len(object.Handle) != 22 || object.Size != int64(len(object.Data)) || object.SHA256 != shaBytes(object.Data) || !validObjectKey(object.PhysicalPath) { - return ObjectStage{}, errors.New("invalid object import entry") - } - providerPath, ok := providerPathFromLocator(object.PhysicalPath) - if !ok { - return ObjectStage{}, errors.New("invalid object import locator") - } - total += object.Size - stagingPath := ".governance-release-stage/" + releaseRevision + "/" + providerPath - if !validObjectLocator(stagingPath) { - return ObjectStage{}, errors.New("invalid object staging locator") - } - if err := importer.store.Put(ctx, importer.config.Provider, stagingPath, bytes.NewReader(object.Data), object.Size); err != nil { - return ObjectStage{}, errors.New("write staged release object") - } - size, digest, err := importer.store.Stat(ctx, importer.config.Provider, stagingPath) - if err != nil || size != object.Size || digest != object.SHA256 { - return ObjectStage{}, errors.New("verify staged release object") - } - stage.Objects = append(stage.Objects, StagedObject{Handle: object.Handle, StagingPath: stagingPath, FinalPath: providerPath, Size: object.Size, SHA256: object.SHA256}) - } - if total != snapshot.TotalBytes { - return ObjectStage{}, errors.New("object import total mismatch") - } - return stage, nil +// CheckLegacyObjectWrites has no configuration bypass. Document-level staging +// and promotion do not carry an immutable WriteSet/attempt grant, so they cannot +// participate in the exclusive object write domain. Read-only export is intact. +func CheckLegacyObjectWrites() error { + return errors.New("legacy object writes disabled: use the frozen-plan library worker and object gateway") } -func (importer *ObjectImporter) Promote(ctx context.Context, stage ObjectStage) error { - if stage.Provider != importer.config.Provider || !validSearchIdentifier(stage.ReleaseRevision) { - return errors.New("invalid object promotion stage") - } - for _, object := range stage.Objects { - if !validObjectLocator(object.StagingPath) || !validObjectLocator(object.FinalPath) || !validLowerSHA256(object.SHA256) || object.Size < 0 { - return errors.New("invalid object promotion entry") - } - if err := importer.store.Copy(ctx, importer.config.Provider, object.StagingPath, object.FinalPath); err != nil { - return errors.New("promote release object") - } - size, digest, err := importer.store.Stat(ctx, importer.config.Provider, object.FinalPath) - if err != nil || size != object.Size || digest != object.SHA256 { - return errors.New("verify promoted release object") - } - } - return nil +func (importer *ObjectImporter) Stage(context.Context, string, ObjectSnapshot) (ObjectStage, error) { + return ObjectStage{}, CheckLegacyObjectWrites() +} + +func (importer *ObjectImporter) Promote(context.Context, ObjectStage) error { + return CheckLegacyObjectWrites() } // rewriteLocatorBucket 把资源定位符里的桶换成目标桶,结构保持不变: diff --git a/internal/releaseadapter/v071/object_import_test.go b/internal/releaseadapter/v071/object_import_test.go index 8564dd0..6d6232f 100644 --- a/internal/releaseadapter/v071/object_import_test.go +++ b/internal/releaseadapter/v071/object_import_test.go @@ -1,11 +1,9 @@ package v071 import ( - "bytes" "context" "errors" "io" - "reflect" "testing" ) @@ -30,7 +28,7 @@ func TestProviderPathFromLocatorUnwrapsNestedSchemes(t *testing.T) { } } -func TestObjectImporterStagesThenPromotesWithoutDelete(t *testing.T) { +func TestObjectImporterRetiredWithoutStorageCalls(t *testing.T) { data := []byte("hello") snapshot := ObjectSnapshot{Objects: []AssetObject{{ResourceID: "res-1", Handle: "ABCDEFGHIJKLMNOPQRSTUV", Provider: "minio", PhysicalPath: "storage://source-backend/10000/knowledge/source.txt", Size: 5, SHA256: "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", Data: data}}, TotalBytes: 5} snapshot.SHA256 = objectSnapshotDigest(snapshot.Objects) @@ -39,22 +37,14 @@ func TestObjectImporterStagesThenPromotesWithoutDelete(t *testing.T) { if err != nil { t.Fatal(err) } - stage, err := importer.Stage(context.Background(), "release-v1", snapshot) - if err != nil { - t.Fatal(err) + if _, err := importer.Stage(context.Background(), "release-v1", snapshot); err == nil { + t.Fatal("legacy staging must be disabled") } - if len(stage.Objects) != 1 || stage.Objects[0].FinalPath != "10000/knowledge/source.txt" { - t.Fatalf("stage=%#v", stage) + if err := importer.Promote(context.Background(), ObjectStage{ReleaseRevision: "release-v1", Provider: "oss"}); err == nil { + t.Fatal("legacy promotion must be disabled") } - if err := importer.Promote(context.Background(), stage); err != nil { - t.Fatal(err) - } - wantCalls := []string{"put|oss|.governance-release-stage/release-v1/10000/knowledge/source.txt", "stat|oss|.governance-release-stage/release-v1/10000/knowledge/source.txt", "copy|oss|.governance-release-stage/release-v1/10000/knowledge/source.txt|10000/knowledge/source.txt", "stat|oss|10000/knowledge/source.txt"} - if !reflect.DeepEqual(store.calls, wantCalls) { - t.Fatalf("calls=%v want=%v", store.calls, wantCalls) - } - if !bytes.Equal(store.objects["oss|10000/knowledge/source.txt"], data) { - t.Fatal("final bytes differ") + if len(store.calls) != 0 || len(store.objects) != 0 { + t.Fatal("disabled importer touched storage") } } diff --git a/internal/releaseadapter/v071/oss_version_list.go b/internal/releaseadapter/v071/oss_version_list.go new file mode 100644 index 0000000..a8487e2 --- /dev/null +++ b/internal/releaseadapter/v071/oss_version_list.go @@ -0,0 +1,79 @@ +package v071 + +import ( + "context" + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "net/url" +) + +type ossListedVersion struct { + Key string `xml:"Key" json:"key"` + VersionID string `xml:"VersionId" json:"version_id"` +} +type ossExactVersionListing struct { + Versions []ossListedVersion `json:"versions"` + DeleteMarkers []ossListedVersion `json:"delete_markers"` + RequestIDs []string `json:"request_ids"` +} + +// Query the exact key as prefix; never scan a bucket to infer ownership. Listing +// is only discovery: deletion still requires full exact-version readback proof. +func (s *ossVersionStore) listExactVersions(ctx context.Context, key string) (ossExactVersionListing, error) { + result := ossExactVersionListing{Versions: []ossListedVersion{}, DeleteMarkers: []ossListedVersion{}} + if !validObjectKey(key) || key == "" { + return result, errors.New("exact OSS listing key required") + } + q := url.Values{"versions": {""}, "prefix": {key}, "max-keys": {"100"}} + seen := map[string]bool{} + seenMarkers := map[string]bool{} + for page := 0; page < 100; page++ { + resp, err := s.request(ctx, http.MethodGet, "", q, nil, nil) + if err != nil { + return result, err + } + var value struct { + XMLName xml.Name `xml:"ListVersionsResult"` + Name string `xml:"Name"` + Prefix string `xml:"Prefix"` + Truncated *bool `xml:"IsTruncated"` + NextKey string `xml:"NextKeyMarker"` + NextVersion string `xml:"NextVersionIdMarker"` + Versions []ossListedVersion `xml:"Version"` + Deletes []ossListedVersion `xml:"DeleteMarker"` + CommonPrefixes []string `xml:"CommonPrefixes>Prefix"` + } + if resp.StatusCode != 200 { + resp.Body.Close() + return result, fmt.Errorf("OSS list versions status %d", resp.StatusCode) + } + err = xml.NewDecoder(io.LimitReader(resp.Body, 1024*1024)).Decode(&value) + resp.Body.Close() + if err != nil || value.Name != s.bucket || value.Prefix != key || value.Truncated == nil || len(value.CommonPrefixes) != 0 { + return result, errors.New("OSS version listing identity/completeness not proven") + } + result.RequestIDs = append(result.RequestIDs, resp.Header.Get("x-oss-request-id")) + for _, v := range append(append([]ossListedVersion{}, value.Versions...), value.Deletes...) { + if v.Key != key || v.VersionID == "" || seen[v.VersionID] { + return result, errors.New("OSS listing contains unexpected key or duplicate version") + } + seen[v.VersionID] = true + } + result.Versions = append(result.Versions, value.Versions...) + result.DeleteMarkers = append(result.DeleteMarkers, value.Deletes...) + if !*value.Truncated { + return result, nil + } + marker := value.NextKey + "\x00" + value.NextVersion + if value.NextKey != key || value.NextVersion == "" || seenMarkers[marker] { + return result, errors.New("OSS listing pagination incomplete") + } + seenMarkers[marker] = true + q.Set("key-marker", value.NextKey) + q.Set("version-id-marker", value.NextVersion) + } + return result, errors.New("OSS version listing page budget exceeded") +} diff --git a/internal/releaseadapter/v071/oss_version_list_test.go b/internal/releaseadapter/v071/oss_version_list_test.go new file mode 100644 index 0000000..76c6c37 --- /dev/null +++ b/internal/releaseadapter/v071/oss_version_list_test.go @@ -0,0 +1,68 @@ +package v071 + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func TestContractOSSVersionListQueryIsReadOnly(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + if r.Method != "GET" || r.URL.Query().Get("prefix") != "kg-library-test-r4/key" { + t.Error("unscoped or non-read request") + } + fmt.Fprint(w, `isolated-bucketkg-library-test-r4/keyfalse`) + })) + defer server.Close() + s, err := newOSSVersionStore(S3ObjectStoreConfig{Provider: "oss", Endpoint: "https://oss.example.test", Bucket: "isolated-bucket", AccessKeyID: "fixture-access", SecretAccessKey: "fixture-secret", HTTPClient: &http.Client{Transport: ossRouteTransport{strings.TrimPrefix(server.URL, "http://"), http.DefaultTransport}}}) + if err != nil { + t.Fatal(err) + } + resp, err := s.request(context.Background(), "GET", "", url.Values{"versions": {""}, "prefix": {"kg-library-test-r4/key"}, "max-keys": {"100"}}, nil, nil) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if calls != 1 { + t.Fatal("listing not issued") + } +} + +func TestContractOSSExactVersionListingRejectsIncomplete(t *testing.T) { + for _, body := range []string{ + `isolated-bucketkey`, + `wrong-bucketkeyfalse`, + `isolated-bucketkeytrue`, + `isolated-bucketkeyfalseotherv1`, + } { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, body) })) + s, err := newOSSVersionStore(S3ObjectStoreConfig{Provider: "oss", Endpoint: "https://oss.example.test", Bucket: "isolated-bucket", AccessKeyID: "fixture-access", SecretAccessKey: "fixture-secret", HTTPClient: &http.Client{Transport: ossRouteTransport{strings.TrimPrefix(server.URL, "http://"), http.DefaultTransport}}}) + if err != nil { + t.Fatal(err) + } + if _, err = s.listExactVersions(context.Background(), "key"); err == nil { + t.Error("incomplete listing accepted") + } + server.Close() + } +} + +func TestContractOSSVersionAppendDoesNotAdvertiseConditionalCreate(t *testing.T) { + s, err := newOSSVersionStore(S3ObjectStoreConfig{Provider: "oss", Endpoint: "https://oss.example.test", Bucket: "isolated-bucket", AccessKeyID: "fixture-access", SecretAccessKey: "fixture-secret"}) + if err != nil { + t.Fatal(err) + } + if _, ok := any(s).(conditionalObjectStore); ok { + t.Fatal("append-only version API claims conditional create") + } + old := &S3ObjectStore{provider: "oss"} + if old.ConditionalCapability(context.Background()) == nil { + t.Fatal("OSS conditional write gate weakened") + } +} diff --git a/internal/releaseadapter/v071/oss_version_store.go b/internal/releaseadapter/v071/oss_version_store.go new file mode 100644 index 0000000..741cb1d --- /dev/null +++ b/internal/releaseadapter/v071/oss_version_store.go @@ -0,0 +1,231 @@ +package v071 + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha1" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strings" + "time" +) + +// Native OSS version operations deliberately do NOT implement conditionalObjectStore: +// OSS documents forbid-overwrite as ineffective on versioned buckets. Appending a +// version is recoverable, but is not an atomic absent-key create. Keep that policy +// decision separate from this protocol rather than silently weakening the gate. +type ossVersionStore struct { + endpoint *url.URL + bucket, access, secret string + maxBytes int64 + client *http.Client +} + +func newOSSVersionStore(c S3ObjectStoreConfig) (*ossVersionStore, error) { + u, err := url.Parse(c.Endpoint) + if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || c.Provider != "oss" || c.ForcePathStyle || c.Bucket == "" || strings.ContainsAny(c.Bucket, "/.: ") || c.AccessKeyID == "" || c.SecretAccessKey == "" { + return nil, errors.New("invalid native OSS configuration") + } + if c.MaxObjectBytes == 0 { + c.MaxObjectBytes = 100 * 1024 * 1024 + } + if c.MaxObjectBytes < 1 { + return nil, errors.New("invalid OSS size limit") + } + client := &http.Client{Timeout: 2 * time.Minute} + if c.HTTPClient != nil { + clone := *c.HTTPClient + client = &clone + } + client.CheckRedirect = func(*http.Request, []*http.Request) error { return errors.New("OSS redirect refused") } + return &ossVersionStore{u, c.Bucket, c.AccessKeyID, c.SecretAccessKey, c.MaxObjectBytes, client}, nil +} + +func (s *ossVersionStore) request(ctx context.Context, method, key string, q url.Values, body []byte, headers http.Header) (*http.Response, error) { + if key != "" && (!validObjectKey(key) || strings.Contains(key, "://") || strings.HasPrefix(key, "/")) { + return nil, errors.New("invalid OSS key") + } + u := *s.endpoint + u.Host = s.bucket + "." + s.endpoint.Host + u.Path = "/" + key + u.RawQuery = q.Encode() + req, err := http.NewRequestWithContext(ctx, method, u.String(), bytes.NewReader(body)) + if err != nil { + return nil, errors.New("invalid OSS request") + } + req.Header = headers.Clone() + if req.Header == nil { + req.Header = make(http.Header) + } + req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat)) + resource := "/" + s.bucket + "/" + key + keys := make([]string, 0, len(q)) + for k := range q { + if k == "prefix" || k == "max-keys" || k == "key-marker" || k == "version-id-marker" { + if method != http.MethodGet || key != "" || !q.Has("versions") || q.Get("prefix") == "" { + return nil, errors.New("OSS listing must be exact-key scoped and read-only") + } + continue // These list filters are not OSS V1 signed subresources. + } + if k != "versionId" && k != "versioning" && k != "versions" { + return nil, errors.New("unsupported OSS subresource") + } + keys = append(keys, k) + } + sort.Strings(keys) + for i, k := range keys { + if i == 0 { + resource += "?" + } else { + resource += "&" + } + resource += k + if q.Get(k) != "" { + resource += "=" + q.Get(k) + } + } + oss := map[string]string{} + for k, v := range req.Header { + lower := strings.ToLower(k) + if strings.HasPrefix(lower, "x-oss-") { + oss[lower] = strings.TrimSpace(strings.Join(v, ",")) + } + } + keys = keys[:0] + for k := range oss { + keys = append(keys, k) + } + sort.Strings(keys) + canonical := "" + for _, k := range keys { + canonical += k + ":" + oss[k] + "\n" + } + toSign := method + "\n" + req.Header.Get("Content-MD5") + "\n" + req.Header.Get("Content-Type") + "\n" + req.Header.Get("Date") + "\n" + canonical + resource + mac := hmac.New(sha1.New, []byte(s.secret)) + _, _ = mac.Write([]byte(toSign)) + req.Header.Set("Authorization", "OSS "+s.access+":"+base64.StdEncoding.EncodeToString(mac.Sum(nil))) + // No retry middleware and no redirect: an ambiguous write remains one attempt. + resp, err := s.client.Do(req) + if err != nil { + return nil, errors.New("native OSS transport outcome unknown") + } + return resp, nil +} +func (s *ossVersionStore) versioning(ctx context.Context) error { + resp, err := s.request(ctx, http.MethodGet, "", url.Values{"versioning": {""}}, nil, nil) + if err != nil { + return err + } + defer resp.Body.Close() + var value struct { + Status string `xml:"Status"` + } + if resp.StatusCode != 200 || xml.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&value) != nil || value.Status != "Enabled" { + return errors.New("OSS versioning is not confirmed Enabled") + } + return nil +} +func (s *ossVersionStore) observeVersion(ctx context.Context, key, version string) (objectObservation, error) { + q := url.Values{} + if version != "" { + if version == "null" { + return objectObservation{}, errors.New("null is not an immutable OSS version") + } + q.Set("versionId", version) + } + resp, err := s.request(ctx, http.MethodGet, key, q, nil, nil) + if err != nil { + return objectObservation{}, err + } + defer resp.Body.Close() + if resp.StatusCode == 404 { + var failure struct { + Code string `xml:"Code"` + } + if xml.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&failure) != nil || (failure.Code != "NoSuchKey" && failure.Code != "NoSuchVersion") { + return objectObservation{}, errors.New("OSS 404 is not an authoritative missing object version") + } + return objectObservation{}, nil + } + if resp.StatusCode != 200 { + return objectObservation{}, fmt.Errorf("OSS version read status %d", resp.StatusCode) + } + got := resp.Header.Get("x-oss-version-id") + if got == "" || got == "null" || version != "" && got != version || resp.Header.Get("ETag") == "" || resp.ContentLength < 0 || resp.ContentLength > s.maxBytes { + return objectObservation{}, errors.New("OSS version identity incomplete") + } + hash := sha256.New() + size, err := io.Copy(hash, io.LimitReader(resp.Body, s.maxBytes+1)) + if err != nil || size != resp.ContentLength { + return objectObservation{}, errors.New("OSS version body incomplete") + } + return objectObservation{Exists: true, VersionID: got, ETag: resp.Header.Get("ETag"), Owner: resp.Header.Get("x-oss-meta-kg-release-owner"), Bytes: size, SHA256: hex.EncodeToString(hash.Sum(nil))}, nil +} + +// appendVersion is explicit about its semantics. Callers need an approved version- +// append plan and a persisted intent; this is not wired as CreateObject. +func (s *ossVersionStore) appendVersion(ctx context.Context, key string, body []byte, owner string) (objectObservation, error) { + if len(owner) != 64 || int64(len(body)) > s.maxBytes { + return objectObservation{}, errObjectWriteRejected + } + if _, err := hex.DecodeString(owner); err != nil { + return objectObservation{}, errObjectWriteRejected + } + if err := s.versioning(ctx); err != nil { + return objectObservation{}, err + } + resp, err := s.request(ctx, http.MethodPut, key, nil, body, http.Header{"Content-Type": {"application/octet-stream"}, "X-Oss-Meta-Kg-Release-Owner": {owner}}) + if err != nil { + return objectObservation{}, err + } + defer resp.Body.Close() + version := resp.Header.Get("x-oss-version-id") + if resp.StatusCode != 200 || version == "" || version == "null" { + return objectObservation{}, errors.New("OSS append receipt unknown") + } + observation, err := s.observeVersion(ctx, key, version) + sum := sha256.Sum256(body) + if err != nil { + return objectObservation{}, err + } + if !observation.Exists || observation.Owner != owner || observation.Bytes != int64(len(body)) || observation.SHA256 != hex.EncodeToString(sum[:]) { + return objectObservation{}, errors.New("OSS exact version readback mismatch") + } + return observation, nil +} +func (s *ossVersionStore) removeVersion(ctx context.Context, key string, want objectObservation) error { + if !want.Exists || want.VersionID == "" || want.VersionID == "null" || want.ETag == "" || want.Owner == "" || want.SHA256 == "" { + return errors.New("OSS deletion requires complete owned version receipt") + } + got, err := s.observeVersion(ctx, key, want.VersionID) + if err != nil { + return err + } + if !got.Exists { + return nil + } + if got != want { + return errors.New("OSS exact version differs from receipt") + } + resp, sendErr := s.request(ctx, http.MethodDelete, key, url.Values{"versionId": {want.VersionID}}, nil, nil) + if resp != nil { + resp.Body.Close() + } + after, readErr := s.observeVersion(ctx, key, want.VersionID) + if readErr != nil { + return readErr + } + if after.Exists { + return fmt.Errorf("OSS exact version delete unconfirmed: %v", sendErr) + } + return nil +} diff --git a/internal/releaseadapter/v071/oss_version_store_integration_test.go b/internal/releaseadapter/v071/oss_version_store_integration_test.go new file mode 100644 index 0000000..551b13c --- /dev/null +++ b/internal/releaseadapter/v071/oss_version_store_integration_test.go @@ -0,0 +1,185 @@ +package v071 + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +type ossLiveVersionPlan struct { + Owner string `json:"owner"` + Body string `json:"body"` +} +type ossLivePlan struct { + Bucket string `json:"bucket"` + Endpoint string `json:"endpoint"` + Key string `json:"key"` + Versions []ossLiveVersionPlan `json:"versions"` +} + +// A persisted exact-key plan is mandatory. Repeating a failed invocation cannot +// create a new key or silently repeat an ambiguous PUT. Recovery only reconciles +// and cleans versions justified by the existing intent, never appends versions. +func TestContractOSSExactVersionsRealOptIn(t *testing.T) { + if os.Getenv("KG_OSS_VERSION_TEST_ALLOW") != "1" { + t.Skip("real OSS writes require explicitly approved isolated prefix") + } + root := os.Getenv("KG_OSS_VERSION_TEST_EVIDENCE") + prefix := os.Getenv("KG_OSS_VERSION_TEST_PREFIX") + info, err := os.Lstat(root) + if prefix != "kg-library-test-r4/" || !filepath.IsAbs(root) || err != nil || !info.IsDir() || info.Mode().Perm()&0077 != 0 { + t.Fatal("approved prefix and private persistent directory required") + } + var plan ossLivePlan + raw, err := os.ReadFile(filepath.Join(root, "run-plan.json")) + if err != nil || json.Unmarshal(raw, &plan) != nil { + t.Fatal("persisted exact-key plan required") + } + suffix := strings.TrimPrefix(plan.Key, prefix) + nonce, err := hex.DecodeString(suffix) + if err != nil || len(nonce) != 16 || prefix+suffix != plan.Key || plan.Bucket != "dobot-weknora-test" || plan.Endpoint != "https://oss-cn-shenzhen.aliyuncs.com" || len(plan.Versions) != 2 { + t.Fatal("plan outside exact authorization") + } + for _, v := range plan.Versions { + owner, e := hex.DecodeString(v.Owner) + if e != nil || len(owner) != 32 || v.Body == "" { + t.Fatal("invalid test version plan") + } + } + if plan.Versions[0].Owner == plan.Versions[1].Owner || plan.Versions[0].Body == plan.Versions[1].Body { + t.Fatal("test versions must differ") + } + s, err := newOSSVersionStore(S3ObjectStoreConfig{Provider: "oss", Endpoint: plan.Endpoint, Bucket: plan.Bucket, AccessKeyID: os.Getenv("KG_OSS_VERSION_TEST_ACCESS_KEY"), SecretAccessKey: os.Getenv("KG_OSS_VERSION_TEST_SECRET_KEY")}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + save := func(name string, value any) { + t.Helper() + raw, e := json.MarshalIndent(value, "", " ") + if e != nil { + t.Fatal(e) + } + if e = persistImmutableJSON(filepath.Join(root, name+".json"), raw); e != nil { + t.Fatal(e) + } + } + cleanup := func() { + t.Helper() + listed, e := s.listExactVersions(ctx, plan.Key) + if e != nil { + t.Fatal("reconciliation listing", e) + } + save("cleanup-lists/"+time.Now().UTC().Format("20060102T150405.000000000"), listed) + if len(listed.DeleteMarkers) != 0 { + t.Fatal("unexpected delete markers; no blind cleanup") + } + for _, v := range listed.Versions { + observed, e := s.observeVersion(ctx, plan.Key, v.VersionID) + if e != nil { + t.Fatal(e) + } + matched := false + for i, want := range plan.Versions { + sum := sha256.Sum256([]byte(want.Body)) + intent, e := os.ReadFile(filepath.Join(root, string(rune('a'+i))+"-intent.json")) + var recorded ossLiveVersionPlan + if e == nil && json.Unmarshal(intent, &recorded) == nil && recorded == want && observed.Exists && observed.Owner == want.Owner && observed.Bytes == int64(len(want.Body)) && observed.SHA256 == hex.EncodeToString(sum[:]) { + matched = true + } + } + if !matched { + t.Fatal("listed version lacks exact durable intent proof") + } + save("delete-intent-"+hex.EncodeToString([]byte(v.VersionID)), observed) + if e = s.removeVersion(ctx, plan.Key, observed); e != nil { + t.Fatal(e) + } + absent, e := s.observeVersion(ctx, plan.Key, v.VersionID) + if e != nil || absent.Exists { + t.Fatal("deleted version still present", e) + } + save("deleted-"+hex.EncodeToString([]byte(v.VersionID)), map[string]any{"version_id": v.VersionID, "absent": true}) + } + after, e := s.listExactVersions(ctx, plan.Key) + if e != nil { + t.Fatal(e) + } + if len(after.Versions) != 0 || len(after.DeleteMarkers) != 0 { + t.Fatal("exact-key version/delete-marker residue") + } + current, e := s.observeVersion(ctx, plan.Key, "") + if e != nil || current.Exists { + t.Fatal("latest object residue", e) + } + save("cleanup", map[string]any{"key": plan.Key, "listing": after, "latest_absent": true}) + } + if os.Getenv("KG_OSS_VERSION_TEST_RECOVER") == "1" { + cleanup() + return + } + if _, e := os.Stat(filepath.Join(root, "a-intent.json")); !os.IsNotExist(e) { + t.Fatal("prior write attempt exists; reconcile exact key, do not re-run PUT") + } + initial, err := s.listExactVersions(ctx, plan.Key) + if err != nil { + t.Fatal(err) + } + if len(initial.Versions) != 0 || len(initial.DeleteMarkers) != 0 { + t.Fatal("planned random key has pre-existing versions") + } + save("baseline", initial) + observations := []objectObservation{} + for i, want := range plan.Versions { + name := string(rune('a' + i)) + save(name+"-intent", want) + observed, e := s.appendVersion(ctx, plan.Key, []byte(want.Body), want.Owner) + if e != nil { + t.Fatal("append unresolved; use exact-key recovery, no blind PUT retry", e) + } + save(name+"-receipt", observed) + observations = append(observations, observed) + } + if observations[0].VersionID == observations[1].VersionID { + t.Fatal("version identities not distinct") + } + // Re-read BOTH immutable versions after the second PUT, not just latest. + for i, want := range observations { + got, e := s.observeVersion(ctx, plan.Key, want.VersionID) + if e != nil || got != want { + t.Fatal("exact-version readback differs", e) + } + save(string(rune('a'+i))+"-readback", got) + } + listed, err := s.listExactVersions(ctx, plan.Key) + if err != nil || len(listed.Versions) != 2 || len(listed.DeleteMarkers) != 0 { + t.Fatal("unexpected pre-cleanup versions", err) + } + save("two-versions", listed) + // Prove deleting the older exact version leaves the newer version unchanged. + save("old-delete-intent", observations[0]) + if err = s.removeVersion(ctx, plan.Key, observations[0]); err != nil { + t.Fatal(err) + } + current, err := s.observeVersion(ctx, plan.Key, "") + if err != nil || current != observations[1] { + t.Fatal("old-version delete changed latest", err) + } + save("newer-preserved", current) + if err = s.removeVersion(ctx, plan.Key, observations[0]); err != nil { + t.Fatal("exact delete replay", err) + } + old, err := s.observeVersion(ctx, plan.Key, observations[0].VersionID) + if err != nil || old.Exists { + t.Fatal("old version residue", err) + } + save("old-deleted", map[string]any{"version_id": observations[0].VersionID, "absent": true}) + cleanup() +} diff --git a/internal/releaseadapter/v071/oss_version_store_test.go b/internal/releaseadapter/v071/oss_version_store_test.go new file mode 100644 index 0000000..6c4da7d --- /dev/null +++ b/internal/releaseadapter/v071/oss_version_store_test.go @@ -0,0 +1,168 @@ +package v071 + +import ( + "context" + "crypto/hmac" + "crypto/sha1" + "encoding/base64" + "fmt" + "io" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" +) + +type ossRouteTransport struct { + server string + inner http.RoundTripper +} + +func (t ossRouteTransport) RoundTrip(r *http.Request) (*http.Response, error) { + clone := r.Clone(r.Context()) + u := *r.URL + clone.URL = &u + clone.URL.Scheme = "http" + clone.URL.Host = t.server + clone.Host = r.URL.Host + return t.inner.RoundTrip(clone) +} +func TestContractOSSNativeExactVersionProtocol(t *testing.T) { + // Loopback HTTP protocol fixture, not a real OSS service. + type version struct{ body, owner string } + versions := map[string]version{} + latest := "" + puts := 0 + deletes := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Host != "isolated-bucket.oss.example.test" { + t.Errorf("not virtual host: %s", r.Host) + } + canonical := "" + keys := []string{} + for k := range r.Header { + if strings.HasPrefix(strings.ToLower(k), "x-oss-") { + keys = append(keys, strings.ToLower(k)) + } + } + sort.Strings(keys) + for _, k := range keys { + canonical += k + ":" + r.Header.Get(k) + "\n" + } + resource := "/isolated-bucket" + r.URL.Path + if r.URL.Query().Has("versioning") { + resource += "?versioning" + } else if v := r.URL.Query().Get("versionId"); v != "" { + resource += "?versionId=" + v + } + mac := hmac.New(sha1.New, []byte("fixture-secret")) + fmt.Fprint(mac, r.Method+"\n\n"+r.Header.Get("Content-Type")+"\n"+r.Header.Get("Date")+"\n"+canonical+resource) + if r.Header.Get("Authorization") != "OSS fixture-access:"+base64.StdEncoding.EncodeToString(mac.Sum(nil)) { + t.Error("invalid native signature") + w.WriteHeader(403) + return + } + if r.URL.Query().Has("versioning") { + if r.Method != "GET" { + t.Fatal("bucket setting write") + } + fmt.Fprint(w, "Enabled") + return + } + v := r.URL.Query().Get("versionId") + if v == "" { + v = latest + } + switch r.Method { + case "PUT": + puts++ + data, _ := io.ReadAll(r.Body) + v = fmt.Sprint(puts) + versions[v] = version{string(data), r.Header.Get("x-oss-meta-kg-release-owner")} + latest = v + w.Header().Set("x-oss-version-id", v) + w.WriteHeader(200) + case "GET": + item, ok := versions[v] + if !ok { + w.WriteHeader(404) + fmt.Fprint(w, "NoSuchVersion") + return + } + w.Header().Set("x-oss-version-id", v) + w.Header().Set("ETag", "etag-"+v) + w.Header().Set("x-oss-meta-kg-release-owner", item.owner) + w.Header().Set("Content-Length", fmt.Sprint(len(item.body))) + fmt.Fprint(w, item.body) + case "DELETE": + if !r.URL.Query().Has("versionId") { + t.Error("blind delete") + w.WriteHeader(400) + return + } + deletes++ + delete(versions, v) + w.WriteHeader(204) + default: + w.WriteHeader(405) + } + })) + defer server.Close() + client := &http.Client{Transport: ossRouteTransport{strings.TrimPrefix(server.URL, "http://"), http.DefaultTransport}} + s, err := newOSSVersionStore(S3ObjectStoreConfig{Provider: "oss", Endpoint: "https://oss.example.test", Bucket: "isolated-bucket", AccessKeyID: "fixture-access", SecretAccessKey: "fixture-secret", HTTPClient: client}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + own, err := s.appendVersion(ctx, "kg-test/a b+中文", []byte("original"), strings.Repeat("a", 64)) + if err != nil { + t.Fatal(err) + } + foreign, err := s.appendVersion(ctx, "kg-test/a b+中文", []byte("later foreign bytes"), strings.Repeat("b", 64)) + if err != nil { + t.Fatal(err) + } + wrong := own + wrong.Owner = strings.Repeat("c", 64) + if s.removeVersion(ctx, "kg-test/a b+中文", wrong) == nil || deletes != 0 { + t.Fatal("wrong owner deleted version") + } + if err = s.removeVersion(ctx, "kg-test/a b+中文", own); err != nil { + t.Fatal(err) + } + current, err := s.observeVersion(ctx, "kg-test/a b+中文", "") + if err != nil || current != foreign { + t.Fatal("later version changed", err) + } + if err = s.removeVersion(ctx, "kg-test/a b+中文", own); err != nil || deletes != 1 { + t.Fatal("delete replay not idempotent", err) + } + if puts != 2 { + t.Fatalf("unexpected puts %d", puts) + } +} + +// A proxy/bucket 404 is not proof that an exact object version was deleted. +func TestContractOSSNonObject404IsNotAbsence(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(404) + fmt.Fprint(w, "NoSuchBucket") + })) + defer server.Close() + s, err := newOSSVersionStore(S3ObjectStoreConfig{Provider: "oss", Endpoint: "https://oss.example.test", Bucket: "isolated-bucket", AccessKeyID: "fixture-access", SecretAccessKey: "fixture-secret", HTTPClient: &http.Client{Transport: ossRouteTransport{strings.TrimPrefix(server.URL, "http://"), http.DefaultTransport}}}) + if err != nil { + t.Fatal(err) + } + if _, err = s.observeVersion(context.Background(), "key", "version"); err == nil { + t.Fatal("bucket/proxy 404 incorrectly proves object absence") + } +} + +func TestContractOSSRejectsPathStyleAndMissingCredentials(t *testing.T) { + for _, c := range []S3ObjectStoreConfig{{Provider: "oss", Endpoint: "http://oss.example.test", Bucket: "bucket", AccessKeyID: "test", SecretAccessKey: "test"}, {Provider: "oss", Endpoint: "https://oss.example.test", Bucket: "bucket", AccessKeyID: "test", SecretAccessKey: "test", ForcePathStyle: true}} { + if _, err := newOSSVersionStore(c); err == nil { + t.Fatal("unsafe configuration accepted") + } + } +} diff --git a/internal/releaseadapter/v071/postgres_export.go b/internal/releaseadapter/v071/postgres_export.go index 2811836..53ba041 100644 --- a/internal/releaseadapter/v071/postgres_export.go +++ b/internal/releaseadapter/v071/postgres_export.go @@ -10,6 +10,8 @@ import ( "sort" "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/libraryprofile" ) var resourceReferencePattern = regexp.MustCompile(`resource://([A-Za-z0-9_-]{22})`) @@ -28,7 +30,31 @@ type TableSnapshot struct { } type PostgresSnapshot struct { - Tables []TableSnapshot + Catalog migrationCatalog `json:"catalog,omitempty"` + Tables []TableSnapshot + // SchemaVersion 是导出/导入两侧共同的 profile 标识:归档必须与目标同版本, + // 否则行里的列语义(例如 0.9.0 新增的 NOT NULL 列)不可比。 + SchemaVersion int `json:"schema_version,omitempty"` + Profile string `json:"profile,omitempty"` +} + +// schemaProfile 解析快照声明的 profile。0 表示既有内存夹具(0.7.1), +// 只把"没有声明版本"解释成 74,不把未知版本解释成任何 profile。 +func (snapshot PostgresSnapshot) schemaProfile() (SchemaProfile, error) { + profile, err := libraryprofile.For(snapshot.SchemaVersion) + if err != nil { + if snapshot.SchemaVersion != 0 { + return SchemaProfile{}, err + } + profile, err = libraryprofile.For(libraryprofile.LegacyVersion) + if err != nil { + return SchemaProfile{}, err + } + } + resolved := SchemaProfile{Profile: profile} + resolved.Tables = append(resolved.Tables, profile.RequiredTables...) + resolved.Tables = append(resolved.Tables, profile.OptionalTables...) + return resolved, nil } func (snapshot PostgresSnapshot) Table(name string) TableSnapshot { diff --git a/internal/releaseadapter/v071/postgres_import.go b/internal/releaseadapter/v071/postgres_import.go index ed22ad7..db0c277 100644 --- a/internal/releaseadapter/v071/postgres_import.go +++ b/internal/releaseadapter/v071/postgres_import.go @@ -2,8 +2,6 @@ package v071 import ( "context" - "crypto/sha256" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -69,10 +67,13 @@ func (importer *PostgresImporter) Replace(ctx context.Context, identity Postgres return errors.New("begin PostgreSQL document import") } defer tx.Rollback(ctx) - var version int - var dirty bool - if err := tx.QueryRow(ctx, `SELECT version, dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { - return errors.New("target WeKnora schema contract mismatch") + profile, err := ResolveSchemaProfile(ctx, tx, "target WeKnora") + if err != nil { + return err + } + // 目标版本必须与归档同 profile:0.7.1 的归档不能写进 0.9.0,反之亦然。 + if err := requireSameProfile(snapshot.SchemaVersion, profile, "import"); err != nil { + return err } if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, identity.KnowledgeID); err != nil { return errors.New("lock target knowledge") @@ -179,10 +180,12 @@ func (importer *PostgresImporter) ReplaceWiki(ctx context.Context, identity Post return errors.New("begin PostgreSQL wiki import") } defer tx.Rollback(ctx) - var version int - var dirty bool - if err := tx.QueryRow(ctx, `SELECT version, dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { - return errors.New("target WeKnora schema contract mismatch") + profile, err := ResolveSchemaProfile(ctx, tx, "target WeKnora") + if err != nil { + return err + } + if err := requireSameProfile(snapshot.SchemaVersion, profile, "wiki import"); err != nil { + return err } if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 1))`, identity.KnowledgeBaseID); err != nil { return errors.New("lock target wiki knowledge base") @@ -207,10 +210,8 @@ func (importer *PostgresImporter) Disable(ctx context.Context, identity Postgres return errors.New("begin PostgreSQL disable") } defer tx.Rollback(ctx) - var version int - var dirty bool - if err := tx.QueryRow(ctx, `SELECT version, dirty FROM schema_migrations LIMIT 1`).Scan(&version, &dirty); err != nil || version != 74 || dirty { - return errors.New("target WeKnora schema contract mismatch") + if _, err := ResolveSchemaProfile(ctx, tx, "target WeKnora"); err != nil { + return err } if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, identity.KnowledgeID); err != nil { return errors.New("lock target knowledge") @@ -246,9 +247,15 @@ func (importer *PostgresImporter) prepareSnapshot(identity PostgresIdentity, sna return PostgresSnapshot{}, nil, nil, errors.New("PostgreSQL import snapshot is incomplete") } prepared := cloneSnapshot(snapshot) + // 表集合按快照所属 profile 判定:0.9.0 的归档里有 wiki_page_issues, + // 面向单文档发布的白名单没有它,用白名单会把合法归档判成非法。 + profile, err := snapshot.schemaProfile() + if err != nil { + return PostgresSnapshot{}, nil, nil, err + } known := map[string]bool{} for index, table := range prepared.Tables { - if !validReleaseTable(table.Name) || known[table.Name] || table.RowCount != len(table.Rows) || newTableSnapshot(table.Name, table.Rows).SHA256 != table.SHA256 { + if !profile.HasTable(table.Name) || known[table.Name] || table.RowCount != len(table.Rows) || newTableSnapshot(table.Name, table.Rows).SHA256 != table.SHA256 { return PostgresSnapshot{}, nil, nil, errors.New("PostgreSQL import snapshot is invalid") } known[table.Name] = true @@ -388,11 +395,11 @@ func (importer *PostgresImporter) prepareResourceRow(raw json.RawMessage, tenant } } targetPath := "storage://" + importer.config.TargetStorageBackendID + "/" + providerPath - digest := sha256.Sum256([]byte(targetPath)) row["storage_backend_id"] = importer.config.TargetStorageBackendID row["provider"] = importer.config.TargetProvider row["physical_path"] = targetPath - row["location_hash"] = hex.EncodeToString(digest[:]) + // 与全库搬运共用同一个哈希实现(F08):契约是 sha256(最终 physical_path)。 + row["location_hash"] = resourceLocationHash(targetPath) encoded, err := json.Marshal(row) if err != nil { return nil, resourceIdentityPair{}, errors.New("rewrite target resource") @@ -518,7 +525,9 @@ func validObjectLocator(value string) bool { } func cloneSnapshot(snapshot PostgresSnapshot) PostgresSnapshot { - result := PostgresSnapshot{Tables: make([]TableSnapshot, len(snapshot.Tables))} + // 复制快照不得改契约:SchemaVersion/Profile 丢掉会让下游按未知版本(=0.7.1)处理。 + result := PostgresSnapshot{Tables: make([]TableSnapshot, len(snapshot.Tables)), + SchemaVersion: snapshot.SchemaVersion, Profile: snapshot.Profile} for index, table := range snapshot.Tables { result.Tables[index] = table result.Tables[index].Rows = append([]json.RawMessage(nil), table.Rows...) diff --git a/internal/releaseadapter/v071/remap.go b/internal/releaseadapter/v071/remap.go index 7a1e01b..6975120 100644 --- a/internal/releaseadapter/v071/remap.go +++ b/internal/releaseadapter/v071/remap.go @@ -135,5 +135,8 @@ func replaceTable(snapshot PostgresSnapshot, replacement TableSnapshot) Postgres if !replaced { tables = append(tables, replacement) } - return PostgresSnapshot{Tables: tables} + // SchemaVersion/Profile 描述的是这份快照的 schema 契约,不是表内容:重建快照时 + // 丢掉它们,下游读到的就是"版本未知",而未知版本按 0.7.1 处理——134 的归档 + // 于是被当成 74 搬运,跨版本闸门形同不存在。 + return PostgresSnapshot{Tables: tables, SchemaVersion: snapshot.SchemaVersion, Profile: snapshot.Profile} } diff --git a/internal/releaseadapter/v071/remap_test.go b/internal/releaseadapter/v071/remap_test.go index 137486c..330a7d6 100644 --- a/internal/releaseadapter/v071/remap_test.go +++ b/internal/releaseadapter/v071/remap_test.go @@ -173,3 +173,26 @@ func TestPlanItemTargetBaseFallsBackToTestedBase(t *testing.T) { t.Fatalf("unbound TargetBase = %q, want the tested base", unbound.TargetBase()) } } + +// 范围改写只换身份,不改 schema 契约:改写后的快照若丢掉 SchemaVersion/Profile, +// 下游读到的就是"版本未知",而未知版本会被当作 0.7.1 处理——134 的归档于是被当成 +// 74 搬,跨版本闸门形同不存在。 +func TestRemapKnowledgeBasePreservesSchemaProfile(t *testing.T) { + bundle := crossBaseBundle(t) + bundle.Postgres.SchemaVersion = 134 + bundle.Postgres.Profile = "v090" + if err := bundle.RemapKnowledgeBase("prod-kb"); err != nil { + t.Fatalf("remap: %v", err) + } + if bundle.Postgres.SchemaVersion != 134 || bundle.Postgres.Profile != "v090" { + t.Fatalf("remapped snapshot lost its schema profile: %d/%q", + bundle.Postgres.SchemaVersion, bundle.Postgres.Profile) + } + tables := map[string]bool{} + for _, table := range bundle.Postgres.Tables { + tables[table.Name] = true + } + if len(tables) != len(bundle.Postgres.Tables) { + t.Fatal("remap duplicated a table") + } +} diff --git a/internal/releaseadapter/v071/s3_object_store.go b/internal/releaseadapter/v071/s3_object_store.go index b198408..e54e2eb 100644 --- a/internal/releaseadapter/v071/s3_object_store.go +++ b/internal/releaseadapter/v071/s3_object_store.go @@ -114,24 +114,38 @@ func (store *S3ObjectStore) Put(ctx context.Context, provider, objectPath string // Delete 删除单个对象;只用于显式清理(保留策略未接线,不会自动调用)。 func (store *S3ObjectStore) Delete(ctx context.Context, provider, objectPath string) error { - if provider != store.provider || !validObjectLocator(objectPath) { + // 与 Open/Put 同一个校验:真实资源路径是 storage:///:///, + // 只有 validObjectKey 接受这种嵌套形状(validObjectLocator 只认单层)。 + if provider != store.provider || !validObjectKey(objectPath) { return errors.New("invalid release object delete") } - if _, err := store.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(store.bucket), Key: aws.String(objectPath)}); err != nil { + key, ok := providerPathFromLocator(objectPath) + if !ok { + return errors.New("invalid release object delete") + } + if _, err := store.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(store.bucket), Key: aws.String(key)}); err != nil { return errors.New("delete release object") } return nil } +// Stat 的入参形状必须与 Open/Put 完全相同:真实资源路径是 +// storage:///:///,而落盘/读取都只认裸 key。 +// 曾经这里把整串当 key,于是 Put/Open 能成功、Stat 必然 404——"对象在桶里但 +// 校验说读不到"。测试也只喂裸 key,绕开了这条不一致。 func (store *S3ObjectStore) Stat(ctx context.Context, provider, objectPath string) (int64, string, error) { - if provider != store.provider || !validObjectLocator(objectPath) { + if provider != store.provider || !validObjectKey(objectPath) { return 0, "", errors.New("invalid release object read") } - head, err := store.client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(store.bucket), Key: aws.String(objectPath)}) + key, ok := providerPathFromLocator(objectPath) + if !ok { + return 0, "", errors.New("invalid release object read") + } + head, err := store.client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(store.bucket), Key: aws.String(key)}) if err != nil || head.ContentLength == nil || *head.ContentLength < 0 || *head.ContentLength > store.maxObjectBytes { return 0, "", errors.New("inspect release object") } - object, err := store.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(store.bucket), Key: aws.String(objectPath)}) + object, err := store.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(store.bucket), Key: aws.String(key)}) if err != nil { return 0, "", errors.New("read release object") } @@ -145,11 +159,16 @@ func (store *S3ObjectStore) Stat(ctx context.Context, provider, objectPath strin } func (store *S3ObjectStore) Copy(ctx context.Context, provider, sourcePath, targetPath string) error { - if provider != store.provider || !validObjectLocator(sourcePath) || !validObjectLocator(targetPath) { + if provider != store.provider || !validObjectKey(sourcePath) || !validObjectKey(targetPath) { return errors.New("invalid release object copy") } - copySource := url.PathEscape(store.bucket + "/" + sourcePath) - if _, err := store.client.CopyObject(ctx, &s3.CopyObjectInput{Bucket: aws.String(store.bucket), Key: aws.String(targetPath), CopySource: aws.String(copySource)}); err != nil { + sourceKey, sourceOK := providerPathFromLocator(sourcePath) + targetKey, targetOK := providerPathFromLocator(targetPath) + if !sourceOK || !targetOK { + return errors.New("invalid release object copy") + } + copySource := url.PathEscape(store.bucket + "/" + sourceKey) + if _, err := store.client.CopyObject(ctx, &s3.CopyObjectInput{Bucket: aws.String(store.bucket), Key: aws.String(targetKey), CopySource: aws.String(copySource)}); err != nil { return errors.New("copy release object") } return nil diff --git a/internal/releaseadapter/v071/s3_object_store_integration_test.go b/internal/releaseadapter/v071/s3_object_store_integration_test.go index 8b8b555..52c9b28 100644 --- a/internal/releaseadapter/v071/s3_object_store_integration_test.go +++ b/internal/releaseadapter/v071/s3_object_store_integration_test.go @@ -3,11 +3,20 @@ package v071 import ( "bytes" "context" + "fmt" "io" "os" + "strings" "testing" + "time" ) +// 这条用例必须喂**真实定位符**:WeKnora 的资源路径是 +// storage:///:///,而 Stat/Open/Put/Copy +// 都必须把它拆成同一个裸 key。 +// +// 历史缺陷:Stat/Delete/Copy 曾把整串定位符当对象键,而测试只喂裸 key, +// 于是"在桶里但校验读不到"这条不一致一直没被发现。 func TestS3ObjectStoreIntegration(t *testing.T) { endpoint := os.Getenv("TEST_MINIO_ENDPOINT") access := os.Getenv("TEST_MINIO_ACCESS_KEY") @@ -24,34 +33,81 @@ func TestS3ObjectStoreIntegration(t *testing.T) { if err := store.EnsureBucket(ctx); err != nil { t.Fatal(err) } + // 每次运行用独立前缀:同一桶里留下的旧对象不能让"读不到"的负例假通过。 + prefix := fmt.Sprintf("fix-stat-locator/%d", time.Now().UnixNano()) + key := prefix + "/source.txt" + locator := "storage://source-backend/minio://" + bucket + "/" + key data := []byte("synthetic object release content") - if err := store.Put(ctx, "minio", "stage/source.txt", bytes.NewReader(data), int64(len(data))); err != nil { - t.Fatal(err) + if err := store.Put(ctx, "minio", locator, bytes.NewReader(data), int64(len(data))); err != nil { + t.Fatalf("put by locator: %v", err) } - reader, err := store.Open(ctx, "minio", "storage://source-backend/stage/source.txt") + + // 正例 1:带 storage:// 前缀的定位符 —— 与 Put 用的是同一份字节。 + size, digest, err := store.Stat(ctx, "minio", locator) if err != nil { - t.Fatal(err) + t.Fatalf("stat by storage locator: %v", err) } - opened, err := io.ReadAll(reader) + if size != int64(len(data)) || digest != shaBytes(data) { + t.Fatalf("stat size=%d digest=%s", size, digest) + } + + // 正例 2:只带 provider scheme 的定位符也算同一个对象。 + if size, digest, err = store.Stat(ctx, "minio", "minio://"+bucket+"/"+key); err != nil { + t.Fatalf("stat by provider locator: %v", err) + } + if size != int64(len(data)) || digest != shaBytes(data) { + t.Fatalf("stat by provider locator size=%d digest=%s", size, digest) + } + + reader, err := store.Open(ctx, "minio", locator) + if err != nil { + t.Fatalf("open by locator: %v", err) + } + opened, readErr := io.ReadAll(reader) closeErr := reader.Close() - if err != nil || closeErr != nil || !bytes.Equal(opened, data) { - t.Fatalf("opened=%q err=%v close=%v", opened, err, closeErr) + if readErr != nil || closeErr != nil || !bytes.Equal(opened, data) { + t.Fatalf("opened=%q err=%v close=%v", opened, readErr, closeErr) } - size, digest, err := store.Stat(ctx, "minio", "stage/source.txt") - if err != nil { - t.Fatal(err) + + finalLocator := "storage://source-backend/minio://" + bucket + "/" + prefix + "/final/source.txt" + if err := store.Copy(ctx, "minio", locator, finalLocator); err != nil { + t.Fatalf("copy by locator: %v", err) } - if size != int64(len(data)) || digest != shaBytes(data) { - t.Fatalf("size=%d digest=%s", size, digest) - } - if err := store.Copy(ctx, "minio", "stage/source.txt", "final/source.txt"); err != nil { - t.Fatal(err) - } - size, digest, err = store.Stat(ctx, "minio", "final/source.txt") - if err != nil { - t.Fatal(err) - } - if size != int64(len(data)) || digest != shaBytes(data) { + if size, digest, err = store.Stat(ctx, "minio", finalLocator); err != nil { + t.Fatalf("stat copied object: %v", err) + } else if size != int64(len(data)) || digest != shaBytes(data) { t.Fatalf("copy size=%d digest=%s", size, digest) } + + // 负例 1:桶里没有这个键 ⇒ 必须报错,不能返回 0 字节当成"对象为空"。 + if _, _, err := store.Stat(ctx, "minio", "storage://source-backend/minio://"+bucket+"/"+prefix+"/missing.txt"); err == nil { + t.Fatal("stat of a missing key must fail") + } + // 负例 2:provider 不匹配 ⇒ 直接拒绝(不能拿别人家的定位符读本桶)。 + if _, _, err := store.Stat(ctx, "oss", locator); err == nil { + t.Fatal("stat must reject a foreign provider") + } + // 负例 3:结构非法的定位符(穿越路径)⇒ 拒绝。 + if _, _, err := store.Stat(ctx, "minio", "storage://source-backend/minio://"+bucket+"/../"+key); err == nil { + t.Fatal("stat must reject a traversal locator") + } + // 负例 4:Copy 源不存在 ⇒ 报错,不能"成功"出一个空对象。 + if err := store.Copy(ctx, "minio", "storage://source-backend/minio://"+bucket+"/"+prefix+"/missing.txt", finalLocator+".copy"); err == nil { + t.Fatal("copy from a missing source must fail") + } + // 负例 5:读回来的摘要必须与写入内容不同时不相等(防止把长度当摘要)。 + if strings.TrimSpace(digest) == "" { + t.Fatal("stat must return a content digest") + } + + // Delete 也必须吃同一个定位符(它和 Stat 是同一类"按路径操作"的入口)。 + if err := store.Delete(ctx, "minio", finalLocator); err != nil { + t.Fatalf("delete by locator: %v", err) + } + if _, _, err := store.Stat(ctx, "minio", finalLocator); err == nil { + t.Fatal("stat after delete must fail") + } + t.Cleanup(func() { + _ = store.Delete(context.Background(), "minio", "storage://source-backend/minio://"+bucket+"/"+key) + }) } diff --git a/internal/releaseadapter/v071/schema_probe_fixture_test.go b/internal/releaseadapter/v071/schema_probe_fixture_test.go new file mode 100644 index 0000000..fadc1fe --- /dev/null +++ b/internal/releaseadapter/v071/schema_probe_fixture_test.go @@ -0,0 +1,50 @@ +package v071 + +import ( + "knowledge-governance/internal/libraryprofile" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +// schemaProbeRows 给"按 SQL 打桩"的既有夹具提供 information_schema 能力探测答案。 +// 0.7.1 的假库一律按 profile 声明的表/列回答,这样能力探测在单测里也是真的被走了一遍, +// 而不是被桩悄悄放行。 +type schemaProbeRows struct { + pairs [][2]string + index int +} + +func legacySchemaProbeRows() *schemaProbeRows { + profile, err := libraryprofile.For(libraryprofile.LegacyVersion) + if err != nil { + panic(err) + } + rows := &schemaProbeRows{} + for _, table := range profile.RequiredTables { + for _, column := range profile.RequiredColumns[table] { + rows.pairs = append(rows.pairs, [2]string{table, column}) + } + } + return rows +} + +func (r *schemaProbeRows) Close() {} +func (r *schemaProbeRows) Err() error { return nil } +func (r *schemaProbeRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} } +func (r *schemaProbeRows) FieldDescriptions() []pgconn.FieldDescription { return nil } +func (r *schemaProbeRows) RawValues() [][]byte { return nil } +func (r *schemaProbeRows) Conn() *pgx.Conn { return nil } +func (r *schemaProbeRows) Next() bool { + if r.index >= len(r.pairs) { + return false + } + r.index++ + return true +} +func (r *schemaProbeRows) Scan(dest ...any) error { + *dest[0].(*string) = r.pairs[r.index-1][0] + *dest[1].(*string) = r.pairs[r.index-1][1] + return nil +} +func (r *schemaProbeRows) Values() ([]any, error) { return nil, nil } diff --git a/internal/releaseadapter/v071/schema_profile.go b/internal/releaseadapter/v071/schema_profile.go new file mode 100644 index 0000000..8f63bf0 --- /dev/null +++ b/internal/releaseadapter/v071/schema_profile.go @@ -0,0 +1,145 @@ +package v071 + +import ( + "context" + "fmt" + "sort" + + "github.com/jackc/pgx/v5" + + "knowledge-governance/internal/libraryprofile" +) + +// SchemaProfile 是"版本号 + 能力探测"两者都通过之后的解析结果。 +// +// Tables 是**实际存在**的表(必需表按声明顺序 + 存在的可选表)。导出/编目/校验 +// 只按它取数:0.9.0 没有 wiki_log_entries,硬编码表清单会在第一条查询上炸, +// 而"表不存在就跳过约束"会让 0.7.1 少一个必需表也悄悄通过。 +type SchemaProfile struct { + libraryprofile.Profile + Tables []string +} + +// HasTable 报告解析后的表集合里是否包含该表。 +func (p SchemaProfile) HasTable(name string) bool { + for _, candidate := range p.Tables { + if candidate == name { + return true + } + } + return false +} + +// CatalogTables 是编目/归档用的表清单(与 Tables 同序,sorted 便于稳定摘要)。 +func (p SchemaProfile) CatalogTables() []string { + tables := append([]string(nil), p.Tables...) + sort.Strings(tables) + return tables +} + +type schemaProbeDB interface { + QueryRow(ctx context.Context, sql string, args ...any) pgx.Row + Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) +} + +// ResolveSchemaProfile 解析并校验一侧的 schema 契约。 +// +// 顺序是刻意的:先读版本(未知版本失败关闭、dirty 一律失败),再用 +// information_schema 证明 profile 声明的东西真的存在。只信版本号等于把 +// "迁移进度"当成"能力契约",而两者在生产上经常不同步。 +func ResolveSchemaProfile(ctx context.Context, db schemaProbeDB, role string) (SchemaProfile, error) { + var version int + var dirty bool + if err := db.QueryRow(ctx, `SELECT version,dirty FROM schema_migrations ORDER BY version DESC LIMIT 1`).Scan(&version, &dirty); err != nil { + return SchemaProfile{}, fmt.Errorf("read %s schema_migrations: %w", role, err) + } + profile, err := profileForMigration(version, dirty, role) + if err != nil { + return SchemaProfile{}, err + } + columns, err := probeSchemaColumns(ctx, db, profile) + if err != nil { + return SchemaProfile{}, fmt.Errorf("%s schema version %d: %w", role, version, err) + } + return verifySchemaCapabilities(profile, columns, role, version) +} + +// profileForMigration 只做"版本号 + dirty → profile"的判定,不碰数据库。 +// dirty 与未知版本都必须失败:前者是半截迁移,后者是没见过的契约。 +func profileForMigration(version int, dirty bool, role string) (libraryprofile.Profile, error) { + if dirty { + return libraryprofile.Profile{}, fmt.Errorf("%s schema is dirty at version %d: refusing to snapshot or write", role, version) + } + profile, err := libraryprofile.For(version) + if err != nil { + return libraryprofile.Profile{}, fmt.Errorf("%s schema: %w", role, err) + } + return profile, nil +} + +// verifySchemaCapabilities 用 information_schema 的实际列集合校正 profile: +// 必需表/列缺失就精确点名,存在才进"实际表集合"。 +func verifySchemaCapabilities(profile libraryprofile.Profile, columns map[string]map[string]bool, role string, version int) (SchemaProfile, error) { + resolved := SchemaProfile{Profile: profile} + for _, table := range profile.RequiredTables { + if _, ok := columns[table]; !ok { + return SchemaProfile{}, fmt.Errorf("%s schema version %d: required table %s is missing", role, version, table) + } + resolved.Tables = append(resolved.Tables, table) + } + for _, table := range profile.OptionalTables { + if _, ok := columns[table]; ok { + resolved.Tables = append(resolved.Tables, table) + } + } + for _, table := range resolved.Tables { + for _, column := range profile.RequiredColumns[table] { + if !columns[table][column] { + return SchemaProfile{}, fmt.Errorf("%s schema version %d: required column %s.%s is missing", role, version, table, column) + } + } + } + return resolved, nil +} + +// probeSchemaColumns 一次读回 profile 涉及表的列集合。 +func probeSchemaColumns(ctx context.Context, db schemaProbeDB, profile libraryprofile.Profile) (map[string]map[string]bool, error) { + names := make([]string, 0, len(profile.RequiredTables)+len(profile.OptionalTables)) + names = append(names, profile.RequiredTables...) + names = append(names, profile.OptionalTables...) + sort.Strings(names) + rows, err := db.Query(ctx, `SELECT table_name, column_name FROM information_schema.columns WHERE table_schema='public' AND table_name=ANY($1)`, names) + if err != nil { + return nil, fmt.Errorf("probe schema capabilities: %w", err) + } + defer rows.Close() + columns := map[string]map[string]bool{} + for rows.Next() { + var table, column string + if err := rows.Scan(&table, &column); err != nil { + return nil, fmt.Errorf("probe schema capabilities: %w", err) + } + if columns[table] == nil { + columns[table] = map[string]bool{} + } + columns[table][column] = true + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("probe schema capabilities: %w", err) + } + return columns, nil +} + +// requireSameProfile 拒绝跨版本搬运:0.9.0 归档不能落到 0.7.1,反之也不行。 +// 本轮只支持 090↔090(以及既有 74↔74)。 +func requireSameProfile(sourceVersion int, target SchemaProfile, direction string) error { + if sourceVersion == 0 { + // 老的内存夹具没有声明版本:按 0.7.1 处理,行为不变。 + sourceVersion = libraryprofile.LegacyVersion + } + if sourceVersion != target.SchemaVersion { + return fmt.Errorf("%s refused: archive schema version %d cannot be applied to target schema version %d (cross-version %s is not supported)", + direction, sourceVersion, target.SchemaVersion, direction) + } + return nil +} diff --git a/internal/releaseadapter/v071/schema_profile_v090_test.go b/internal/releaseadapter/v071/schema_profile_v090_test.go new file mode 100644 index 0000000..4cd15a3 --- /dev/null +++ b/internal/releaseadapter/v071/schema_profile_v090_test.go @@ -0,0 +1,126 @@ +package v071 + +import ( + "os" + "strings" + "testing" + + "knowledge-governance/internal/libraryprofile" +) + +func TestSchemaProfileFailsClosedOnUnknownVersion(t *testing.T) { + _, err := profileForMigration(135, false, "test") + if err == nil || !strings.Contains(err.Error(), "135") || !strings.Contains(err.Error(), "134") { + t.Fatalf("unknown version must fail with the real version number, got %v", err) + } +} + +func TestSchemaProfileRejectsDirtySchema(t *testing.T) { + _, err := profileForMigration(134, true, "test") + if err == nil || !strings.Contains(err.Error(), "dirty") { + t.Fatalf("dirty schema must be refused, got %v", err) + } +} + +func TestSchemaProfileNamesMissingTableAndColumn(t *testing.T) { + profile, err := libraryprofile.For(134) + if err != nil { + t.Fatal(err) + } + columns := map[string]map[string]bool{} + for _, table := range append(append([]string{}, profile.RequiredTables...), profile.OptionalTables...) { + columns[table] = map[string]bool{} + for _, column := range profile.RequiredColumns[table] { + columns[table][column] = true + } + } + delete(columns, "wiki_pages") + if _, err := verifySchemaCapabilities(profile, columns, "test", 134); err == nil || !strings.Contains(err.Error(), "wiki_pages") { + t.Fatalf("missing required table must be named, got %v", err) + } + + columns["wiki_pages"] = map[string]bool{"id": true, "tenant_id": true, "knowledge_base_id": true} + if _, err := verifySchemaCapabilities(profile, columns, "test", 134); err == nil || !strings.Contains(err.Error(), "wiki_pages.slug") { + t.Fatalf("missing required column must be named, got %v", err) + } + columns["wiki_pages"]["slug"] = true + if _, err := verifySchemaCapabilities(profile, columns, "test", 134); err != nil { + t.Fatalf("complete capabilities must pass: %v", err) + } +} + +func TestSchemaProfileV071BehaviourUnchanged(t *testing.T) { + legacy, err := libraryprofile.For(74) + if err != nil { + t.Fatal(err) + } + if !legacy.HasTable("wiki_log_entries") || !legacy.RequiresPart("wiki/wiki_log_entries") { + t.Fatal("0.7.1 must still require wiki_log_entries") + } + if legacy.EmbeddingDimension != 1024 { + t.Fatalf("0.7.1 dimension contract must stay 1024, got %d", legacy.EmbeddingDimension) + } + v090, err := libraryprofile.For(134) + if err != nil { + t.Fatal(err) + } + if v090.RequiresPart("wiki/wiki_log_entries") || !v090.AllowsPart("wiki/wiki_log_entries") { + t.Fatal("0.9.0 wiki_log_entries must be optional") + } + if v090.HasTable("wiki_log_entries") == false { + t.Fatal("optional table should still be addressable when present") + } + resolved := SchemaProfile{Profile: v090, Tables: v090.RequiredTables} + if resolved.HasTable("wiki_log_entries") { + t.Fatal("0.9.0 export table set must exclude an absent optional table") + } +} + +func TestTargetIndexNameResolvesToConfigurationOnly(t *testing.T) { + profile, err := libraryprofile.For(134) + if err != nil { + t.Fatal(err) + } + name, err := resolveTargetIndexName("", "weknora_v090_chunks", profile) + if err != nil || name != "weknora_v090_chunks" { + t.Fatalf("empty vector store must fall back to the configured index, got %q/%v", name, err) + } + if _, err := resolveTargetIndexName("", "", profile); err == nil || !strings.Contains(err.Error(), "index name unresolved") { + t.Fatalf("no source must fail instead of resolving to an empty name, got %v", err) + } + if _, err := resolveTargetIndexName("idx_a", "idx_b", profile); err == nil || !strings.Contains(err.Error(), "does not match") { + t.Fatalf("conflicting index sources must be refused, got %v", err) + } +} + +// 0.9.0 与 0.7.1 的映射必须算出不同摘要:同样的 1024 维不等于同一份契约。 +func TestIndexMappingDigestSeparatesSchemaVersions(t *testing.T) { + legacy := []byte(`{"weknora_v071_chunks":{"mappings":{"properties":{ + "chunk_id":{"type":"text","fields":{"keyword":{"type":"keyword"}}}, + "knowledge_id":{"type":"text","fields":{"keyword":{"type":"keyword"}}}, + "knowledge_base_id":{"type":"text","fields":{"keyword":{"type":"keyword"}}}, + "embedding":{"type":"dense_vector","dims":1024}}}}}`) + legacyDigest, err := IndexMappingDigest(legacy) + if err != nil { + t.Fatal(err) + } + if path := os.Getenv("KG_V090_MAPPING_JSON"); path != "" { + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + v090Digest, err := IndexMappingDigest(raw) + if err != nil { + t.Fatalf("real 0.9.0 mapping must be digestible: %v", err) + } + if v090Digest == legacyDigest { + t.Fatal("0.9.0 and 0.7.1 mappings must not share a digest") + } + if len(v090Digest) != 64 { + t.Fatalf("unexpected digest shape %q", v090Digest) + } + } + if _, err := IndexMappingDigest([]byte(`{"a":{"mappings":{}},"b":{"mappings":{}}}`)); err == nil { + t.Fatal("multi-index mapping responses must be refused") + } +} diff --git a/internal/releaseadapter/v071/search.go b/internal/releaseadapter/v071/search.go index a9a908b..68ac369 100644 --- a/internal/releaseadapter/v071/search.go +++ b/internal/releaseadapter/v071/search.go @@ -22,6 +22,9 @@ type SearchIdentity struct { TenantID uint64 KnowledgeBaseID string KnowledgeID string + // NoTenantField 表示该版本的索引文档不带 tenant_id(0.9.0 就是这样)。 + // 归属校验只能比 knowledge_base_id,否则"本来就是自己的文档"会被判冲突。 + NoTenantField bool } type SearchDocument struct { @@ -275,6 +278,37 @@ func (exporter *SearchExporter) MappingSHA256(ctx context.Context) (string, erro } func (exporter *SearchExporter) requestJSON(ctx context.Context, method, path string, payload any, result any) error { + return exporter.requestJSONWithReplay(ctx, method, path, payload, result, true) +} + +// IndexUUID 读目标索引的实际 UUID。同名重建会得到新 UUID —— 恢复派发用它识别 +// "目标被替换",不是用它证明历史未发送。索引不存在按 errIndexMissing 返回。 +func (exporter *SearchExporter) IndexUUID(ctx context.Context) (string, error) { + var rows []struct { + Index string `json:"index"` + UUID string `json:"uuid"` + } + path := "/_cat/indices/" + url.PathEscape(exporter.index) + "?format=json&h=index,uuid" + if err := exporter.requestJSON(ctx, http.MethodGet, path, nil, &rows); err != nil { + return "", err + } + for _, row := range rows { + if row.Index == exporter.index && row.UUID != "" { + return row.UUID, nil + } + } + return "", errors.New("target index uuid is missing") +} + +// requestJSONOnce 关闭传输层对该请求的重放能力(GetBody=nil):恢复标记 create +// 每个许可只能落地至多一次真实请求,不能让 keep-alive 重连把它悄悄发第二遍。 +// Go 的 Transport 只会自动重试"可重放"的请求;Body 非空且 GetBody 为 nil 时, +// PUT/POST 不再满足该条件。 +func (exporter *SearchExporter) requestJSONOnce(ctx context.Context, method, path string, payload any, result any) error { + return exporter.requestJSONWithReplay(ctx, method, path, payload, result, false) +} + +func (exporter *SearchExporter) requestJSONWithReplay(ctx context.Context, method, path string, payload any, result any, replayable bool) error { var body io.Reader if payload != nil { encoded, err := json.Marshal(payload) @@ -298,6 +332,9 @@ func (exporter *SearchExporter) requestJSON(ctx context.Context, method, path st if payload != nil { request.Header.Set("Content-Type", "application/json") } + if !replayable { + request.GetBody = nil + } if exporter.authorizationToken != "" { request.Header.Set("Authorization", "Bearer "+exporter.authorizationToken) } @@ -363,9 +400,14 @@ func searchDocumentsDigest(documents []SearchDocument) (string, error) { func canonicalJSON(raw json.RawMessage) (json.RawMessage, error) { var value any - if err := json.Unmarshal(raw, &value); err != nil { + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + if err := decoder.Decode(&value); err != nil { return nil, err } + if !json.Valid(raw) { + return nil, errors.New("invalid JSON") + } return json.Marshal(value) } diff --git a/internal/releaseadapter/v071/search_write.go b/internal/releaseadapter/v071/search_write.go index 430e7dc..13bd404 100644 --- a/internal/releaseadapter/v071/search_write.go +++ b/internal/releaseadapter/v071/search_write.go @@ -101,7 +101,7 @@ func (exporter *SearchExporter) PruneScope(ctx context.Context, identity SearchI end = len(stale) } payload := map[string]any{ - "query": map[string]any{"ids": map[string]any{"values": stale[start:end]}}, + "query": map[string]any{"bool": map[string]any{"filter": append(scopeFilterFor(inspection.fields, identity), map[string]any{"ids": map[string]any{"values": stale[start:end]}})}}, } var response struct { Deleted int `json:"deleted"` @@ -126,6 +126,10 @@ func scopeFilterFor(fields searchFieldNames, identity SearchIdentity) []any { // BulkIndex 把归档里的原始文档与向量直接写入生产索引(不解析、不重新 Embedding)。 // 写入前补齐 tenant_id/knowledge_base_id,避免归档文档缺字段时落到别的库。 func (exporter *SearchExporter) BulkIndex(ctx context.Context, documents []librarysnapshot.IndexDocument, identity SearchIdentity) error { + return exporter.bulkIndex(ctx, documents, identity, nil) +} + +func (exporter *SearchExporter) bulkIndex(ctx context.Context, documents []librarysnapshot.IndexDocument, identity SearchIdentity, guards map[string]indexWriteGuard) error { if len(documents) == 0 { return nil } @@ -139,16 +143,31 @@ func (exporter *SearchExporter) BulkIndex(ctx context.Context, documents []libra if err := json.Unmarshal(document.Source, &source); err != nil { return errors.New("archived index document is not an object") } - source["tenant_id"], _ = json.Marshal(identity.TenantID) + // 0.9.0 的索引文档没有 tenant_id:补上去会让恢复后的文档与目标契约不一致。 + if !identity.NoTenantField { + source["tenant_id"], _ = json.Marshal(identity.TenantID) + } source["knowledge_base_id"], _ = json.Marshal(identity.KnowledgeBaseID) encoded, err := json.Marshal(source) if err != nil { return err } payload = encoded - action, err := json.Marshal(map[string]any{"index": map[string]string{ - "_index": exporter.index, "_id": document.ID, - }}) + operation := "index" + metadata := map[string]any{"_index": exporter.index, "_id": document.ID} + if guards != nil { + guard, ok := guards[document.ID] + if !ok { + return errors.New("missing index write guard") + } + if !guard.Found { + operation = "create" + } else { + metadata["if_seq_no"] = *guard.SeqNo + metadata["if_primary_term"] = *guard.PrimaryTerm + } + } + action, err := json.Marshal(map[string]any{operation: metadata}) if err != nil { return err } @@ -189,6 +208,18 @@ func (exporter *SearchExporter) BulkIndex(ctx context.Context, documents []libra if err := json.Unmarshal(raw, &parsed); err != nil { return errors.New("Elasticsearch bulk response invalid") } + if len(parsed.Items) == len(documents) { + for i, item := range parsed.Items { + if len(item) != 1 { + return errors.New("invalid bulk item result") + } + for operation, result := range item { + if (operation != "index" && operation != "create") || result.ID != documents[i].ID || result.Status < 200 || result.Status >= 300 || result.Error != nil { + return fmt.Errorf("Elasticsearch item outcome not confirmed: %s status %d", documents[i].ID, result.Status) + } + } + } + } if parsed.Errors { for _, item := range parsed.Items { for _, result := range item { diff --git a/internal/releaseadapter/v071/target_id_expect_test.go b/internal/releaseadapter/v071/target_id_expect_test.go new file mode 100644 index 0000000..958cb96 --- /dev/null +++ b/internal/releaseadapter/v071/target_id_expect_test.go @@ -0,0 +1,131 @@ +package v071 + +import ( + "crypto/sha256" + "fmt" + "strings" + "testing" +) + +// 测试侧独立实现的目标 ID 推导:公式来自产品文档(scoped-sha256-v1), +// 不复用生产 mapper/rowTransform,避免"用实现证明实现"。 +func expectedTargetID(tenant uint64, kb, table, source string) string { + sum := sha256.Sum256([]byte("knowledge-governance/target-identity/v1\x00" + + fmt.Sprintf("%d", tenant) + "\x00" + kb + "\x00" + table + "\x00" + source)) + var raw [16]byte + copy(raw[:], sum[:16]) + raw[6] = raw[6]&0x0f | 0x50 + raw[8] = raw[8]&0x3f | 0x80 + return fmt.Sprintf("%x-%x-%x-%x-%x", raw[0:4], raw[4:6], raw[6:8], raw[8:10], raw[10:16]) +} + +func expectedIndexID(source string) string { + return expectedTargetID(wsTargetTenant, wsTargetKB, "index_chunks", source) +} + +// expectedTargetRow 按已知引用字段语义改写一行期望数据,供独立 oracle 使用。 +func expectedTargetRow(table string, row map[string]any) map[string]any { + out := make(map[string]any, len(row)) + for k, v := range row { + out[k] = v + } + str := func(key string) (string, bool) { s, ok := out[key].(string); return s, ok } + mapped := func(key, targetTable string) { + if s, ok := str(key); ok && s != "" { + out[key] = expectedTargetID(wsTargetTenant, wsTargetKB, targetTable, s) + } + } + switch table { + case "knowledges": + mapped("id", "knowledges") + case "chunks": + mapped("id", "chunks") + mapped("knowledge_id", "knowledges") + mapped("tag_id", "knowledge_tags") + for _, key := range []string{"parent_chunk_id", "pre_chunk_id", "next_chunk_id"} { + mapped(key, "chunks") + } + for _, key := range []string{"relation_chunks", "indirect_relation_chunks"} { + if list, ok := out[key].([]any); ok { + for i, item := range list { + if s, ok := item.(string); ok { + list[i] = expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", s) + } + } + } + } + case "knowledge_tags": + mapped("id", "knowledge_tags") + case "knowledge_tag_relations": + mapped("knowledge_id", "knowledges") + mapped("tag_id", "knowledge_tags") + case "wiki_folders": + mapped("id", "wiki_folders") + mapped("parent_id", "wiki_folders") + case "wiki_pages": + mapped("id", "wiki_pages") + mapped("folder_id", "wiki_folders") + if list, ok := out["chunk_refs"].([]any); ok { + for i, item := range list { + if s, ok := item.(string); ok { + list[i] = expectedTargetID(wsTargetTenant, wsTargetKB, "chunks", s) + } + } + } + if list, ok := out["source_refs"].([]any); ok { + for i, item := range list { + if s, ok := item.(string); ok { + id, suffix := s, "" + if cut := strings.IndexByte(s, '|'); cut >= 0 { + id, suffix = s[:cut], s[cut:] + } + list[i] = expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", id) + suffix + } + } + } + case "wiki_page_issues": + mapped("id", "wiki_page_issues") + mapped("knowledge_id", "knowledges") + mapped("page_id", "wiki_pages") + if list, ok := out["suspected_knowledge_ids"].([]any); ok { + for i, item := range list { + if s, ok := item.(string); ok { + list[i] = expectedTargetID(wsTargetTenant, wsTargetKB, "knowledges", s) + } + } + } + case "wiki_log_entries": + mapped("knowledge_id", "knowledges") + mapped("page_id", "wiki_pages") + case "resource_bindings": + mapped("id", "resource_bindings") + if ownerType, _ := out["owner_type"].(string); ownerType == "knowledge" { + mapped("owner_id", "knowledges") + } else if ownerType == "chunk" { + mapped("owner_id", "chunks") + } + } + return out +} + +// expectedIndexSource 按语义改写索引文档里的引用(正文/向量不动)。 +func expectedIndexSource(t *testing.T, source map[string]any) map[string]any { + t.Helper() + out := make(map[string]any, len(source)) + for k, v := range source { + out[k] = v + } + for key, targetTable := range map[string]string{"chunk_id": "chunks", "knowledge_id": "knowledges", "tag_id": "knowledge_tags"} { + if s, ok := out[key].(string); ok && s != "" { + out[key] = expectedTargetID(wsTargetTenant, wsTargetKB, targetTable, s) + } + } + if s, ok := out["tenant_id"]; ok { + if number, ok := s.(float64); ok && number == float64(wsSourceTenant) { + out["tenant_id"] = float64(wsTargetTenant) + } + } + out["tenant_id"] = float64(wsTargetTenant) + out["knowledge_base_id"] = wsTargetKB + return out +} diff --git a/internal/releaseadapter/v071/testdata/catalog-v071-r11.json b/internal/releaseadapter/v071/testdata/catalog-v071-r11.json new file mode 100644 index 0000000..0ccfcb2 --- /dev/null +++ b/internal/releaseadapter/v071/testdata/catalog-v071-r11.json @@ -0,0 +1,2004 @@ +{ + "columns": [ + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "id", + "default_expr": "uuid_generate_v4()" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "tenant_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "knowledge_base_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "knowledge_id", + "default_expr": "" + }, + { + "type": "text", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "content", + "default_expr": "" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "chunk_index", + "default_expr": "" + }, + { + "type": "boolean", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "is_enabled", + "default_expr": "true" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "start_at", + "default_expr": "" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "end_at", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "pre_chunk_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "next_chunk_id", + "default_expr": "" + }, + { + "type": "character varying(20)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "chunk_type", + "default_expr": "'text'::character varying" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "parent_chunk_id", + "default_expr": "" + }, + { + "type": "text", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "image_info", + "default_expr": "" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "relation_chunks", + "default_expr": "" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "indirect_relation_chunks", + "default_expr": "" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "created_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "updated_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "deleted_at", + "default_expr": "" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "metadata", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "tag_id", + "default_expr": "" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "status", + "default_expr": "0" + }, + { + "type": "character varying(64)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "content_hash", + "default_expr": "" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "flags", + "default_expr": "1" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "chunks", + "column_name": "seq_id", + "default_expr": "nextval('chunks_seq_id_seq'::regclass)" + }, + { + "type": "text", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "chunks", + "column_name": "video_info", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledge_tag_relations", + "column_name": "knowledge_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledge_tag_relations", + "column_name": "tag_id", + "default_expr": "" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledge_tag_relations", + "column_name": "created_at", + "default_expr": "now()" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "id", + "default_expr": "" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "tenant_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "knowledge_base_id", + "default_expr": "" + }, + { + "type": "character varying(128)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "name", + "default_expr": "" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "color", + "default_expr": "" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "sort_order", + "default_expr": "0" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "created_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "updated_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "deleted_at", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledge_tags", + "column_name": "seq_id", + "default_expr": "nextval('knowledge_tags_seq_id_seq'::regclass)" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "id", + "default_expr": "uuid_generate_v4()" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "tenant_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "knowledge_base_id", + "default_expr": "" + }, + { + "type": "character varying(50)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "type", + "default_expr": "" + }, + { + "type": "character varying(255)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "title", + "default_expr": "" + }, + { + "type": "text", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "description", + "default_expr": "" + }, + { + "type": "character varying(2048)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "source", + "default_expr": "" + }, + { + "type": "character varying(50)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "parse_status", + "default_expr": "'unprocessed'::character varying" + }, + { + "type": "character varying(50)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "enable_status", + "default_expr": "'enabled'::character varying" + }, + { + "type": "character varying(64)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "embedding_model_id", + "default_expr": "" + }, + { + "type": "character varying(255)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "file_name", + "default_expr": "" + }, + { + "type": "character varying(50)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "file_type", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "file_size", + "default_expr": "" + }, + { + "type": "text", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "file_path", + "default_expr": "" + }, + { + "type": "character varying(64)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "file_hash", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "storage_size", + "default_expr": "0" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "metadata", + "default_expr": "" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "created_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "updated_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "processed_at", + "default_expr": "" + }, + { + "type": "text", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "error_message", + "default_expr": "" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "deleted_at", + "default_expr": "" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "summary_status", + "default_expr": "'none'::character varying" + }, + { + "type": "json", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "knowledges", + "column_name": "last_faq_import_result", + "default_expr": "" + }, + { + "type": "character varying(50)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "channel", + "default_expr": "'web'::character varying" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "knowledges", + "column_name": "pending_subtasks_count", + "default_expr": "0" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resource_bindings", + "column_name": "id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resource_bindings", + "column_name": "resource_id", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resource_bindings", + "column_name": "tenant_id", + "default_expr": "" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resource_bindings", + "column_name": "owner_type", + "default_expr": "" + }, + { + "type": "character varying(64)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resource_bindings", + "column_name": "owner_id", + "default_expr": "" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resource_bindings", + "column_name": "relation", + "default_expr": "'attachment'::character varying" + }, + { + "type": "timestamp without time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "resource_bindings", + "column_name": "created_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "id", + "default_expr": "" + }, + { + "type": "character varying(22)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "handle", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "tenant_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "resources", + "column_name": "storage_backend_id", + "default_expr": "" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "provider", + "default_expr": "" + }, + { + "type": "text", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "physical_path", + "default_expr": "" + }, + { + "type": "character varying(64)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "location_hash", + "default_expr": "" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "kind", + "default_expr": "'file'::character varying" + }, + { + "type": "character varying(255)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "mime_type", + "default_expr": "''::character varying" + }, + { + "type": "character varying(1024)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "original_name", + "default_expr": "''::character varying" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "size", + "default_expr": "0" + }, + { + "type": "character varying(64)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "content_hash", + "default_expr": "''::character varying" + }, + { + "type": "character varying(16)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "lifecycle", + "default_expr": "'persistent'::character varying" + }, + { + "type": "timestamp without time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "resources", + "column_name": "expires_at", + "default_expr": "" + }, + { + "type": "character varying(16)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "resources", + "column_name": "state", + "default_expr": "'active'::character varying" + }, + { + "type": "timestamp without time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "resources", + "column_name": "created_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp without time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "resources", + "column_name": "updated_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp without time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "resources", + "column_name": "deleted_at", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "id", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "tenant_id", + "default_expr": "0" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "knowledge_base_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "parent_id", + "default_expr": "''::character varying" + }, + { + "type": "character varying(255)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "name", + "default_expr": "" + }, + { + "type": "character varying(1024)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "path", + "default_expr": "''::character varying" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "depth", + "default_expr": "0" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "sort_order", + "default_expr": "0" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "created_at", + "default_expr": "now()" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_folders", + "column_name": "updated_at", + "default_expr": "now()" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_folders", + "column_name": "deleted_at", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "id", + "default_expr": "nextval('wiki_log_entries_id_seq'::regclass)" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "tenant_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "knowledge_base_id", + "default_expr": "" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "action", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "knowledge_id", + "default_expr": "''::character varying" + }, + { + "type": "text", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "doc_title", + "default_expr": "''::text" + }, + { + "type": "text", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "summary", + "default_expr": "''::text" + }, + { + "type": "jsonb", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "pages_affected", + "default_expr": "'[]'::jsonb" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_log_entries", + "column_name": "created_at", + "default_expr": "now()" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "id", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "tenant_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "knowledge_base_id", + "default_expr": "" + }, + { + "type": "character varying(255)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "slug", + "default_expr": "" + }, + { + "type": "character varying(50)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "issue_type", + "default_expr": "" + }, + { + "type": "text", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "description", + "default_expr": "" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "suspected_knowledge_ids", + "default_expr": "" + }, + { + "type": "character varying(20)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "status", + "default_expr": "'pending'::character varying" + }, + { + "type": "character varying(100)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "reported_by", + "default_expr": "" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "created_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "updated_at", + "default_expr": "CURRENT_TIMESTAMP" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_page_issues", + "column_name": "deleted_at", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "id", + "default_expr": "" + }, + { + "type": "bigint", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "tenant_id", + "default_expr": "" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "knowledge_base_id", + "default_expr": "" + }, + { + "type": "character varying(255)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "slug", + "default_expr": "" + }, + { + "type": "character varying(512)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "title", + "default_expr": "''::character varying" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "page_type", + "default_expr": "'summary'::character varying" + }, + { + "type": "character varying(32)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "status", + "default_expr": "'published'::character varying" + }, + { + "type": "text", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "content", + "default_expr": "''::text" + }, + { + "type": "text", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "summary", + "default_expr": "''::text" + }, + { + "type": "character varying(255)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "parent_slug", + "default_expr": "''::character varying" + }, + { + "type": "character varying(36)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "folder_id", + "default_expr": "''::character varying" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_pages", + "column_name": "category_path", + "default_expr": "'[]'::jsonb" + }, + { + "type": "character varying(1024)", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "wiki_path", + "default_expr": "''::character varying" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "depth", + "default_expr": "0" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "sort_order", + "default_expr": "0" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_pages", + "column_name": "source_refs", + "default_expr": "'[]'::jsonb" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_pages", + "column_name": "chunk_refs", + "default_expr": "'[]'::jsonb" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_pages", + "column_name": "in_links", + "default_expr": "'[]'::jsonb" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_pages", + "column_name": "out_links", + "default_expr": "'[]'::jsonb" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_pages", + "column_name": "page_metadata", + "default_expr": "'{}'::jsonb" + }, + { + "type": "jsonb", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_pages", + "column_name": "aliases", + "default_expr": "'[]'::jsonb" + }, + { + "type": "integer", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "version", + "default_expr": "1" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "created_at", + "default_expr": "now()" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": true, + "generated": "", + "table_name": "wiki_pages", + "column_name": "updated_at", + "default_expr": "now()" + }, + { + "type": "timestamp with time zone", + "identity": "", + "not_null": false, + "generated": "", + "table_name": "wiki_pages", + "column_name": "deleted_at", + "default_expr": "" + } + ], + "indexes": [ + { + "name": "chunks_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX chunks_pkey ON public.chunks USING btree (id)", + "table_name": "chunks", + "unique_index": true + }, + { + "name": "idx_chunks_chunk_type", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_chunks_chunk_type ON public.chunks USING btree (chunk_type)", + "table_name": "chunks", + "unique_index": false + }, + { + "name": "idx_chunks_content_hash", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_chunks_content_hash ON public.chunks USING btree (content_hash)", + "table_name": "chunks", + "unique_index": false + }, + { + "name": "idx_chunks_kb_tenant", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_chunks_kb_tenant ON public.chunks USING btree (knowledge_base_id, tenant_id)", + "table_name": "chunks", + "unique_index": false + }, + { + "name": "idx_chunks_knowledge_enabled", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_chunks_knowledge_enabled ON public.chunks USING btree (knowledge_id, is_enabled, deleted_at)", + "table_name": "chunks", + "unique_index": false + }, + { + "name": "idx_chunks_parent_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_chunks_parent_id ON public.chunks USING btree (parent_chunk_id)", + "table_name": "chunks", + "unique_index": false + }, + { + "name": "idx_chunks_seq_id", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX idx_chunks_seq_id ON public.chunks USING btree (seq_id)", + "table_name": "chunks", + "unique_index": true + }, + { + "name": "idx_chunks_tag", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_chunks_tag ON public.chunks USING btree (tag_id)", + "table_name": "chunks", + "unique_index": false + }, + { + "name": "idx_chunks_tenant_kg", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_chunks_tenant_kg ON public.chunks USING btree (tenant_id, knowledge_id)", + "table_name": "chunks", + "unique_index": false + }, + { + "name": "idx_ktr_knowledge", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_ktr_knowledge ON public.knowledge_tag_relations USING btree (knowledge_id)", + "table_name": "knowledge_tag_relations", + "unique_index": false + }, + { + "name": "idx_ktr_tag", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_ktr_tag ON public.knowledge_tag_relations USING btree (tag_id)", + "table_name": "knowledge_tag_relations", + "unique_index": false + }, + { + "name": "knowledge_tag_relations_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX knowledge_tag_relations_pkey ON public.knowledge_tag_relations USING btree (knowledge_id, tag_id)", + "table_name": "knowledge_tag_relations", + "unique_index": true + }, + { + "name": "idx_knowledge_tags_kb", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_knowledge_tags_kb ON public.knowledge_tags USING btree (tenant_id, knowledge_base_id)", + "table_name": "knowledge_tags", + "unique_index": false + }, + { + "name": "idx_knowledge_tags_kb_name", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX idx_knowledge_tags_kb_name ON public.knowledge_tags USING btree (tenant_id, knowledge_base_id, name)", + "table_name": "knowledge_tags", + "unique_index": true + }, + { + "name": "idx_knowledge_tags_seq_id", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX idx_knowledge_tags_seq_id ON public.knowledge_tags USING btree (seq_id)", + "table_name": "knowledge_tags", + "unique_index": true + }, + { + "name": "knowledge_tags_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX knowledge_tags_pkey ON public.knowledge_tags USING btree (id)", + "table_name": "knowledge_tags", + "unique_index": true + }, + { + "name": "idx_knowledges_base_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_knowledges_base_id ON public.knowledges USING btree (knowledge_base_id)", + "table_name": "knowledges", + "unique_index": false + }, + { + "name": "idx_knowledges_enable_status", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_knowledges_enable_status ON public.knowledges USING btree (enable_status)", + "table_name": "knowledges", + "unique_index": false + }, + { + "name": "idx_knowledges_parse_status", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_knowledges_parse_status ON public.knowledges USING btree (parse_status)", + "table_name": "knowledges", + "unique_index": false + }, + { + "name": "idx_knowledges_summary_status", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_knowledges_summary_status ON public.knowledges USING btree (summary_status)", + "table_name": "knowledges", + "unique_index": false + }, + { + "name": "idx_knowledges_tenant_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_knowledges_tenant_id ON public.knowledges USING btree (tenant_id)", + "table_name": "knowledges", + "unique_index": false + }, + { + "name": "knowledges_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX knowledges_pkey ON public.knowledges USING btree (id)", + "table_name": "knowledges", + "unique_index": true + }, + { + "name": "idx_resource_bindings_owner", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_resource_bindings_owner ON public.resource_bindings USING btree (tenant_id, owner_type, owner_id)", + "table_name": "resource_bindings", + "unique_index": false + }, + { + "name": "idx_resource_bindings_unique", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX idx_resource_bindings_unique ON public.resource_bindings USING btree (resource_id, owner_type, owner_id, relation)", + "table_name": "resource_bindings", + "unique_index": true + }, + { + "name": "resource_bindings_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX resource_bindings_pkey ON public.resource_bindings USING btree (id)", + "table_name": "resource_bindings", + "unique_index": true + }, + { + "name": "idx_resources_backend", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_resources_backend ON public.resources USING btree (storage_backend_id)", + "table_name": "resources", + "unique_index": false + }, + { + "name": "idx_resources_tenant", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_resources_tenant ON public.resources USING btree (tenant_id)", + "table_name": "resources", + "unique_index": false + }, + { + "name": "idx_resources_tenant_location", + "valid": true, + "predicate": "(deleted_at IS NULL)", + "definition": "CREATE UNIQUE INDEX idx_resources_tenant_location ON public.resources USING btree (tenant_id, location_hash) WHERE (deleted_at IS NULL)", + "table_name": "resources", + "unique_index": true + }, + { + "name": "resources_handle_key", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX resources_handle_key ON public.resources USING btree (handle)", + "table_name": "resources", + "unique_index": true + }, + { + "name": "resources_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX resources_pkey ON public.resources USING btree (id)", + "table_name": "resources", + "unique_index": true + }, + { + "name": "idx_wiki_folders_deleted_at", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_folders_deleted_at ON public.wiki_folders USING btree (deleted_at)", + "table_name": "wiki_folders", + "unique_index": false + }, + { + "name": "idx_wiki_folders_parent", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_folders_parent ON public.wiki_folders USING btree (knowledge_base_id, parent_id)", + "table_name": "wiki_folders", + "unique_index": false + }, + { + "name": "idx_wiki_folders_parent_name", + "valid": true, + "predicate": "(deleted_at IS NULL)", + "definition": "CREATE UNIQUE INDEX idx_wiki_folders_parent_name ON public.wiki_folders USING btree (knowledge_base_id, parent_id, name) WHERE (deleted_at IS NULL)", + "table_name": "wiki_folders", + "unique_index": true + }, + { + "name": "wiki_folders_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX wiki_folders_pkey ON public.wiki_folders USING btree (id)", + "table_name": "wiki_folders", + "unique_index": true + }, + { + "name": "idx_wiki_log_entries_kb_id_desc", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_log_entries_kb_id_desc ON public.wiki_log_entries USING btree (knowledge_base_id, id DESC)", + "table_name": "wiki_log_entries", + "unique_index": false + }, + { + "name": "idx_wiki_log_entries_tenant_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_log_entries_tenant_id ON public.wiki_log_entries USING btree (tenant_id)", + "table_name": "wiki_log_entries", + "unique_index": false + }, + { + "name": "wiki_log_entries_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX wiki_log_entries_pkey ON public.wiki_log_entries USING btree (id)", + "table_name": "wiki_log_entries", + "unique_index": true + }, + { + "name": "idx_wiki_page_issues_knowledge_base_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_page_issues_knowledge_base_id ON public.wiki_page_issues USING btree (knowledge_base_id)", + "table_name": "wiki_page_issues", + "unique_index": false + }, + { + "name": "idx_wiki_page_issues_slug", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_page_issues_slug ON public.wiki_page_issues USING btree (slug)", + "table_name": "wiki_page_issues", + "unique_index": false + }, + { + "name": "idx_wiki_page_issues_status", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_page_issues_status ON public.wiki_page_issues USING btree (status)", + "table_name": "wiki_page_issues", + "unique_index": false + }, + { + "name": "idx_wiki_page_issues_tenant_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_page_issues_tenant_id ON public.wiki_page_issues USING btree (tenant_id)", + "table_name": "wiki_page_issues", + "unique_index": false + }, + { + "name": "wiki_page_issues_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX wiki_page_issues_pkey ON public.wiki_page_issues USING btree (id)", + "table_name": "wiki_page_issues", + "unique_index": true + }, + { + "name": "idx_wiki_pages_deleted_at", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_deleted_at ON public.wiki_pages USING btree (deleted_at)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_folder", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_folder ON public.wiki_pages USING btree (knowledge_base_id, folder_id)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_folder_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_folder_id ON public.wiki_pages USING btree (folder_id)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_fulltext", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_fulltext ON public.wiki_pages USING gin (to_tsvector('simple'::regconfig, (((COALESCE(title, ''::character varying))::text || ' '::text) || COALESCE(content, ''::text))))", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_kb_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_kb_id ON public.wiki_pages USING btree (knowledge_base_id)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_kb_slug", + "valid": true, + "predicate": "(deleted_at IS NULL)", + "definition": "CREATE UNIQUE INDEX idx_wiki_pages_kb_slug ON public.wiki_pages USING btree (knowledge_base_id, slug) WHERE (deleted_at IS NULL)", + "table_name": "wiki_pages", + "unique_index": true + }, + { + "name": "idx_wiki_pages_page_type", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_page_type ON public.wiki_pages USING btree (knowledge_base_id, page_type)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_parent_slug", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_parent_slug ON public.wiki_pages USING btree (knowledge_base_id, parent_slug)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_source_refs", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_source_refs ON public.wiki_pages USING gin (source_refs jsonb_path_ops)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_source_refs_text", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_source_refs_text ON public.wiki_pages USING gin (to_tsvector('simple'::regconfig, (source_refs)::text))", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_tenant_id", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_tenant_id ON public.wiki_pages USING btree (tenant_id)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_title_trgm", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_title_trgm ON public.wiki_pages USING gin (lower((title)::text) gin_trgm_ops)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "idx_wiki_pages_tree", + "valid": true, + "predicate": "", + "definition": "CREATE INDEX idx_wiki_pages_tree ON public.wiki_pages USING btree (knowledge_base_id, page_type, wiki_path, sort_order, title)", + "table_name": "wiki_pages", + "unique_index": false + }, + { + "name": "wiki_pages_pkey", + "valid": true, + "predicate": "", + "definition": "CREATE UNIQUE INDEX wiki_pages_pkey ON public.wiki_pages USING btree (id)", + "table_name": "wiki_pages", + "unique_index": true + } + ], + "triggers": [], + "relations": [ + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "chunks", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "knowledge_tag_relations", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "knowledge_tags", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "knowledges", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "resource_bindings", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "resources", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "wiki_folders", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "wiki_log_entries", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "wiki_page_issues", + "row_security": false + }, + { + "kind": "r", + "inherits": false, + "partition": false, + "table_name": "wiki_pages", + "row_security": false + } + ], + "sequences": [ + { + "seqmax": 9223372036854775807, + "seqmin": 1, + "seqcache": 1, + "seqcycle": false, + "seqstart": 100000000, + "sequence": "chunks_seq_id_seq", + "table_name": "chunks", + "column_name": "seq_id", + "seqincrement": 1 + }, + { + "seqmax": 9223372036854775807, + "seqmin": 1, + "seqcache": 1, + "seqcycle": false, + "seqstart": 10000000, + "sequence": "knowledge_tags_seq_id_seq", + "table_name": "knowledge_tags", + "column_name": "seq_id", + "seqincrement": 1 + }, + { + "seqmax": 9223372036854775807, + "seqmin": 1, + "seqcache": 1, + "seqcycle": false, + "seqstart": 1, + "sequence": "wiki_log_entries_id_seq", + "table_name": "wiki_log_entries", + "column_name": "id", + "seqincrement": 1 + } + ], + "constraints": [ + { + "name": "chunks_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "chunks", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "knowledge_tag_relations_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (knowledge_id, tag_id)", + "table_name": "knowledge_tag_relations", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "knowledge_tags_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "knowledge_tags", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "knowledges_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "knowledges", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "resource_access_grants_resource_id_fkey", + "type": "f", + "namespace": "public", + "definition": "FOREIGN KEY (resource_id) REFERENCES resources(id) ON DELETE CASCADE", + "table_name": "resource_access_grants", + "referenced_table": "resources", + "referenced_namespace": "public" + }, + { + "name": "resource_bindings_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "resource_bindings", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "resource_bindings_resource_id_fkey", + "type": "f", + "namespace": "public", + "definition": "FOREIGN KEY (resource_id) REFERENCES resources(id) ON DELETE CASCADE", + "table_name": "resource_bindings", + "referenced_table": "resources", + "referenced_namespace": "public" + }, + { + "name": "resources_handle_key", + "type": "u", + "namespace": "public", + "definition": "UNIQUE (handle)", + "table_name": "resources", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "resources_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "resources", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "wiki_folders_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "wiki_folders", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "wiki_log_entries_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "wiki_log_entries", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "wiki_page_issues_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "wiki_page_issues", + "referenced_table": "", + "referenced_namespace": "" + }, + { + "name": "wiki_pages_pkey", + "type": "p", + "namespace": "public", + "definition": "PRIMARY KEY (id)", + "table_name": "wiki_pages", + "referenced_table": "", + "referenced_namespace": "" + } + ] +} \ No newline at end of file diff --git a/internal/releaseadapter/v071/three_lane_integration_test.go b/internal/releaseadapter/v071/three_lane_integration_test.go index f17f608..29857bd 100644 --- a/internal/releaseadapter/v071/three_lane_integration_test.go +++ b/internal/releaseadapter/v071/three_lane_integration_test.go @@ -6,7 +6,7 @@ import ( "encoding/json" "net/http/httptest" "os" - "path/filepath" + "strings" "testing" "time" @@ -17,7 +17,7 @@ import ( releaseworkflow "knowledge-governance/internal/workflows/release" ) -func TestThreeLaneReleaseAndRollbackV071Integration(t *testing.T) { +func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) { sourceDatabaseURL := os.Getenv("TEST_WEKNORA_V071_DATABASE_URL") targetDatabaseURL := os.Getenv("TEST_WEKNORA_V071_TARGET_DATABASE_URL") minioEndpoint := os.Getenv("TEST_MINIO_ENDPOINT") @@ -110,49 +110,29 @@ func TestThreeLaneReleaseAndRollbackV071Integration(t *testing.T) { if _, err := exporter.Export(ctx, first); err != nil { t.Fatalf("export preflight: %v", err) } - firstResult, err := publisher.Publish(ctx, first) - if err != nil { - t.Fatal(err) + // The former document-level write lane is deliberately retired. Keep its + // original source fixture, but prove refusal rather than silently exercising + // a direct PUT/COPY path outside the frozen-plan gateway. + targetSnapshot, e := NewPostgresExporter(targetPool) + if e != nil { + t.Fatal(e) } - if firstResult.PreviousProductionRevision != "absent" || firstResult.ProductionRevision != "review-release-1" { - t.Fatalf("first=%#v", firstResult) + identity := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-release-safe", KnowledgeID: "knowledge-release-safe"} + before, e := targetSnapshot.Export(ctx, identity) + if e != nil { + t.Fatal(e) } - second := first - second.ReleaseExecutionID = "rx-release-2" - second.PublicationID = "tp-release-2" - second.SourceRevision = "source-v2" - second.ReleaseRevision = "review-release-2" - second.PreviousProductionRevision = firstResult.ProductionRevision - secondResult, err := publisher.Publish(ctx, second) - if err != nil { - t.Fatal(err) + if _, e = publisher.Publish(ctx, first); e == nil || !strings.Contains(e.Error(), "stage v0.7.1 release assets") { + t.Fatal("legacy lane was not rejected at object gate", e) } - if secondResult.PreviousProductionRevision != "review-release-1" || secondResult.ProductionRevision != "review-release-2" { - t.Fatalf("second=%#v", secondResult) + after, e := targetSnapshot.Export(ctx, identity) + if e != nil { + t.Fatal(e) } - rollback, err := publisher.Rollback(ctx, second) - if err != nil { - t.Fatal(err) - } - if rollback.ProductionRevision != "review-release-1" { - t.Fatalf("rollback=%#v", rollback) + beforeBytes, _ := json.Marshal(before) + afterBytes, _ := json.Marshal(after) + if !bytes.Equal(beforeBytes, afterBytes) || targetSearchState.has("es-release") { + t.Fatal("retired lane changed PG or search") } - targetSnapshot, err := NewPostgresExporter(targetPool) - if err != nil { - t.Fatal(err) - } - actual, err := targetSnapshot.Export(ctx, PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-release-safe", KnowledgeID: "knowledge-release-safe"}) - if err != nil { - t.Fatal(err) - } - if actual.Table("chunks").RowCount != 1 || !targetSearchState.has("es-release") { - t.Fatalf("target rows=%d search=%v", actual.Table("chunks").RowCount, targetSearchState.has("es-release")) - } - for _, key := range []string{"10000/knowledge-release-safe/synthetic.txt", "10000/knowledge-release-safe/image.png"} { - size, _, err := targetObjects.Stat(ctx, "minio", key) - if err != nil || size == 0 { - t.Fatalf("asset=%s size=%d err=%v", filepath.Base(key), size, err) - } - } } diff --git a/internal/releaseadapter/v071/v090_fixture_test.go b/internal/releaseadapter/v071/v090_fixture_test.go new file mode 100644 index 0000000..0b609f2 --- /dev/null +++ b/internal/releaseadapter/v071/v090_fixture_test.go @@ -0,0 +1,183 @@ +package v071 + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "os" + "strconv" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// 0.9.0 fixture:真实 pg_dump(schema_migrations=134,83 表,无 wiki_log_entries)。 +// 只用于显式指定的隔离库;governance 与周报邮件库一律不许指到这里。 +const v090SchemaEnv = "KG_V090_SCHEMA_SQL" + +func v090SchemaSQL(t *testing.T) string { + t.Helper() + path := os.Getenv(v090SchemaEnv) + if path == "" { + t.Skip("requires " + v090SchemaEnv + " pointing at the captured WeKnora 0.9.0 schema dump") + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", v090SchemaEnv, err) + } + lines := strings.Split(string(raw), "\n") + kept := make([]string, 0, len(lines)) + for _, line := range lines { + // psql 元命令(\restrict/\unrestrict)只对 psql 有意义,驱动执行要剔除。 + if strings.HasPrefix(line, "\\") { + continue + } + kept = append(kept, line) + } + // 装载会话本身也要把 search_path 还给 public,否则后续查询会找不到表。 + return strings.Join(kept, "\n") + "\nSET search_path TO public, pg_catalog;\n" +} + +// v090Pool 打开一个显式隔离库并重建 public schema,然后装 0.9.0 真实 schema。 +func v090Pool(t *testing.T, env string) *pgxpool.Pool { + t.Helper() + dsn := os.Getenv(env) + if dsn == "" { + t.Skip("requires " + env) + } + cfg, err := pgxpool.ParseConfig(dsn) + if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" { + t.Fatalf("%s must name an explicitly isolated kg_library_test_ database", env) + } + // dump 里有 set_config('search_path',''),新连接必须显式给回 public。 + cfg.ConnConfig.RuntimeParams["search_path"] = "public, pg_catalog" + ctx := context.Background() + db, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(db.Close) + if _, err = db.Exec(ctx, `DROP SCHEMA public CASCADE; CREATE SCHEMA public`); err != nil { + t.Fatalf("reset schema: %v", err) + } + if _, err = db.Exec(ctx, v090SchemaSQL(t)); err != nil { + t.Fatalf("install 0.9.0 schema: %v", err) + } + // 该 dump 会把会话 search_path 置空,这里一律写全限定名。 + if _, err = db.Exec(ctx, `INSERT INTO public.schema_migrations(version,dirty) VALUES (134,false)`); err != nil { + t.Fatalf("stamp schema_migrations: %v", err) + } + return db +} + +const v090Tenant = 10000 +const v090KB = "kb-v090" +const v090Knowledge = "kn-v090-doc" +const v090ChunkOne = "ck-v090-1" +const v090ChunkTwo = "ck-v090-2" +const v090Folder = "wf-v090-1" +const v090Page = "wp-v090-1" +const v090Tag = "tg-v090-1" +const v090Resource = "rs-v090-1" + +// seedV090 造 1 KB / 1 文档 / 2 分块 / 1 wiki 页 / 1 wiki 目录 / 1 资源。 +// Wiki 必须非空:空表通过等于没有验证 wiki 部件。 +func seedV090(t *testing.T, ctx context.Context, db *pgxpool.Pool) PostgresIdentity { + t.Helper() + statements := []string{ + `INSERT INTO models(id,tenant_id,name,type,source,parameters) VALUES ('bge-m3-v090',$1,'bge-m3','embedding','local','{"embedding_parameters":{"dimension":1024}}'::jsonb)`, + `INSERT INTO knowledge_bases(id,name,tenant_id,embedding_model_id,summary_model_id,indexing_strategy) VALUES ('` + v090KB + `','v090 fixture',$1,'bge-m3-v090','bge-m3-v090','{"graph_enabled":false}'::jsonb)`, + `INSERT INTO knowledges(id,tenant_id,knowledge_base_id,type,title,source,parse_status,pending_subtasks_count) VALUES ('` + v090Knowledge + `',$1,'` + v090KB + `','file','0.9.0 夹具','fixture://kn-v090','completed',0)`, + `INSERT INTO chunks(id,tenant_id,knowledge_base_id,knowledge_id,content,chunk_index,start_at,end_at) VALUES + ('` + v090ChunkOne + `',$1,'` + v090KB + `','` + v090Knowledge + `','第一段正文',0,0,5), + ('` + v090ChunkTwo + `',$1,'` + v090KB + `','` + v090Knowledge + `','第二段正文',1,5,10)`, + `INSERT INTO wiki_folders(id,tenant_id,knowledge_base_id,name,path) VALUES ('` + v090Folder + `',$1,'` + v090KB + `','夹具目录','/fixture')`, + `INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,title,content,source_refs,chunk_refs,folder_id) VALUES ('` + v090Page + `',$1,'` + v090KB + `','fixture-page','夹具页','wiki 正文','["` + v090Knowledge + `"]'::jsonb,'["` + v090ChunkOne + `"]'::jsonb,'` + v090Folder + `')`, + `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES ('` + v090Tag + `',$1,'` + v090KB + `','夹具标签')`, + `INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES ('` + v090Knowledge + `','` + v090Tag + `')`, + } + for _, statement := range statements { + if _, err := db.Exec(ctx, strings.ReplaceAll(statement, "$1", strconv.Itoa(v090Tenant))); err != nil { + t.Fatalf("seed: %v\n%s", err, statement) + } + } + // 资源行必须带真实的 physical_path/size/content_hash:封存会逐字节核对。 + content := []byte("fixture-object-bytes") + sum := sha256.Sum256(content) + if _, err := db.Exec(ctx, `INSERT INTO resources(id,handle,tenant_id,provider,physical_path,location_hash,size,content_hash) + VALUES ($1,$2,$3,'minio','fixture/kn-v090.bin',$4,$5,$6)`, + v090Resource, "abcdefghijklmnopqrstuv", v090Tenant, "fixture-location-hash", int64(len(content)), hex.EncodeToString(sum[:])); err != nil { + t.Fatalf("seed resource: %v", err) + } + if _, err := db.Exec(ctx, `INSERT INTO resource_bindings(id,resource_id,tenant_id,owner_type,owner_id) + VALUES ('rb-v090-1',$1,$2,'knowledge',$3)`, v090Resource, v090Tenant, v090Knowledge); err != nil { + t.Fatalf("seed binding: %v", err) + } + return PostgresIdentity{TenantID: v090Tenant, KnowledgeBaseID: v090KB} +} + +// seedV090Binding 只在目标库造 KB/模型绑定:导入的是文档行,不是 KB 定义。 +func seedV090Binding(t *testing.T, ctx context.Context, db *pgxpool.Pool) error { + t.Helper() + for _, statement := range []string{ + `INSERT INTO models(id,tenant_id,name,type,source,parameters) VALUES ('bge-m3-v090',$1,'bge-m3','embedding','local','{"embedding_parameters":{"dimension":1024}}'::jsonb)`, + `INSERT INTO knowledge_bases(id,name,tenant_id,embedding_model_id,summary_model_id,indexing_strategy) VALUES ('` + v090KB + `','v090 fixture target',$1,'bge-m3-v090','bge-m3-v090','{"graph_enabled":false}'::jsonb)`, + } { + if _, err := db.Exec(ctx, strings.ReplaceAll(statement, "$1", strconv.Itoa(v090Tenant))); err != nil { + return err + } + } + return nil +} + +// v090Objects 只在测试里替代对象存储:字节来自夹具常量,不连任何 S3/OSS。 +type v090Objects map[string][]byte + +func (o v090Objects) Open(_ context.Context, provider, physicalPath string) (io.ReadCloser, error) { + if provider != "minio" { + return nil, errors.New("unsupported provider in fixture") + } + content, ok := o[physicalPath] + if !ok { + return nil, errors.New("fixture object missing") + } + return io.NopCloser(bytes.NewReader(content)), nil +} + +// v090IndexSnapshot 按导出分块合成索引快照:本切片不做真实 ES 采集, +// 但文档/映射摘要走的是与线上同一套校验,不能凭空绕过。 +func v090IndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA string) SearchSnapshot { + t.Helper() + var documents []SearchDocument + for _, raw := range pg.Table("chunks").Rows { + var chunk struct { + ID string `json:"id"` + TenantID uint64 `json:"tenant_id"` + KnowledgeBaseID string `json:"knowledge_base_id"` + KnowledgeID string `json:"knowledge_id"` + Content string `json:"content"` + } + if err := json.Unmarshal(raw, &chunk); err != nil { + t.Fatalf("decode chunk: %v", err) + } + source, err := json.Marshal(map[string]any{ + "chunk_id": chunk.ID, "tenant_id": chunk.TenantID, + "knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID, + "content": chunk.Content, "source_id": chunk.ID, "source_type": 0, + }) + if err != nil { + t.Fatalf("encode index document: %v", err) + } + documents = append(documents, SearchDocument{ID: "doc-" + chunk.ID, Source: source}) + } + digest, err := searchDocumentsDigest(documents) + if err != nil { + t.Fatalf("index digest: %v", err) + } + return SearchSnapshot{Documents: documents, MappingSHA256: mappingSHA, DocumentsSHA256: digest} +} diff --git a/internal/releasebundle/manifest.go b/internal/releasebundle/manifest.go index 5ceb474..092b19c 100644 --- a/internal/releasebundle/manifest.go +++ b/internal/releasebundle/manifest.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "fmt" "sort" "strings" "time" @@ -152,8 +153,16 @@ func Validate(manifest Manifest, target TargetContract, mapping KnowledgeBaseMap } func validateManifestFields(manifest Manifest) error { - if manifest.FormatVersion != FormatVersionV1 || manifest.Contract.WeKnoraVersion != WeKnoraVersionV071 || - manifest.Contract.MigrationVersion != WeKnoraMigrationV071 || manifest.Contract.EmbeddingDimension != EmbeddingDimensionV071 || + // 单文档发布包只认 0.7.1 的表集合与契约。别的版本必须**明确拒绝并说明原因**, + // 不能落进下面那句泛化的 "unsupported release contract"——那让人分不清是版本 + // 不支持还是字段写错了。0.9.0 的整库内容走整库发布路径(libraryprofile v090)。 + if manifest.Contract.MigrationVersion != WeKnoraMigrationV071 || + manifest.Contract.WeKnoraVersion != WeKnoraVersionV071 { + return fmt.Errorf("release bundle schema contract %s/%d is not supported: single-document release handles only v0.7.1 (74); WeKnora 0.9.0 (134) requires the library-level publish path", + manifest.Contract.WeKnoraVersion, manifest.Contract.MigrationVersion) + } + if manifest.FormatVersion != FormatVersionV1 || + manifest.Contract.EmbeddingDimension != EmbeddingDimensionV071 || manifest.Contract.RetrieverEngine != "elasticsearch_v8" || manifest.Contract.TenantID == 0 || manifest.CreatedAt.IsZero() { return errors.New("unsupported release contract") } diff --git a/internal/releasebundle/manifest_test.go b/internal/releasebundle/manifest_test.go index 892b765..b0ed8b1 100644 --- a/internal/releasebundle/manifest_test.go +++ b/internal/releasebundle/manifest_test.go @@ -165,3 +165,27 @@ func TestValidateRejectsUndeclaredOrDriftedMapping(t *testing.T) { }) } } + +// 单文档发布包只支持 0.7.1 契约。0.9.0(134)的包必须被**明确拒绝并说明原因**: +// 静默按 74 处理会让 0.9.0 的表集合/索引文档走错写入路径,而泛化错误又让人分不清 +// "版本不支持"和"字段写错"。 +func TestSealRejectsNonV071SchemaContractExplicitly(t *testing.T) { + manifest := validManifest() + manifest.Contract.WeKnoraVersion = "v0.9.0" + manifest.Contract.MigrationVersion = 134 + _, err := Seal(manifest) + if err == nil { + t.Fatal("0.9.0 release bundle must be refused") + } + for _, want := range []string{"v0.9.0", "134", "74", "library-level publish"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("rejection message must name %q, got %v", want, err) + } + } + // 只改版本号、不改 WeKnora 版本同样必须拒绝:两者必须成对出现。 + manifest = validManifest() + manifest.Contract.MigrationVersion = 134 + if _, err := Seal(manifest); err == nil { + t.Fatal("schema version 134 with a v0.7.1 label must be refused") + } +} diff --git a/internal/testbarrier/barrier.go b/internal/testbarrier/barrier.go new file mode 100644 index 0000000..c98fb60 --- /dev/null +++ b/internal/testbarrier/barrier.go @@ -0,0 +1,163 @@ +// Package testbarrier 是"本机真实 worker 中断演练"的固定同步屏障。 +// +// 为什么需要它:真杀 worker 只有在"写了一半"的那一刻才有意义,靠 sleep 猜时间会 +// 错过阶段(旧脚本就是这样永远 exit 0 的)。屏障把"进程确实停在某个固定点"变成一个 +// 文件事实:worker 到达点位后写 /.hit,然后等演练方写 /.go +// 才继续。演练方看到 .hit 再 SIGKILL,命中是确定的,不是碰运气。 +// +// 安全边界(**默认关闭**): +// - 只有 KG_TEST_BARRIER_DIR 与 KG_TEST_BARRIER_POINTS 两个环境变量同时给出才生效; +// 生产/测试栈的常规 env 里没有它们,所以行为与不接线完全一致。 +// - 只在本机测试栈用:目录由 compose overlay 指向本机归档根下的 barrier/ 子目录。 +// - 有硬超时(默认 120s):没人来放行就自己继续,绝不把 worker 永久挂住。 +// - 同一 (point) 在一次演练里只停一次:进程被杀后重启的 worker 看到上一次的 .hit +// 就直接通过,接管不会被第二次拦住。 +// - 不改 WeKnora,也不碰发布代码的语义:它只是在既有阶段之间加一个可关闭的等待。 +package testbarrier + +import ( + "context" + "encoding/json" + "fmt" + "log" + "os" + "path/filepath" + "strings" + "time" +) + +const ( + // EnvDir 是屏障目录(本机受限注入;为空 = 关闭)。 + EnvDir = "KG_TEST_BARRIER_DIR" + // EnvPoints 是允许停留的点位,逗号分隔,例如 "after:database"(为空 = 关闭)。 + EnvPoints = "KG_TEST_BARRIER_POINTS" + // EnvTimeout 是单次等待上限(Go duration,默认 120s)。 + EnvTimeout = "KG_TEST_BARRIER_TIMEOUT" +) + +// hit 是"worker 已到达该点位"的现场记录。 +type hit struct { + Point string `json:"point"` + Subject string `json:"subject"` + PID int `json:"pid"` + At string `json:"at"` +} + +// Settings 是从环境变量解析出来的屏障配置。 +type Settings struct { + Dir string + Points map[string]bool + Timeout time.Duration +} + +// FromEnv 解析配置;两个必需变量缺一个就返回 enabled=false(默认关闭)。 +func FromEnv() (Settings, bool) { + dir := strings.TrimSpace(os.Getenv(EnvDir)) + raw := strings.TrimSpace(os.Getenv(EnvPoints)) + if dir == "" || raw == "" { + return Settings{}, false + } + points := map[string]bool{} + for _, item := range strings.Split(raw, ",") { + if name := strings.TrimSpace(item); name != "" { + points[name] = true + } + } + if len(points) == 0 { + return Settings{}, false + } + timeout := 120 * time.Second + if value := strings.TrimSpace(os.Getenv(EnvTimeout)); value != "" { + if parsed, err := time.ParseDuration(value); err == nil && parsed > 0 { + timeout = parsed + } + } + return Settings{Dir: dir, Points: points, Timeout: timeout}, true +} + +// Enabled 报告屏障是否已在本进程启用(演练方用它确认注入生效)。 +func Enabled() bool { + _, enabled := FromEnv() + return enabled +} + +// Wait 在指定点位停留:写 .hit、等 .go(或超时)。未启用的点位/进程直接返回。 +// +// 返回错误只表示"屏障自身写不下现场"(目录不可写等),调用方据此照常继续—— +// 屏障是演练设施,坏掉不许让生产写入失败。 +func Wait(ctx context.Context, point, subject string) error { + settings, enabled := FromEnv() + if !enabled || !settings.Points[point] { + return nil + } + if err := os.MkdirAll(settings.Dir, 0700); err != nil { + return fmt.Errorf("test barrier dir unusable: %w", err) + } + base := filepath.Join(settings.Dir, safeName(point)) + hitPath := base + ".hit" + if _, err := os.Stat(hitPath); err == nil { + // 上一次演练已经在这个点位停过(进程被杀后重启):直接通过,别把接管再拦住。 + log.Printf("test barrier point=%s subject=%s: previous hit exists, continuing", point, subject) + return nil + } + record, err := json.Marshal(hit{Point: point, Subject: subject, PID: os.Getpid(), At: time.Now().UTC().Format(time.RFC3339Nano)}) + if err != nil { + return err + } + if err := writeAtomic(hitPath, record); err != nil { + return err + } + log.Printf("test barrier point=%s subject=%s pid=%d: waiting for release", point, subject, os.Getpid()) + + deadline := time.Now().Add(settings.Timeout) + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + for { + if _, err := os.Stat(base + ".go"); err == nil { + // 一次性放行:删掉放行标记,避免下一次演练被同一份标记直接放走。 + _ = os.Remove(base + ".go") + log.Printf("test barrier point=%s subject=%s: released", point, subject) + return nil + } + if time.Now().After(deadline) { + _ = writeAtomic(base+".timeout", []byte(time.Now().UTC().Format(time.RFC3339Nano))) + log.Printf("test barrier point=%s subject=%s: timeout after %s, continuing (演练会看到 .timeout)", point, subject, settings.Timeout) + return nil + } + select { + case <-ctx.Done(): + log.Printf("test barrier point=%s subject=%s: context done, continuing", point, subject) + return nil + case <-ticker.C: + } + } +} + +// safeName 让点位名可以安全地当文件名("after:database" → "after-database")。 +func safeName(point string) string { + replacer := strings.NewReplacer(":", "-", "/", "-", " ", "-") + return replacer.Replace(point) +} + +func writeAtomic(path string, payload []byte) error { + temporary := path + ".tmp" + file, err := os.OpenFile(temporary, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600) + if err != nil { + return err + } + if _, err := file.Write(payload); err != nil { + file.Close() + _ = os.Remove(temporary) + return err + } + if err := file.Sync(); err != nil { + file.Close() + _ = os.Remove(temporary) + return err + } + if err := file.Close(); err != nil { + _ = os.Remove(temporary) + return err + } + return os.Rename(temporary, path) +} diff --git a/internal/testbarrier/barrier_test.go b/internal/testbarrier/barrier_test.go new file mode 100644 index 0000000..be59b4b --- /dev/null +++ b/internal/testbarrier/barrier_test.go @@ -0,0 +1,136 @@ +package testbarrier + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" +) + +// 屏障自己必须是"确定命中"的设施:它要能在真实进程里把写入停住,再由演练方放行, +// 而不是靠 sleep 猜。这里用真实文件握手验证整条路径。 + +func TestWaitIsNoopByDefault(t *testing.T) { + dir := t.TempDir() + t.Setenv(EnvDir, "") + t.Setenv(EnvPoints, "") + if Enabled() { + t.Fatal("屏障默认必须关闭") + } + start := time.Now() + if err := Wait(context.Background(), "after:database", "job-x"); err != nil { + t.Fatalf("disabled barrier must not error: %v", err) + } + if time.Since(start) > time.Second { + t.Fatal("disabled barrier must return immediately") + } + if entries, _ := os.ReadDir(dir); len(entries) != 0 { + t.Fatalf("disabled barrier must not write anything: %v", entries) + } +} + +func TestWaitStopsUntilReleasedThenLetsTakeoverThrough(t *testing.T) { + dir := t.TempDir() + t.Setenv(EnvDir, dir) + t.Setenv(EnvPoints, "after:database,after:resources") + t.Setenv(EnvTimeout, "5s") + if !Enabled() { + t.Fatal("two env variables must enable the barrier") + } + + done := make(chan error, 1) + go func() { done <- Wait(context.Background(), "after:database", "libsync-internal-1") }() + + hitPath := filepath.Join(dir, "after-database.hit") + record := waitForFile(t, hitPath, 2*time.Second) + var parsed hit + if err := json.Unmarshal(record, &parsed); err != nil { + t.Fatalf("hit file must be JSON: %v", err) + } + if parsed.Subject != "libsync-internal-1" || parsed.PID != os.Getpid() || parsed.Point != "after:database" { + t.Fatalf("hit file does not describe this worker: %+v", parsed) + } + select { + case err := <-done: + t.Fatalf("barrier must still be waiting before release (err=%v)", err) + case <-time.After(150 * time.Millisecond): + } + + // 演练方放行(正常演练里是 SIGNAL:这里验证放行路径本身)。 + if err := os.WriteFile(filepath.Join(dir, "after-database.go"), []byte("go"), 0600); err != nil { + t.Fatal(err) + } + if err := <-done; err != nil { + t.Fatalf("released barrier must return nil: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "after-database.go")); !os.IsNotExist(err) { + t.Fatal("放行标记必须被消费掉,否则下一次演练会被它直接放走") + } + + // 进程被杀后重启:同一个点位已经有 .hit,必须立刻通过,不许再拦住接管。 + start := time.Now() + if err := Wait(context.Background(), "after:database", "libsync-internal-1"); err != nil { + t.Fatal(err) + } + if time.Since(start) > time.Second { + t.Fatal("takeover must not be blocked by an existing hit") + } + // 没配置的点位不停。 + if err := Wait(context.Background(), "after:wiki", "libsync-internal-1"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "after-wiki.hit")); !os.IsNotExist(err) { + t.Fatal("未配置的点位不许停留") + } +} + +func TestWaitTimesOutInsteadOfHangingWorker(t *testing.T) { + dir := t.TempDir() + t.Setenv(EnvDir, dir) + t.Setenv(EnvPoints, "after:database") + t.Setenv(EnvTimeout, "150ms") + start := time.Now() + if err := Wait(context.Background(), "after:database", "job-timeout"); err != nil { + t.Fatalf("timeout must be a no-error continue: %v", err) + } + if elapsed := time.Since(start); elapsed < 150*time.Millisecond || elapsed > 3*time.Second { + t.Fatalf("超时后必须自己继续,实际等待 %s", elapsed) + } + if _, err := os.Stat(filepath.Join(dir, "after-database.timeout")); err != nil { + t.Fatalf("超时必须留下 .timeout 证据(演练方据此判 missed): %v", err) + } +} + +func TestWaitReportsUnusableDirWithoutBlocking(t *testing.T) { + // 屏障目录建不出来(父路径是普通文件):必须报错但不阻塞——屏障是演练设施, + // 坏掉不许让生产写入卡住。 + parent := filepath.Join(t.TempDir(), "not-a-dir") + if err := os.WriteFile(parent, []byte("x"), 0600); err != nil { + t.Fatal(err) + } + t.Setenv(EnvDir, filepath.Join(parent, "barrier")) + t.Setenv(EnvPoints, "after:database") + t.Setenv(EnvTimeout, "5s") + start := time.Now() + if err := Wait(context.Background(), "after:database", "job"); err == nil { + t.Fatal("目录不可建时必须报错(演练方据此判无效注入)") + } + if time.Since(start) > time.Second { + t.Fatal("目录不可建时不许阻塞") + } +} + +func waitForFile(t *testing.T, path string, limit time.Duration) []byte { + t.Helper() + deadline := time.Now().Add(limit) + for time.Now().Before(deadline) { + if raw, err := os.ReadFile(path); err == nil && len(raw) > 0 { + return raw + } + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("等待屏障现场文件超时:%s", path) + return nil +} diff --git a/internal/versionhistory/development_notes_history_test.go b/internal/versionhistory/development_notes_history_test.go new file mode 100644 index 0000000..7445006 --- /dev/null +++ b/internal/versionhistory/development_notes_history_test.go @@ -0,0 +1,111 @@ +package versionhistory + +import ( + "encoding/json" + "os" + "strings" + "testing" + + "knowledge-governance/internal/governance" +) + +func TestAllHistoricalDevelopmentNotesBindExactCommit(t *testing.T) { + changelogBytes, err := os.ReadFile("../../CHANGELOG.md") + if err != nil { + t.Fatal(err) + } + changelog := string(changelogBytes) + fixtureBytes, err := os.ReadFile("testdata/development_notes_history.json") + if err != nil { + t.Fatal(err) + } + var entries []struct { + Version string `json:"version"` + SHA string `json:"sha"` + } + if err := json.Unmarshal(fixtureBytes, &entries); err != nil { + t.Fatal(err) + } + if len(entries) != 270 { + t.Fatalf("history fixture must contain 270 missing development versions, got %d", len(entries)) + } + seen := map[string]string{} + wrong := strings.Repeat("f", 40) + for _, entry := range entries { + if prev, ok := seen[entry.Version]; ok && prev != entry.SHA { + t.Fatalf("version %s bound to multiple commits", entry.Version) + } + seen[entry.Version] = entry.SHA + notes := governance.ExtractDevelopmentNotesForCommit(changelog, entry.Version, entry.SHA) + if strings.TrimSpace(notes) == "" { + t.Fatalf("version %s sha %s has no exact-SHA notes", entry.Version, entry.SHA) + } + if strings.Contains(notes, "目标提交:"+entry.SHA) == false { + t.Fatalf("version %s body does not carry its exact target line", entry.Version) + } + if leaked := governance.ExtractDevelopmentNotesForCommit(changelog, entry.Version, wrong); leaked != "" { + t.Fatalf("version %s notes leaked to wrong SHA: %q", entry.Version, leaked) + } + } + // 相邻/前缀版本不能互相命中。 + if notes := governance.ExtractDevelopmentNotesForCommit(changelog, "0.1.35", entries[0].SHA); notes != "" { + t.Fatalf("0.1.35 leaked notes for another commit: %q", notes) + } +} + +func TestMergeNotesUseFirstParentFactsAndRenameStats(t *testing.T) { + body, err := os.ReadFile("../../CHANGELOG.md") + if err != nil { + t.Fatal(err) + } + changelog := string(body) + for _, tc := range []struct { + version string + sha string + wants []string + minLen int + }{ + {"0.1.207", "034c0b3a1c0b9fc5884750cc0d9929c0df4ac314", []string{"第一父", "108 个文件", "+10643/-548", "cmd/worker/library_baseline.go"}, 500}, + {"0.1.35", "330fd12b3f30376c3aee757ba2a9f4ba3f8bcf27", []string{"第一父", "121 个文件", "+9065/-376", "qa_mirror.go"}, 400}, + {"0.1.340", "5e1482e349e23728f8f2f1aeb770422eba2e5b5f", []string{"统计:47 个文件,+2485/-336", "canary_test.go"}, 500}, + } { + notes := governance.ExtractDevelopmentNotesForCommit(changelog, tc.version, tc.sha) + if len(notes) < tc.minLen { + t.Fatalf("%s notes too shallow: %d chars", tc.version, len(notes)) + } + for _, want := range tc.wants { + if !strings.Contains(notes, want) { + t.Fatalf("%s notes missing %q: %q", tc.version, want, notes) + } + } + } +} + +func TestSameVersionDifferentSHAsKeepOwnNotes(t *testing.T) { + body, err := os.ReadFile("../../CHANGELOG.md") + if err != nil { + t.Fatal(err) + } + changelog := string(body) + f337 := "f33730ed7437536c3d1e01cc2f20231af076b531" + notes := governance.ExtractDevelopmentNotesForCommit(changelog, "0.1.28", f337) + for _, want := range []string{"开发版本历史", "第一父", "development_notes.go"} { + if !strings.Contains(notes, want) { + t.Fatalf("f337 notes missing real version-history scope %q: %q", want, notes) + } + } + for _, forbidden := range []string{"持久本地副本", "每 5 分钟", "安全 Markdown"} { + if strings.Contains(notes, forbidden) { + t.Fatalf("f337 notes still carry the other 0.1.28 commit's body %q: %q", forbidden, notes) + } + } + // Same version number, two target SHAs: exact-SHA selection must not cross. + dual := "## 开发快照 snapshot/v0.1.28 - 2026-10-18\n目标提交:" + f337 + "\n\n### Changed\n\n- 版本历史修复\n\n" + + "## 开发快照 snapshot/v0.1.28 - 2026-10-18\n目标提交:3e7fcce0b1b077dd6c44f2a4d535813232b941fb\n\n### Added\n\n- 持久本地问答副本\n" + if got := governance.ExtractDevelopmentNotesForCommit(dual, "0.1.28", f337); !strings.Contains(got, "版本历史修复") || strings.Contains(got, "持久本地") { + t.Fatalf("same-version f337 selected wrong block: %q", got) + } + if got := governance.ExtractDevelopmentNotesForCommit(dual, "0.1.28", "3e7fcce0b1b077dd6c44f2a4d535813232b941fb"); !strings.Contains(got, "持久本地") || strings.Contains(got, "版本历史修复") { + t.Fatalf("same-version 3e7 selected wrong block: %q", got) + } +} diff --git a/internal/versionhistory/development_notes_plain_test.go b/internal/versionhistory/development_notes_plain_test.go new file mode 100644 index 0000000..afbc003 --- /dev/null +++ b/internal/versionhistory/development_notes_plain_test.go @@ -0,0 +1,133 @@ +package versionhistory + +import ( + "os" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +const plainNotesFixture = `# Changelog + +## 开发快照 0.1.351(索引预检使用目标映射 ID) + +### Fixed + +- 索引预检使用目标映射 ID + +## 开发快照 0.1.35(前缀相似版本) + +### Fixed + +- 不应被 0.1.351 命中 + +## 开发快照 0.1.350(首次复用取消本库历史来源门槛) + +### Changed + +- 首次复用说明 +` + +func TestPlainDevelopmentHeadingExactVersion(t *testing.T) { + got := governance.ExtractDevelopmentNotes(plainNotesFixture, "0.1.351") + if got == "" || !strings.Contains(got, "索引预检使用目标映射 ID") || strings.Contains(got, "首次复用说明") { + t.Fatalf("plain 0.1.351 notes wrong: %q", got) + } + if other := governance.ExtractDevelopmentNotes(plainNotesFixture, "0.1.35"); strings.Contains(other, "索引预检") { + t.Fatalf("0.1.35 must not match 0.1.351 body: %q", other) + } + if other := governance.ExtractDevelopmentNotes(plainNotesFixture, "0.1.3"); other != "" { + t.Fatalf("0.1.3 must not prefix-match 0.1.35/0.1.351: %q", other) + } + if next := governance.ExtractDevelopmentNotes(plainNotesFixture, "0.1.350"); !strings.Contains(next, "首次复用说明") || strings.Contains(next, "索引预检") { + t.Fatalf("adjacent version bleed: %q", next) + } +} + +func TestPlainDevelopmentHeadingEmptyBodyAndLegacyFormat(t *testing.T) { + if got := governance.ExtractDevelopmentNotes("## 开发快照 0.1.351(空)\n\n## 开发快照 0.1.350(下一版)\n\n- x\n", "0.1.351"); got != "" { + t.Fatalf("empty body must stay empty: %q", got) + } + legacy := "## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n### Fixed\n\n- legacy body\n" + if got := governance.ExtractDevelopmentNotes(legacy, "0.1.1"); !strings.Contains(got, "legacy body") { + t.Fatalf("legacy snapshot format regressed: %q", got) + } +} + +func TestRealChangelogDevelopmentNotes(t *testing.T) { + body, err := os.ReadFile("../../CHANGELOG.md") + if err != nil { + t.Fatal(err) + } + changelog := string(body) + for _, tc := range []struct{ version, want string }{ + {"0.1.351", "索引预检"}, + {"0.1.350", "首次同步可复用"}, + } { + notes := governance.ExtractDevelopmentNotes(changelog, tc.version) + if notes == "" || !strings.Contains(notes, tc.want) { + t.Fatalf("real CHANGELOG %s notes missing: %q", tc.version, notes) + } + if other := governance.ExtractDevelopmentNotes(changelog, "0.1.35"); strings.Contains(other, "首次同步可复用") || strings.Contains(other, "索引预检") { + t.Fatalf("0.1.35 matched a longer version's body: %q", other) + } + } +} + +func TestDeriveVersionsPlainHeadingReleaseNotes(t *testing.T) { + text := "# Changelog\n\n## 开发快照 0.1.1(索引预检使用目标映射 ID)\n\n### Fixed\n\n- plain delivered notes\n\n## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n### Fixed\n\n- legacy duplicate heading\n\n## [0.1.0] - 2026-10-13\n\n### Added\n\n- baseline\n" + result := DeriveVersions(DeriveInput{ + Commits: []RawCommit{{SHA: "a", CommittedAt: time.Now()}, {SHA: "b", Parents: []string{"a"}, CommittedAt: time.Now()}}, + Tags: []RawTag{{Name: "v0.1.0", TargetSHA: "a", Annotated: true}}, + Changelog: func(string) (string, error) { + return text, nil + }, + }) + for _, record := range result.Records { + if record.CommitSHA == "b" { + if record.RecordKind != governance.RecordKindDevelopment || !strings.Contains(record.ReleaseNotes, "plain delivered notes") || + strings.Contains(record.ReleaseNotes, "legacy duplicate") { + t.Fatalf("DeriveVersions plain heading notes wrong: %q kind=%s label=%s", record.ReleaseNotes, record.RecordKind, record.VersionLabel) + } + return + } + } + t.Fatal("development record b missing") +} + +func TestPlainDevelopmentArchiveBindsExactCommit(t *testing.T) { + sha := strings.Repeat("a", 40) + archive := "## 开发快照 0.1.351(索引预检使用目标映射 ID)\n\n目标提交:" + sha + "\n\n### Fixed\n\n- archived plain notes\n" + if got := governance.ExtractDevelopmentNotesForCommit(archive, "0.1.351", sha); !strings.Contains(got, "archived plain notes") { + t.Fatalf("plain archive notes missing for exact commit: %q", got) + } + if got := governance.ExtractDevelopmentNotesForCommit(archive, "0.1.351", strings.Repeat("b", 40)); got != "" { + t.Fatalf("plain archive notes leaked to wrong commit: %q", got) + } +} + +func TestRealChangelogVersionInventory(t *testing.T) { + body, err := os.ReadFile("../../CHANGELOG.md") + if err != nil { + t.Fatal(err) + } + changelog := string(body) + for _, version := range []string{"0.1.351", "0.1.350", "0.1.349", "0.1.348"} { + notes := governance.ExtractDevelopmentNotes(changelog, version) + heading := "" + for _, line := range strings.Split(changelog, "\n") { + if strings.HasPrefix(line, "## 开发快照 "+version) || strings.HasPrefix(line, "## 开发快照 snapshot/v"+version) { + heading = line + break + } + } + t.Logf("version=%s heading=%q notes_bytes=%d", version, heading, len(notes)) + if version == "0.1.351" || version == "0.1.350" { + if notes == "" { + t.Fatalf("%s has a CHANGELOG section but no extracted notes", version) + } + } + } +} diff --git a/internal/versionhistory/testdata/development_notes_history.json b/internal/versionhistory/testdata/development_notes_history.json new file mode 100644 index 0000000..8c978b0 --- /dev/null +++ b/internal/versionhistory/testdata/development_notes_history.json @@ -0,0 +1,1082 @@ +[ + { + "version": "0.1.349", + "sha": "0d9091e4644cf3eb053fe2c852bdbab90a51cc24" + }, + { + "version": "0.1.348", + "sha": "e0fc2c32b89b7ac74f2346057b43436f9404ba3a" + }, + { + "version": "0.1.347", + "sha": "604295549840dd2f4fbe2f91f4ac74d529cc5ca2" + }, + { + "version": "0.1.346", + "sha": "a55319d9726f063baf43b7fe1e3fb7768946a4d8" + }, + { + "version": "0.1.345", + "sha": "017765763a74919fdcc0591454ae85d3415f6a43" + }, + { + "version": "0.1.344", + "sha": "bd452e85b3b40083ac13c35cd9afa04dd978c714" + }, + { + "version": "0.1.343", + "sha": "71f23c67639f3ea8f0171a56d0198ac815ca216a" + }, + { + "version": "0.1.342", + "sha": "b4add6c9b0912294ceb9e00a8d54a4bd955f9135" + }, + { + "version": "0.1.341", + "sha": "f9457fab52eb84c7af0edad492aad23fa59658ea" + }, + { + "version": "0.1.340", + "sha": "5e1482e349e23728f8f2f1aeb770422eba2e5b5f" + }, + { + "version": "0.1.339", + "sha": "4421dd38cec74fcfcdde177e65238a9ca38c42e5" + }, + { + "version": "0.1.338", + "sha": "22fb33aa7573f56903a588bf6ca27b9d01e8a006" + }, + { + "version": "0.1.337", + "sha": "0d180aa401e388667b01475f497e5afc91396ccf" + }, + { + "version": "0.1.336", + "sha": "0a87dc8e037c4d7c61b8c566e9e9ca10e8b62308" + }, + { + "version": "0.1.335", + "sha": "96472c1ddee829b58e7daf5f099a852c666b1b33" + }, + { + "version": "0.1.334", + "sha": "bad9034cf76e69c5b11009b469c5f5ca48a9433f" + }, + { + "version": "0.1.333", + "sha": "f330a75641cc1a69c1253458b079e69419709384" + }, + { + "version": "0.1.332", + "sha": "19ec03c4171e8700425c01d960d1ba5ae17c3c40" + }, + { + "version": "0.1.331", + "sha": "6209072e43172c4d52c595b9330c6c7fbab2615a" + }, + { + "version": "0.1.330", + "sha": "e61f05c98cfd2cef067f3303965b543097d733eb" + }, + { + "version": "0.1.329", + "sha": "a9d5adf78f1213ca9f058588ae3f4ba4b040f41e" + }, + { + "version": "0.1.328", + "sha": "e8f80694735dc12db4412a2c3f6724f390e87517" + }, + { + "version": "0.1.327", + "sha": "b7d6661a4e774721c05f3cb085fcb87e4658d15e" + }, + { + "version": "0.1.326", + "sha": "97da6ceba86862703a6ed848d511161711bb5b88" + }, + { + "version": "0.1.325", + "sha": "7cdbb74c8fd75c76abeb480516781e8c98713ef5" + }, + { + "version": "0.1.324", + "sha": "1aa60c159ebaac6c47799cd41bca6931ea3f85a1" + }, + { + "version": "0.1.323", + "sha": "245cefd6b0206827ba99ff88f92b206ef45cc335" + }, + { + "version": "0.1.322", + "sha": "1e2bb385c77f3fe3b93152922e7666736a356936" + }, + { + "version": "0.1.321", + "sha": "bf7f5fa03c75752f237735ada53e808e3d19a397" + }, + { + "version": "0.1.320", + "sha": "24608e132bcc5026d8a305e545c69347533a595c" + }, + { + "version": "0.1.319", + "sha": "80254756f1e0ef604b448ab98d7fe02f8c0e80dd" + }, + { + "version": "0.1.318", + "sha": "37f2dc73f92b1c2f8d826315ac19743ec640fae5" + }, + { + "version": "0.1.317", + "sha": "9e31a6f95641b78c577a9aa4b70c5956ddef2afd" + }, + { + "version": "0.1.316", + "sha": "1c58f1ef7eb43c0848626d965420901906602af4" + }, + { + "version": "0.1.315", + "sha": "3b7ad9061c7068980971c7fc4a66cd3b03198a8f" + }, + { + "version": "0.1.314", + "sha": "882e38591d919886446b49523ad315678c6eddc6" + }, + { + "version": "0.1.313", + "sha": "a1112d368a127ab73f706617200182ec47ed5e7a" + }, + { + "version": "0.1.312", + "sha": "ca32f2e661d06f9b2dd76b6f1ba4a6086dbf5364" + }, + { + "version": "0.1.311", + "sha": "513aa9e6f5e87b916583fa1d3d418363f547dcfd" + }, + { + "version": "0.1.310", + "sha": "3bce6c7a3fb1b870c4dcbca554b1ba75f464e5f9" + }, + { + "version": "0.1.309", + "sha": "18a4b83f7844589fced0d7d86b5897b2d945e3b7" + }, + { + "version": "0.1.308", + "sha": "7b2ab642f7788466c8bb0cdf662c9c49825483cf" + }, + { + "version": "0.1.307", + "sha": "0a7c9f85105657ed91e9bf0a156952dfc8d36947" + }, + { + "version": "0.1.306", + "sha": "e09fddcb74b49cea56256106e632c29b404f6446" + }, + { + "version": "0.1.305", + "sha": "fad26166a466de2d3533523e4fad69f93af01bc2" + }, + { + "version": "0.1.304", + "sha": "47be4ae502b728222b219aeb1d630ad273690eb5" + }, + { + "version": "0.1.303", + "sha": "6827fa922fc688c2af43bde0baef2ce0bc34fad2" + }, + { + "version": "0.1.302", + "sha": "c31a7df4cae151daa6515f0e754f388c7764eebb" + }, + { + "version": "0.1.301", + "sha": "770252b55aef80f777820e37bd9944a875858ddf" + }, + { + "version": "0.1.300", + "sha": "c256f2985cadf1ce7617bbc86312b9a8e21e79b0" + }, + { + "version": "0.1.299", + "sha": "f1cddfb60117dada470af05f0b400c3e78984ee9" + }, + { + "version": "0.1.298", + "sha": "d2ff089b9554708dff7c473d3f25246920fadac0" + }, + { + "version": "0.1.297", + "sha": "12b37690ec95afef6c7fd4a6e575a13f4104bd52" + }, + { + "version": "0.1.296", + "sha": "a1472ff29fad05013819640b53bca42c214b455f" + }, + { + "version": "0.1.295", + "sha": "f076c3af9cbba8a23f6e8f9749e926ea963fd118" + }, + { + "version": "0.1.294", + "sha": "59eb12296a7fa4abdc9ec149426c72ee68a9e779" + }, + { + "version": "0.1.293", + "sha": "6ec18212948f368a266d3274bcf2f203535805bb" + }, + { + "version": "0.1.292", + "sha": "099e58b5dc902e7f463a8404d3aa864481547c27" + }, + { + "version": "0.1.291", + "sha": "e760d85427ff733726a591778d97e6fdbeae4dc6" + }, + { + "version": "0.1.290", + "sha": "98e7279632227aea8ce2281db5843264ccb6d423" + }, + { + "version": "0.1.289", + "sha": "30f223bcc4ef19aea5622468c2baf39d08e5b6c7" + }, + { + "version": "0.1.288", + "sha": "2cbeca8d1d865d3b2b0b0d1e6c04567991a394f8" + }, + { + "version": "0.1.287", + "sha": "b39902ef9060b955436d47ae9c705efe0cf81abf" + }, + { + "version": "0.1.286", + "sha": "68f03bb30e3bd1b2d2bf812583904691b6a85e7b" + }, + { + "version": "0.1.285", + "sha": "93c0f34aac02af0341dc7d9dfb35f669a21c6dd3" + }, + { + "version": "0.1.284", + "sha": "98ccb9366e4070b2ffa2d080186c2ce023e370a0" + }, + { + "version": "0.1.283", + "sha": "07a9caf22b61586bd790bd8a78c08be66a5a5e27" + }, + { + "version": "0.1.282", + "sha": "eea0a0ec3b929b91e95d1464310d6eb337c2de11" + }, + { + "version": "0.1.281", + "sha": "1d2fff8639613eb11514c6d94d805b2f71e86e6c" + }, + { + "version": "0.1.280", + "sha": "066dc45a2563e924db49c98327f129c034c8667b" + }, + { + "version": "0.1.279", + "sha": "ff257064c3bef2fef7baf837cc597eda72e6d11b" + }, + { + "version": "0.1.278", + "sha": "de867078c6da4a7aeac0a403b89cb8c9cf218e61" + }, + { + "version": "0.1.277", + "sha": "b15633d37c340f4ee971aca845aa0ebe5db4fb98" + }, + { + "version": "0.1.276", + "sha": "c938a4f4bf257be90ba8963328ec5368e92b2903" + }, + { + "version": "0.1.275", + "sha": "ba1989b04217b0b268e1068ab1ff40ac270029af" + }, + { + "version": "0.1.274", + "sha": "a98828dc4a5eb064066e7bfd31a9e513b2f56a34" + }, + { + "version": "0.1.273", + "sha": "e292b6f674bcefe893c6f295190c68ec5d20b5c1" + }, + { + "version": "0.1.272", + "sha": "30686dd288448a243bcfcd9e5e3742060ffef379" + }, + { + "version": "0.1.271", + "sha": "8ce78e28fabf99eb0093abb7d051c779fda71658" + }, + { + "version": "0.1.270", + "sha": "044fb37b2c7ae14153db35920fec4350963bd9ad" + }, + { + "version": "0.1.269", + "sha": "e34306b2dbbe58bde2de613be62291fe84c4cdcc" + }, + { + "version": "0.1.268", + "sha": "943b617b1f778a5a75db13eb2d9e50b8180f3569" + }, + { + "version": "0.1.266", + "sha": "99055a582eea241909089ec78ee6fadc45fdcdb6" + }, + { + "version": "0.1.267", + "sha": "90ab1c3a5ede520fecd2d71362c0699dd16e992b" + }, + { + "version": "0.1.265", + "sha": "0df0e3cb1e076e1a19bfd7da9eee38ba9ea29c47" + }, + { + "version": "0.1.264", + "sha": "f4bd1980bfeda7f4d5e9f5138d13e025726ca82e" + }, + { + "version": "0.1.263", + "sha": "8df19f9368193a83393f2422b7808fe7e0b00077" + }, + { + "version": "0.1.262", + "sha": "8d838d9cb40143b1400b95757aeb9bb0f03be2ab" + }, + { + "version": "0.1.261", + "sha": "5afd8c0140e3929ed2165057e3154c372cf6eea3" + }, + { + "version": "0.1.260", + "sha": "8febe12d7df42a0a945445d709a379c52de9d4c1" + }, + { + "version": "0.1.259", + "sha": "5eef13b6151a1f4b56861568cf38b3008df6c534" + }, + { + "version": "0.1.258", + "sha": "d0c6d57283f4a5bc16db2dfd97d2eb3c737aaad7" + }, + { + "version": "0.1.257", + "sha": "ee9d0787946c7cef2f7fe3b918c34cd6e6818aa9" + }, + { + "version": "0.1.256", + "sha": "a50cd734233e07fff941d6a3778f48f4d95c6de5" + }, + { + "version": "0.1.255", + "sha": "286f1fb375331658e86ebb84278e061a5d2954a1" + }, + { + "version": "0.1.254", + "sha": "3e4020c327c7226859da6cd7d9b5812ebfd5d519" + }, + { + "version": "0.1.253", + "sha": "56f8f4fd7ea659b897cc127ed7760429ef1fc6bf" + }, + { + "version": "0.1.252", + "sha": "7ab2eb1ccf4c3bc716ca6c103c163b9b8ae49cfe" + }, + { + "version": "0.1.251", + "sha": "323f9ae50230dc00608f32b9ad53e32f02973cc6" + }, + { + "version": "0.1.250", + "sha": "52c0186172319c08ab3d62bb4473707e0492fbc1" + }, + { + "version": "0.1.249", + "sha": "657fd251fbcc2d1e8d1724b182ac98ec608cfa07" + }, + { + "version": "0.1.248", + "sha": "468ae6491891607645ff9c90c1358eb37e288729" + }, + { + "version": "0.1.247", + "sha": "06c2db19fcd7a4bf3c7f0bbee0686ca730c4933e" + }, + { + "version": "0.1.246", + "sha": "70c181370db2339c9157c3f41c055e388e158e3e" + }, + { + "version": "0.1.245", + "sha": "8a68ed1819afb159e7d269f7b92819e539527794" + }, + { + "version": "0.1.244", + "sha": "9300865d23436a7426b535e1577ab2557b5dc57c" + }, + { + "version": "0.1.243", + "sha": "6400fd1bbedb1e9e7d58c3e60b8b9f69d8c903a4" + }, + { + "version": "0.1.242", + "sha": "e6472b0ec67684a6e0e09372d67699ac9454f0b3" + }, + { + "version": "0.1.241", + "sha": "a7d643635ad8de1fae3a1e65dd93edc436e17c28" + }, + { + "version": "0.1.240", + "sha": "afe9affc2aea5b84d936c257ad853a58770e4d2a" + }, + { + "version": "0.1.239", + "sha": "98294b9583c0c877f5dd31db61e5146ff548010b" + }, + { + "version": "0.1.238", + "sha": "4f0852a94dd36aca68b646f192b4dc2e6ba51ac1" + }, + { + "version": "0.1.237", + "sha": "c2ab658033ffaa2ae8001134528214fe14f25c07" + }, + { + "version": "0.1.236", + "sha": "d0310761b6a266722cbe772ab997727c69454183" + }, + { + "version": "0.1.235", + "sha": "780ab988c4676fab1816415fa35d15288343063a" + }, + { + "version": "0.1.234", + "sha": "c57c22c65e7e9f9a9a739b80597c65c34760e7b5" + }, + { + "version": "0.1.233", + "sha": "8a3aa800a3e0ecd59a4878557f3ec47ee99f891c" + }, + { + "version": "0.1.232", + "sha": "85b3596e0ef5c9fc54f35b691b92721bd80b3b25" + }, + { + "version": "0.1.231", + "sha": "6bdc17474c344fd8f343363515fa6ee67bd936c2" + }, + { + "version": "0.1.230", + "sha": "d5447280018614224e902f34595b57df35b258e7" + }, + { + "version": "0.1.229", + "sha": "4a70c2a848f687ed94dbd841a6ed10f3e5243219" + }, + { + "version": "0.1.228", + "sha": "d0fe257531b7412c60b238e44c4d25f6f82a5cb7" + }, + { + "version": "0.1.227", + "sha": "1d70059d328977fcae01589992d16f5d407dbe5f" + }, + { + "version": "0.1.226", + "sha": "ba852f3dc20119cf9a18aebde73d217acbe6f63d" + }, + { + "version": "0.1.225", + "sha": "a19cf819fc4284e722129c52701fbd3ae45b355d" + }, + { + "version": "0.1.224", + "sha": "465cae80bd00a70d054036e6bef68862a3ff8818" + }, + { + "version": "0.1.223", + "sha": "ed307f3c2014f5896c2580795402e32db1af5453" + }, + { + "version": "0.1.222", + "sha": "0d3a016a9e06657088a82c591f3ba60238cafee1" + }, + { + "version": "0.1.221", + "sha": "0088004cd6cec924092a39de63b95c0b570d7045" + }, + { + "version": "0.1.220", + "sha": "67743f22854d4bc378be7030ac30aa72f196e07b" + }, + { + "version": "0.1.219", + "sha": "f0bd6fb0d250aa713767638a973c3916c530008f" + }, + { + "version": "0.1.218", + "sha": "27828ff21e7c66846ba41ed50894814915fdf36f" + }, + { + "version": "0.1.217", + "sha": "18683ca63ca10dc8238d230eeb677608e911dd81" + }, + { + "version": "0.1.216", + "sha": "0252492e53b76c48c2deca86f5c497c055ba73ac" + }, + { + "version": "0.1.215", + "sha": "cf3f4662ccb88d6b6bf640749e628ec16017ccab" + }, + { + "version": "0.1.214", + "sha": "74fb04b2d1e50b1f227a19d0c0582394beff4f4f" + }, + { + "version": "0.1.213", + "sha": "402173263ecc2e18c2f216ead0b397b7c79f5d6e" + }, + { + "version": "0.1.212", + "sha": "72ea9726e7073d5c4cbb8b459cfef0cd1c48e38d" + }, + { + "version": "0.1.211", + "sha": "168fc2ecb7427140233825460c3a9897b4677ed3" + }, + { + "version": "0.1.210", + "sha": "f0f5571518bd644429da4fa3148219da2e0e1042" + }, + { + "version": "0.1.209", + "sha": "a0a7a266394557e338860eb8b272349ee44bfc4c" + }, + { + "version": "0.1.208", + "sha": "e0768f2caadb3359b680586b9355157f20987062" + }, + { + "version": "0.1.207", + "sha": "034c0b3a1c0b9fc5884750cc0d9929c0df4ac314" + }, + { + "version": "0.1.206", + "sha": "5defe238e0b992ab4d0037f63d04606d9e16cd2c" + }, + { + "version": "0.1.205", + "sha": "c27a0c14cc0a2a34f61b80e4a2d40994ba44ae2e" + }, + { + "version": "0.1.204", + "sha": "a42b101a7b50cadd70b9e369c32aaeb0311712ae" + }, + { + "version": "0.1.203", + "sha": "3284658eb1d5d64de8693f83732fb4ed3030293f" + }, + { + "version": "0.1.202", + "sha": "517d5f862df92230c494ae3bdeddd06021810a9e" + }, + { + "version": "0.1.201", + "sha": "f9c15a8f14353865258fd1c4bba19c9df5f621df" + }, + { + "version": "0.1.200", + "sha": "271f9f5f0992d03e409affe0f1fd91326fa33f5e" + }, + { + "version": "0.1.199", + "sha": "24d2546cbb99e2d5d1d8e126a1bf5d06af9ee457" + }, + { + "version": "0.1.198", + "sha": "691e4e0225b8b2b861be80a58a134158c81603ee" + }, + { + "version": "0.1.197", + "sha": "8d2ed8ebe61fcf5ef9a5e1b25923e6456c52c5c8" + }, + { + "version": "0.1.196", + "sha": "c14dd01f08ca1d7a5fccbe5ffdc0b69ed3463962" + }, + { + "version": "0.1.195", + "sha": "6ed06357f9a0fa7787796beb149d053407a6b3eb" + }, + { + "version": "0.1.194", + "sha": "5d42cba6c628fa32dc41caa05d3580e4d1924c45" + }, + { + "version": "0.1.193", + "sha": "a47f9323e060074d90eb1a3db53d826711e81ba5" + }, + { + "version": "0.1.192", + "sha": "4c79052a189ad2be3892498905774d77fc40a67e" + }, + { + "version": "0.1.191", + "sha": "18276d0839ce44b4fbf36675ced45884ab379cae" + }, + { + "version": "0.1.189", + "sha": "c40696145b43a47ea0cef6d83ae2fbe00bb3677f" + }, + { + "version": "0.1.190", + "sha": "cfad0034995de0fdd4a437de336502dc574fb0b3" + }, + { + "version": "0.1.188", + "sha": "47eb23cf6873e3c3487ef3b07cbfd547e43dd5f9" + }, + { + "version": "0.1.187", + "sha": "a06945516fe8de5a41c0bc7ae765627d536fb02d" + }, + { + "version": "0.1.186", + "sha": "e508abd958834d93515e86add2fa2e89a5b09e4c" + }, + { + "version": "0.1.185", + "sha": "c542a1333a869cfe1c8ef855c8e22640a9607419" + }, + { + "version": "0.1.184", + "sha": "1aecd9d6af0e2f7e8da6710f9bc73711ecb76e81" + }, + { + "version": "0.1.183", + "sha": "c2402947a96e19b26279c8f93168d7b67c87d3eb" + }, + { + "version": "0.1.182", + "sha": "958292d1ff2246b39c43bfe7d93e2b15e407bf6f" + }, + { + "version": "0.1.181", + "sha": "bc49b85b5627b5947b87d96df2089b444fd4df75" + }, + { + "version": "0.1.180", + "sha": "a6406209bd2a4a037ba5804bdaae8f78d255bbbb" + }, + { + "version": "0.1.179", + "sha": "b061a9686c636bb8d92419907f68fd3703baf678" + }, + { + "version": "0.1.178", + "sha": "2e39e495694a4d7f69273a4704ea1eb2ad9675fc" + }, + { + "version": "0.1.177", + "sha": "cb0090802b51dba5de2b72af8c9c348e18d80369" + }, + { + "version": "0.1.176", + "sha": "7d4ffdbfe5feb2d36f8ea5aa92009b57891086e2" + }, + { + "version": "0.1.175", + "sha": "84e8a0dfdcaf4fe42e650ebbb00b839e97f9b83c" + }, + { + "version": "0.1.174", + "sha": "faaf003707d17dd8550d3be5c98f4cf3c2420e82" + }, + { + "version": "0.1.173", + "sha": "4d6ecda3102e9f3d93d828a2ca8aa99d29669750" + }, + { + "version": "0.1.172", + "sha": "f2d6f3f64682680173ac8e697cb27e0f7bb73a24" + }, + { + "version": "0.1.171", + "sha": "37a8370f7be519f327334adb913173bd9d41abed" + }, + { + "version": "0.1.170", + "sha": "11c52ad81b425355205221666aae1b1561b71ef3" + }, + { + "version": "0.1.169", + "sha": "ee7688f24eb5a5b9f6dcd18afc6bb672fdaf0f6d" + }, + { + "version": "0.1.168", + "sha": "9d0fe33c130fe95ffffd105251d5f9d1c7491139" + }, + { + "version": "0.1.167", + "sha": "f82eb0735f4cae339c542ac52c953256d3a7126b" + }, + { + "version": "0.1.166", + "sha": "1faf5137ea53adee61e7c0aac4940a39ec832139" + }, + { + "version": "0.1.165", + "sha": "fd71ea349e81694c8a9b4892379a1d49f24dd273" + }, + { + "version": "0.1.164", + "sha": "906c282986c2fa3576616bd52fd1e4024f12b022" + }, + { + "version": "0.1.163", + "sha": "23cc6c0afe08de3110aae4beaf3bb0caaf5815da" + }, + { + "version": "0.1.162", + "sha": "1f482e4b49b24ca30150d66ce2400059310b4fbd" + }, + { + "version": "0.1.161", + "sha": "0ef79846e83bff0469b47a5dd20366e04498592c" + }, + { + "version": "0.1.160", + "sha": "c7dafe987e8267cf65bc9904099c74858d748116" + }, + { + "version": "0.1.159", + "sha": "f055fc174dc40d0dfbee35ed262144abe13c303c" + }, + { + "version": "0.1.158", + "sha": "b007acd4437d269778b2033dcf57e66e8f007490" + }, + { + "version": "0.1.157", + "sha": "7e4900b51b809b10f08efb91801d28cd6d1f07b0" + }, + { + "version": "0.1.156", + "sha": "1a04dfb4faf2e0ac4e76a63c89c9e32d384c3fa1" + }, + { + "version": "0.1.155", + "sha": "5afe151c7d9648e23b5c8c341af98f81629aaa46" + }, + { + "version": "0.1.154", + "sha": "faf8027890463be00fdfecaf3d9899f8d431edd5" + }, + { + "version": "0.1.153", + "sha": "3643e9bf82f01ce1b78ecc0a52b67a6ef2f77d12" + }, + { + "version": "0.1.152", + "sha": "ec737a9a65822b2a9d5bf893bce6a54d0fbe5c7b" + }, + { + "version": "0.1.151", + "sha": "96fffb5081142a843103637b54963f1e384abc01" + }, + { + "version": "0.1.150", + "sha": "962bed8f53236925b188f603547c3c3236878f8e" + }, + { + "version": "0.1.149", + "sha": "38d04488de00455b29e3d62d3d34de7271d05eaf" + }, + { + "version": "0.1.148", + "sha": "6fe98c9a30a68282598afa4a25961b2fff1a17ce" + }, + { + "version": "0.1.147", + "sha": "fe6e218d9cd5b600e90ed2986204337869225a29" + }, + { + "version": "0.1.146", + "sha": "1609a0c9be5d5192df5bfa9414473346d179ac61" + }, + { + "version": "0.1.145", + "sha": "d1dbb2b9454836ce9d382981d25eccfa0c6cc152" + }, + { + "version": "0.1.144", + "sha": "288e01a01aef1b3fe5c895b0fe9dc06b4b84d7f4" + }, + { + "version": "0.1.143", + "sha": "b76a433574b17c27607ca3146724652f73330264" + }, + { + "version": "0.1.142", + "sha": "def6022048e9bf3273d99d8a2eddfc1178048421" + }, + { + "version": "0.1.141", + "sha": "e7ba2057aca11a5b56bff96156e1af1360a8b02a" + }, + { + "version": "0.1.140", + "sha": "cef25d92a62ace37c5ecdeed07ba270dbe50c6cc" + }, + { + "version": "0.1.139", + "sha": "f722ea87271a9d8d5bec465ee07f75bba4861d54" + }, + { + "version": "0.1.138", + "sha": "e47e6d825dd21d883ae529e705dbc6306c411d7a" + }, + { + "version": "0.1.137", + "sha": "7a2188a0ee7cd17c93142f25450128781c37a856" + }, + { + "version": "0.1.136", + "sha": "ea4cffbcaa54c0055ddcaeb812cb93a8ededbce3" + }, + { + "version": "0.1.135", + "sha": "c72b71d78afd1d72cefdc6ced301001172ccc968" + }, + { + "version": "0.1.134", + "sha": "ca51cbe2029cec6ddc41d978c378d2d67c2564b2" + }, + { + "version": "0.1.133", + "sha": "6fea763c9baf17b6f1e445b0f8b6fe525a3e928f" + }, + { + "version": "0.1.132", + "sha": "ac3b39510247b9f26458a578d47cbad2b5846aa3" + }, + { + "version": "0.1.131", + "sha": "8a68ea2da240134f5ac484d74412468048261473" + }, + { + "version": "0.1.130", + "sha": "a2d051f6b3e7e0895eb4aaafdb941093536d82f5" + }, + { + "version": "0.1.129", + "sha": "0b9dbe12cfbb30584b2dd3dc1a726822cd5c7f4e" + }, + { + "version": "0.1.128", + "sha": "6ca8481e8e8c22f401d3ef1cbea9e9b9dbe2de6f" + }, + { + "version": "0.1.127", + "sha": "8da4666e76f8b46cad29e41d2fdd0b98663c53bc" + }, + { + "version": "0.1.126", + "sha": "281699a43104af6ce5344b17375ac7102f3e563d" + }, + { + "version": "0.1.125", + "sha": "444b8202108adc4309d6cc77da77eefe089fad71" + }, + { + "version": "0.1.124", + "sha": "67a48faf23996b7cf55d2ed589e4235f9b4d4754" + }, + { + "version": "0.1.123", + "sha": "7e3075f0fc77c51821925d7c7194c6c759678b87" + }, + { + "version": "0.1.122", + "sha": "2038462dbbd09b4bee00ea8d647c2bb0e94f538d" + }, + { + "version": "0.1.121", + "sha": "7b8cc0384b9160d488be6ed308b2007d9d6ef91f" + }, + { + "version": "0.1.120", + "sha": "f91359f881077d1fad17fca021973c6beb54553f" + }, + { + "version": "0.1.119", + "sha": "12bb839d8a2cc138d3e4034d4dae559a52c3d094" + }, + { + "version": "0.1.118", + "sha": "3ad48ff32cf301b70555e93409d8593b3b571be0" + }, + { + "version": "0.1.117", + "sha": "e313ae12f29bd5579f779122cf6a26a87a98a87d" + }, + { + "version": "0.1.116", + "sha": "e3db157ba8d78f6046114055a24f7812e224e576" + }, + { + "version": "0.1.115", + "sha": "7e1610da44387c1cd86af2605311997e8249c47a" + }, + { + "version": "0.1.106", + "sha": "9f990158b97c0f6d0ec010b01a80f540042d5945" + }, + { + "version": "0.1.95", + "sha": "74aef1e373513ec605750313b7002528575bf50e" + }, + { + "version": "0.1.94", + "sha": "1b09f7d35bcb7a4b2a79417996933b1b45a31c95" + }, + { + "version": "0.1.93", + "sha": "d8d143eca004b83cbd9226f088ddf8ad79f2317f" + }, + { + "version": "0.1.92", + "sha": "52f411783581f3aa586ff86838ca99ba69b1b251" + }, + { + "version": "0.1.91", + "sha": "7448d130ec71cbfd4f31b9a2eff4bc8ef7b57f2e" + }, + { + "version": "0.1.90", + "sha": "f0b12412a1fa6cd7251692cc485369c3dd789f1c" + }, + { + "version": "0.1.89", + "sha": "5b6e154459d510a26e8434ad521f5009b803a0a1" + }, + { + "version": "0.1.88", + "sha": "8930ef29cdfd091dfb0897c195799fba002e12bd" + }, + { + "version": "0.1.87", + "sha": "a55d7f454e74f3a123b62180adad90a7ab16868b" + }, + { + "version": "0.1.86", + "sha": "b55292bba16666fd2a7b20c1f06fd3a440781bc0" + }, + { + "version": "0.1.85", + "sha": "02ee5da231d8f761a756db06aad4ab4b3a225767" + }, + { + "version": "0.1.84", + "sha": "e744114ff438cbbf15d98dd46a5e74f900d0b1be" + }, + { + "version": "0.1.83", + "sha": "c8f05ee46f61ee2ec6a8f20a31fea5783a61b283" + }, + { + "version": "0.1.82", + "sha": "1e8d8e3cdf30d94fad4b99ce1e5ede3da5d402fd" + }, + { + "version": "0.1.81", + "sha": "842bfccc1b92613212589b66db39a24ad29975ed" + }, + { + "version": "0.1.80", + "sha": "740f0e69baf33f64b9dec7b5689f56cd3159baa6" + }, + { + "version": "0.1.79", + "sha": "020cae1228d2c5a30808baadf42444fdd91a3236" + }, + { + "version": "0.1.78", + "sha": "017cbcb851901c1ad0a7571aaea211fafae0ace7" + }, + { + "version": "0.1.77", + "sha": "b3992bfa0f5c61cdb102393d8fba12b9cae58308" + }, + { + "version": "0.1.76", + "sha": "2902ba0af2dbb01bbab49dee5662f23833d74d56" + }, + { + "version": "0.1.75", + "sha": "555bc6ff5614a672d82ff5c103f92da04b86bb93" + }, + { + "version": "0.1.74", + "sha": "1dda055e4c5ea2b0556141ee5efac7de2ba2e526" + }, + { + "version": "0.1.73", + "sha": "f87d3fad9be11f1164137d1e28f2599dccab43fd" + }, + { + "version": "0.1.72", + "sha": "23b19350cce09a18a52ccfa9d0e66e9b2c2539a6" + }, + { + "version": "0.1.71", + "sha": "1a9d1fff8391e531b0af6b6b32f0ae0ee86e057a" + }, + { + "version": "0.1.70", + "sha": "822fb652ffaea9088e31f87ad1abf5a8b4fdc3ff" + }, + { + "version": "0.1.69", + "sha": "600e9a2dc2464d0013f40375d71ab3937ce4e401" + }, + { + "version": "0.1.68", + "sha": "eed83039ab08c7ed88a6bf2c01c3d1f0ad299bdb" + }, + { + "version": "0.1.67", + "sha": "43b1e423fec01a3534dac4dfba9b6152d4bab36c" + }, + { + "version": "0.1.66", + "sha": "5aa32492de54c9ac32841e8fef96489697611d10" + }, + { + "version": "0.1.65", + "sha": "68162895528ef3a1f42be18693d32915fc3abfde" + }, + { + "version": "0.1.64", + "sha": "1d33ff697632c8ab81ce2ae305ed200ef1fd2da6" + }, + { + "version": "0.1.35", + "sha": "330fd12b3f30376c3aee757ba2a9f4ba3f8bcf27" + }, + { + "version": "0.1.28", + "sha": "f33730ed7437536c3d1e01cc2f20231af076b531" + } +] \ No newline at end of file diff --git a/internal/weknoraaccess/client.go b/internal/weknoraaccess/client.go new file mode 100644 index 0000000..2ce9dab --- /dev/null +++ b/internal/weknoraaccess/client.go @@ -0,0 +1,96 @@ +package weknoraaccess + +import ( + "context" + "errors" + "time" + + "knowledge-governance/internal/platform/weknora" + "knowledge-governance/internal/readiness" +) + +var ErrNotConfigured = errors.New("WeKnora 有效端点/凭据未配置") + +// defaultBusinessTimeout matches appconfig's TEST_WEKNORA_HTTP_TIMEOUT default. +// The readiness probe has its own 10s cap; it must not bound upload/poll calls. +const defaultBusinessTimeout = 60 * time.Second + +// Client resolves the effective WeKnora target on every call. It deliberately +// owns no cached *weknora.Client: endpoint, key and binding are console-managed. +type Client struct { + Resolver readiness.Resolver + Timeout time.Duration + AllowDockerHTTP bool +} + +func (client *Client) with(ctx context.Context, call func(*weknora.Client) error) error { + target, err := client.Resolver.Resolve(ctx) + if err != nil { + return err + } + if target.BaseURL == "" || target.APIKey == "" { + return ErrNotConfigured + } + timeout := client.Timeout + if timeout <= 0 { + timeout = defaultBusinessTimeout + } + remote, err := weknora.NewClient(weknora.ClientConfig{ + BaseURL: target.BaseURL, + APIKey: target.APIKey, + Timeout: timeout, + AllowDockerHTTP: client.AllowDockerHTTP, + }) + if err != nil { + return err + } + return call(remote) +} + +func (client *Client) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) { + var knowledge weknora.Knowledge + err := client.with(ctx, func(remote *weknora.Client) error { + value, err := remote.UploadFile(ctx, request) + knowledge = value + return err + }) + return knowledge, err +} + +func (client *Client) ListKnowledge(ctx context.Context, knowledgeBaseID string, page, pageSize int) ([]weknora.Knowledge, int64, error) { + var items []weknora.Knowledge + var total int64 + err := client.with(ctx, func(remote *weknora.Client) error { + value, count, err := remote.ListKnowledge(ctx, knowledgeBaseID, page, pageSize) + items, total = value, count + return err + }) + return items, total, err +} + +func (client *Client) GetKnowledge(ctx context.Context, knowledgeID string) (weknora.Knowledge, error) { + var knowledge weknora.Knowledge + err := client.with(ctx, func(remote *weknora.Client) error { + value, err := remote.GetKnowledge(ctx, knowledgeID) + knowledge = value + return err + }) + return knowledge, err +} + +func (client *Client) ListChunks(ctx context.Context, knowledgeID string, page, pageSize int, chunkTypes []string) ([]weknora.Chunk, int64, error) { + var chunks []weknora.Chunk + var total int64 + err := client.with(ctx, func(remote *weknora.Client) error { + value, count, err := remote.ListChunks(ctx, knowledgeID, page, pageSize, chunkTypes) + chunks, total = value, count + return err + }) + return chunks, total, err +} + +func (client *Client) DeleteKnowledge(ctx context.Context, knowledgeID string) error { + return client.with(ctx, func(remote *weknora.Client) error { + return remote.DeleteKnowledge(ctx, knowledgeID) + }) +} diff --git a/internal/weknoraaccess/client_test.go b/internal/weknoraaccess/client_test.go new file mode 100644 index 0000000..6faedc2 --- /dev/null +++ b/internal/weknoraaccess/client_test.go @@ -0,0 +1,110 @@ +package weknoraaccess + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "knowledge-governance/internal/readiness" +) + +// F13:worker 的 upload/poll/validate/remove 必须与 API 探测一样,每次调用重新读 +// 当前端点、凭据和绑定;启动时捕获 env 会让页面改配置后两套身份分叉。 +func TestDynamicClientReResolvesEndpointKeyAndBinding(t *testing.T) { + server := func(wantKey, id string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-API-Key") != wantKey { + w.WriteHeader(http.StatusUnauthorized) + return + } + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"` + id + `"}}`)) + })) + } + first, second := server("key-1", "kn-1"), server("key-2", "kn-2") + defer first.Close() + defer second.Close() + var endpoint, key, binding = first.URL, "key-1", "kb-old" + client := &Client{ + Resolver: readiness.Resolver{ + Endpoint: func(context.Context) string { return endpoint }, + ReadKey: func() (string, error) { return key, nil }, + LoadBinding: func(context.Context) (string, error) { return binding, nil }, + DefaultKB: "kb-env", + }, + Timeout: time.Second, + } + if knowledge, err := client.GetKnowledge(context.Background(), "kn-1"); err != nil || knowledge.ID != "kn-1" { + t.Fatalf("first target = %#v, %v", knowledge, err) + } + target, err := client.Resolver.Resolve(context.Background()) + if err != nil || target.KnowledgeBaseID != "kb-old" { + t.Fatalf("binding target = %#v, %v", target, err) + } + endpoint, key, binding = second.URL, "key-2", "kb-new" + target, err = client.Resolver.Resolve(context.Background()) + if err != nil || target.KnowledgeBaseID != "kb-new" { + t.Fatalf("changed binding target = %#v, %v", target, err) + } + if knowledge, err := client.GetKnowledge(context.Background(), "kn-2"); err != nil || knowledge.ID != "kn-2" { + t.Fatalf("rotated endpoint/key = %#v, %v", knowledge, err) + } +} + +// F13 timeout regression: the configured business timeout (default 60s) must +// reach upload/poll clients unchanged; only a missing/zero value falls back. +// The readiness probe's 10s cap must not leak into business HTTP. +func TestConfiguredBusinessTimeoutIsNotCappedToProbeTimeout(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-time.After(11 * time.Second): + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"slow-but-valid"}}`)) + case <-r.Context().Done(): + } + })) + defer server.Close() + client := &Client{ + Resolver: readiness.Resolver{ + Endpoint: func(context.Context) string { return server.URL }, + ReadKey: func() (string, error) { return "isolated-test-key", nil }, + DefaultKB: "isolated-test-kb", + }, + Timeout: 60 * time.Second, + } + started := time.Now() + item, err := client.GetKnowledge(context.Background(), "slow-but-valid") + if err != nil { + t.Fatalf("60s business timeout rejected 11s response after %s: %v", time.Since(started), err) + } + if item.ID != "slow-but-valid" { + t.Fatalf("wrong response identity: %q", item.ID) + } +} + +// An explicit short timeout is still honoured for callers that need it. +func TestExplicitShortBusinessTimeoutStillApplies(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-time.After(300 * time.Millisecond): + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"too-late"}}`)) + case <-r.Context().Done(): + } + })) + defer server.Close() + client := &Client{ + Resolver: readiness.Resolver{ + Endpoint: func(context.Context) string { return server.URL }, + ReadKey: func() (string, error) { return "isolated-test-key", nil }, + DefaultKB: "isolated-test-kb", + }, + Timeout: 50 * time.Millisecond, + } + started := time.Now() + if _, err := client.GetKnowledge(context.Background(), "too-late"); err == nil { + t.Fatal("explicit 50ms timeout did not bound the call") + } + if elapsed := time.Since(started); elapsed > 2*time.Second { + t.Fatalf("explicit short timeout took %s", elapsed) + } +} diff --git a/internal/workflows/artifactfetch/handler.go b/internal/workflows/artifactfetch/handler.go index 59fbb3b..48ee049 100644 --- a/internal/workflows/artifactfetch/handler.go +++ b/internal/workflows/artifactfetch/handler.go @@ -181,7 +181,7 @@ func NewCommandRunner(pythonPath, scriptPath, spoolRoot, spoolPrefix string, max // ——钉钉取件在真实链路上会整体失败(2026-10-10 端到端验收实测;脚本单跑正常, // 因为那只绕过了这个白名单)。 var dwsEnvNames = []string{ - "ARTIFACT_DINGTALK_FETCHER", "DWS_BIN", "DWS_CONFIG_DIR", "DWS_HOME", "DWS_DISABLE_KEYCHAIN", + "ARTIFACT_DINGTALK_FETCHER", "PP_AUTH_STATE_FILE", "PP_LEGACY_CREDENTIALS_FILE", "DWS_BIN", "DWS_CONFIG_DIR", "DWS_HOME", "DWS_DISABLE_KEYCHAIN", } func forwardedDWSEnv() []string { diff --git a/internal/workflows/testweknora/poll.go b/internal/workflows/testweknora/poll.go index 83a2d20..8af0a59 100644 --- a/internal/workflows/testweknora/poll.go +++ b/internal/workflows/testweknora/poll.go @@ -35,7 +35,9 @@ type PollHandlerConfig struct { Client PollClient PollDelay time.Duration StallAfter time.Duration - Now func() time.Time + // StallAfterSource 可选:返回当前生效的停滞阈值(来自活动 UI 配置)。 + StallAfterSource func() time.Duration + Now func() time.Time } type PollHandler struct { @@ -43,7 +45,10 @@ type PollHandler struct { client PollClient pollDelay time.Duration stallAfter time.Duration - now func() time.Time + // stallAfterSource 存在时优先于 stallAfter:页面保存的“解析停滞阈值” + // 必须真的决定判定,而不是只写进数据库。 + stallAfterSource func() time.Duration + now func() time.Time } type pollPayload struct { @@ -60,7 +65,7 @@ func NewPollHandler(config PollHandlerConfig) (*PollHandler, error) { } return &PollHandler{ store: config.Store, client: config.Client, pollDelay: config.PollDelay, - stallAfter: config.StallAfter, now: config.Now, + stallAfter: config.StallAfter, stallAfterSource: config.StallAfterSource, now: config.Now, }, nil } @@ -103,7 +108,13 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error { } return nil } - cutoff := now.Add(-handler.stallAfter) + stall := handler.stallAfter + if handler.stallAfterSource != nil { + if fromSettings := handler.stallAfterSource(); fromSettings > 0 { + stall = fromSettings + } + } + cutoff := now.Add(-stall) lastProgress := publication.LastProgressAt if lastProgress == nil { lastProgress = publication.ProcessingStartedAt diff --git a/internal/workflows/testweknora/poll_test.go b/internal/workflows/testweknora/poll_test.go index d511ad2..4987fcc 100644 --- a/internal/workflows/testweknora/poll_test.go +++ b/internal/workflows/testweknora/poll_test.go @@ -186,3 +186,61 @@ func (store *pollStoreStub) MarkStalled(_ context.Context, _ string, _ int, cuto store.stalledCutoff = cutoff return nil } + +// F02 验收:停滞判定必须用“活动配置”的阈值,而不是启动时的常量。 +// 同一条已经停在同一进度上的解析任务:阈值 30 分钟判停,阈值 2 小时不判停。 +func TestPollHandlerStallThresholdFollowsActiveSettings(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"processing","updated_at":"2026-09-04T03:00:00Z"}}`)) + })) + defer server.Close() + client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: server.URL, APIKey: "test-key", Timeout: time.Second}) + if err != nil { + t.Fatal(err) + } + now := time.Date(2026, time.September, 4, 4, 0, 0, 0, time.UTC) + progressAt := now.Add(-45 * time.Minute) + makeStore := func() *pollStoreStub { + return &pollStoreStub{publication: postgresstore.PublicationForPoll{ + ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1", + ProcessingState: governance.ProcessingProcessing, PollSequence: 3, + LastProgressAt: &progressAt, ProcessingStartedAt: &progressAt, + }} + } + payload := jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":3}`)} + + // 启动常量 30 分钟、活动配置也是 30 分钟:45 分钟没进度 → 判停。 + store := makeStore() + handler, err := NewPollHandler(PollHandlerConfig{ + Store: store, Client: client, PollDelay: 15 * time.Second, + StallAfter: 30 * time.Minute, Now: func() time.Time { return now }, + }) + if err != nil { + t.Fatal(err) + } + if err := handler.Handle(context.Background(), payload); err != nil { + t.Fatalf("Handle() error = %v", err) + } + if !store.stalledMarked { + t.Fatal("30 分钟阈值下 45 分钟无进度应判停") + } + + // 活动配置改成 2 小时:同一条任务不应再判停。 + store = makeStore() + handler, err = NewPollHandler(PollHandlerConfig{ + Store: store, Client: client, PollDelay: 15 * time.Second, + StallAfter: 30 * time.Minute, + StallAfterSource: func() time.Duration { return 2 * time.Hour }, + Now: func() time.Time { return now }, + }) + if err != nil { + t.Fatal(err) + } + if err := handler.Handle(context.Background(), payload); err != nil { + t.Fatalf("Handle() error = %v", err) + } + if store.stalledMarked { + t.Fatal("活动配置 2 小时阈值下不应判停:阈值没有接入实际判定") + } +} diff --git a/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json b/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json new file mode 100644 index 0000000..4274b37 --- /dev/null +++ b/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json @@ -0,0 +1 @@ +{"version":"5.0.3","results":[[":web/src/SystemSettings.test.tsx",{"duration":80.9154110000004,"failed":false}],[":web/src/App.test.tsx",{"duration":170.91958499999964,"failed":false}],[":web/src/releaseTargetsMaintenance.test.tsx",{"duration":173.9886260000003,"failed":false}],[":web/src/uiSettings.test.ts",{"duration":99.68425899999988,"failed":false}],[":web/src/SourceCatalogBrowser.test.tsx",{"duration":175.785707,"failed":false}],[":web/src/qaDashboardData.test.ts",{"duration":73.02293600000007,"failed":false}],[":web/src/documentWorkbench.test.ts",{"duration":96.15424099999996,"failed":false}],[":web/src/qaAllRecords.test.ts",{"duration":152.09659499999998,"failed":false}],[":web/src/RestoreVerificationSection.test.tsx",{"duration":84.09929499999998,"failed":false}],[":web/src/testPublications.test.ts",{"duration":86.20621000000006,"failed":false}],[":web/src/qaWeeklyMail.test.tsx",{"duration":29.665081999999984,"failed":false}],[":web/src/QADashboardDrawing.test.tsx",{"duration":186.94307500000014,"failed":false}],[":web/src/WeKnoraMonitor.test.tsx",{"duration":130.89790200000016,"failed":false}],[":web/src/QARegions.test.tsx",{"duration":84.83084199999985,"failed":false}],[":web/src/VersionHistory.test.tsx",{"duration":159.26085299999977,"failed":false}],[":web/src/versionHistory.test.ts",{"duration":67.0329569999999,"failed":false}],[":web/src/qaWeeklyDrafts.test.ts",{"duration":39.51927999999998,"failed":false}],[":web/src/BackupScheduleSection.test.tsx",{"duration":81.48795600000017,"failed":false}],[":web/src/reviewRelease.test.ts",{"duration":106.13751400000001,"failed":false}],[":web/src/sourceConnections.test.ts",{"duration":78.89484100000004,"failed":false}],[":web/src/QAOperations.test.tsx",{"duration":424.92283799999996,"failed":false}],[":web/src/sourceCatalog.test.ts",{"duration":95.76727200000005,"failed":false}],[":web/src/ReleaseTargets.test.tsx",{"duration":451.82828299999983,"failed":false}],[":web/src/qaAI.test.ts",{"duration":756.2418210000001,"failed":false}],[":web/src/QADepartmentStatistics.test.tsx",{"duration":89.61084699999992,"failed":false}],[":web/src/restoreVerification.test.ts",{"duration":16.331383999999957,"failed":false}],[":web/src/qaWeekly.test.ts",{"duration":99.11194999999998,"failed":false}],[":web/src/qaRegionCommit.test.ts",{"duration":29.786290000000008,"failed":false}],[":web/src/dingtalkSources.test.ts",{"duration":59.28961800000002,"failed":false}],[":web/src/ProductionBindingsSection.test.tsx",{"duration":26.84802999999988,"failed":false}],[":web/src/qaPeopleAnalysis.test.ts",{"duration":19.440447000000177,"failed":false}],[":web/src/QAAI.test.tsx",{"duration":32.667184000000134,"failed":false}],[":web/src/monitor.test.ts",{"duration":52.59250799999995,"failed":false}],[":web/src/librarySyncAuth.test.ts",{"duration":67.74206000000004,"failed":false}],[":web/src/productionBindings.test.ts",{"duration":73.58735700000011,"failed":false}],[":web/src/QAPeopleAnalysis.test.tsx",{"duration":91.05679600000008,"failed":false}],[":web/src/QAQuality.test.tsx",{"duration":42.46089099999995,"failed":false}],[":web/src/SnapshotHistory.test.tsx",{"duration":90.46311500000002,"failed":false}],[":web/src/qaOrg.test.ts",{"duration":19.41472399999998,"failed":false}],[":web/src/qaDepartmentStatistics.test.ts",{"duration":18.951908000000003,"failed":false}],[":web/src/qaOps.test.ts",{"duration":63.670158999999785,"failed":false}],[":web/src/libraryRestore.test.ts",{"duration":54.70203500000002,"failed":false}],[":web/src/qaMaster.test.ts",{"duration":66.88271699999996,"failed":false}],[":web/src/qaQuality.test.ts",{"duration":18.43339600000013,"failed":false}],[":web/src/monitorTasks.test.ts",{"duration":20.76826600000004,"failed":false}],[":web/src/SourceLinkManager.test.tsx",{"duration":19.90849800000001,"failed":false}],[":web/src/qaOrgSync.test.ts",{"duration":15.829886999999871,"failed":false}],[":web/src/dingtalkSession.test.ts",{"duration":73.78475800000001,"failed":false}],[":web/src/qaDownvote.test.ts",{"duration":89.650529,"failed":false}],[":web/src/qaCumulativeTrend.test.ts",{"duration":12.971153000000186,"failed":false}],[":web/src/SourceCatalogBrowser.refreshState.test.tsx",{"duration":121.82865199999969,"failed":false}],[":web/src/SourceCatalogBrowser.focus.test.tsx",{"duration":301.9396649999999,"failed":false}],[":web/src/ReleaseTargets.mount.test.tsx",{"duration":749.2230810000001,"failed":false}],[":web/src/WeKnoraMonitor.focus.test.tsx",{"duration":182.1726060000001,"failed":false}],[":web/src/backupSchedule.test.ts",{"duration":68.236715,"failed":false}],[":web/src/RestoreVerificationSection.mounted.test.tsx",{"duration":176.1726789999998,"failed":false}],[":web/src/qaWeeks.test.ts",{"duration":17.514981999999975,"failed":false}],[":web/src/DocumentWorkbench.test.tsx",{"duration":73.41132799999991,"failed":false}],[":web/src/scopeRules.test.ts",{"duration":78.10301100000004,"failed":false}],[":web/src/qaMonthly.test.ts",{"duration":80.38505299999997,"failed":false}],[":web/src/routingBindings.test.ts",{"duration":85.94489099999998,"failed":false}],[":web/src/qaPersonDisplay.test.ts",{"duration":11.294210000000021,"failed":false}],[":web/src/authMembers.test.ts",{"duration":61.20540499999993,"failed":false}],[":web/src/qaWeeklyDraftAPI.test.ts",{"duration":52.350087999999914,"failed":false}],[":web/src/qaMirror.test.ts",{"duration":12.037162999999964,"failed":false}],[":web/src/libraryOverviewFetch.test.ts",{"duration":63.46936799999992,"failed":false}],[":web/src/LegacySourceAssociation.test.tsx",{"duration":63.97963500000003,"failed":false}],[":web/src/qaRegionalUpgrade.test.ts",{"duration":14.882514999999898,"failed":false}],[":web/src/QADashboard.test.tsx",{"duration":58.515443000000005,"failed":false}],[":web/src/sourceRefreshPolicy.test.ts",{"duration":21.714442000000076,"failed":false}],[":web/src/qaAttribution.test.ts",{"duration":16.41384400000004,"failed":false}],[":web/src/QAMirrorSync.test.tsx",{"duration":29.915631000000076,"failed":false}],[":web/src/QAUsage.test.tsx",{"duration":19.47709500000019,"failed":false}],[":web/src/ReleasePlanner.test.tsx",{"duration":28.713968000000023,"failed":false}],[":web/src/qaAILocalDerivation.test.tsx",{"duration":17.265169000000014,"failed":false}],[":web/src/qaWeeklyClipboard.test.ts",{"duration":16.19790599999999,"failed":false}],[":web/src/assets.test.ts",{"duration":11.851150999999959,"failed":false}],[":web/src/ScopeRuleEditor.test.tsx",{"duration":15.922602999999981,"failed":false}],[":web/src/QAAnswerMarkdown.test.tsx",{"duration":58.82955800000002,"failed":false}],[":web/src/workspace.test.ts",{"duration":12.109188000000017,"failed":false}],[":web/src/qaDashboardMonthly.test.ts",{"duration":19.60739699999999,"failed":false}],[":web/src/SourceManagement.test.tsx",{"duration":26.36754899999994,"failed":false}],[":web/src/QAMonthly.test.tsx",{"duration":26.428301000000033,"failed":false}],[":web/src/operationKey.test.ts",{"duration":10.967223999999987,"failed":false}],[":web/src/SourceCatalogBrowser.locator.test.tsx",{"duration":126.60211500000014,"failed":false}],[":web/src/sourceSettingsAudit.test.ts",{"duration":14.357719999999972,"failed":false}],[":web/src/QAModelSettings.test.tsx",{"duration":26.314527,"failed":false}],[":web/src/qaRegionSelection.test.ts",{"duration":10.417541000000028,"failed":false}],[":web/src/QAWeekPicker.test.tsx",{"duration":51.81196299999999,"failed":false}],[":web/src/qaDepartmentTree.test.ts",{"duration":32.99394199999995,"failed":false}],[":web/src/releasePlanner.test.ts",{"duration":9.93926799999997,"failed":false}],[":web/src/QAWeeklyEditor.test.tsx",{"duration":25.598812000000066,"failed":false}],[":web/src/jobs.test.ts",{"duration":12.596463999999969,"failed":false}],[":web/src/PasswordInput.test.tsx",{"duration":19.170389999999998,"failed":false}],[":web/src/qaPeriodInput.test.ts",{"duration":17.17975100000001,"failed":false}],[":web/src/qaHistoricalTrend.test.ts",{"duration":10.793980000000033,"failed":false}],[":web/src/qaSummaryExport.test.ts",{"duration":11.574117000000001,"failed":false}],[":web/src/DingtalkSourceDiscovery.test.tsx",{"duration":23.480369999999994,"failed":false}],[":web/src/FilenameFilterEditor.test.tsx",{"duration":24.150856999999974,"failed":false}],[":web/src/responsiveStyles.test.ts",{"duration":8.723348999999985,"failed":false}],[":web/src/qaRegionUsage.test.ts",{"duration":6.74253600000003,"failed":false}],[":web/src/qaDashboardLive.test.ts",{"duration":11.843148999999983,"failed":false}],[":web/src/workspaceContext.test.tsx",{"duration":19.699157000000014,"failed":false}],[":web/src/QAPeriodInput.test.tsx",{"duration":25.957416000000023,"failed":false}],[":web/src/qaLedgerDate.test.ts",{"duration":13.539719999999988,"failed":false}],[":web/src/qaLedgerWindow.test.ts",{"duration":47.41202199999998,"failed":false}],[":web/src/qaInlineFields.test.ts",{"duration":7.287382000000036,"failed":false}],[":web/src/DingtalkSessionControl.test.tsx",{"duration":19.42170500000003,"failed":false}],[":web/src/qaDashboardExport.test.ts",{"duration":9.175053000000048,"failed":false}],[":web/src/qaLedgerRendering.test.ts",{"duration":6.678890000000024,"failed":false}]]} \ No newline at end of file diff --git a/scripts/artifact_fetch.py b/scripts/artifact_fetch.py index 1c00c2e..a2ffa70 100644 --- a/scripts/artifact_fetch.py +++ b/scripts/artifact_fetch.py @@ -278,7 +278,7 @@ def pp_find_entry(manifest): def pp_download(manifest, max_bytes): entry = pp_find_entry(manifest) if entry is None: - raise MissingSource("PP ledger entry for this locator no longer exists") + entry = {} # Ledger titles may omit the extension; recover the true file name from the # local path or source URL before type checks run. manifest_name = manifest.setdefault("name", "") @@ -301,9 +301,23 @@ def pp_download(manifest, max_bytes): if expected_hash and len(expected_hash) == 64 and actual != expected_hash: raise FetchError("PP local copy hash mismatch (ledger changed?)", retryable=True, code="local_mismatch") return str(candidate), size, actual, True - url = entry.get("url", "") - if not url: - raise MissingSource("PP ledger entry has no local file and no download URL") + from pp_client import active_client, record_observation, observation, PPError + client = None + try: + client = active_client() + inventory = client.inventory(client.login()) + record_observation(client.config, observation('valid')) + except PPError as error: + if client is not None: + record_observation(client.config, observation(error.state)) + raise FetchError(str(error), retryable=error.state == 'unavailable', code='pp_' + error.state) from None + locator = manifest.get('locator_hash', '') + matches = [row for row in inventory['items'] if row.get('online') == 1 and (row.get('potalGroup') or {}).get('groupName') == '公开' and digest_of(str(row.get('fileUrl') or '').strip()) == locator] + if not matches: + raise MissingSource('PP file is no longer visible in the configured portal') + url = str(matches[0].get('fileUrl') or '').strip() + if not pathlib.PurePosixPath(manifest['name']).suffix: + manifest['name'] += pathlib.PurePosixPath(urllib.parse.unquote(urllib.parse.urlsplit(url).path)).suffix path, size, actual = http_get(url, {}, 180, max_bytes) expected_hash = str(entry.get("sha256", "")).lower() if expected_hash and len(expected_hash) == 64 and actual != expected_hash: diff --git a/scripts/check_deps_vuln.py b/scripts/check_deps_vuln.py index f1e87a9..53690fa 100644 --- a/scripts/check_deps_vuln.py +++ b/scripts/check_deps_vuln.py @@ -172,14 +172,43 @@ def npm_audit(args: list[str]) -> tuple[dict, str | None]: return {}, f"npm audit 输出解析不了(exit={p.returncode}):{(p.stdout or p.stderr)[:300]}" +def advisory_ids(vulns: dict, name: str, seen: set[str] | None = None) -> list[str]: + """收集一个包命中的 GHSA 编号,沿 via 里的依赖链向上追。 + + 为什么不能只看本包的 via:npm 对 fdir/tinyglobby/vite 这类"由于依赖了有洞的包" + 的条目,via 里只有依赖名(字符串),直接取 url 会得到空 id;空 id 的发现既没法 + 写进例外表(例外要求 id 非空),也会让排查人以为"没有具体漏洞"。追到链底才是 + 真正要豁免/修复的那条公告。 + """ + seen = seen or set() + if name in seen: + return [] + seen.add(name) + entry = vulns.get(name) + if not isinstance(entry, dict): + return [] + ids: list[str] = [] + for via in entry.get("via") or []: + if isinstance(via, dict) and via.get("url"): + ids.append(str(via["url"]).rsplit("/", 1)[-1]) + elif isinstance(via, str): + ids.extend(advisory_ids(vulns, via, seen)) + # 去重但保持稳定顺序,便于例外表逐字核对 + out: list[str] = [] + for item in ids: + if item and item not in out: + out.append(item) + return out + + def audit_findings(data: dict, scope: str) -> list[dict]: out = [] - for name, adv in (data.get("vulnerabilities") or {}).items(): + vulns = data.get("vulnerabilities") or {} + for name, adv in vulns.items(): if not isinstance(adv, dict): continue sev = str(adv.get("severity") or "").lower() - ids = [v.get("url", "").rsplit("/", 1)[-1] - for v in (adv.get("via") or []) if isinstance(v, dict) and v.get("url")] + ids = advisory_ids(vulns, name) out.append({"tool": "npm-audit", "id": ids[0] if ids else "", "package": name, "severity": sev, "scope": scope, "detail": f"isDirect={adv.get('isDirect')} range={adv.get('range')}"}) diff --git a/scripts/ci_checks.py b/scripts/ci_checks.py index 51ffcdf..bf1a1d2 100644 --- a/scripts/ci_checks.py +++ b/scripts/ci_checks.py @@ -37,7 +37,7 @@ from typing import Callable ROOT = Path(__file__).resolve().parent.parent WEB = ROOT / "web" REPORT_DEFAULT = ROOT / "ci-report.json" -POLICY_REVISION = "ci-checks/3" # 判据变更时改这里,报告里跟着变 +POLICY_REVISION = "ci-checks/5" # 判据变更时改这里,报告里跟着变 MANIFESTS = ["go.mod", "go.sum", "web/package.json", "web/package-lock.json"] SUCCESS, FAILURE, SKIPPED, NOT_RUN = "success", "failure", "skipped", "not_run" @@ -251,6 +251,13 @@ def checks() -> list[Check]: [py3, "scripts/ci_checks.py", "--internal-web-test"], env=env), Check("contracts", "版本与变更记录契约(不许 SKIP;开发构建不许自称正式版)", [py3, "scripts/ci_checks.py", "--internal-contracts", g], env=env), + # 演练判据本身也要被验:认领/决策行缺一条、只有汇总行、杀前日志都不许算通过。 + # 2026-10-29 那次演练 exit 5 就是"脚本要的老文案只有一条代码路径会打印"。 + Check("takeover-log-contract", "接管日志契约(认领/决策行判据 + 正负例自检)", + [py3, "scripts/takeover_log_contract.py", "--self-test"]), + # F12:运行镜像少 COPY 一个模块只会在真实刷新时炸;静态闭包比对进日常门禁。 + Check("runtime-scripts", "运行镜像脚本依赖闭包(缺模块负例必须红)", + [py3, "scripts/test_runtime_script_packaging.py"]), Check("version", "CHANGELOG 与版本记录(四类小节无空栏目 + 正式 tag 与提交内版本一致)", [py3, "scripts/check_changelog.py", "--tags"]), Check("security-secrets", "密钥泄漏扫描(含扫描器自检)", @@ -353,9 +360,88 @@ def cmd_internal_web_test() -> int: return 0 if status == SUCCESS and p.returncode == 0 else 1 +CONTRACT_PASS_TESTS = ("TestNumberMatchesChangelog", "TestDevBuildDoesNotClaimRelease") +# 负例必须失败在**预期断言**上。下面这些标记说明失败来自编译/网络/工具链: +# 那种 rc!=0 什么也不能证明(构建坏了也会非 0),不能拿它当"断言真的活着"。 +CONTRACT_INFRA_MARKERS = ( + "build failed", "cannot find package", "no required module provides", "undefined:", + "no such host", "dial tcp", "i/o timeout", "tls handshake timeout", "network is unreachable", + "connection refused", "signal: killed", "permission denied", "go: downloading", +) + + +def judge_contract_positive(rc: int, text: str, tests: tuple[str, ...] = CONTRACT_PASS_TESTS) -> tuple[bool, str]: + """正向:**进程成功** + 每个必需测试真 PASS + 没有失败事件。 + + 只看 `--- PASS: X` 是不够的:同一进程里别的测试失败时 go test 仍会打印 + 指定测试的 PASS 行,退出码却是非 0。那种"两个 PASS"证明不了这一轮测试成功 + (F19 的原始缺陷:383 行拿到 rc1 却没用来判断)。 + """ + if rc != 0: + return False, f"正向测试进程退出码 {rc} != 0:指定测试的 PASS 行不能证明这一轮测试成功" + if "--- FAIL:" in text: + failed = [line.strip() for line in text.splitlines() if line.strip().startswith("--- FAIL:")] + return False, f"正向测试里有失败事件:{failed[:3]}" + if re.search(r"^FAIL\b", text, re.M): + return False, "正向测试包整体 FAIL" + for name in tests: + if f"--- SKIP: {name}" in text: + return False, f"{name} 被跳过(跳过不算通过)" + if f"--- PASS: {name}" not in text: + return False, f"{name} 没有真正 PASS(被 SKIP 或没跑到)" + return True, "进程退出码 0,且每个必需测试都真的 PASS" + + +def judge_contract_negative(rc: int, text: str, expected: str = "TestDevBuildDoesNotClaimRelease") -> tuple[bool, str]: + """负例:必须非 0,且失败归因于**预期断言**,不是编译/网络等基础设施错误。""" + if rc == 0: + return False, "负例竟然通过:这条断言是死的" + lowered = text.lower() + for marker in CONTRACT_INFRA_MARKERS: + if marker in lowered: + return False, f"负例因基础设施/编译问题失败(命中 {marker!r}),不能算预期断言生效" + if f"--- FAIL: {expected}" not in text: + return False, f"负例没有失败在预期断言 {expected} 上(没有它的 FAIL 行)" + return True, f"负例非 0 且失败在 {expected}" + + +def contract_judgement_problems() -> list[str]: + """判据本身的**反例自检**:这些分支必须由函数判定,不能靠远端 CI 碰巧没有别的问题。 + + verify 的 contracts 每一步都会先跑它,所以"判据被改坏"在本地就会红, + 而不是等到某天真的出现"进程非 0 但两个 PASS"时才静默放行。 + """ + passes = ("--- PASS: TestNumberMatchesChangelog\n" + "--- PASS: TestDevBuildDoesNotClaimRelease\n") + cases = [ + ("正向 rc=0 且两个 PASS ⇒ 绿", judge_contract_positive(0, passes)[0], True), + ("正向 rc=1 但两个 PASS 都在 ⇒ 仍要红(F19 原始缺陷)", + judge_contract_positive(1, passes + "--- FAIL: TestSomethingElse\n")[0], False), + ("正向 rc=1、PASS 齐全、无 FAIL 行 ⇒ 仍要红", + judge_contract_positive(1, passes)[0], False), + ("正向缺必需 PASS ⇒ 红", judge_contract_positive(0, "--- FAIL:\n")[0], False), + ("正向必需测试被 SKIP ⇒ 红", + judge_contract_positive(0, "--- SKIP: TestDevBuildDoesNotClaimRelease\n")[0], False), + ("负例 rc=0 ⇒ 红", judge_contract_negative(0, "PASS\n")[0], False), + ("负例失败在预期断言 ⇒ 绿", + judge_contract_negative(1, "--- FAIL: TestDevBuildDoesNotClaimRelease\n")[0], True), + ("负例因编译错误非 0 ⇒ 红", + judge_contract_negative(1, "build failed: undefined: foo\n")[0], False), + ("负例因网络错误非 0 ⇒ 红", + judge_contract_negative(1, "dial tcp 10.0.0.1:443: i/o timeout\n")[0], False), + ("负例非 0 但没有预期断言的 FAIL 行 ⇒ 红", + judge_contract_negative(1, "--- FAIL: TestOther\n")[0], False), + ] + return [f"版本契约判据:{name} 期望 {want},实际 {got}" for name, got, want in cases if got != want] + + def cmd_internal_contracts(go: str) -> int: """版本契约:结构 + 注入身份必须**真 PASS**(SKIP 判红), - 并且**开发构建不许自称正式版**(负例:标成 release ⇒ 必须红)。""" + 并且**开发构建不许自称正式版**(负例:标成 release ⇒ 必须红且红在预期断言上)。 + + 判据同时核三件事:进程退出码、必需测试集合、负例失败归因—— + 缺任意一件,"绿"就可能是别的测试失败/编译错误伪装出来的。 + """ qa_rc = subprocess.run(py("-m", "unittest", "discover", "-s", "scripts", "-p", "test_qa_env.py", "-v"), cwd=ROOT).returncode if qa_rc: @@ -367,6 +453,10 @@ def cmd_internal_contracts(go: str) -> int: snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode if snapshot_rc: return 1 + judgement = contract_judgement_problems() + if judgement: + print(f"❌ 版本契约判据本身不成立:{judgement}", file=sys.stderr) + return 1 rc = subprocess.run(py("scripts/check_changelog.py"), cwd=ROOT).returncode if rc: return 1 @@ -376,7 +466,7 @@ def cmd_internal_contracts(go: str) -> int: return 1 print(f"-- 版本契约:显示版本 {ident['display_version']}({ident['build_kind']}" f"|release_version={ident['release_version']!r})--") - tests = ("TestNumberMatchesChangelog", "TestDevBuildDoesNotClaimRelease") + tests = CONTRACT_PASS_TESTS def run(ld: str) -> tuple[int, str]: p = subprocess.run([go, "test", f"-ldflags={ld}", "-count=1", "-run", "Test", "-v", "-json", @@ -386,28 +476,25 @@ def cmd_internal_contracts(go: str) -> int: rc1, text = run(ldflags_for(ident)) print(text[-2000:], end="") - # ⚠️ 被跳过的断言等于没有断言:必须看到 PASS,SKIP 一律判红。 - # 用 in 而不是 `| grep -q`:pipefail 下 grep -q 会因 SIGPIPE 谎报失败(trap-7)。 - for name in tests: - if f"--- PASS: {name}" not in text: - print(f"❌ 版本契约 {name} 没有真正 PASS(被 SKIP 或没跑到)—— " - f"缺 -ldflags,或 CHANGELOG / 构建身份有问题", file=sys.stderr) - return 1 - if f"--- SKIP: {name}" in text: - print(f"❌ 版本契约 {name} 被跳过(构建身份没注入)—— 跳过不算通过", file=sys.stderr) - return 1 + ok, why = judge_contract_positive(rc1, text, tests) + if not ok: + print(f"❌ 版本契约不成立:{why} —— 缺 -ldflags,或 CHANGELOG / 构建身份有问题", + file=sys.stderr) + return 1 # 负例:把开发构建标成正式版(ReleaseVersion 指向 CHANGELOG 里没有的号)⇒ **必须红**。 # 没有这条,"开发版沿用正式版号"这个病会静默回归。 + # 而且必须红在**预期断言**上:编译错误也会非 0,那种"红"证明不了断言活着。 bogus = "9.9.9" if ident.get("release_version") != "9.9.9" else "8.8.8" - rc2, _ = run(ldflags_for(ident, build_kind="release", release_version=bogus)) - if rc2 == 0: - print(f"❌ 把构建标成正式版(BuildKind=release / ReleaseVersion={bogus})竟然还是绿的 —— " - f"这条断言是死的", file=sys.stderr) + rc2, text2 = run(ldflags_for(ident, build_kind="release", release_version=bogus)) + print(text2[-2000:], end="") + ok, why = judge_contract_negative(rc2, text2, "TestDevBuildDoesNotClaimRelease") + if not ok: + print(f"❌ 负例不合格:{why}", file=sys.stderr) return 1 - print(f"-- 负例确认:自称正式版({bogus})⇒ 红 ✓ --") + print(f"-- 负例确认:自称正式版({bogus})⇒ 红于预期断言 ✓ --") print("✅ 版本契约成立:注入 == CHANGELOG 顶部(没有正式版本时为空)," - "开发构建带 dev 标识,且断言真的执行了") + "开发构建带 dev 标识,进程退出码与断言归因都已核对") return 0 @@ -447,6 +534,8 @@ CHECK_MANIFEST: dict[str, tuple[str, ...]] = { "tests-go": ("local", "ci"), "tests-web": ("local", "ci"), "contracts": ("local", "ci"), + "takeover-log-contract": ("local", "ci"), + "runtime-scripts": ("local", "ci"), "version": ("local", "ci"), "security-secrets": ("local", "ci"), "security-deps": ("local", "ci"), @@ -541,13 +630,16 @@ def self_test() -> int: # 完整 SHA 的形状 if not FULL_SHA.match("a" * 40) or FULL_SHA.match("a" * 12): problems.append("完整 SHA 的形状判定不对(12 位短 sha 必须判为不完整)") + # 版本契约判据的反例(F19)——与 verify 里 contracts 那一步共用同一份逻辑 + problems.extend(contract_judgement_problems()) if problems: print("❌ 汇总逻辑自检失败:", file=sys.stderr) for p in problems: print(f" · {p}", file=sys.stderr) return 1 - print(f"✅ 汇总逻辑自检通过:{len(cases)} 个分支" - f"(含'必需项未运行/被跳过/缺失/重复/未知项都不得报全绿')+ 清单一致性 + 完整 SHA 形状") + print(f"✅ 汇总逻辑自检通过:{len(cases)} 个汇总分支" + f"(含'必需项未运行/被跳过/缺失/重复/未知项都不得报全绿')" + f" + 10 个版本契约判据反例 + 清单一致性 + 完整 SHA 形状") return 0 diff --git a/scripts/library-capture-v090.sh b/scripts/library-capture-v090.sh new file mode 100755 index 0000000..d32fdf6 --- /dev/null +++ b/scripts/library-capture-v090.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Whole-library capture entry point for the RDS-backed WeKnora 0.9.0 test stack +# (Compose project weknora-v090). +# +# Why a separate file instead of a parameterised one: this stack has no source +# PostgreSQL container and no governance PostgreSQL container. Both databases are +# managed instances (RDS). -source-pg / -governance-pg are therefore passed empty, +# which is libraryctl's documented signal to resolve them from the source app +# container env (DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD + LIBRARY_SOURCE_DB_SSLMODE) +# and from LIBRARY_GOVERNANCE_DSN_FILE (0600 file). Keeping the 0.7.1 entry point +# untouched means a change here can never alter a stack that already ran. +# +# Every service of the Compose project is declared below: exactly one writer (app) +# and a reason for each sibling which must NOT be stopped. ProjectController +# refuses to run if the project gains a service that is not declared here, so a +# new container cannot be silently left outside the maintenance window. +# +# Credentials are read at call time (container env / 0600 file) and are never +# printed. Nothing here writes to the source stack except SIGTERM/SIGSTART of the +# declared writer. +set -euo pipefail + +# The binary is pinned by the caller on purpose: there is no "whatever is in this +# directory" fallback, so a stale build next to the script cannot be executed by +# accident against a live stack. +BIN="${LIBRARYCTL_BIN:-}" +if [ -z "$BIN" ]; then + echo "LIBRARYCTL_MISSING: set LIBRARYCTL_BIN to the libraryctl binary built for this run" >&2 + exit 1 +fi +if [ ! -x "$BIN" ]; then + echo "LIBRARYCTL_NOT_EXECUTABLE: $BIN is not an executable file" >&2 + exit 1 +fi + +# Archives/journals live outside the home directory on this host (they survive the +# operator account); both roots stay overridable for an isolated rehearsal. +ARCHIVE_ROOT="${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}" +JOURNAL_ROOT="${LIBRARY_JOURNAL_ROOT:-/var/lib/knowledge-governance/freeze}" + +# Reasons must not contain commas: the flag is comma-separated. +NON_WRITERS="frontend=UI only; no knowledge writes" +NON_WRITERS+=",docreader=parse RPC service; app persists parse output" +NON_WRITERS+=",elasticsearch=search store; not an initiator" +NON_WRITERS+=",redis=queue/cache store; not an initiator" + +exec "$BIN" "$@" \ + -project weknora-v090 \ + -writers app \ + -source-app weknora-v090-app \ + -source-es weknora-v090-elasticsearch \ + -source-pg "" \ + -governance-pg "" \ + -non-writers "$NON_WRITERS" \ + -archive "$ARCHIVE_ROOT" \ + -journal "$JOURNAL_ROOT" \ No newline at end of file diff --git a/scripts/library-kill-takeover.sh b/scripts/library-kill-takeover.sh new file mode 100755 index 0000000..cacea09 --- /dev/null +++ b/scripts/library-kill-takeover.sh @@ -0,0 +1,851 @@ +#!/usr/bin/env bash +# library-kill-takeover.sh —— 真实 worker 中断演练(只在本机测试栈) +# +# 判据只有一条:**真的把 worker 进程 SIGKILL 掉(exit 137)→ 同一个作业被认领并 +# 真跑完写入链路 → 目标按该快照的期望内容恢复并校验 → 服务/入口恢复**,全成立才 exit 0。 +# missed / notrun / timeout / 只同快照收尾 一律非 0,并在 evidence 里写成 not_run 而不是"通过"。 +# +# ⚠️ 2026-10-29T19:56Z 这次真演练(exit 5)教会两件事,都是判据缺陷: +# 1) 脚本要的文案 `library job resumed after worker restart` 只有"新建队列行" +# 那条代码路径会打印;真实走的是"队列行已存在"那条。于是 worker 只留下汇总行 +# `library job takeover sweep: 1 resumed`,脚本判不出是哪个作业、也判不出它是否被认领。 +# 现在改由 scripts/takeover_log_contract.py 判**认领行 + 决策行**(都带作业 id 与 +# target/backup,且时间戳必须晚于杀点);只有汇总行/别的作业/杀前日志一律不算证据。 +# 2) 老判据要求 `prebackup:skipped`。真实接管是"复用崩溃前那份预备份重跑整条链路", +# 阶段会写成 succeeded(release.go 记的是"预备份 ")。**不能因此取消备份校验**: +# 现在要求预备份快照身份与崩溃前一致、清单文件字节/mtime 未变、版本行 created_at +# 仍是首次登记时刻(复用而非重做),写集合摘要也不变。 +# +# 为什么不再用 `docker kill`: +# docker kill/stop 走 Docker API 的"手动停止",restart policy 不生效(`unless-stopped` +# 也不生效),容器就一直躺着。2026-10-29T19:16Z 的现场就是这样:脚本等了 420s 判失败, +# 最后由人工 `docker start` 才接管。那不是"崩溃自恢复",只是"有人按了开始"。 +# 现在的命中手段是**宿主机向容器 PID1 发 SIGKILL**(同一 uid 才允许):这才是进程崩溃, +# Docker 看到的是进程死亡 ⇒ restart policy 按策略拉起,语义与真实故障一致。 +# 若策略没在限期内拉起,脚本可以显式 `docker start`,但必须在 evidence 里记成 +# restart_source=manual_start,**不许**算成"自动恢复"。 +# +# 命中点位仍是"固定同步屏障"(internal/testbarrier,默认关闭,仅本机注入): +# worker 在指定阶段写完后写 /after-database.hit 并停住 → 本脚本看到 .hit +# → SIGKILL → 按策略重启/显式拉起 → 启动扫描认领同一作业。 +# 屏障目录在本机归档根下(/barrier),没人放行就自行继续(记 not_run)。 +# +# 期望内容按**目标快照自己的 manifest** 取(knowledges/chunks/wiki_pages),不是写死 +# 4/38/31:同一个脚本既能跑 sync 也能跑 restore,期望随快照变。resources 不进默认 +# 期望——同租户其它知识库的资源不在预备份范围内(trap-16),目标里会保留它们。 +# +# 用法: +# bash scripts/library-kill-takeover.sh --check # 前置体检(不是演练通过) +# bash scripts/library-kill-takeover.sh --run --scope internal --confirm-kill \ +# --kind restore --snapshot <目标快照 id> +# → 打印 ARMED 后,父在页面上发起该作业;脚本自己命中、杀、验证、收尾 +# bash scripts/library-kill-takeover.sh --restore # 撤掉屏障注入 +# 可选:--kind sync|restore|auto(默认 auto,给了就强校验作业类型) +# --snapshot (校验命中的作业目标就是它) +# --job <业务作业 id>|--since +# --expect "knowledges=..,chunks=..,wiki_pages=.."(覆盖 manifest 推导) +# --expect-decision fresh|pending_final(默认 fresh;at after:database 之后 +# 只能是 fresh——pending_final 等于"只差收尾",正是上一轮的假完成) +# --allow-same-snapshot(允许目标快照 == 中断前生效版本;这条**不能**当完整续作验收) +# --manual-start 0|1(策略未拉起时是否显式 docker start,默认 1) +# +set -uo pipefail + +SCRIPT_VERSION=4 +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MODE="" +SCOPE="internal" +KIND="auto" +EXPECT_SNAPSHOT="" +EXPECT_JOB="" +SINCE="" +CONFIRM_KILL=0 +ALLOW_SAME_SNAPSHOT=0 +MANUAL_START=1 +EXPECT_DECISION="${EXPECT_DECISION:-fresh}" +EXPECT_COUNTS="${EXPECT_COUNTS:-}" +VERIFIER="${WRITESET_VERIFIER:-$HOME/.hermes/handoffs/release-current-version-takeover/verify-writeset}" +LOG_CONTRACT="${TAKEOVER_LOG_CONTRACT:-$SCRIPT_DIR/takeover_log_contract.py}" + +WORKER_CONTAINER="${WORKER_CONTAINER:-knowledge-governance-p1-worker-1}" +GOV_DB_CONTAINER="${GOV_DB_CONTAINER:-knowledge-governance-p1-postgres-1}" +GOV_DB_USER="${GOV_DB_USER:-governance}" +GOV_DB_NAME="${GOV_DB_NAME:-governance}" +COMPOSE_PROJECT="${COMPOSE_PROJECT:-knowledge-governance-p1}" +COMPOSE_SERVICE="${COMPOSE_SERVICE:-worker}" +BARRIER_POINT="${BARRIER_POINT:-after:database}" +BARRIER_TIMEOUT="${BARRIER_TIMEOUT:-300s}" +HIT_WAIT_S="${HIT_WAIT_S:-900}" +KILL_PROOF_S="${KILL_PROOF_S:-30}" +POLICY_RESTART_WAIT_S="${POLICY_RESTART_WAIT_S:-20}" +RESTART_WAIT_S="${RESTART_WAIT_S:-90}" +TAKEOVER_WAIT_S="${TAKEOVER_WAIT_S:-420}" +DRILL_HOME="${DRILL_HOME:-$HOME/.local/share/knowledge-governance/drills}" + +while [ $# -gt 0 ]; do + case "$1" in + --check) MODE=check ;; + --run) MODE=run ;; + --restore) MODE=restore ;; + --scope) SCOPE="${2:-}"; shift ;; + --kind) KIND="${2:-}"; shift ;; + --snapshot) EXPECT_SNAPSHOT="${2:-}"; shift ;; + --job) EXPECT_JOB="${2:-}"; shift ;; + --since) SINCE="${2:-}"; shift ;; + --expect) EXPECT_COUNTS="${2:-}"; shift ;; + --expect-decision) EXPECT_DECISION="${2:-}"; shift ;; + --point) BARRIER_POINT="${2:-}"; shift ;; + --manual-start) MANUAL_START="${2:-}"; shift ;; + --allow-same-snapshot) ALLOW_SAME_SNAPSHOT=1 ;; + --confirm-kill) CONFIRM_KILL=1 ;; + -h|--help) sed -n '1,42p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 64 ;; + esac + shift +done + +if [ -z "$MODE" ]; then + echo "must pass one of --check | --run | --restore" >&2 + exit 64 +fi +case "$KIND" in + auto|sync|restore) ;; + *) echo "--kind must be auto|sync|restore (got $KIND)" >&2; exit 64 ;; +esac +case "$MANUAL_START" in + 0|1) ;; + *) echo "--manual-start must be 0|1" >&2; exit 64 ;; +esac +case "$EXPECT_DECISION" in + fresh|pending_final) ;; + *) echo "--expect-decision must be fresh|pending_final (got $EXPECT_DECISION)" >&2; exit 64 ;; +esac + +# set -u:所有跨函数使用的变量先给默认值 +WORKER_IMAGE_ID="" +WORKER_IMAGE="" +WORKER_CONTAINER_ID="" +ARCHIVE_ROOT_IN_CONTAINER="" +ARCHIVE_HOST="" +BARRIER_HOST="" +TARGET_INSTANCE="" +TARGET_PROJECT="" +TARGET_INGRESS_SERVICE="" +TARGET_WRITERS="" +INGRESS_CONTAINER="" +TARGET_DB_CONTAINER="" +TARGET_DB_USER="" +TARGET_DB_NAME="" +HIT_SUBJECT="" +JOB_ID="" +JOB_STATE="" +JOB_SCOPE="" +JOB_KIND="" +JOB_SNAPSHOT="" +JOB_TARGET="" +JOB_CREATED="" +PRE_EFFECTIVE="" +WS_DIGEST="" +WS_REUSED="" +WS_TARGET="" +WS_BACKUP="" +WS_FILE="" +WS_FILE_SHA="" +WS_BACKUP_SHA="" +WS_BACKUP_MTIME="" +WS_BACKUP_CREATED="" +WS_REUSED="" +DECISION="" +CLAIM_AT="" +LOG_RAW="" +KILLED_AT="" +KILL_PID="" +KILL_PROOF="" +RESTART_SOURCE="" +RESTART_COUNT_BEFORE="" +EVENTS_PID="" +STATUS_OVERRIDE="" +ARMED=0 +COMPOSE_ARGS=() + +STAMP="$(date -u +%Y%m%dT%H%M%SZ)" +EVIDENCE="$DRILL_HOME/$STAMP" +mkdir -p "$EVIDENCE" || { echo "cannot create evidence dir $EVIDENCE" >&2; exit 70; } +CHECKS="$EVIDENCE/checks.tsv" +: >"$CHECKS" + +log() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" | tee -a "$EVIDENCE/phases.log"; } +# record +record() { + printf '%s\t%s\t%s\n' "$1" "$2" "${3:-}" >>"$CHECKS" + log "CHECK $1 = $2${3:+ ($3)}" +} +die() { # die + record "$2" fail "$3" + log "ABORT: $2 — $3" + finish "$1" +} + +# ---------- 小工具 ---------- +worker_env() { # 只读非敏感变量 + docker inspect "$WORKER_CONTAINER" --format '{{range .Config.Env}}{{println .}}{{end}}' 2>/dev/null | + sed -n "s/^$1=//p" | head -1 +} +gov_sql() { docker exec "$GOV_DB_CONTAINER" psql -U "$GOV_DB_USER" -d "$GOV_DB_NAME" -Atc "$1" 2>>"$EVIDENCE/psql.log"; } +container_field() { docker inspect "$1" --format "$2" 2>/dev/null; } +archive_root_host() { + docker inspect "$WORKER_CONTAINER" --format '{{range .Mounts}}{{.Destination}}={{.Source}}{{println}}{{end}}' 2>/dev/null | + sed -n "s#^$1=##p" | head -1 +} +container_of_service() { # + docker ps -a --filter "label=com.docker.compose.project=$1" \ + --format '{{.Names}}|{{.Label "com.docker.compose.service"}}' | awk -F'|' -v svc="$2" '$2==svc{print $1; exit}' +} +health_of() { + local status + status="$(docker inspect "$1" --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}no_healthcheck{{end}}' 2>/dev/null)" + echo "${status:-unknown}" +} +url_part() { # + case "$2" in + user) sed -E 's#^[a-zA-Z0-9+]+://([^:/@]+).*#\1#' <<<"$1" ;; + host) sed -E 's#^[a-zA-Z0-9+]+://[^@]*@([^:/]+).*#\1#' <<<"$1" ;; + db) sed -E 's#^[a-zA-Z0-9+]+://[^/]+/([^?]+).*#\1#' <<<"$1" ;; + *) echo "" ;; + esac +} +now_epoch() { date -u +%s; } +utc_now() { date -u +%Y-%m-%dT%H:%M:%SZ; } + +# 目标快照自己的期望内容:只认归档里的 manifest(不写死 4/38/31)。 +# resources 故意不进默认期望:同租户其它知识库的资源不在预备份范围(trap-16), +# 目标里会保留它们,把 21 写成期望就会永远红。 +snapshot_expectations() { # + python3 - "$ARCHIVE_HOST/versions/$1.json" "$SCOPE" <<'PY' +import json, sys, pathlib +path, scope = sys.argv[1], sys.argv[2] +try: + manifest = json.loads(pathlib.Path(path).read_text(encoding="utf-8")) +except Exception as exc: + sys.exit("读不到目标快照 manifest(%s):%s" % (path, exc)) +if manifest.get("format") != "weknora-library-snapshot/v1": + sys.exit("manifest format=%r 不是 weknora-library-snapshot/v1" % manifest.get("format")) +if manifest.get("scope") != scope: + sys.exit("manifest scope=%r 与请求 %r 不一致" % (manifest.get("scope"), scope)) +counts = {p["name"]: p["count"] for p in manifest.get("parts", []) if p.get("kind") == "database"} +for table in ("knowledges", "chunks"): + if table not in counts: + sys.exit("manifest 缺少 database.%s:不能推导期望" % table) +wiki = [p["count"] for p in manifest.get("parts", []) if p.get("kind") == "wiki" and p.get("name") == "wiki_pages"] +print("knowledges=%d,chunks=%d,wiki_pages=%d" % (counts["knowledges"], counts["chunks"], wiki[0] if wiki else 0)) +PY +} + +finish() { # finish + local code="$1" status="PASS" + if [ -n "$EVENTS_PID" ]; then kill "$EVENTS_PID" 2>/dev/null; fi + if grep -q $'\tfail\t' "$CHECKS" 2>/dev/null; then status="FAIL"; fi + if grep -q $'\tnot_run\t' "$CHECKS" 2>/dev/null && [ "$code" -eq 0 ]; then status="FAIL"; fi + [ -n "$STATUS_OVERRIDE" ] && status="$STATUS_OVERRIDE" + cp "$CHECKS" "$EVIDENCE/checks.snapshot.tsv" 2>/dev/null + cat >"$EVIDENCE/summary.json" </dev/null 2>&1 || die 2 preflight_docker "docker 命令不可用" + docker info >/dev/null 2>&1 || die 2 preflight_docker "docker daemon 不可用" + docker compose version >/dev/null 2>&1 || die 2 preflight_docker "docker compose 不可用" + command -v python3 >/dev/null 2>&1 || die 2 preflight_docker "python3 不可用(推导期望内容要用)" + record preflight_docker pass "docker + compose + python3 可用" + + docker inspect "$WORKER_CONTAINER" >/dev/null 2>&1 || die 2 preflight_worker "worker 容器不存在:$WORKER_CONTAINER" + WORKER_IMAGE_ID="$(container_field "$WORKER_CONTAINER" '{{.Image}}')" + WORKER_IMAGE="$(container_field "$WORKER_CONTAINER" '{{.Config.Image}}')" + WORKER_CONTAINER_ID="$(container_field "$WORKER_CONTAINER" '{{.Id}}')" + local running + running="$(container_field "$WORKER_CONTAINER" '{{.State.Running}}')" + [ "$running" = "true" ] || die 2 preflight_worker "worker 没在运行(先把它起回来)" + record preflight_worker pass "image=$WORKER_IMAGE id=$WORKER_IMAGE_ID running=$running" + + # 仅本机:worker 连的治理库必须就是本机这个容器(拒绝把屏障注入到远程栈)。 + local gov_host + gov_host="$(url_part "$(worker_env DATABASE_URL)" host)" + [ "$gov_host" = "$GOV_DB_CONTAINER" ] || die 2 preflight_local_only \ + "worker 连的治理库是 ${gov_host:-?},不是本机 $GOV_DB_CONTAINER:拒绝在非本机栈注入屏障" + [ "$(gov_sql 'select 1')" = "1" ] || die 2 preflight_gov_db "治理库读不到($GOV_DB_CONTAINER/$GOV_DB_NAME)" + record preflight_local_only pass "governance db=$GOV_DB_CONTAINER" + + ARCHIVE_ROOT_IN_CONTAINER="$(worker_env LIBRARY_ARCHIVE_ROOT)" + [ -n "$ARCHIVE_ROOT_IN_CONTAINER" ] || die 2 preflight_archive "worker 没有 LIBRARY_ARCHIVE_ROOT" + ARCHIVE_HOST="$(archive_root_host "$ARCHIVE_ROOT_IN_CONTAINER")" + { [ -n "$ARCHIVE_HOST" ] && [ -d "$ARCHIVE_HOST" ]; } || die 2 preflight_archive "归档根在宿主机上找不到(容器内 $ARCHIVE_ROOT_IN_CONTAINER)" + [ -d "$ARCHIVE_HOST/writesets" ] || die 2 preflight_archive "归档根下没有 writesets/:台账不在预期位置" + [ -d "$ARCHIVE_HOST/versions" ] || die 2 preflight_archive "归档根下没有 versions/:快照清单不在预期位置" + [ -w "$ARCHIVE_HOST" ] || die 2 preflight_archive "归档根宿主机路径不可写:$ARCHIVE_HOST" + BARRIER_HOST="$ARCHIVE_HOST/barrier" + record preflight_archive pass "archive=$ARCHIVE_HOST barrier=$BARRIER_HOST" + + # --restore 只负责把注入撤掉:它必须能在"上一轮没有收尾"(甚至还有作业在飞)时也跑通, + # 否则 preflight_not_armed 会把它自己锁死(实测过)。 + if [ "$MODE" = "restore" ]; then + record preflight_done pass "restore 模式:只校验 docker/worker/归档根,不检查在飞作业与维护窗口" + return 0 + fi + + TARGET_INSTANCE="$(worker_env LIBRARY_TARGET_INSTANCE)" + TARGET_PROJECT="$(worker_env LIBRARY_TARGET_PROJECT)" + TARGET_INGRESS_SERVICE="$(worker_env LIBRARY_TARGET_INGRESS_SERVICE)" + TARGET_WRITERS="$(worker_env LIBRARY_TARGET_WRITERS)" + [ -n "$TARGET_INSTANCE" ] || die 2 preflight_topology "worker 没有 LIBRARY_TARGET_INSTANCE(维护目标未接线)" + [ -n "$TARGET_PROJECT" ] || die 2 preflight_topology "worker 没有 LIBRARY_TARGET_PROJECT" + docker inspect "$TARGET_INSTANCE" >/dev/null 2>&1 || die 2 preflight_topology "目标写入者容器缺失:$TARGET_INSTANCE" + INGRESS_CONTAINER="$(container_of_service "$TARGET_PROJECT" "$TARGET_INGRESS_SERVICE")" + [ -n "$INGRESS_CONTAINER" ] || die 2 preflight_topology "目标项目 $TARGET_PROJECT 下找不到入口服务 $TARGET_INGRESS_SERVICE" + local instance_running + instance_running="$(container_field "$TARGET_INSTANCE" '{{.State.Running}}')" + [ "$instance_running" = "true" ] || die 2 preflight_topology \ + "目标写入者 $TARGET_INSTANCE 没在运行:先按预备份恢复并收尾,再来演练" + record preflight_topology pass "instance=$TARGET_INSTANCE running=$instance_running project=$TARGET_PROJECT writers=$TARGET_WRITERS ingress=$INGRESS_CONTAINER" + + local held held_instance + held="$(gov_sql "select count(*) from library_maintenance where released_at is null")" + held_instance="$(gov_sql "select count(*) from library_instance_maintenance where released_at is null")" + if [ "$held" != "0" ] || [ "$held_instance" != "0" ]; then + local owner + owner="$(gov_sql "select coalesce(owner_job_id,'?') from library_maintenance where released_at is null limit 1")" + die 2 preflight_no_open_window "已有未释放的维护窗口(owner=${owner:-?} scope=$held instance=$held_instance):先恢复/收尾" + fi + record preflight_no_open_window pass "no unreleased maintenance" + + local in_flight queued + in_flight="$(gov_sql "select coalesce(string_agg(id||'/'||state, ','),'') from library_jobs where state in ('pending','running')")" + [ -z "$in_flight" ] || die 2 preflight_no_inflight "已有在飞的整库作业:$in_flight(一次只演练一个作业)" + queued="$(gov_sql "select count(*) from jobs where type like 'library.%' and state in ('pending','running','retry')")" + [ "$queued" = "0" ] || die 2 preflight_no_inflight "队列里还有 $queued 个 library.* 作业在飞/排队" + record preflight_no_inflight pass "no in-flight library jobs" + + # 镜像必须真的带屏障代码:只拷脚本不换镜像,等待会永远落空(旧脚本的病)。 + local supported + supported="$(docker run --rm --entrypoint grep "$WORKER_IMAGE_ID" -ac KG_TEST_BARRIER_DIR /app/worker 2>/dev/null | tr -dc '0-9')" + [ "${supported:-0}" -ge 1 ] || die 2 preflight_barrier_supported \ + "镜像 $WORKER_IMAGE 里没有屏障代码(grep KG_TEST_BARRIER_DIR=${supported:-0}):先部署带屏障的 worker 镜像" + record preflight_barrier_supported pass "image $WORKER_IMAGE contains barrier" + + local target_db_url + target_db_url="$(worker_env LIBRARY_PRODUCTION_DATABASE_URL)" + TARGET_DB_CONTAINER="$(url_part "$target_db_url" host)" + TARGET_DB_USER="$(url_part "$target_db_url" user)" + TARGET_DB_NAME="$(url_part "$target_db_url" db)" + [ -n "$TARGET_DB_CONTAINER" ] || die 2 preflight_target_db "worker 没有 LIBRARY_PRODUCTION_DATABASE_URL:无法独立核对目标内容" + docker inspect "$TARGET_DB_CONTAINER" >/dev/null 2>&1 || die 2 preflight_target_db "目标库容器不存在:$TARGET_DB_CONTAINER" + record preflight_target_db pass "target db=$TARGET_DB_CONTAINER/$TARGET_DB_NAME user=$TARGET_DB_USER" + + # 独立写集合校验器缺失 ⇒ 失败。上一版在缺失时把 canonical 记成 not_run 还 pass, + # 等于"没有校验也算校验过"。 + if [ ! -x "$VERIFIER" ]; then + die 2 preflight_verifier "写集合独立校验器不存在或不可执行:$VERIFIER(缺校验不许当通过;用 WRITESET_VERIFIER 指向它)" + fi + record preflight_verifier pass "verifier=$VERIFIER" + + # 判据本身也要被验:脚本缺失或自检红,演练中途就只能靠人肉判断了。 + [ -f "$LOG_CONTRACT" ] || die 2 preflight_log_contract "接管日志判据脚本不存在:$LOG_CONTRACT" + python3 "$LOG_CONTRACT" --self-test >>"$EVIDENCE/log-contract.log" 2>&1 || die 2 preflight_log_contract \ + "接管日志判据自检没通过(见 log-contract.log):判据坏了不许当演练通过" + record preflight_log_contract pass "contract=$LOG_CONTRACT self-test=ok" + + [ -z "$(worker_env KG_TEST_BARRIER_DIR)" ] || die 2 preflight_not_armed \ + "worker 已经带着屏障注入在跑(上一轮没收尾):先 --restore" + record preflight_not_armed pass "barrier not armed" + + if [ -n "$EXPECT_JOB" ]; then + case "$EXPECT_JOB" in + libsync-*|librestore-*|libbase-*) ;; + *) die 2 preflight_job_arg "--job 不是整库作业 id:$EXPECT_JOB" ;; + esac + fi + if [ -n "$EXPECT_SNAPSHOT" ]; then + [ "${#EXPECT_SNAPSHOT}" -ge 16 ] || die 2 preflight_job_arg "--snapshot 不像快照 id:$EXPECT_SNAPSHOT" + fi + record preflight_done pass "OK" +} + +# ---------- 屏障注入 / 撤销 ---------- +compose_argv() { # + local override="$1" cfg project_dir file + cfg="$(container_field "$WORKER_CONTAINER" '{{index .Config.Labels "com.docker.compose.project.config_files"}}')" + [ -n "$cfg" ] || { echo "worker 不是 compose 起的:找不到 config_files 标签" >&2; return 1; } + project_dir="$(container_field "$WORKER_CONTAINER" '{{index .Config.Labels "com.docker.compose.project.working_dir"}}')" + COMPOSE_ARGS=(-p "$COMPOSE_PROJECT") + [ -n "$project_dir" ] && COMPOSE_ARGS+=(--project-directory "$project_dir") + while IFS= read -r file; do + # 注入用的 overlay 会被 compose 记进容器的 config_files 标签;原样重放就等于 + # 自己把注入又加回去(实测 --restore 撤不掉)。这里按文件名排除演练 overlay。 + case "$file" in + ""|*/barrier.override.yaml) continue ;; + esac + COMPOSE_ARGS+=(-f "$file") + done < <(tr ',' '\n' <<<"$cfg") + [ -n "$override" ] && COMPOSE_ARGS+=(-f "$override") + return 0 +} + +write_override() { + cat >"$EVIDENCE/barrier.override.yaml" <&1 | grep -q "worker-1 started"; then + return 0 + fi + sleep 1 + done + return 1 +} + +arm_barrier() { + rm -rf "$BARRIER_HOST" + mkdir -p "$BARRIER_HOST" || die 2 arm_barrier "屏障目录建不出来:$BARRIER_HOST" + write_override + compose_argv "$EVIDENCE/barrier.override.yaml" || die 2 arm_barrier "compose 配置取不到" + log "recreating $WORKER_CONTAINER with barrier point=$BARRIER_POINT" + docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps --force-recreate "$COMPOSE_SERVICE" >>"$EVIDENCE/compose.log" 2>&1 || + die 2 arm_barrier "compose up 失败(见 compose.log)" + wait_worker_ready || die 2 arm_barrier "worker 重启后没有就绪" + local armed + armed="$(worker_env KG_TEST_BARRIER_DIR)" + [ "$armed" = "$ARCHIVE_ROOT_IN_CONTAINER/barrier" ] || die 2 arm_barrier "屏障注入没生效(KG_TEST_BARRIER_DIR=${armed:-空})" + # 注入会重建容器:镜像/容器身份以重建后的为准(后面要比对"重启前后同镜像")。 + WORKER_CONTAINER_ID="$(container_field "$WORKER_CONTAINER" '{{.Id}}')" + WORKER_IMAGE_ID="$(container_field "$WORKER_CONTAINER" '{{.Image}}')" + ARMED=1 + record arm_barrier pass "dir=$armed point=$BARRIER_POINT timeout=$BARRIER_TIMEOUT container=$WORKER_CONTAINER_ID" +} + +restore_barrier() { + rm -rf "$BARRIER_HOST" + compose_argv "" || die 7 restore "compose 配置取不到" + docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps --force-recreate "$COMPOSE_SERVICE" >>"$EVIDENCE/compose.log" 2>&1 || + die 7 restore "compose up(撤销注入)失败" + wait_worker_ready || die 7 restore "worker 撤销注入后没有就绪" + [ -z "$(worker_env KG_TEST_BARRIER_DIR)" ] || die 7 restore "屏障注入还在(KG_TEST_BARRIER_DIR 非空)" + [ "$(container_field "$WORKER_CONTAINER" '{{.Image}}')" = "$WORKER_IMAGE_ID" ] || die 7 restore \ + "撤销注入后镜像变了:$WORKER_IMAGE_ID -> $(container_field "$WORKER_CONTAINER" '{{.Image}}')" + ARMED=0 + record restore pass "barrier env removed, image unchanged" +} + +# ---------- 命中、锁作业、取证 ---------- +wait_for_hit() { + local base deadline + base="$BARRIER_HOST/$(sed 's/[:/ ]/-/g' <<<"$BARRIER_POINT")" + deadline=$(( $(now_epoch) + HIT_WAIT_S )) + log "ARMED: 现在请在页面上发起作业(scope=$SCOPE kind=$KIND target=${EXPECT_SNAPSHOT:-未指定})。等待屏障点位 $BARRIER_POINT 命中 …" + while [ "$(now_epoch)" -lt "$deadline" ]; do + if [ -f "$base.timeout" ]; then + cp "$base.timeout" "$EVIDENCE/" 2>/dev/null + die 3 wait_for_hit "屏障超时(worker 已自行继续):这次没有停在写入中间,判 not_run" + fi + if [ -f "$base.hit" ]; then + cp "$base.hit" "$EVIDENCE/" + HIT_SUBJECT="$(sed -n 's/.*"subject":"\([^"]*\)".*/\1/p' "$base.hit")" + record wait_for_hit pass "hit=$BARRIER_POINT subject=${HIT_SUBJECT:-?}" + return 0 + fi + sleep 1 + done + die 3 wait_for_hit "等待屏障命中超时(${HIT_WAIT_S}s):作业没有到达 $BARRIER_POINT,判 not_run" +} + +lock_job() { + JOB_ID="${EXPECT_JOB:-$HIT_SUBJECT}" + [ -n "$JOB_ID" ] || die 3 lock_job "屏障现场没有作业身份,也没有 --job" + if [ -n "$EXPECT_JOB" ] && [ "$HIT_SUBJECT" != "$EXPECT_JOB" ]; then + die 3 lock_job "屏障命中的是别的作业(hit=$HIT_SUBJECT 期望=$EXPECT_JOB):拒绝继续" + fi + local row others + row="$(gov_sql "select state||'|'||scope||'|'||kind||'|'||coalesce(snapshot_id,'')||'|'||coalesce(target_snapshot_id,'')||'|'||created_at::text from library_jobs where id='$JOB_ID'")" + [ -n "$row" ] || die 3 lock_job "治理库里没有作业 $JOB_ID" + IFS='|' read -r JOB_STATE JOB_SCOPE JOB_KIND JOB_SNAPSHOT JOB_TARGET JOB_CREATED <<<"$row" + [ "$JOB_SCOPE" = "$SCOPE" ] || die 3 lock_job "作业 scope=$JOB_SCOPE 与请求 $SCOPE 不一致" + [ "$JOB_STATE" = "running" ] || die 3 lock_job "作业状态是 $JOB_STATE 不是 running:命中时它已经不在写入路径上了" + if [ "$KIND" != "auto" ] && [ "$JOB_KIND" != "$KIND" ]; then + die 3 lock_job "作业 kind=$JOB_KIND 与请求 --kind $KIND 不一致(期望内容也会按错的那一类推导)" + fi + if [ -n "$EXPECT_SNAPSHOT" ] && [ "$JOB_TARGET" != "$EXPECT_SNAPSHOT" ]; then + die 3 lock_job "作业目标快照 $JOB_TARGET 与 --snapshot $EXPECT_SNAPSHOT 不一致:拒绝把它当这次演练" + fi + if [ -n "$SINCE" ]; then + local since_epoch created_epoch + if [[ "$SINCE" =~ ^[0-9]+$ ]]; then since_epoch="$SINCE"; else since_epoch="$(date -u -d "$SINCE" +%s 2>/dev/null || echo 0)"; fi + created_epoch="$(date -u -d "$JOB_CREATED" +%s 2>/dev/null || echo 0)" + { [ "$since_epoch" -gt 0 ] && [ "$created_epoch" -ge "$since_epoch" ]; } || + die 3 lock_job "作业创建时间 $JOB_CREATED 不满足 --since $SINCE(或 --since 解析不了)" + fi + # 目标快照 == 中断前的当前生效版本 ⇒ 这次"接管"只可能走同快照快速收尾, + # 证明不了完整续作(2026-10-29 的现场正是如此)。杀之前就拒绝,别浪费一次中断。 + PRE_EFFECTIVE="$(gov_sql "select coalesce(snapshot_id,'') from library_versions where scope='$SCOPE' and kind='production_effective' and superseded_at is null")" + if [ -n "$PRE_EFFECTIVE" ] && [ "$JOB_TARGET" = "$PRE_EFFECTIVE" ] && [ "$ALLOW_SAME_SNAPSHOT" -ne 1 ]; then + die 3 lock_job "目标快照 $JOB_TARGET 就是中断前的当前生效版本:同快照收尾不能当完整续作的验收证据(要演练请换一个没生效过的快照;确要同快照加 --allow-same-snapshot)" + fi + others="$(gov_sql "select coalesce(string_agg(id, ','),'') from library_jobs where state in ('pending','running') and id<>'$JOB_ID'")" + [ -z "$others" ] || die 3 lock_job "还有别的作业在飞:$others(只允许杀这一个作业的执行者)" + + local expected + if [ -n "$EXPECT_COUNTS" ]; then + expected="$EXPECT_COUNTS" + log "期望内容来自 --expect:$expected" + else + expected="$(snapshot_expectations "$JOB_TARGET")" || die 3 lock_job "推导目标快照的期望内容失败($JOB_TARGET)" + EXPECT_COUNTS="$expected" + log "期望内容来自快照 manifest($JOB_TARGET):$expected;resources 不在默认期望内(同租户其它知识库资源会保留)" + fi + case "$expected" in + *=*) ;; + *) die 3 lock_job "期望内容形状不对:$expected" ;; + esac + record lock_job pass "kind=$JOB_KIND job=$JOB_ID state=running scope=$JOB_SCOPE target=$JOB_TARGET pre_effective=${PRE_EFFECTIVE:-none} expect=$EXPECT_COUNTS created=$JOB_CREATED" +} + +read_writeset_evidence() { + local row + row="$(gov_sql "select coalesce(evidence->>'writeset_digest','')||'|'||coalesce(evidence->>'writeset_reused_rows','')||'|'||coalesce(evidence->>'writeset_target_snapshot','')||'|'||coalesce(evidence->>'backup_snapshot','')||'|'||created_at::text||'|'||coalesce(evidence->>'backup_reused','') from library_versions where scope='$SCOPE' and kind='production_prebackup' and source_job_id='$JOB_ID'")" + [ -n "$row" ] || die 4 read_writeset "作业 $JOB_ID 还没有预备份版本记录:屏障点位早于台账登记,不能当「写集合已登记」的证据" + IFS='|' read -r WS_DIGEST WS_REUSED WS_TARGET WS_BACKUP WS_BACKUP_CREATED WS_REUSED <<<"$row" + [ -n "$WS_DIGEST" ] || die 4 read_writeset "预备份记录里没有 writeset_digest:接管会失败,这次不算可接管" + [ "$WS_TARGET" = "$JOB_TARGET" ] || die 4 read_writeset "写集合绑定目标 $WS_TARGET 与作业目标 $JOB_TARGET 不一致" + WS_FILE="$ARCHIVE_HOST/writesets/$WS_DIGEST.json" + [ -s "$WS_FILE" ] || die 4 read_writeset "写集合文件不存在或为空:$WS_FILE" + grep -q "\"digest\":\"$WS_DIGEST\"" "$WS_FILE" || die 4 read_writeset "写集合文件自述摘要与登记不一致($WS_DIGEST)" + grep -q "\"job_id\":\"$JOB_ID\"" "$WS_FILE" || die 4 read_writeset "写集合文件不属于作业 $JOB_ID" + # 崩溃前那份预备份的身份与字节也拍下来:接管是否"复用同一份、没被重做覆盖" + # 只能靠事后比对(快照 id + 清单字节 + 清单 mtime + 版本行首次登记时刻)。 + local backup_manifest + backup_manifest="$ARCHIVE_HOST/versions/$WS_BACKUP.json" + [ -s "$backup_manifest" ] || die 4 read_writeset "预备份快照清单不存在或为空:$backup_manifest" + WS_BACKUP_SHA="$(sha256sum "$backup_manifest" | awk '{print $1}')" + WS_BACKUP_MTIME="$(stat -c %Y "$backup_manifest")" + WS_FILE_SHA="$(sha256sum "$WS_FILE" | awk '{print $1}')" + # 独立校验器是必需的(preflight 已确认存在):它判定不符就不能继续。 + "$VERIFIER" -archive-root "$ARCHIVE_HOST" -digest "$WS_DIGEST" -job "$JOB_ID" -scope "$SCOPE" \ + >>"$EVIDENCE/verifier.log" 2>&1 || die 4 read_writeset "独立校验器判定写集合摘要不符(见 verifier.log)" + record read_writeset pass "digest=$WS_DIGEST reused=${WS_REUSED:-0} backup=$WS_BACKUP backup_manifest_sha=$WS_BACKUP_SHA backup_manifest_mtime=$WS_BACKUP_MTIME backup_registered_at=$WS_BACKUP_CREATED writeset_sha=$WS_FILE_SHA canonical=verified" +} + +kill_worker() { + [ "$CONFIRM_KILL" -eq 1 ] || die 4 kill "缺少 --confirm-kill:杀容器必须是显式动作" + local before_restart job_state deadline owner_uid + before_restart="$(container_field "$WORKER_CONTAINER" '{{.RestartCount}}')" + job_state="$(gov_sql "select state from library_jobs where id='$JOB_ID'")" + [ "$job_state" = "running" ] || die 4 kill "杀之前作业状态变成 $job_state:这次不构成写入中的中断" + KILL_PID="$(container_field "$WORKER_CONTAINER" '{{.State.Pid}}')" + [ -n "$KILL_PID" ] && [ "$KILL_PID" -gt 1 ] || die 4 kill "读不到 worker 的宿主机 PID(${KILL_PID:-空})" + + # 只有"同一 uid"或 root 才能向容器 PID1 发信号;先证明能杀,再谈演练。 + owner_uid="$(stat -c %u "/proc/$KILL_PID" 2>/dev/null)" + if [ "$(id -u)" != "0" ] && [ "${owner_uid:-x}" != "$(id -u)" ]; then + die 4 kill "宿主机 PID $KILL_PID 属于 uid=${owner_uid:-?},当前 uid=$(id -u) 无权 SIGKILL:不能用「进程崩溃」语义演练(换 --manual-start 方案前先解决权限)" + fi + kill -0 "$KILL_PID" 2>/dev/null || die 4 kill "PID $KILL_PID 不存活,杀不到真实进程" + + # 退出码证据从 docker events 取:restart policy 会很快把容器拉起来, + # State.ExitCode 随即被重置成 0,事后 inspect 读不到 137(这正是上一版没留下 + # "真的 137"证据的原因之一)。 + : >"$EVIDENCE/docker-events.log" + timeout 180 docker events --filter "container=$WORKER_CONTAINER_ID" --since "$(now_epoch)" \ + --format '{{json .}}' >>"$EVIDENCE/docker-events.log" 2>>"$EVIDENCE/docker.log" & + EVENTS_PID=$! + # 给监听器 1s 就位:抢在同一秒里杀,die 事件可能早于 attach 被错过, + # 那样只会误报"没有 137 证据"(假红),不会假绿。 + sleep 1 + + KILLED_AT="$(utc_now)" + RESTART_COUNT_BEFORE="$before_restart" + log "SIGKILL worker container PID1 host_pid=$KILL_PID (job=$JOB_ID at $KILLED_AT) — 进程崩溃语义,不是 docker kill" + kill -9 "$KILL_PID" 2>>"$EVIDENCE/docker.log" || die 4 kill "向 PID $KILL_PID 发送 SIGKILL 失败" + + deadline=$(( $(now_epoch) + KILL_PROOF_S )) + KILL_PROOF="" + while [ "$(now_epoch)" -lt "$deadline" ]; do + if grep '"Action":"die"' "$EVIDENCE/docker-events.log" 2>/dev/null | grep -q '"exitCode":"137"'; then + KILL_PROOF="docker-events die exitCode=137" + break + fi + sleep 1 + done + [ -n "$KILL_PROOF" ] || die 4 kill "docker events 里没有 exitCode=137 的 die 事件(${KILL_PROOF_S}s 内):这次没有证明真被杀" + record kill pass "container=$WORKER_CONTAINER id=$WORKER_CONTAINER_ID host_pid=$KILL_PID exit=137 proof=\"$KILL_PROOF\" killed_at=$KILLED_AT restart_before=$RESTART_COUNT_BEFORE semantics=process-crash-sigkill" +} + +wait_restart() { + local deadline running + deadline=$(( $(now_epoch) + POLICY_RESTART_WAIT_S )) + RESTART_SOURCE="" + while [ "$(now_epoch)" -lt "$deadline" ]; do + running="$(container_field "$WORKER_CONTAINER" '{{.State.Running}}')" + if [ "$running" = "true" ] && [ "$(container_field "$WORKER_CONTAINER" '{{.State.Pid}}')" != "$KILL_PID" ]; then + RESTART_SOURCE="policy" + break + fi + sleep 1 + done + if [ -z "$RESTART_SOURCE" ]; then + if [ "$MANUAL_START" -ne 1 ]; then + die 5 restart "restart policy 在 ${POLICY_RESTART_WAIT_S}s 内没有拉起(未允许显式 docker start):这次不算自动接管" + fi + log "restart policy 没有在 ${POLICY_RESTART_WAIT_S}s 内拉起:显式 docker start(记 restart_source=manual_start,不是自动恢复)" + docker start "$WORKER_CONTAINER" >>"$EVIDENCE/docker.log" 2>&1 || die 5 restart "显式 docker start 失败" + RESTART_SOURCE="manual_start" + deadline=$(( $(now_epoch) + RESTART_WAIT_S )) + while [ "$(now_epoch)" -lt "$deadline" ]; do + running="$(container_field "$WORKER_CONTAINER" '{{.State.Running}}')" + [ "$running" = "true" ] && break + sleep 1 + done + [ "$running" = "true" ] || die 5 restart "显式启动后容器仍没运行" + fi + local image_after cid_after restarts_after + image_after="$(container_field "$WORKER_CONTAINER" '{{.Image}}')" + cid_after="$(container_field "$WORKER_CONTAINER" '{{.Id}}')" + restarts_after="$(container_field "$WORKER_CONTAINER" '{{.RestartCount}}')" + [ "$image_after" = "$WORKER_IMAGE_ID" ] || die 5 restart "重启后镜像变了:$WORKER_IMAGE_ID -> $image_after(不是同一个产物)" + [ "$cid_after" = "$WORKER_CONTAINER_ID" ] || die 5 restart "重启后容器身份变了:$WORKER_CONTAINER_ID -> $cid_after" + record restart pass "source=$RESTART_SOURCE image_unchanged=1 container_unchanged=1 restart_count=$RESTART_COUNT_BEFORE->$restarts_after" +} + +wait_takeover() { + local deadline state="" last_note=0 out rc CONTRACT_OUT + deadline=$(( $(now_epoch) + TAKEOVER_WAIT_S )) + log "等待同一个作业被认领(lease 30s + 扫描 30s,上限 ${TAKEOVER_WAIT_S}s)…" + while [ "$(now_epoch)" -lt "$deadline" ]; do + state="$(gov_sql "select state from library_jobs where id='$JOB_ID'")" + case "$state" in succeeded|failed|cancelled) break ;; esac + # 60s 没动静就把现场抓下来(别再空等到底才知道为什么)。 + if [ $(( $(now_epoch) - last_note )) -ge 60 ]; then + last_note="$(now_epoch)" + docker logs --since "$KILLED_AT" "$WORKER_CONTAINER" 2>&1 | tail -5 >>"$EVIDENCE/worker.log" + log "接管等待中:job state=${state:-?} worker_running=$(container_field "$WORKER_CONTAINER" '{{.State.Running}}') queue=$(gov_sql "select coalesce(string_agg(type||':'||state,','),'') from jobs where type like 'library.%' and state in ('pending','running','retry')")" + fi + sleep 2 + done + case "$state" in + succeeded) ;; + failed|cancelled) die 5 wait_takeover "作业终态是 $state(接管失败):$(gov_sql "select coalesce(error,'') from library_jobs where id='$JOB_ID'")" ;; + *) die 5 wait_takeover "等待接管超时(最后状态 ${state:-?}):不算成功" ;; + esac + + # 认领与决策都要有**本作业 id** 的行,且时间戳晚于杀点。 + # 汇总行(`library job takeover sweep: 1 resumed`)不算证据:它既不说是哪个作业, + # 也不说是否真的被认领(别的 worker 抢走、attach 失败都只影响计数)。 + LOG_RAW="$EVIDENCE/worker-log-raw.txt" + # -t 才有每行时间戳:判据要证明"这些行出现在杀之后",没有时间戳就只能判红。 + docker logs -t --since "$KILLED_AT" "$WORKER_CONTAINER" >"$LOG_RAW" 2>&1 + CONTRACT_OUT="$EVIDENCE/log-contract.log" + python3 "$LOG_CONTRACT" --log "$LOG_RAW" --job "$JOB_ID" --target "$JOB_TARGET" \ + --backup "$WS_BACKUP" --since "$KILLED_AT" --expect-decision "$EXPECT_DECISION" \ + >"$CONTRACT_OUT" 2>&1; rc=$? + out="$(cat "$CONTRACT_OUT")" + if [ "$rc" -ne 0 ]; then + die 5 wait_takeover "接管日志契约不成立(rc=$rc,见 log-contract.log):$(tr '\n' ' ' <"$CONTRACT_OUT" | cut -c1-400)" + fi + CLAIM_AT="$(sed -n 's/.*claim_at=\([^ ]*\).*/\1/p' <<<"$out" | head -1)" + DECISION="$(sed -n 's/.*decision=\([^ ]*\).*/\1/p' <<<"$out" | head -1)" + [ -n "$DECISION" ] || die 5 wait_takeover "判据脚本没给出决策(输出:$out)" + record wait_takeover pass "same job succeeded; restart_source=$RESTART_SOURCE; claim_at=${CLAIM_AT:-?}; decision=$DECISION; contract=ok" +} + +verify_stages_complete() { + local stages missing="" stage + stages="$(gov_sql "select stage||':'||state from library_job_stages where job_id='$JOB_ID'")" + for stage in database resources index wiki verify; do + grep -qx "$stage:succeeded" <<<"$stages" || missing+="$stage " + done + [ -z "$missing" ] || die 6 verify_stages \ + "作业没有真跑完写入链路:未 succeeded 的阶段 = $missing(stages=$(tr '\n' ',' <<<"$stages"))" + record verify_stages pass "database/resources/index/wiki/verify 全部 succeeded" +} + +verify_takeover_semantics() { + local stages pre_state finalize_at eff after_digest + local backup_now backup_created_now backup_sha_now backup_mtime_now pre_reused_now + stages="$(gov_sql "select coalesce(string_agg(stage||':'||state, ',' order by updated_at),'') from library_job_stages where job_id='$JOB_ID'")" + pre_state="$(gov_sql "select coalesce(state,'') from library_job_stages where job_id='$JOB_ID' and stage='prebackup'")" + # 接管复用崩溃前那份预备份:阶段既可能写成 skipped(只标记不重跑),也可能写成 + # succeeded(release.go 记"预备份 "——真实 2026-10-29 现场就是这种)。 + # 两种都接受,但**不能因此取消备份校验**:必须证明复用的是同一份、没被重做覆盖。 + case "$pre_state" in + skipped|succeeded) ;; + *) die 6 verify_takeover "prebackup 阶段是 ${pre_state:-缺失}:既不是复用(skipped)也不是复用后重跑(succeeded),接管路径不成立(stages=$stages)" ;; + esac + finalize_at="$(gov_sql "select coalesce(max(updated_at)::text,'') from library_job_stages where job_id='$JOB_ID' and stage='finalize' and state='succeeded'")" + [ -n "$finalize_at" ] || die 6 verify_takeover "finalize 没有成功(stages=$stages)" + + backup_now="$(gov_sql "select coalesce(snapshot_id,'') from library_versions where scope='$SCOPE' and kind='production_prebackup' and source_job_id='$JOB_ID'")" + [ "$backup_now" = "$WS_BACKUP" ] || die 6 verify_takeover \ + "预备份身份变了:崩溃前 $WS_BACKUP → 现在 ${backup_now:-空}(重做了备份 = 把半写状态当成可回滚基线)" + backup_created_now="$(gov_sql "select created_at::text from library_versions where scope='$SCOPE' and kind='production_prebackup' and source_job_id='$JOB_ID'")" + [ "$backup_created_now" = "$WS_BACKUP_CREATED" ] || die 6 verify_takeover \ + "预备份版本行的首次登记时刻被改写:$WS_BACKUP_CREATED → $backup_created_now(复用被洗成重做)" + backup_sha_now="$(sha256sum "$ARCHIVE_HOST/versions/$backup_now.json" 2>/dev/null | awk '{print $1}')" + [ "$backup_sha_now" = "$WS_BACKUP_SHA" ] || die 6 verify_takeover \ + "预备份清单字节变了:$WS_BACKUP_SHA → ${backup_sha_now:-缺失}(同一快照 id 下内容被重写)" + backup_mtime_now="$(stat -c %Y "$ARCHIVE_HOST/versions/$backup_now.json" 2>/dev/null)" + [ "$backup_mtime_now" = "$WS_BACKUP_MTIME" ] || die 6 verify_takeover \ + "预备份清单文件被重新写过(mtime $WS_BACKUP_MTIME → ${backup_mtime_now:-缺失}):崩溃后重做了备份" + pre_reused_now="$(gov_sql "select coalesce(evidence->>'backup_reused','') from library_versions where scope='$SCOPE' and kind='production_prebackup' and source_job_id='$JOB_ID'")" + if [ "$pre_state" = "succeeded" ] && [ "$pre_reused_now" != "true" ]; then + die 6 verify_takeover \ + "prebackup 记成 succeeded 但版本证据没有 backup_reused=true:分不清'复用'与'重做了备份'(evidence=$pre_reused_now)" + fi + record verify_takeover pass "stages=$stages decision=$DECISION finalize_at=$finalize_at prebackup=$pre_state backup=$backup_now registered_at=$backup_created_now manifest_sha=$backup_sha_now reused=${pre_reused_now:-no}" + + eff="$(gov_sql "select coalesce(snapshot_id,'')||'|'||coalesce(source_job_id,'')||'|'||coalesce(superseded_at::text,'') from library_versions where scope='$SCOPE' and kind='production_effective' and superseded_at is null")" + local eff_snapshot eff_job eff_superseded + IFS='|' read -r eff_snapshot eff_job eff_superseded <<<"$eff" + [ "$eff_snapshot" = "$JOB_TARGET" ] || die 6 verify_effective "当前生效版本是 ${eff_snapshot:-无},不是本作业目标 $JOB_TARGET" + [ "$eff_job" = "$JOB_ID" ] || die 6 verify_effective "生效版本来源作业是 ${eff_job:-无},不是 $JOB_ID(同快照由别作业登记不算本次完成)" + [ -z "$eff_superseded" ] || die 6 verify_effective "生效版本已被顶替($eff_superseded)" + after_digest="$(gov_sql "select coalesce(evidence->>'writeset_digest','') from library_versions where scope='$SCOPE' and kind='production_prebackup' and source_job_id='$JOB_ID'")" + [ "$after_digest" = "$WS_DIGEST" ] || die 6 verify_effective "接管后写集合摘要变了($WS_DIGEST -> ${after_digest:-空})" + record verify_effective pass "effective=$eff_snapshot job=$JOB_ID writeset=$after_digest" +} + +verify_target_counts() { + local part table want got failed=0 detail="" sql="" + for part in ${EXPECT_COUNTS//,/ }; do + table="${part%%=*}" + case "$table" in + *[!a-z_]*) die 6 verify_counts "期望里的表名不合法:$table" ;; + esac + sql+="select '$table='||count(*) from $table; " + done + got="$(docker exec "$TARGET_DB_CONTAINER" psql -U "$TARGET_DB_USER" -d "$TARGET_DB_NAME" -Atc "$sql" \ + 2>>"$EVIDENCE/psql.log")" + [ -n "$got" ] || die 6 verify_counts "目标库读数失败($TARGET_DB_CONTAINER/$TARGET_DB_NAME)" + for part in ${EXPECT_COUNTS//,/ }; do + table="${part%%=*}"; want="${part##*=}" + if ! grep -qx "$table=$want" <<<"$got"; then + failed=$((failed + 1)) + detail+="$table=$(sed -n "s/^$table=//p" <<<"$got")(want $want) " + fi + done + [ "$failed" -eq 0 ] || die 6 verify_counts "目标内容与期望不符:$detail(实际 $(tr '\n' ' ' <<<"$got"))" + record verify_counts pass "counts=$(tr '\n' ' ' <<<"$got")" +} + +verify_service_restored() { + local instance_running ingress_running held held_instance released released_instance + instance_running="$(container_field "$TARGET_INSTANCE" '{{.State.Running}}')" + ingress_running="$(container_field "$INGRESS_CONTAINER" '{{.State.Running}}')" + [ "$instance_running" = "true" ] || die 6 verify_service "目标写入者 $TARGET_INSTANCE 没有恢复运行" + [ "$ingress_running" = "true" ] || die 6 verify_service "入口 $INGRESS_CONTAINER 没有恢复运行" + held="$(gov_sql "select count(*) from library_maintenance where released_at is null")" + held_instance="$(gov_sql "select count(*) from library_instance_maintenance where released_at is null")" + released="$(gov_sql "select count(*) from library_maintenance where owner_job_id='$JOB_ID' and released_at is not null")" + released_instance="$(gov_sql "select count(*) from library_instance_maintenance where owner_job_id='$JOB_ID' and released_at is not null")" + { [ "$held" = "0" ] && [ "$held_instance" = "0" ]; } || die 6 verify_service \ + "还有未释放的维护占用(scope=$held instance=$held_instance)" + { [ "$released" -ge 1 ] && [ "$released_instance" -ge 1 ]; } || die 6 verify_service \ + "本作业的维护记录没有释放证据(scope=$released instance=$released_instance)" + record verify_service pass "instance_running=$instance_running ingress_running=$ingress_running health(instance)=$(health_of "$TARGET_INSTANCE") health(ingress)=$(health_of "$INGRESS_CONTAINER") released=$released/$released_instance" +} + +save_evidence() { + { + echo "# 脱敏证据(job=$JOB_ID kind=$JOB_KIND scope=$SCOPE target=$JOB_TARGET killed_at=$KILLED_AT restart_source=$RESTART_SOURCE)" + echo "## library_jobs" + gov_sql "select id||E'\t'||scope||E'\t'||kind||E'\t'||state||E'\t'||stage||E'\t'||coalesce(snapshot_id,'')||E'\t'||coalesce(target_snapshot_id,'')||E'\t'||created_at::text||E'\t'||coalesce(finished_at::text,'') from library_jobs where id='$JOB_ID'" + echo "## library_job_stages" + gov_sql "select stage||E'\t'||state||E'\t'||coalesce(total::text,'')||E'\t'||coalesce(completed::text,'')||E'\t'||coalesce(detail,'')||E'\t'||updated_at::text from library_job_stages where job_id='$JOB_ID' order by updated_at" + echo "## library_versions(本作业)" + gov_sql "select kind||E'\t'||snapshot_id||E'\t'||source_job_id||E'\t'||created_at::text||E'\t'||coalesce(superseded_at::text,'')||E'\t'||evidence::text from library_versions where source_job_id='$JOB_ID' order by created_at" + echo "## 维护占用(本作业;实例表列是 owner_scope)" + gov_sql "select 'scope|'||scope||'|'||state||'|'||coalesce(released_at::text,'not_released') from library_maintenance where owner_job_id='$JOB_ID' union all select 'instance|'||owner_scope||'|'||state||'|'||coalesce(released_at::text,'not_released') from library_instance_maintenance where owner_job_id='$JOB_ID'" + echo "## 目标内容计数" + docker exec "$TARGET_DB_CONTAINER" psql -U "$TARGET_DB_USER" -d "$TARGET_DB_NAME" -Atc "select 'knowledges='||count(*) from knowledges union all select 'chunks='||count(*) from chunks union all select 'resources='||count(*) from resources union all select 'wiki_pages='||count(*) from wiki_pages" 2>/dev/null + } >"$EVIDENCE/job-evidence.txt" + docker logs --since "$KILLED_AT" "$WORKER_CONTAINER" >"$EVIDENCE/worker.log" 2>&1 + log "evidence written: $EVIDENCE/job-evidence.txt" +} + +# ---------- 主流程 ---------- +log "library-kill-takeover v$SCRIPT_VERSION mode=$MODE scope=$SCOPE kind=$KIND target=${EXPECT_SNAPSHOT:-未指定} evidence=$EVIDENCE" +preflight + +case "$MODE" in + check) + STATUS_OVERRIDE="READY_FOR_PARENT" + finish 0 + ;; + restore) + restore_barrier + finish 0 + ;; + run) + [ "$CONFIRM_KILL" -eq 1 ] || die 4 kill "缺少 --confirm-kill" + arm_barrier + wait_for_hit + lock_job + read_writeset_evidence + kill_worker + wait_restart + wait_takeover + verify_stages_complete + verify_takeover_semantics + verify_target_counts + verify_service_restored + save_evidence + restore_barrier + STATUS_OVERRIDE="DRILL_PASSED" + finish 0 + ;; +esac \ No newline at end of file diff --git a/scripts/live_catalog_refresh.py b/scripts/live_catalog_refresh.py index 3fcdb74..607b7c0 100644 --- a/scripts/live_catalog_refresh.py +++ b/scripts/live_catalog_refresh.py @@ -8,6 +8,7 @@ import argparse,csv,io,json,os,pathlib,re,subprocess,sys,tempfile from collections import deque sys.path.insert(0,'/app/scripts') from source_catalog_import import build_alist_source,build_dingtalk_sources,build_pp_live_source,catalog_sql,validate_source +from pp_client import active_client,record_observation,observation,PPError class RefreshBlocked(RuntimeError):pass _source_name='';_last_directory='' @@ -39,12 +40,16 @@ def run_psql(sql): if result.returncode:raise RuntimeError('catalog activation failed') def refresh_pp(): - sys.path.insert(0,'/sources/pp');from download_scope_a import login,fetch_inventory emit('connecting',10,'正在登录PP资料下载中心') - try:token=login('/run/source-secrets/pp_credentials.json') - except Exception as error:raise RefreshBlocked('PP登录失败,请在来源链接更新凭据') from error - emit('scanning',35,'正在实时读取PP公开资料清单') - inventory=fetch_inventory(token) + client=None + try: + client=active_client();token=client.login() + emit('scanning',35,'正在实时读取PP公开资料清单') + inventory=client.inventory(token) + record_observation(client.config,observation('valid')) + except PPError as error: + if client is not None:record_observation(client.config,observation(error.state)) + raise RefreshBlocked(str(error)+',请在数据源配置检查PP连接') from error emit('building',75,'正在构建PP八类目录快照',len(inventory.get('items',[])),len(inventory.get('items',[]))) manifest={} try: diff --git a/scripts/pp_client.py b/scripts/pp_client.py new file mode 100644 index 0000000..1f118f9 --- /dev/null +++ b/scripts/pp_client.py @@ -0,0 +1,213 @@ +"""PP read-only API client; the only PP authentication protocol implementation. + +API checks and new worker tasks load the same atomically activated configuration. +Secrets enter the check subprocess on stdin, never through argv or stdout. +""" +import contextlib +import datetime +import fcntl +import json +import os +import pathlib +import stat +import sys +import tempfile +import urllib.error +import urllib.parse +import urllib.request + +DEFAULT_BASE = "https://api.dobot.cn" +DEFAULT_STATE = "/data/source-auth/pp/settings.json" +MESSAGES = { + "valid": "认证有效 · 目录可读", + "incomplete": "配置未完成,请填写账号和密码", + "auth_failed": "PP 拒绝认证,请检查账号和密码", + "permission_denied": "已认证,但目录权限不足", + "unavailable": "PP 暂时无法检查,请稍后重试", + "invalid_response": "PP 接口地址或返回格式不兼容", +} + +class PPError(Exception): + def __init__(self, state): + self.state = state + super().__init__(MESSAGES[state]) + +def observation(state): + return {"state": state, "message": MESSAGES[state], "checked_at": datetime.datetime.now(datetime.timezone.utc).isoformat()} + +def validate_base(raw, allow_http=False): + if not isinstance(raw, str) or len(raw) > 300 or raw.strip() != raw: + raise PPError("invalid_response") + try: + u = urllib.parse.urlsplit(raw) + if (u.scheme not in (("https", "http") if allow_http else ("https",)) + or not u.hostname or u.username is not None or u.password is not None + or u.path not in ("", "/") or u.query or u.fragment or "?" in raw or "#" in raw): + raise PPError("invalid_response") + _ = u.port + except ValueError: + raise PPError("invalid_response") from None + return raw.rstrip("/") + +def load_config(path=None): + p = pathlib.Path(path or os.environ.get("PP_AUTH_STATE_FILE") or DEFAULT_STATE) + if p.exists(): + info = p.lstat() + if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) & 0o077: + raise PPError("incomplete") + state = json.loads(p.read_text(encoding="utf-8")) + config = state.get("active") + if not isinstance(config, dict): + raise PPError("incomplete") + else: + legacy_path = os.environ.get("PP_LEGACY_CREDENTIALS_FILE") + if not legacy_path: + raise PPError("incomplete") + legacy = pathlib.Path(legacy_path) + try: + config = json.loads(legacy.read_text(encoding="utf-8")) + except (OSError, ValueError): + raise PPError("incomplete") from None + config = {**config, "base_url": config.get("base_url") or DEFAULT_BASE, "id": "legacy"} + validate_base(config.get("base_url")) + if not config.get("username") or not config.get("password"): + raise PPError("incomplete") + return config + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + +class Client: + def __init__(self, config, allow_http=False, timeout=20): + self.config = dict(config) + self.base = validate_base(config.get("base_url"), allow_http) + self.timeout = timeout + self.opener = urllib.request.build_opener(NoRedirect()) + + def request(self, path, token="", body=None, login=False): + headers = {"Accept": "application/json", "User-Agent": "KnowledgeGovernance/PPReadOnly"} + if token: + headers["Authorization"] = "Bearer " + token + if body is not None: + headers["Content-Type"] = "application/x-www-form-urlencoded" + req = urllib.request.Request(self.base + path, data=body, headers=headers) + try: + with self.opener.open(req, timeout=self.timeout) as response: + raw = response.read((8 << 20) + 1) + if len(raw) > 8 << 20: + raise PPError("invalid_response") + payload = json.loads(raw) + except urllib.error.HTTPError as error: + error.close() + if error.code == 401 or (error.code == 403 and login): + raise PPError("auth_failed") from None + if error.code == 403: + raise PPError("permission_denied") from None + if error.code in (408, 425, 429) or error.code >= 500: + raise PPError("unavailable") from None + raise PPError("invalid_response") from None + except (TimeoutError, OSError): + raise PPError("unavailable") from None + except (ValueError, TypeError): + raise PPError("invalid_response") from None + if not isinstance(payload, dict) or not isinstance(payload.get("code"), int) or isinstance(payload.get("code"), bool): + raise PPError("invalid_response") + if payload["code"] != 0: + code = payload["code"] + if code in (408, 429) or 500 <= code < 600: + raise PPError("unavailable") + if login or code == 401: + raise PPError("auth_failed") + if code == 403: + raise PPError("permission_denied") + raise PPError("invalid_response") + return payload.get("data") + + def login(self): + if not self.config.get("username") or not self.config.get("password"): + raise PPError("incomplete") + body = urllib.parse.urlencode({"username": self.config["username"], "password": self.config["password"]}).encode() + data = self.request("/admin/login/token", body=body, login=True) + token = data.get("access_token") if isinstance(data, dict) else None + if not isinstance(token, str) or not token: + raise PPError("invalid_response") + return token + + def page(self, token, current=1, size=200): + query = urllib.parse.urlencode({"current": current, "size": size}) + data = self.request("/potal/file/back/page?" + query, token=token) + total = data.get("total") if isinstance(data, dict) else None + # PP serializes Java Long counts as canonical decimal strings. + if (isinstance(total, str) and len(total) <= 19 and total.isascii() and total.isdecimal() + and (total == "0" or not total.startswith("0"))): + total = int(total) + if (not isinstance(data, dict) or not isinstance(data.get("list"), list) + or not isinstance(total, int) or isinstance(total, bool) + or total < 0 or not isinstance(data.get("hasNextPage"), bool)): + raise PPError("invalid_response") + return {**data, "total": total} + + def check(self): + try: + self.page(self.login(), size=1) + return observation("valid") + except PPError as error: + return observation(error.state) + + def inventory(self, token): + items = [] + for current in range(1, 10001): + page = self.page(token, current) + items.extend(page["list"]) + if not page["hasNextPage"]: + if len(items) != page["total"]: + raise PPError("invalid_response") + return {"reported_total": page["total"], "pages": current, "items": items} + raise PPError("invalid_response") + +def record_observation(config, result, path=None): + """An old task may update only the observation of its own active revision.""" + p = pathlib.Path(path or os.environ.get("PP_AUTH_STATE_FILE") or DEFAULT_STATE) + if not p.is_file(): + return + with os.fdopen(os.open(str(p) + ".lock", os.O_CREAT | os.O_RDWR, 0o600), "r+", encoding="utf-8") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + state = json.loads(p.read_text(encoding="utf-8")) + if not state.get("active") or state["active"].get("id") != config.get("id"): + return + old = state.get("observation") + if result.get("state") == "unavailable" and isinstance(old, dict): + result = {**result, "previous": old.get("previous") or old} + state["observation"] = result + fd, temp = tempfile.mkstemp(prefix=".pp-next-", dir=p.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as out: + json.dump(state, out, ensure_ascii=False) + out.flush() + os.fsync(out.fileno()) + os.replace(temp, p) + directory = os.open(p.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(temp) + +def active_client(): + return Client(load_config()) + +def main(): + try: + config = json.load(sys.stdin) + result = Client(config).check() + except PPError as error: + result = observation(error.state) + except Exception: + result = observation("unavailable") + print(json.dumps(result, ensure_ascii=False)) + +if __name__ == "__main__": + main() diff --git a/scripts/takeover_log_contract.py b/scripts/takeover_log_contract.py new file mode 100755 index 0000000..373df0a --- /dev/null +++ b/scripts/takeover_log_contract.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 +"""接管日志契约:从真实 worker 日志里证明"这个作业被认领了、并且做了哪个接管决策"。 + +为什么要有这份独立判据 +---------------------- +2026-10-29T19:56Z 的 `after:database` 演练里,worker 只打印了汇总行 +`library job takeover sweep: 1 resumed, 0 failed without backup`:汇总既没说 +是**哪个**作业,也没说它是不是真的被本进程认领(被别的 worker 抢走、attach 失败 +都只影响计数)。演练脚本当时要求的老文案 `library job resumed after worker restart` +只在"新建队列行"那条路径打印,真实走的却是"队列行已存在"那条 ⇒ 判据与实现各说一套, +演练 exit 5。这里把契约固化成可执行判据。 + +判据(三条缺一不可): + 1. 一行 `library job takeover claimed ... key=value ...`,且 target/backup 与本次作业一致; + 2. 一行 `library job takeover decision= ...`,且 等于期望决策; + 3. 两行的时间戳都 >= 杀点(取自 `docker logs -t` 的行首时间戳):杀之前的旧日志不算。 +只接受**带本作业 id** 的行:汇总行(takeover sweep / 没有 id 的 resume 统计)一律不算证据; +别的作业的认领行也不算。 + +用法: + python3 scripts/takeover_log_contract.py --log worker.log --job \ + --target <快照> --backup <预备份快照> --since 2026-10-29T19:56:49Z + python3 scripts/takeover_log_contract.py --self-test # 正负例自检(门禁 CI 里跑) +退出码:0 成立 / 2 判据不成立(原因逐条打印)/ 3 日志读不到 / 64 参数不合法 +""" +from __future__ import annotations + +import argparse +import datetime as dt +import re +import sys +from dataclasses import dataclass, field +from pathlib import Path + +LINE_TS = re.compile(r"^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z) (.*)$") +# Go 的 log 默认带 LstdFlags(`2026/10/29 19:57:21 `),`docker logs -t` 又在最前面加 +# 自己的 RFC3339 时间戳 ⇒ 行体里还有一层"年/月/日 时:分:秒"。判据只认行首那一个。 +GO_TS = re.compile(r"^\d{4}/\d\d/\d\d \d\d:\d\d:\d\d(?:\.\d+)? ") +CLAIM_PREFIX = "library job {job} takeover claimed " +DECISION_PREFIX = "library job {job} takeover decision=" +ANY_CLAIM = re.compile(r"library job (\S+) takeover claimed ") +ANY_DECISION = re.compile(r"library job (\S+) takeover decision=(\S+)") + +REQUIRED_CLAIM_KEYS = ("at", "kind", "scope", "target", "backup", "queue", "path") +TAKEOVER_DECISIONS = ("fresh", "pending_final", "superseded", "foreign_effective", "unknown") + + +def parse_ts(value: str) -> dt.datetime | None: + """解析 `docker logs -t` 的 RFC3339(可能带纳秒)时间戳;解析不了就是 None。""" + text = value.strip() + if text.endswith("Z"): + text = text[:-1] + "+00:00" + if "." in text: + head, tail = text.split(".", 1) + # 纳秒 → 微秒:Python 只认 6 位,直接截断(比较用,不需要更高精度) + frac = re.match(r"(\d+)", tail) + zone = tail[frac.end():] if frac else "" + text = head + "." + (frac.group(1)[:6].ljust(6, "0") if frac else "000000") + zone + try: + parsed = dt.datetime.fromisoformat(text) + except ValueError: + return None + return parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.timezone.utc) + + +def key_values(body: str) -> dict[str, str]: + """按 key=value 取字段(不按位置猜):Go 侧改字段名会让演练直接红,而不是静默放过。""" + out: dict[str, str] = {} + for token in body.split(): + if "=" in token: + key, _, value = token.partition("=") + if key and value: + out[key] = value + return out + + +@dataclass +class Result: + ok: bool + reasons: list[str] = field(default_factory=list) + info: dict[str, str] = field(default_factory=dict) + + +@dataclass +class Entry: + ts: dt.datetime | None + body: str + + +def split_lines(lines: list[str]) -> list[Entry]: + entries: list[Entry] = [] + for raw in lines: + line = raw.rstrip("\n") + if not line.strip(): + continue + match = LINE_TS.match(line) + if match: + entries.append(Entry(parse_ts(match.group(1)), GO_TS.sub("", match.group(2), count=1))) + else: + # 没有 docker -t 前缀就无法证明"这是杀之后的日志":仍然保留(去掉内层 + # Go 时间戳后照常识别),由判据显式判红,而不是当成通过。 + entries.append(Entry(None, GO_TS.sub("", line, count=1))) + return entries + + +def evaluate(lines: list[str], job: str, target: str, backup: str, since: dt.datetime, + expect_decision: str = "fresh") -> Result: + entries = split_lines(lines) + claim_prefix = CLAIM_PREFIX.format(job=job) + decision_prefix = DECISION_PREFIX.format(job=job) + + claims = [e for e in entries if e.body.startswith(claim_prefix)] + decisions = [e for e in entries if e.body.startswith(decision_prefix)] + after = lambda e: e.ts is not None and e.ts >= since # noqa: E731 + + fresh_claims = [e for e in claims if after(e)] + fresh_decisions = [e for e in decisions if after(e)] + aggregate = [e for e in entries if "takeover sweep" in e.body or re.search( + r"library job resume: \d+ resumed", e.body)] + other_claims = [(m.group(1), e) for e in entries for m in [ANY_CLAIM.search(e.body)] + if m and m.group(1) != job] + other_decisions = [(m.group(1), m.group(2), e) for e in entries + for m in [ANY_DECISION.search(e.body)] if m and m.group(1) != job] + + reasons: list[str] = [] + info: dict[str, str] = {} + + if not fresh_claims: + if claims: + reasons.append("本作业的认领行全都出现在杀点 %s 之前:杀之前的日志不能证明这次接管" + % since.isoformat()) + elif other_claims: + reasons.append("只有别的作业的认领行(%s):不是本作业被认领" + % ", ".join(sorted({j for j, _ in other_claims}))) + elif aggregate: + reasons.append("只看到汇总行(%s):汇总既不说哪个作业,也不说它是否被认领" + % aggregate[0].body.strip()[:120]) + else: + reasons.append("日志里没有本作业的认领行 `%s…`" % claim_prefix.strip()) + else: + kv = key_values(fresh_claims[-1].body) + info["claim_at"] = kv.get("at", "") + info["claim_path"] = kv.get("path", "") + info["claim_queue"] = kv.get("queue", "") + missing = [k for k in REQUIRED_CLAIM_KEYS if not kv.get(k)] + if missing: + reasons.append("认领行缺字段 %s(key=value 契约):%s" + % (",".join(missing), fresh_claims[-1].body.strip())) + if kv.get("target") and kv["target"] != target: + reasons.append("认领行的 target=%s 不是本次目标 %s(别的作业/别的快照的认领)" + % (kv["target"], target)) + if kv.get("backup") and backup and kv["backup"] != backup: + reasons.append("认领行的 backup=%s 不是崩溃前登记的那份预备份 %s(换了基线)" + % (kv["backup"], backup)) + + if not fresh_decisions: + if decisions: + reasons.append("本作业的决策行全都出现在杀点之前:不能证明这次接管的决策") + else: + reasons.append("日志里没有本作业的接管决策行 `%s…`" % decision_prefix) + else: + decision = fresh_decisions[-1].body[len(decision_prefix):].split()[0] + info["decision"] = decision + if decision not in TAKEOVER_DECISIONS: + reasons.append("未知的接管决策 %r(期望 %s)" % (decision, expect_decision)) + elif decision != expect_decision: + reasons.append("接管决策是 %s,期望 %s(在 after:database 之后不可能是" + "「只差收尾」,同快照收尾=上一轮的假完成)" % (decision, expect_decision)) + kv = key_values(fresh_decisions[-1].body) + if kv.get("target") and kv["target"] != target: + reasons.append("决策行的 target=%s 不是本次目标 %s" % (kv["target"], target)) + + return Result(ok=not reasons, reasons=reasons, info=info) + + +def read_log(path: Path) -> list[str] | None: + if not path.is_file(): + return None + return path.read_text(encoding="utf-8", errors="replace").splitlines() + + +# ── 自检:正例必须先绿,负例必须逐条红(否则判据是死的)────────────────── +FIXTURE_JOB = "librestore-internal-1793303791259342087" +FIXTURE_TARGET = "0d982f7667be35227c18b89ca08e83d37a44e5d08a1582a8874be08eee5b61e7" +FIXTURE_BACKUP = "69eb5a90f303b3fb9e0ebffececb92dcf2f62701fd459d58871ac305053bd510" +FIXTURE_SINCE = "2026-10-29T19:56:49Z" + +FIXTURE_AGGREGATE = ("2026-10-29T19:57:20.123456789Z 2026/10/29 19:57:20 " + "library job takeover sweep: 1 resumed, 0 failed without backup") +FIXTURE_CLAIM = ("2026-10-29T19:57:20.500000000Z 2026/10/29 19:57:20 library job %s takeover claimed " + "at=2026-10-29T19:57:20Z kind=restore scope=internal target=%s backup=%s " + "queue=q65e9fd4d932b262659cdb0dcbedb92ce path=existing-queue" + % (FIXTURE_JOB, FIXTURE_TARGET, FIXTURE_BACKUP)) +FIXTURE_DECISION = ("2026-10-29T19:57:22.000000000Z 2026/10/29 19:57:22 library job %s takeover decision=fresh " + "at=2026-10-29T19:57:22Z kind=restore scope=internal target=%s backup=%s " + "finalize_only=false" % (FIXTURE_JOB, FIXTURE_TARGET, FIXTURE_BACKUP)) +PRE_KILL_CLAIM = FIXTURE_CLAIM.replace("2026-10-29T19:57:20.500000000Z", "2026-10-29T19:56:40.000000000Z") +PRE_KILL_DECISION = FIXTURE_DECISION.replace("2026-10-29T19:57:22.000000000Z", "2026-10-29T19:56:41.000000000Z") + + +def self_test() -> int: + since = parse_ts(FIXTURE_SINCE) + assert since is not None + cases: list[tuple[str, list[str], bool, str, str]] = [ + ("正例:认领+决策都在杀之后", [FIXTURE_AGGREGATE, FIXTURE_CLAIM, FIXTURE_DECISION], + True, "fresh", ""), + ("负例:只有汇总行(上一轮的真实形状)", [FIXTURE_AGGREGATE, FIXTURE_DECISION], + False, "fresh", "汇总"), + ("负例:认领属于别的作业", + [FIXTURE_CLAIM.replace(FIXTURE_JOB, "libsync-internal-other"), FIXTURE_DECISION], + False, "fresh", "别的作业"), + ("负例:认领/决策都在杀之前(杀前日志伪通过)", [PRE_KILL_CLAIM, PRE_KILL_DECISION], + False, "fresh", "杀点"), + ("负例:有认领没决策", [FIXTURE_CLAIM], False, "fresh", "决策行"), + ("负例:有决策没认领", [FIXTURE_DECISION], False, "fresh", "认领行"), + ("负例:认领的 target 不是本次目标", + [FIXTURE_CLAIM.replace(FIXTURE_TARGET, "fc595511c7388d8e6cab3de37af8a2b6a64ede47241918684e81f2fb5d0e1f16"), + FIXTURE_DECISION], False, "fresh", "target="), + ("负例:认领的 backup 换了(重做了备份)", + [FIXTURE_CLAIM.replace(FIXTURE_BACKUP, "0fea01923a7c6073d06d7310588e737359f44ecee5ab1fd8f5892eba8e208b63"), + FIXTURE_DECISION], False, "fresh", "backup="), + ("负例:决策是 pending_final(同快照收尾)", + [FIXTURE_CLAIM, FIXTURE_DECISION.replace("decision=fresh", "decision=pending_final")], + False, "fresh", "pending_final"), + ("负例:没有 docker -t 时间戳(无法证明在杀之后)", + [FIXTURE_CLAIM.split(" ", 1)[1], FIXTURE_DECISION.split(" ", 1)[1]], + False, "fresh", "杀点"), + ("正例:期望决策可显式放宽为 pending_final", + [FIXTURE_CLAIM, FIXTURE_DECISION.replace("decision=fresh", "decision=pending_final")], + True, "pending_final", ""), + ] + failed = 0 + for name, lines, want_ok, expect, want_reason in cases: + result = evaluate(lines, FIXTURE_JOB, FIXTURE_TARGET, FIXTURE_BACKUP, since, expect) + if result.ok != want_ok: + print("❌ %s:期望 ok=%s,实际 ok=%s(%s)" + % (name, want_ok, result.ok, ";".join(result.reasons)), file=sys.stderr) + failed += 1 + continue + if not want_ok and want_reason not in ";".join(result.reasons): + print("❌ %s:红了但理由不对(期望含 %r,实际 %r)" + % (name, want_reason, result.reasons), file=sys.stderr) + failed += 1 + continue + if want_ok and want_reason: + print("❌ 自检夹具写错了:正例不该要求失败理由 %r" % want_reason, file=sys.stderr) + failed += 1 + if failed: + print("❌ 接管日志契约自检:%d 条不成立" % failed, file=sys.stderr) + return 1 + print("✅ 接管日志契约自检通过:%d 条(正例 %d / 负例 %d),负例逐条红" + % (len(cases), sum(1 for c in cases if c[2]), sum(1 for c in cases if not c[2]))) + return 0 + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description="接管日志契约判据") + parser.add_argument("--log", type=Path, help="docker logs -t 的输出") + parser.add_argument("--job", help="业务作业 id") + parser.add_argument("--target", help="目标快照(作业的 target_snapshot_id)") + parser.add_argument("--backup", default="", help="崩溃前登记的预备份快照(可省略)") + parser.add_argument("--since", help="杀点时刻(RFC3339);早于它的日志不算证据") + parser.add_argument("--expect-decision", default="fresh", + choices=TAKEOVER_DECISIONS, help="期望的接管决策(默认 fresh)") + parser.add_argument("--self-test", action="store_true", help="只跑正负例自检") + args = parser.parse_args(argv) + + if args.self_test: + return self_test() + if not (args.log and args.job and args.target and args.since): + print("必须给 --log/--job/--target/--since(或用 --self-test)", file=sys.stderr) + return 64 + since = parse_ts(args.since) + if since is None: + print("--since 不是 RFC3339:%r" % args.since, file=sys.stderr) + return 64 + lines = read_log(args.log) + if lines is None: + print("读不到日志:%s" % args.log, file=sys.stderr) + return 3 + + result = evaluate(lines, args.job, args.target, args.backup, since, args.expect_decision) + if not result.ok: + for reason in result.reasons: + print("❌ " + reason, file=sys.stderr) + return 2 + print("OK claim_at=%s path=%s queue=%s decision=%s target=%s backup=%s" + % (result.info.get("claim_at", "?"), result.info.get("claim_path", "?"), + result.info.get("claim_queue", "?"), result.info.get("decision", "?"), + args.target, args.backup or "?")) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) \ No newline at end of file diff --git a/scripts/test-scope.json b/scripts/test-scope.json index 80e0103..61b9603 100644 --- a/scripts/test-scope.json +++ b/scripts/test-scope.json @@ -9,6 +9,226 @@ "⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。" ], "optional": [ + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestDS02FullShapeOracleIsolated", + "reason": "需显式一次性本机PG/ES/MinIO:十表逐列/引用/向量/对象字节独立oracle、零Embedding计数与正文/向量/引用/映射变异自检;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestDS02LegacyCompatibilityMatrixIsolated", + "reason": "需显式一次性本机PG/ES/MinIO:旧manifest/V1/空作业或目标身份的正式入口拒绝且全数据hash不变;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestDS02FrozenBundleIsolated", + "reason": "需 KG_DS02_BUNDLE 指向的冻结输入 bundle 加一次性本机PG/ES/MinIO:与旧SHA同一bundle hash的新侧发布与独立oracle;普通CI没有bundle,跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestDS02ProcessIdentity", + "reason": "需隔离运行器注入 test-only nonce/commit/源码树与二进制哈希期望;普通CI没有注入,跳过不是通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestR13AnchorWriteFailureBlocksTargetIsolated", + "reason": "需显式一次性本机治理PG:真实约束拒绝写锚点,验证目标零写入且不留假基线;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR13OrphanOraclePropagatesDriverFailureIsolated", + "reason": "需显式一次性本机PG:用真实 statement timeout 让校验查询中途失败,断言不是\"无孤儿\";普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR13OrphanOracleRejectsMalformedAndUnknownDocumentsIsolated", + "reason": "需显式一次性本机PG/ES/MinIO:孤儿校验的缺失/未知 knowledge_id 分支;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR12SharedResourceDifferenceMatrixIsolated", + "reason": "需显式一次性本机PG/ES/MinIO:r12 软删除before-image/共享资源差异/外部索引文档字节/索引oracle/对象精确版本;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR12LateWikiFailureKeepsPreExistingObjectVersionsIsolated", + "reason": "需显式一次性本机PG/ES/MinIO:r12 软删除before-image/共享资源差异/外部索引文档字节/索引oracle/对象精确版本;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR12IndexOracleDetectsContentVectorAndMetadataChangesIsolated", + "reason": "需显式一次性本机PG/ES/MinIO:r12 软删除before-image/共享资源差异/外部索引文档字节/索引oracle/对象精确版本;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR12ForeignIndexDocumentStaysByteIdenticalIsolated", + "reason": "需显式一次性本机PG/ES/MinIO:r12 软删除before-image/共享资源差异/外部索引文档字节/索引oracle/对象精确版本;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR12DeletedCascadeBeforeImageAndRestoreIsolated", + "reason": "需显式一次性本机PG/ES/MinIO:r12 软删除before-image/共享资源差异/外部索引文档字节/索引oracle/对象精确版本;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestR11RevokedAuthorizationStopsBeforeFirstWrite", + "reason": "需要显式一次性本机PG治理库:真实授权行在预备份后被撤销,验证零写入与保留预备份;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestR11FinalizeFailureAfterTerminalHoldsThenRepairsWithoutRewrite", + "reason": "需要显式一次性本机PG治理库:真实维护行/作业行/版本事件行上注入收尾故障,验证held与只补收尾不重写;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR11StableIdentityMatrixIsolated", + "reason": "显式一次性本机PG/ES/MinIO目录、身份、自然键及备份/授权边界;r11独立runner保存raw与零写读回。普通CI跳过不是通过。" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR11ReferenceAndCursorIsolated", + "reason": "显式一次性本机PG/ES/MinIO目录、身份、自然键及备份/授权边界;r11独立runner保存raw与零写读回。普通CI跳过不是通过。" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR11NaturalKeyMatrixIsolated", + "reason": "显式一次性本机PG/ES/MinIO目录、身份、自然键及备份/授权边界;r11独立runner保存raw与零写读回。普通CI跳过不是通过。" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR11GrantBoundaryIsolated", + "reason": "显式一次性本机PG/ES/MinIO目录、身份、自然键及备份/授权边界;r11独立runner保存raw与零写读回。普通CI跳过不是通过。" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR11CatalogBindingIsolated", + "reason": "显式一次性本机PG/ES/MinIO目录、身份、自然键及备份/授权边界;r11独立runner保存raw与零写读回。普通CI跳过不是通过。" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR11BackupMutationIsolated", + "reason": "显式一次性本机PG/ES/MinIO目录、身份、自然键及备份/授权边界;r11独立runner保存raw与零写读回。普通CI跳过不是通过。" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10RestoreForeignResourceReferencesIsolated", + "reason": "本机隔离PG/ES/MinIO真实发布后注入未知绑定/外库正文metadata引用,验证Restore在所有副作用前held;普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10ProductionAdmissionIsolated", + "reason": "需要显式一次性本机PG/ES/MinIO隔离资源;r10真实数据契约与实际stack准入另存raw及零写读回,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10SourceRelationClosureIsolated", + "reason": "需要显式一次性本机PG/ES/MinIO隔离资源;r10真实数据契约与实际stack准入另存raw及零写读回,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10IncomingRelationClosureIsolated", + "reason": "需要显式一次性本机PG/ES/MinIO隔离资源;r10真实数据契约与实际stack准入另存raw及零写读回,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10BodyOnlyResourceIsolated", + "reason": "需要显式一次性本机PG/ES/MinIO隔离资源;r10真实数据契约与实际stack准入另存raw及零写读回,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10UnknownResourceShapeIsolated", + "reason": "需要显式一次性本机PG/ES/MinIO隔离资源;r10真实数据契约与实际stack准入另存raw及零写读回,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10SequenceRejectionIsolated", + "reason": "需要显式一次性本机PG/ES/MinIO隔离资源;r10真实数据契约与实际stack准入另存raw及零写读回,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10SequenceOrderingReplayIsolated", + "reason": "需要显式一次性本机PG/ES/MinIO隔离资源;r10真实数据契约与实际stack准入另存raw及零写读回,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestR10SourceSchemaBoundIsolated", + "reason": "需要显式一次性本机PG/ES/MinIO隔离资源;r10真实数据契约与实际stack准入另存raw及零写读回,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestFormalWorkerRecoveryIntent", + "reason": "专属本机隔离进程链:新恢复队列、正式worker/自动grant/维护协调器/PG/ES/MinIO、恢复中SIGKILL与真实ES提交后丢响应;外部隔离runner逐场景执行并单列证据,普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestFormalWorkerDoubleInterruption", + "reason": "仅专属本机隔离部署:实际worker与网关进程、Docker维护入口、独立治理/业务PG、MinIO只读/写身份、ES及隔离构建短租约;普通CI跳过不算通过,进程级证据单列" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayAcquisitionPersistsAttemptDelivery", + "reason": "仅显式一次性 loopback 治理PG和随机MinIO测试桶运行;验证持久grant交付、跨epoch发送身份及unknown阻断,本机隔离证据单列,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewaySharedBucketCoexistenceWithOtherWriters", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行:无整桶证明启动、无关key共存写入不阻塞、同key既有对象拒绝且不改字节、精确回滚;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayAcquisitionCannotHandOverUnknownSend", + "reason": "仅显式一次性 loopback 治理PG和随机MinIO测试桶运行;验证持久grant交付、跨epoch发送身份及unknown阻断,本机隔离证据单列,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayNewEpochPreservesOriginalSendIdentity", + "reason": "仅显式一次性 loopback 治理PG和随机MinIO测试桶运行;验证持久grant交付、跨epoch发送身份及unknown阻断,本机隔离证据单列,普通CI跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayReadinessRequiresJournal", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayRealReplayAndImmutableLedger", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayActualServiceTwoInterruptions", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayAbsenceNeverSettlesUnknown", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayReadOnlyPersistenceBlocksSend", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayIntentCommitFailureNeverSends", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayGrantCannotAuthorizeUnplannedKey", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/objectgateway", + "test": "TestGatewayTargetIdentityOnEveryCall", + "reason": "仅显式一次性loopback kg_library_test_gateway_*治理库、随机MinIO桶及本轮构建网关二进制执行;普通CI不带存储凭据,本机隔离实跑另存raw,跳过不算通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestLibraryReleaseRejectsAnotherTargetBeforeMaintenance", + "reason": "需要 TEST_DATABASE_URL 指向可销毁 PostgreSQL;验证跨目标旧作业在维护与执行代次创建前被拒绝,本地隔离真库补验,CI 无库显式跳过" + }, { "package": "knowledge-governance/internal/releaseadapter/v071", "test": "TestLibrarySourceReadOnlyDiagnostic", @@ -187,6 +407,256 @@ "package": "knowledge-governance/internal/qawemail", "test": "TestScheduledSendRequiresConfirmationAndSendsExactlyOnce", "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实跑通并通过" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestSundaySlotMailsItsOwnWeekBeforeMonday", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库 real PG 上跑通(旧实现真实复现 nothing_confirmed)" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestAutoSendAtSundaySlotMailsTheWeekThatEndsThatDay", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实跑通并通过" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestAutoSendRefusesUnconfirmedChangedAndFutureWeeks", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实跑通并通过" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestAutoSendOnMondayStillMailsThePreviousCompleteWeek", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实跑通并通过" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestManualResendSendsFrozenRevisionOnceAndReadsBackMessageID", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实跑通并通过" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestManualResendWindowRejectsFutureAndTooEarlyWeeks", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实跑通并通过" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestConcurrentAutoAndManualSendDeliverOnce", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实验证并发只投递一次" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestUnknownSendingIsNotResentAndNotMarkedSent", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实跑通并通过" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestFailedSendIsRecordedThenRetriedOnce", + "reason": "需要一个一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库真实跑通并通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestLibraryChunkSequenceIsolated", + "reason": "需要隔离 kg_library_test_* 数据库、随机 ES 索引与真实 S3;本机已实跑跨库序列碰撞、目标分配和原始序列逐行恢复,CI 不提供这些服务" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestLibraryRollbackKeepsPreExistingTargetDataIsolated", + "reason": "需要一次性隔离库 kg_library_test_*、随机 ES 索引与真实对象存储(KG_LIBRARY_TEST_S3_*);验证目标非空/同租户其它知识库/共享资源/历史孤儿/跨租户数据在失败恢复后逐行字节不变,默认 CI 无这些服务,本机已实跑通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestLibraryRestoreRefusesWithoutWriteSetRecordIsolated", + "reason": "同上环境;验证缺少持久化写集合时恢复必须失败且不动目标,默认 CI 跳过不算验证" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestLibraryPreflightRejectsCrossScopeIDConflictIsolated", + "reason": "同上环境;验证跨范围同 ID 资源冲突在任何写入之前被拒绝,默认 CI 跳过不算验证" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestLibraryWikiStageHalfWriteRollbackIsolated", + "reason": "同上环境;验证 wiki 阶段半写(database/resources 已提交)后回滚不留残渣,默认 CI 跳过不算验证" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestLibraryWriteSetRecordTamperRefusesRestoreIsolated", + "reason": "同上环境;验证写集合记录被篡改/删除后取回与恢复都失败,默认 CI 跳过不算验证" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestLibraryKillWorkerThenResumeRecoversWriteSetIsolated", + "reason": "同上环境并用 SIGKILL 杀掉子进程模拟 worker 被杀,验证重启后只按持久写集合恢复且目标原有数据不变;需要本地真实 PG/ES/MinIO,默认 CI 跳过不算验证" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestWriteSetKillHelper", + "reason": "上面 SIGKILL 用例的子进程 fixture,单独运行没有意义;默认 CI 跳过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestLibraryRunAnchorsWriteSetAndKeepsLookingItUpBeyondHistoryWindow", + "reason": "必须在真实 PostgreSQL(TEST_DATABASE_URL 指向可销毁测试库)上跑:要证明的正是 Store 的『版本列表 1..100 上限』与按身份精确查询的差别,假版本库不实现该上限(本轮缺陷就是这样一路绿的);默认 CI 无库 ⇒ 跳过,本机一次性 PG 已实跑:原码红(library version limit out of range)、只改 200→100 仍红(超出窗口找不到)、修后绿" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestTakeoverClassificationUsesExactCurrentVersionBeyondHistoryWindow", + "reason": "必须在真实 PostgreSQL(TEST_DATABASE_URL 指向可销毁测试库)上跑:要证明的是『当前生效版本』不能按最近 N 条找——先灌 250 条历史把窗口挤满,再断言接管判定仍是 pending_final / superseded;假 store 不实现窗口语义,默认 CI 无库 ⇒ 跳过(补验路径:起一次性 PG 后设 TEST_DATABASE_URL 单跑这条)" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestTakeoverRefusesSameSnapshotRegisteredByAnotherJob", + "reason": "必须在真实 PostgreSQL(TEST_DATABASE_URL 指向可销毁测试库)上跑:要证明的是『同一个快照由别的作业登记成生效版本』不能当成本作业的完成证据——版本行 id 由 (kind, scope, 快照) 决定且写入是 upsert(会改写 source_job_id),这个形状只有存储层能造;默认 CI 无库 ⇒ 跳过,本机一次性库已实跑(含负例:撤掉身份判定后判成 pending_final)" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestFailLibraryTakeoverKeepsMaintenanceAndNamesBackup", + "reason": "必须在真实 PostgreSQL 上跑:断言『拒绝接管』的三处落库效果(作业 failed + 留预备份基线 + 维护 released_at 仍为 NULL/state=needs_restore),假 store 只能证明调用了函数;默认 CI 无库 ⇒ 跳过,本机一次性库已实跑(负例:把恢复指引改成\"无需恢复\"即红)" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestPrebackupVersionKeepsFirstRegistrationTimeOnReuse", + "reason": "必须在真实 PostgreSQL(TEST_DATABASE_URL 指向可销毁测试库)上跑:要证明的是 RecordLibraryVersion 的 upsert 语义——预备份版本行只记首次登记时刻(崩溃接管复用时不许把'什么时候拍的备份'洗成现在),而生效版本行仍按最近一次激活写当前时刻。假 store 造不出这个差别。默认 CI 无库 ⇒ 跳过;本机一次性库 kg_takeover_reuse_test 已实跑,两条负例(撤掉保留规则 / 规则漏到所有 kind)均红" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestTakeoverHistoricalRestoreOnRealLedger", + "reason": "必须在真实 PostgreSQL(TEST_DATABASE_URL 指向可销毁测试库)上跑:要证明的是『被顶替的生效版本行属于别的作业』不等于本作业过期——正例要求新恢复授权+本作业独占维护窗口+未变预备份基线时判 fresh;负例逐项撤掉授权/实例占用/基线归属/清单字节都必须回到 superseded。这些形状(版本行 upsert 改写 source_job_id、实例锁行、授权有效期)假 store 造不全;默认 CI 无库 ⇒ 跳过,本机一次性库已实跑正负例" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestFailLibraryJobOrTakeoverKeepsRiskWhenResumed", + "reason": "必须在真实 PostgreSQL 上跑:断言续作早退(授权过期)时作业仍失败但 recovery 必须点名预备份、维护保持未释放且 state=needs_restore,不能出现『无需恢复』;假 store 无法证明三张表的落库效果;默认 CI 无库 ⇒ 跳过,本机一次性库已实跑" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestTakeoverKeepsWriteSetEvidenceAcrossRepeatedInterruptions", + "reason": "必须在真实 PostgreSQL(TEST_DATABASE_URL 指向可销毁测试库)上跑:丢证据的机制是 RecordLibraryVersion 的 evidence=EXCLUDED.evidence 整份覆盖,只有存储层能造出这个形状;用例走两轮中断+接管+最终恢复,断言 writeset_digest/backup_bytes/job/backup_snapshot 全部存活且 created_at 不变。默认 CI 无库 ⇒ 跳过;本机一次性库已实跑:修前红(第 1 次接管后写集合丢失)、修后绿,去掉合并逻辑再跑仍红" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestTakeoverLedgerRefusesForeignOrMissingBackupEvidence", + "reason": "必须在真实 PostgreSQL 上跑:复用未登记的预备份、字节数不一致、写集合被篡改/换作业/换预备份这些负例都依赖版本行身份与 upsert 语义(假 store 造不全);默认 CI 无库 ⇒ 跳过,本机一次性库已实跑(修前红:复用未登记预备份竟然成功)" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestHandoffChainGatesReleaseJobOnVerifiedTransfer", + "reason": "需要隔离的 fixture PostgreSQL(KG_TEST_DSN)与真实 libraryctl 二进制(KG_TEST_LIBRARYCTL);CI 不注入测试库。本机已用独立测试库容器实跑通过,未运行不等于通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestSnapshotCandidatesPaginateBeyondFiftyAndIncludeRecoveryBackups", + "reason": "需要隔离的 fixture PostgreSQL(KG_TEST_DSN)才能验证 >50 条分页与失败作业预备份的枚举;CI 不注入测试库。本机已用独立测试库容器实跑通过(go test ./cmd/worker -run 'TestHandoff|TestSnapshotCandidates' → ok),未运行不等于通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestHandoffReplayDoesNotOverwriteTerminalStateOrDuplicateReleaseJob", + "reason": "需要隔离的 fixture PostgreSQL 与真实 libraryctl 二进制,验证幂等重放不重复投递、迟到失败不改写终态;CI 不注入测试库。本机已实跑通过,未运行不等于通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestHandoffFromAPIBindingHandsOverToRelease", + "reason": "需要隔离 fixture PostgreSQL:从 API 真实前驱(handoff 队列作业已关联)验证交接、错误前驱拒绝、交接后重放。CI 无测试库;本机已实跑(go test ./cmd/worker -count=1 → ok)" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestLateHandoffFailureLeavesHandedOverJobUntouched", + "reason": "需要隔离 fixture PostgreSQL:用测试屏障确定性复现“失败出口时所有权已切给 release”,验证 running/succeeded 零修改。本机已实跑通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestSnapshotOriginOnlyFromCaptureEvents", + "reason": "需要隔离 fixture PostgreSQL:验证 test_sealed 与 production_effective 共存(正常成功链)仍按源绑定识别,以及真冲突/无捕获事件被拒。本机已实跑通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestUnownedHandoffCreatesNoStageRow", + "reason": "需要隔离 fixture PostgreSQL:验证未被持有的 handoff 不建阶段行、不改作业,且用真实 handoff ID 重放时幂等且零写入。CI 无测试库;本机已实跑(go test ./cmd/worker -count=1 → ok)" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestIndexRecoveryHelper", + "reason": "真实ES响应丢失恢复用例的独立子进程;仅由父fixture注入隔离数据库/索引/归档,单独运行跳过不代表恢复通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestContractOSSExactVersionsRealOptIn", + "reason": "真实OSS写入须显式获准的隔离前缀和持久证据目录;未配置不连接云端、不改桶设置;HTTP协议桩通过不能替代真实OSS验收" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestLibraryDuplicateSlugRejectedBeforeWriteIsolated", + "reason": "隔离PG/ES/MinIO夹具,重复slug必须写前拒绝且零对象写;默认CI不连接这些服务" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestContractIndexLostResponseRestartCompensatesIsolated", + "reason": "真实隔离PG/ES/MinIO与新子进程恢复;默认CI无存储服务,跳过不算通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestContractIndexUnknownEvidenceBoundariesIsolated", + "reason": "真实隔离PG/ES/MinIO;归属marker/内容/CAS及未记录finalize负例,默认CI无这些服务" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestContractIndexClaimDoesNotAlterMappingIsolated", + "reason": "真实隔离PG/ES/MinIO;验证mapping哈希不变和成功后无暂态marker,默认CI无这些服务" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestCandidateEmptyTargetFixture", + "reason": "需显式一次性本机PG/ES/MinIO与运行器注入的隔离库/归档根:为候选页面装配并封存独立 fullshape 测试来源、证空目标、登记 test_sealed;普通CI跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestCandidateAttestation", + "reason": "需运行器注入一次性 ed25519 种子与四份真实证据摘要:续签 object-gateway 审计(有效期上限1h);普通CI没有注入,跳过不是通过" + }, + { + "package": "knowledge-governance/cmd/worker", + "test": "TestThreeBlockersVerifyChain", + "reason": "需外置 runner 创建的一次性隔离 PG/ES/MinIO 加真实入口/网关容器与 Automatic+DS01 授权:完整 verify 与同 job recover 纵向链;普通CI没有这些资源,跳过不是通过" + }, + { + "package": "knowledge-governance/internal/httpapi", + "test": "TestStartupReconcileThenHandlerRepairsPendingCapture", + "reason": "需显式一次性隔离 kg_library_test_ PostgreSQL:真实启动收敛+HTTP 核对纵向路径,CI 无库显式跳过;父已在真实隔离库执行 PASS,CI 绿不代表本用例运行" + }, + { + "package": "knowledge-governance/internal/httpapi", + "test": "TestStartupReconcilePreservesFailedCapturesForExactReconcile", + "reason": "需显式一次性隔离 kg_library_test_ PostgreSQL:真实 failed 误判保留、审计与精确核对纵向路径,CI 无库显式跳过;父已在真实隔离库执行 PASS,CI 绿不代表本用例运行" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestSendsReadsBackMessageIDFromNonEmptyHistory", + "reason": "需要一次性 PostgreSQL 与测试主密钥(KG_WEEKLY_MAIL_TEST_DSN/KG_WEEKLY_MAIL_TEST_KEY),CI 不提供;本批已在隔离库 real PG 上先 RED(历史行导致 ErrUnavailable)后 GREEN" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestRealSMTPUnknownAfterDataStaysSendingAndNeverRetries", + "reason": "需要一次性 PostgreSQL + 测试主密钥 + 本机 TLS SMTP 桩;证明真实 SMTPMailer 在 DATA 后丢最终 250 时留 sending 且不重发,CI 无此环境" + }, + { + "package": "knowledge-governance/internal/qawemail", + "test": "TestRealSMTPExplicitRejectionIsFailedAndRetryOnce", + "reason": "需要一次性 PostgreSQL + 测试主密钥 + 本机 TLS SMTP 桩;证明明确 550 记 failed 且可重试一次,CI 无此环境" + }, + { + "package": "knowledge-governance/internal/httpapi", + "test": "TestWeeklyMailSendsHandlerReadsRealHistoryWithMessageID", + "reason": "需要一次性 PostgreSQL + 测试主密钥;验证 GET /weekly-mail/sends 在非空历史下返回 200 与真实 message_id,CI 不提供" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestV090LibraryRoundTripIsolated", + "reason": "需 KG_V090_SCHEMA_SQL 指向真实 WeKnora 0.9.0 schema dump、KG_V090_MAPPING_JSON 指向真实索引映射,以及显式隔离的 kg_library_test_* PG;普通 CI 没有这些输入,跳过不是通过" + }, + { + "package": "knowledge-governance/internal/releaseadapter/v071", + "test": "TestV090ProductionTargetPublishIsolated", + "reason": "需显式一次性本机PG(两份 0.9.0 真 schema 库)/ES/对象存储:真实导出→封存→ProductionLibraryTarget 写入 134 目标→逐表核对→写前镜像回滚,验证 0.9.0 无 wiki_log_entries、chunks 新增 NOT NULL 列走默认值、seq_id 由目标序列分配;普通CI没有这些服务,跳过不是通过" } ] } diff --git a/scripts/test_pp_client.py b/scripts/test_pp_client.py new file mode 100644 index 0000000..c0c8c39 --- /dev/null +++ b/scripts/test_pp_client.py @@ -0,0 +1,71 @@ +import json +import contextlib +import hashlib +import io +import os +from unittest.mock import patch +import pathlib +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +import pp_client + +class PPClientTests(unittest.TestCase): + def setUp(self): + self.calls=[];self.login_code=0;self.list_status=200;self.items=[];self.total=None + owner=self + class Handler(BaseHTTPRequestHandler): + def log_message(self,*args):pass + def do_POST(self): + owner.calls.append((self.command,self.path));self.rfile.read(int(self.headers.get('Content-Length','0'))) + self.send_response(200);self.end_headers();self.wfile.write(json.dumps({'code':owner.login_code,'data':{'access_token':'example-token'} if owner.login_code==0 else {}}).encode()) + def do_GET(self): + owner.calls.append((self.command,self.path)) + if self.path=='/file.pdf': + content=b'%PDF-1.4\nExample PP download\n';self.send_response(200);self.send_header('Content-Length',str(len(content)));self.end_headers();self.wfile.write(content);return + self.send_response(owner.list_status);self.end_headers();self.wfile.write(json.dumps({'code':0,'data':{'list':owner.items,'total':len(owner.items) if owner.total is None else owner.total,'hasNextPage':False}}).encode()) + self.server=HTTPServer(('127.0.0.1',0),Handler);self.thread=threading.Thread(target=self.server.serve_forever,daemon=True);self.thread.start() + self.client=pp_client.Client({'base_url':'http://127.0.0.1:'+str(self.server.server_port),'username':'example','password':'example-password'},allow_http=True) + def tearDown(self):self.server.shutdown();self.server.server_close();self.thread.join() + def test_check_really_logs_in_and_reads_empty_directory(self): + result=self.client.check();self.assertEqual(result['state'],'valid');self.assertEqual([x[0] for x in self.calls],['POST','GET']);self.assertTrue(self.calls[0][1].endswith('/admin/login/token'));self.assertTrue(self.calls[1][1].startswith('/potal/file/back/page?')) + def test_real_vendor_decimal_string_total_is_readable(self): + for count,items in [('0',[]),('1',[{'id':'example'}])]: + with self.subTest(count=count): + self.total=count;self.items=items + self.assertEqual(self.client.check()['state'],'valid') + inventory=self.client.inventory(self.client.login()) + self.assertEqual(inventory['reported_total'],int(count));self.assertEqual(inventory['items'],items) + def test_malformed_vendor_counts_are_not_normalized(self): + for value in ['01',' 1','+1','1.0','-1','١','9'*20,True,1.5,-1]: + with self.subTest(value=value): + self.total=value;self.assertEqual(self.client.check()['state'],'invalid_response') + def test_explicit_rejection_never_reads_catalog(self): + self.login_code=401;result=self.client.check();self.assertEqual(result['state'],'auth_failed');self.assertEqual(len(self.calls),1) + def test_permission_failure_and_transient_remain_distinct(self): + self.list_status=403;self.assertEqual(self.client.check()['state'],'permission_denied');self.list_status=429;self.assertEqual(self.client.check()['state'],'unavailable') + def test_latest_saved_active_config_owns_each_new_task(self): + with tempfile.TemporaryDirectory() as root: + p=pathlib.Path(root)/'settings.json';p.write_text(json.dumps({'active':{'id':'one','base_url':'https://one.example.invalid','username':'example','password':'example-password'}}));p.chmod(0o600) + self.assertEqual(pp_client.load_config(str(p))['id'],'one');p.write_text(json.dumps({'active':{'id':'two','base_url':'https://two.example.invalid','username':'example','password':'example-password'}}));self.assertEqual(pp_client.load_config(str(p))['base_url'],'https://two.example.invalid') + def test_refresh_consumer_uses_the_shared_client(self): + import live_catalog_refresh + with patch('live_catalog_refresh.active_client',return_value=self.client),patch('live_catalog_refresh.build_pp_live_source',side_effect=lambda inventory,manifest:inventory),contextlib.redirect_stdout(io.StringIO()): + result=live_catalog_refresh.refresh_pp() + self.assertEqual(result['items'],[]);self.assertEqual([x[0] for x in self.calls],['POST','GET']) + def test_download_consumer_uses_current_portal_and_real_file_bytes(self): + import artifact_fetch + url=self.client.base+'/file.pdf' + self.items=[{'online':1,'potalGroup':{'groupName':'公开'},'fileUrl':url}] + with patch('pp_client.active_client',return_value=self.client),patch('artifact_fetch.pp_find_entry',return_value=None): + path,size,digest,local=artifact_fetch.pp_download({'locator_hash':hashlib.sha256(url.encode()).hexdigest(),'name':'example.pdf'},1024) + try: + self.assertFalse(local);self.assertGreater(size,0);self.assertEqual(hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest(),digest) + self.assertEqual([x[0] for x in self.calls],['POST','GET','GET']) + finally:os.unlink(path) + def test_missing_state_never_implicitly_reuses_legacy_credentials(self): + fake=json.dumps({'username':'example','password':'synthetic-'+'fixture'}) + with patch.dict(os.environ,{'PP_LEGACY_CREDENTIALS_FILE':''}),patch('pathlib.Path.exists',return_value=False),patch('pathlib.Path.read_text',return_value=fake): + with self.assertRaises(pp_client.PPError):pp_client.load_config('/example-missing/settings.json') +if __name__=='__main__':unittest.main() diff --git a/scripts/test_runtime_script_packaging.py b/scripts/test_runtime_script_packaging.py new file mode 100644 index 0000000..3b952fa --- /dev/null +++ b/scripts/test_runtime_script_packaging.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""运行镜像必须带齐脚本闭包:Dockerfile COPY 漏一个模块 ⇒ 线上入口必败。 + +F12 的真实现象是 live_catalog_refresh 能导入、psql 在、根身份正常, +但 `from dws_dingtalk_scan import walk` 抛 ModuleNotFoundError。只检查主脚本 +自己的 import 不够:被依赖的模块也可能再 import 兄弟模块。这里按源码算出 +闭包,再与 Dockerfile 实际 COPY 进 /app/scripts 的文件比对。 + +纯静态检查:不起容器、不连库、不需要凭据。 +""" +from __future__ import annotations + +import ast +import re +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SCRIPTS = ROOT / "scripts" +APP_SCRIPTS = "/app/scripts" + + +def copied_scripts(dockerfile_text: str) -> set[str]: + """Dockerfile 里 COPY 到 /app/scripts 的源文件名(含续行)。""" + logical = re.sub(r"\\\r?\n\s*", " ", dockerfile_text) + copied: set[str] = set() + for line in logical.splitlines(): + parts = line.split() + targets = [part.rstrip("/") for part in parts] + if not parts or parts[0].upper() != "COPY" or APP_SCRIPTS not in targets: + continue + sources = parts[1:targets.index(APP_SCRIPTS)] + for source in sources: + name = Path(source).name + if name.endswith(".py"): + copied.add(name) + return copied + + +def local_imports(path: Path, siblings: set[str]) -> set[str]: + """该脚本 import 的同目录模块(只认 scripts/ 下真实存在的兄弟文件)。""" + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + found: set[str] = set() + for node in ast.walk(tree): + names: list[str] = [] + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + names = [node.module] + for name in names: + top = name.split(".")[0] + if f"{top}.py" in siblings: + found.add(f"{top}.py") + return found + + +def dependency_closure(scripts_dir: Path, copied: set[str]) -> set[str]: + siblings = {entry.name for entry in scripts_dir.glob("*.py")} + needed = {name for name in copied if (scripts_dir / name).is_file()} + pending = list(needed) + while pending: + current = pending.pop() + for dependency in local_imports(scripts_dir / current, siblings) - needed: + needed.add(dependency) + pending.append(dependency) + return needed + + +def missing_from_image(scripts_dir: Path, dockerfile: Path) -> list[str]: + copied = copied_scripts(dockerfile.read_text(encoding="utf-8")) + return sorted(dependency_closure(scripts_dir, copied) - copied) + + +class RuntimeScriptPackagingTests(unittest.TestCase): + def test_worker_image_ships_every_local_dependency(self): + missing = missing_from_image(SCRIPTS, ROOT / "Dockerfile") + # RED 证据:F12 就是这一行缺失(dws_dingtalk_scan.py),不是宿主环境问题。 + self.assertEqual(missing, [], f"运行镜像缺少脚本依赖:{missing}") + + def test_missing_module_negative_fixture_is_rejected(self): + """去掉扫描模块的 COPY 行必须被判红——证明这个断言真的会因为漏拷而失败。""" + dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8") + broken = dockerfile.replace(" scripts/dws_dingtalk_scan.py", "") + self.assertIn("scripts/live_catalog_refresh.py", broken) + self.assertNotIn("dws_dingtalk_scan.py", broken) + with TemporaryDockerfile(broken) as path: + self.assertEqual(missing_from_image(SCRIPTS, path), ["dws_dingtalk_scan.py"]) + + def test_third_party_and_runtime_paths_are_not_counted_as_shipped(self): + siblings = {entry.name for entry in SCRIPTS.glob("*.py")} + imported = local_imports(SCRIPTS / "artifact_fetch.py", siblings) + self.assertTrue({"axls_to_xlsx.py", "dws_error_map.py"} <= imported) + self.assertNotIn("requests.py", siblings) + + +class TemporaryDockerfile: + def __init__(self, content: str): + self.content = content + self.path = SCRIPTS / ".test-dockerfile-missing-module" + + def __enter__(self) -> Path: + self.path.write_text(self.content, encoding="utf-8") + return self.path + + def __exit__(self, *_exc: object) -> None: + self.path.unlink(missing_ok=True) + + +if __name__ == "__main__": + unittest.main(verbosity=2) \ No newline at end of file diff --git a/scripts/verify_cloud_release_target.py b/scripts/verify_cloud_release_target.py new file mode 100755 index 0000000..3f2446c --- /dev/null +++ b/scripts/verify_cloud_release_target.py @@ -0,0 +1,252 @@ +#!/usr/bin/env python3 +"""云测试发布目标:只读预检。 + +只做 ssh 上的只读命令(docker inspect/ps/exec 的只读查询、curl GET、test、stat), +不启停容器、不写文件、不改配置、不连治理库。每行一个判据:PASS / FAIL / WARN / MANUAL。 + +用法: + python3 scripts/verify_cloud_release_target.py --host weknora-test + python3 scripts/verify_cloud_release_target.py --host weknora-test --snapshot <64位ID> + +退出码:有 FAIL 即 1,否则 0(WARN/MANUAL 不影响退出码,但必须人读)。 +""" + +import argparse +import json +import shlex +import subprocess +import sys + +PROJECT_DEFAULT = "weknora-test-v071" +APP_DEFAULT = "app" +GATE_SERVICE_DEFAULT = "ingress" +DRAIN_DIR_DEFAULT = "/srv/kgtest-gate/state" +ARCHIVE_DEFAULT = "/var/lib/knowledge-governance/library" +GATE_URL_DEFAULT = "http://127.0.0.1:8080/health" +EXECUTOR_DEFAULT = "kgtest-release-executor" +RDS_HOST_DEFAULT = "pgm-wz9ohr9gk919pr1q.pg.rds.aliyuncs.com" + +results = [] + + +def record(level, name, detail): + results.append((level, name, detail)) + print(f"{level:<6} {name}: {detail}", flush=True) + + +def ssh(host, command, timeout=25): + argv = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=8", host, command] + try: + completed = subprocess.run(argv, capture_output=True, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + return 124, "", "ssh timeout" + return completed.returncode, completed.stdout.strip(), completed.stderr.strip() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--host", default="weknora-test") + parser.add_argument("--project", default=PROJECT_DEFAULT) + parser.add_argument("--app-service", default=APP_DEFAULT) + parser.add_argument("--gate-service", default=GATE_SERVICE_DEFAULT) + parser.add_argument("--drain-dir", default=DRAIN_DIR_DEFAULT) + parser.add_argument("--archive", default=ARCHIVE_DEFAULT) + parser.add_argument("--gate-url", default=GATE_URL_DEFAULT) + parser.add_argument("--executor", default=EXECUTOR_DEFAULT) + parser.add_argument("--rds-host", default=RDS_HOST_DEFAULT) + parser.add_argument("--snapshot", default="") + args = parser.parse_args() + host = args.host + + code, _, err = ssh(host, "true") + if code != 0: + record("FAIL", "ssh", f"{host} 不可达({err or code})") + return finish() + record("PASS", "ssh", f"{host} 可达") + + # 1) 项目容器清单:每个服务都必须是写入者或"声明为非写入者",否则窗口拒绝开。 + code, out, err = ssh( + host, + "docker ps -a --filter label=com.docker.compose.project=%s " + "--format '{{.Label \"com.docker.compose.service\"}}'" % shlex.quote(args.project), + ) + services = sorted({line.strip() for line in out.splitlines() if line.strip()}) + if code != 0: + record("FAIL", "project-containers", f"读不到项目容器({err or code})") + services = [] + else: + record("PASS" if services else "FAIL", "project-containers", + f"project={args.project} services={','.join(services) or ''}") + + # 2) 写入者不得发布宿主机端口(否则存在绕开入口闸门的直连通道)。 + containers = {service: f"{args.project}-{service}-1" for service in services} + app_container = containers.get(args.app_service, "") + if app_container: + code, out, err = ssh(host, "docker inspect %s --format '{{json .HostConfig.PortBindings}}'" + % shlex.quote(app_container)) + if code != 0: + record("FAIL", "writer-no-publish", f"inspect {app_container} 失败({err or code})") + else: + bindings = json.loads(out) if out else None + if bindings in (None, {}, "null"): + record("PASS", "writer-no-publish", f"{app_container} 未发布宿主机端口") + else: + record("FAIL", "writer-no-publish", + f"{app_container} 仍发布端口 {out}:拓扑校验会拒绝开维护窗口") + else: + record("FAIL", "writer-no-publish", f"项目里找不到写入者服务 {args.app_service}") + + # 3) 入口闸门存在、健康、发布端口与入口地址端口一致。 + code, out, err = ssh(host, "docker inspect %s --format '{{json .State.Health.Status}} {{json .HostConfig.PortBindings}} {{json .State.Running}}'" + % shlex.quote(f"{args.project}-{args.gate_service}-1")) + if code != 0: + record("FAIL", "gate", f"找不到闸门容器 {args.project}-{args.gate_service}-1({err or code})") + else: + parts = out.split(" ", 2) + health = parts[0] if parts else "" + bindings = parts[1] if len(parts) > 1 else "" + running = parts[2] if len(parts) > 2 else "" + if running.strip() == "true" and health.strip('"') == "healthy" and ":8080->" in bindings: + record("PASS", "gate", f"healthy,发布端口 {bindings}") + else: + record("FAIL", "gate", f"running={running} health={health} bindings={bindings}") + + # 4) 经闸门的健康检查:这是"入口在服务"的实际证据,而不是容器状态。 + code, out, err = ssh(host, "curl -s -o /dev/null -w '%%{http_code}' -m 8 %s" % shlex.quote(args.gate_url)) + if code == 0 and out.strip() == "200": + record("PASS", "gate-health", f"{args.gate_url} -> 200") + else: + record("FAIL", "gate-health", f"{args.gate_url} -> {out or err or code}") + + # 5) 闸门写排空证据的目录必须存在且可写(协调器要在同一真实文件上删/读)。 + code, out, err = ssh(host, "test -d %s && test -w %s && echo ok" % (shlex.quote(args.drain_dir), shlex.quote(args.drain_dir))) + if code == 0 and out.strip() == "ok": + record("PASS", "drain-dir", f"{args.drain_dir} 存在且可写") + else: + record("FAIL", "drain-dir", f"{args.drain_dir} 不存在或不可写({err or code})") + code, out, _ = ssh(host, "stat -c '%%y %%s' %s 2>/dev/null" % shlex.quote(args.drain_dir + "/drain.json")) + if code == 0 and out: + record("WARN", "drain-file", f"已存在 drain.json({out}):协调器开窗口前会先删除并验证不存在") + else: + record("PASS", "drain-file", "无残留 drain.json") + + # 6) 队列:redis 在本项目网络内可达(只读 PING;有口令时 NOAUTH 也算可达)。 + redis_container = containers.get("redis", "") + if redis_container: + code, out, err = ssh(host, "docker exec %s redis-cli ping 2>&1" % shlex.quote(redis_container)) + text = (out or err).strip() + if "PONG" in text or "NOAUTH" in text: + record("PASS", "redis", f"{redis_container}: {text}") + else: + record("FAIL", "redis", f"{redis_container}: {text or code}") + else: + record("FAIL", "redis", "项目里没有 redis 服务") + + # 7) 索引:ES 可达且目标索引存在(只读 HEAD/GET)。 + es_container = containers.get("elasticsearch", "") + if es_container: + code, out, err = ssh(host, "docker exec %s curl -s -o /dev/null -w '%%{http_code}' -m 8 http://localhost:9200/_cluster/health" + % shlex.quote(es_container)) + record("PASS" if out.strip() == "200" else "FAIL", "elasticsearch", + f"{es_container} cluster/health -> {out.strip() or err or code}") + else: + record("FAIL", "elasticsearch", "项目里没有 elasticsearch 服务") + + # 8) RDS:宿主机到 5432 的 TCP 可达(不登录、不带凭据)。 + code, out, err = ssh(host, "timeout 5 bash -c 'cat < /dev/null > /dev/tcp/%s/5432' && echo open" + % shlex.quote(args.rds_host)) + record("PASS" if out.strip() == "open" else "FAIL", "rds-reachable", + f"{args.rds_host}:5432 {'可达' if out.strip() == 'open' else '不可达'}") + + # 9) 归档根:执行器要在这里读快照、写预备份与写集合台账。 + code, out, err = ssh(host, "test -d %s && stat -c '%%a' %s" % (shlex.quote(args.archive), shlex.quote(args.archive))) + if code == 0: + record("PASS" if out.strip() == "700" else "WARN", "archive-root", + f"{args.archive} 权限 {out.strip()}(要求 0700)") + else: + record("FAIL", "archive-root", f"{args.archive} 不存在") + + # 10) 可选的快照包:给出 ID 时只核对版本清单是否已落位(不读 blob)。 + if args.snapshot: + version = f"{args.archive}/versions/{args.snapshot}.json" + code, out, err = ssh(host, "test -f %s && sha256sum %s | cut -d' ' -f1" + % (shlex.quote(version), shlex.quote(version))) + if code == 0 and out.strip() == args.snapshot: + record("PASS", "snapshot", f"{args.snapshot} 已导入且清单摘要自证一致") + else: + record("FAIL", "snapshot", f"{args.snapshot} 未导入或清单摘要不符({out.strip() or err or code})") + + # 11) 其它入口:adapter / DobotAI / frontend 都能到 app。只改 frontend 不够, + # "唯一入口"必须逐条核对:谁能绕过闸门直连 app,就等于闸门关不干净。 + code, out, _ = ssh(host, "docker network ls --format '{{.Name}}'") + networks = set(out.split()) + record("PASS" if "weknora-test-v071-network" in networks else "FAIL", "target-network", + f"weknora-test-v071-network {'存在' if 'weknora-test-v071-network' in networks else '不存在'}") + + def inspect_env(container): + code, env_raw, _ = ssh(host, "docker inspect %s --format '{{json .Config.Env}}'" % shlex.quote(container)) + if code != 0 or not env_raw: + return None + values = {} + for entry in json.loads(env_raw): + key, _, value = entry.partition("=") + values[key] = value + return values + + code, out, _ = ssh(host, "docker ps --format '{{.Names}}'") + running = set(out.split()) + adapter = next((name for name in running if name.startswith("knowledge-adapter-adapter")), "") + if adapter: + env = inspect_env(adapter) or {} + base = env.get("WEKNORA_BASE_URL", "") + ok = base.startswith("http://ingress:") or base.startswith("http://kgtest-ingress:") + record("PASS" if ok else "FAIL", "entry/adapter", + f"{adapter} WEKNORA_BASE_URL={base or ''}(要求指向 ingress,否则 adapter 绕过闸门直连 app)") + else: + record("WARN", "entry/adapter", "未找到 adapter 容器(若它就是知识问答入口,必须改成指向 ingress)") + + dobotai = next((name for name in running if name.startswith("dobotai-dingtalk")), "") + if dobotai: + env = inspect_env(dobotai) or {} + base = env.get("WEKNORA_BASE_URL", "") + code, mode, _ = ssh(host, "docker inspect %s --format '{{.HostConfig.NetworkMode}}'" % shlex.quote(dobotai)) + host_network = mode.strip() == "host" + ok = host_network and base in ("http://127.0.0.1:8080", "http://localhost:8080") + record("PASS" if ok else "FAIL", "entry/dobotai", + f"{dobotai} net={mode.strip()} WEKNORA_BASE_URL={base or ''}(host 网络 + 127.0.0.1:8080 才恰好走闸门)") + else: + record("WARN", "entry/dobotai", "未找到 dobotai-dingtalk 容器") + + if "frontend" in containers: + env = inspect_env(containers["frontend"]) or {} + app_host = env.get("APP_HOST", "") + record("PASS" if app_host == "ingress" else "FAIL", "entry/frontend", + f"frontend APP_HOST={app_host or ''}(要求 ingress)") + + # 11) 发布执行器:在不在跑、角色对不对(只读这一个变量,不打印 env)。 + code, out, err = ssh(host, "docker ps --filter name=%s --format '{{.Status}}'" % shlex.quote(args.executor)) + if code == 0 and out.strip(): + record("PASS", "executor", f"{args.executor} {out.strip()}") + code, role, _ = ssh(host, "docker exec %s printenv LIBRARY_WORKER_ROLE" % shlex.quote(args.executor)) + if code == 0 and role.strip() == "release-executor": + record("PASS", "executor-role", "LIBRARY_WORKER_ROLE=release-executor") + else: + record("FAIL", "executor-role", f"LIBRARY_WORKER_ROLE={role.strip() or ''}(要求 release-executor)") + else: + record("WARN", "executor", f"{args.executor} 未运行(父部署后才会出现)") + + # 12) 图谱:目标 KB 若开了 graph_enabled,发布只写 PG/ES/OSS,图谱会静默变旧。 + record("MANUAL", "target-graph", + "需人工确认目标 KB 的 indexing_strategy.graph_enabled=false(发布路径不写 Neo4j)") + return finish() + + +def finish(): + failures = [row for row in results if row[0] == "FAIL"] + print() + print(f"summary: {len(results)} checks, {len(failures)} FAIL") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/security/dependency-exceptions.json b/security/dependency-exceptions.json index 445d7f3..8e4a1dc 100644 --- a/security/dependency-exceptions.json +++ b/security/dependency-exceptions.json @@ -14,5 +14,61 @@ " expires_on : YYYY-MM-DD,过期当天即失效 —— 过期不是\"继续有效\",是\"重新走一遍审批\"", "纪律:例外是记账,不是免检。到期没人处理 ⇒ 门禁红 ⇒ 必须有人做决定。" ], - "exceptions": [] -} \ No newline at end of file + "exceptions": [ + { + "tool": "npm-audit", + "id": "GHSA-fc5q-39xc-vjpf", + "package": "picomatch", + "severity": "high", + "scope": "dev", + "reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。", + "owner": "姚章浩", + "approved_by": "姚章浩", + "expires_on": "2027-02-15" + }, + { + "tool": "npm-audit", + "id": "GHSA-fc5q-39xc-vjpf", + "package": "fdir", + "severity": "high", + "scope": "dev", + "reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。", + "owner": "姚章浩", + "approved_by": "姚章浩", + "expires_on": "2027-02-15" + }, + { + "tool": "npm-audit", + "id": "GHSA-fc5q-39xc-vjpf", + "package": "tinyglobby", + "severity": "high", + "scope": "dev", + "reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。", + "owner": "姚章浩", + "approved_by": "姚章浩", + "expires_on": "2027-02-15" + }, + { + "tool": "npm-audit", + "id": "GHSA-fc5q-39xc-vjpf", + "package": "vite", + "severity": "high", + "scope": "dev", + "reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。", + "owner": "姚章浩", + "approved_by": "姚章浩", + "expires_on": "2027-02-15" + }, + { + "tool": "npm-audit", + "id": "GHSA-fc5q-39xc-vjpf", + "package": "vitest", + "severity": "high", + "scope": "dev", + "reason": "picomatch ReDoS(GHSA-fc5q-39xc-vjpf)公告范围为 <=4.0.7,npm 上 4.0.7 已是最新、没有修复版本;该链路只在构建/测试工具里解析本仓自己的 glob 模式(vite/vitest/tinyglobby/fdir),不接受外部输入,运行时不加载,故按仅开发依赖记账。到期前若上游发布修复版本必须升级并删除本条。", + "owner": "姚章浩", + "approved_by": "姚章浩", + "expires_on": "2027-02-15" + } + ] +} diff --git a/web/package-lock.json b/web/package-lock.json index b762d00..ff4d1ef 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -17,12 +17,66 @@ "@types/react": "19.1.10", "@types/react-dom": "19.1.7", "@vitejs/plugin-react": "5.0.1", + "jsdom": "^30.1.3", "prettier": "3.9.10", "typescript": "5.9.2", "vite": "7.3.7", "vitest": "5.0.3" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "7.1.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.9.tgz", + "integrity": "sha512-vZ6JQVq8Ivgz6b/IBlAf90wZviXdluY13cQOPO+nJHbmXwGrPl2GcpqUY7a55/8ZVdfONXpCFMpRijOBCHNlcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^3.4.3", + "@csstools/css-color-parser": "^4.2.6", + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "10.0.5", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-10.0.5.tgz", + "integrity": "sha512-EgmJ7oEaGQECTn3H3wmnQpEy4hKY66VvM7VQndwPIQob3p877BgbyOUE3EX0LgXQCciF2H8KMdR+RznqjMNOLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bidi-js": "^1.1.0", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", @@ -305,6 +359,159 @@ "node": ">=6.9.0" } }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", + "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", + "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.7.tgz", + "integrity": "sha512-zgm9yjQz5iJB4VL8RyVwd71TWB8Q89FSxt/NzXoWqPSkEBOVtn9L6vAPtSc9hpKfB0Awo/AL2VKFHjYetBLFHQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.2", + "@csstools/css-calc": "^3.4.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", + "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.16.tgz", + "integrity": "sha512-LsDbJPP/B8cPasUJyTA5S99F7C4G93ngW8hUluXz8CFeOaaRnBPtBiIlvgcPYU0HmHNz8CXg+1vwFrIB4F6Dgw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", + "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -747,6 +954,24 @@ "node": ">=18" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -1405,6 +1630,16 @@ "node": ">=6.0.0" } }, + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/browserslist": { "version": "4.28.8", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.8.tgz", @@ -1537,12 +1772,40 @@ "dev": true, "license": "MIT" }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1560,6 +1823,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/decode-named-character-reference": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", @@ -1602,6 +1872,19 @@ "dev": true, "license": "ISC" }, + "node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -1792,6 +2075,19 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, "node_modules/html-url-attributes": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz", @@ -1864,6 +2160,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1871,6 +2174,56 @@ "dev": true, "license": "MIT" }, + "node_modules/jsdom": { + "version": "30.1.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.3.tgz", + "integrity": "sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^7.1.3", + "@asamuzakjp/dom-selector": "^10.0.3", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.15", + "@exodus/bytes": "^1.16.0", + "css-tree": "^3.2.1", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.0.1", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.1", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.2.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "canvas": "^3.2.3" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -2209,6 +2562,13 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/micromark": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", @@ -2867,6 +3227,19 @@ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", "license": "MIT" }, + "node_modules/parse5": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.0.tgz", + "integrity": "sha512-sq3qBFpee5jeocbFbO48VHlGr8sT7mbXS0vxlKN6sottBtJzrOG3998sr0llSZcQAGgfpdmEYAIZE0P9z0dE8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -2942,6 +3315,16 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/react": { "version": "19.1.1", "resolved": "https://registry.npmjs.org/react/-/react-19.1.1.tgz", @@ -3066,6 +3449,16 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/rollup": { "version": "4.63.1", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz", @@ -3112,6 +3505,19 @@ "fsevents": "~2.3.2" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/scheduler": { "version": "0.26.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", @@ -3224,6 +3630,52 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tldts": { + "version": "7.4.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", + "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.20", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.20.tgz", + "integrity": "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/trim-lines": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", @@ -3258,6 +3710,16 @@ "node": ">=14.17" } }, + "node_modules/undici": { + "version": "8.12.3", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz", + "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/unified": { "version": "11.0.5", "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", @@ -3562,6 +4024,54 @@ } } }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/why-is-node-running": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", @@ -3575,6 +4085,23 @@ "node": ">=20.11" } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/web/package.json b/web/package.json index f99a47b..46de510 100644 --- a/web/package.json +++ b/web/package.json @@ -21,6 +21,7 @@ "@types/react": "19.1.10", "@types/react-dom": "19.1.7", "@vitejs/plugin-react": "5.0.1", + "jsdom": "^30.1.3", "prettier": "3.9.10", "typescript": "5.9.2", "vite": "7.3.7", diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index fdade6a..0c56688 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -1,11 +1,26 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it, vi } from 'vitest' -import App, { JobDashboard, KnowledgeInventory, ModulePage, ReleaseManagement, SourceConnections, WorkspaceShell, reviewGateLabel } from './App' +import App, { + JobDashboard, + KnowledgeInventory, + ModulePage, + ReleaseManagement, + SourceConnections, + WorkspaceShell, + reviewGateLabel, +} from './App' import { AuthContext } from './auth' import type { SourceAssetPage } from './assets' import type { Job } from './jobs' -import type { ReleaseBatchDetail, ReleaseBatchPage, ReleaseExecutionDetail, ReleaseExecutionPage, ReleasePlan, ReviewCandidatePage } from './reviewRelease' +import type { + ReleaseBatchDetail, + ReleaseBatchPage, + ReleaseExecutionDetail, + ReleaseExecutionPage, + ReleasePlan, + ReviewCandidatePage, +} from './reviewRelease' import type { SourceConnectionPage, SourceScanDetail, SourceScanPage } from './sourceConnections' const baseJob: Job = { @@ -25,12 +40,9 @@ const baseJob: Job = { describe('WorkspaceShell', () => { it('renders the approved modules in the left navigation', () => { const html = renderToStaticMarkup( - +
工作区内容
-
, +
) expect(html).toContain('aria-label="功能导航"') @@ -39,18 +51,15 @@ describe('WorkspaceShell', () => { } expect(html).not.toContain('来源链接') expect(html).not.toContain('待处理文件') - expect(html).toContain('本地治理环境') - expect(html).not.toContain('P2 本地治理环境') + expect(html).toContain('云测试环境') + expect(html).not.toContain('本地治理环境') }) it('omits the system open-page tab strip while retaining navigation and the current location', () => { const html = renderToStaticMarkup( - +
工作区内容
-
, +
) expect(html).not.toContain('aria-label="已打开页面"') @@ -66,12 +75,9 @@ describe('WorkspaceShell', () => { it('does not render obsolete module-tab close controls', () => { const html = renderToStaticMarkup( - +
工作区内容
-
, +
) expect(html).not.toContain('aria-label="关闭解析监控标签"') @@ -80,12 +86,9 @@ describe('WorkspaceShell', () => { it('renders a collapsed mobile navigation control', () => { const html = renderToStaticMarkup( - +
工作区内容
-
, +
) expect(html).toContain('aria-label="切换功能导航"') @@ -101,7 +104,7 @@ describe('App', () => { expect(html).not.toContain('aria-label="已打开页面"') expect(html).not.toContain('class="tab-list"') expect(html).not.toContain('class="workspace-tab') - expect(html).toContain('

来源与目录

') + expect(html).toContain('

来源与目录

') expect(html).not.toContain('最近任务') }) }) @@ -115,14 +118,14 @@ describe('ModulePage', () => { loading={false} error={null} onRefresh={vi.fn()} - />, + /> ) expect(html).toContain('治理工作台') expect(html).toContain('P2 · 知识治理总览') expect(html).toContain('PP历史来源清单已接管') expect(html).toContain('生产写入:关闭') - expect(html).toContain('以「系统设置 → 服务配置」的实时探测为准') + expect(html).toContain('以「系统设置 → 知识库映射」的实时探测为准') expect(html).not.toContain('本地测试WeKnora已连接') expect(html).not.toContain('生产WeKnora仍未连接') expect(html).not.toContain('尚未连接测试或生产WeKnora') @@ -141,12 +144,23 @@ describe('ModulePage', () => { error={null} onRefresh={vi.fn()} publicationPage={{ - items: [{ - id: 'pub-1', title: 'Safe title', ingest_state: 'failed', processing_state: 'failed', - retrieval_state: 'unpublished', target_scope: 'internal', change_set_id: 'cs-1', change_type: 'added', can_start: false, - retry_count: 2, last_error: 'remote_parse_failed', - can_retry: true, updated_at: '2026-09-04T05:00:00Z', - }], + items: [ + { + id: 'pub-1', + title: 'Safe title', + ingest_state: 'failed', + processing_state: 'failed', + retrieval_state: 'unpublished', + target_scope: 'internal', + change_set_id: 'cs-1', + change_type: 'added', + can_start: false, + retry_count: 2, + last_error: 'remote_parse_failed', + can_retry: true, + updated_at: '2026-09-04T05:00:00Z', + }, + ], total: 1, limit: 50, offset: 0, @@ -158,7 +172,7 @@ describe('ModulePage', () => { onPublicationPageChange={vi.fn()} onPublicationRefresh={vi.fn()} onRetry={vi.fn()} - />, + /> ) expect(html).toContain('

解析监控

') @@ -177,14 +191,19 @@ describe('ModulePage', () => { loading={false} error={null} onRefresh={vi.fn()} - assetPage={{ items: [], summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 }, limit: 50, offset: 0 }} + assetPage={{ + items: [], + summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 }, + limit: 50, + offset: 0, + }} assetLoading={false} assetError={null} assetState="" onAssetStateChange={vi.fn()} onAssetPageChange={vi.fn()} onAssetRefresh={vi.fn()} - />, + /> ) expect(html).toContain('统一治理清单') @@ -203,15 +222,39 @@ describe('ModulePage', () => { connectionPage={{ items: [ { - id: 'conn-pp', source_type: 'pp', name: 'PP历史公开知识', enabled: false, - schedule_configured: false, health_status: 'healthy', item_count: 613, updated_at: '2026-09-06T01:00:00Z', + id: 'conn-pp', + source_type: 'pp', + name: 'PP历史公开知识', + enabled: false, + schedule_configured: false, + health_status: 'healthy', + item_count: 613, + updated_at: '2026-09-06T01:00:00Z', last_scan: { - id: 'scan-1', state: 'completed', observed_items: 613, unchanged_items: 559, - added_items: 0, updated_items: 0, over_limit_items: 54, missing_items: 0, - planned_uploads: 0, error_code: '', created_at: '2026-09-06T00:59:00Z', completed_at: '2026-09-06T01:00:00Z', + id: 'scan-1', + state: 'completed', + observed_items: 613, + unchanged_items: 559, + added_items: 0, + updated_items: 0, + over_limit_items: 54, + missing_items: 0, + planned_uploads: 0, + error_code: '', + created_at: '2026-09-06T00:59:00Z', + completed_at: '2026-09-06T01:00:00Z', }, }, - { id: 'conn-alist', source_type: 'alist', name: 'AList只读源', enabled: true, schedule_configured: true, health_status: 'healthy', item_count: 42, updated_at: '2026-09-06T01:00:00Z' }, + { + id: 'conn-alist', + source_type: 'alist', + name: 'AList只读源', + enabled: true, + schedule_configured: true, + health_status: 'healthy', + item_count: 42, + updated_at: '2026-09-06T01:00:00Z', + }, ], summary: { total: 2, enabled: 1, disabled: 1, healthy: 1, degraded: 0, unhealthy: 0, unknown: 1 }, }} @@ -220,12 +263,23 @@ describe('ModulePage', () => { onConnectionRefresh={vi.fn()} scanningConnectionId={null} onTriggerSourceScan={vi.fn()} - />, + /> ) expect(html).toContain('

来源连接

') expect(html).not.toContain('conn-pp') - for (const text of ['来源连接', 'PP历史公开知识', 'AList只读源', '613', '已配置', '健康', '最近扫描', '未变化 559', '超过上限 54', '检查快照变化']) { + for (const text of [ + '来源连接', + 'PP历史公开知识', + 'AList只读源', + '613', + '已配置', + '健康', + '最近扫描', + '未变化 559', + '超过上限 54', + '检查快照变化', + ]) { expect(html).toContain(text) } expect(html).toContain('class="source-connections-table"') @@ -236,21 +290,50 @@ describe('ModulePage', () => { describe('KnowledgeInventory', () => { it('renders real source summary and safe paginated asset fields', () => { const page: SourceAssetPage = { - items: [{ - id: 'si-safe', source_type: 'pp', connection_name: 'PP历史公开知识', size_bytes: 52428801, - visibility: 'external', source_change: 'unchanged', content_state: 'over_limit', legacy_status: 'over_limit', - has_publication: false, processing_state: '', retrieval_state: '', updated_at: '2026-09-04T00:00:00Z', - }, { - id: 'si-manual', source_type: 'manual' as never, connection_name: '本地验收', size_bytes: 128, - visibility: 'internal', source_change: 'added', content_state: 'verified', legacy_status: '', - has_publication: true, processing_state: 'pending', retrieval_state: 'unpublished', updated_at: '2026-09-05T00:00:00Z', - }], + items: [ + { + id: 'si-safe', + source_type: 'pp', + connection_name: 'PP历史公开知识', + size_bytes: 52428801, + visibility: 'external', + source_change: 'unchanged', + content_state: 'over_limit', + legacy_status: 'over_limit', + has_publication: false, + processing_state: '', + retrieval_state: '', + updated_at: '2026-09-04T00:00:00Z', + }, + { + id: 'si-manual', + source_type: 'manual' as never, + connection_name: '本地验收', + size_bytes: 128, + visibility: 'internal', + source_change: 'added', + content_state: 'verified', + legacy_status: '', + has_publication: true, + processing_state: 'pending', + retrieval_state: 'unpublished', + updated_at: '2026-09-05T00:00:00Z', + }, + ], summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 }, limit: 50, offset: 0, } const html = renderToStaticMarkup( - , + ) for (const text of ['知识资产', '613', '530', '29', '54', 'PP', '手工验收', '50.0 MiB', '超过旧同步上限']) { @@ -265,21 +348,63 @@ describe('SourceConnections scan workbench', () => { it('renders scan history and selected safe change records', () => { const now = '2026-09-06T06:00:00Z' const page: SourceConnectionPage = { - items: [{ id: 'conn-pp', source_type: 'pp', name: 'PP历史公开知识', enabled: false, schedule_configured: false, health_status: 'healthy', item_count: 613, updated_at: now }], + items: [ + { + id: 'conn-pp', + source_type: 'pp', + name: 'PP历史公开知识', + enabled: false, + schedule_configured: false, + health_status: 'healthy', + item_count: 613, + updated_at: now, + }, + ], summary: { total: 1, enabled: 0, disabled: 1, healthy: 1, degraded: 0, unhealthy: 0, unknown: 0 }, } const scanPage: SourceScanPage = { - items: [{ id: 'scan-1', state: 'completed', observed_items: 613, unchanged_items: 558, added_items: 0, updated_items: 1, over_limit_items: 54, missing_items: 0, planned_uploads: 1, error_code: '', created_at: now, completed_at: now }], - total: 1, limit: 20, offset: 0, + items: [ + { + id: 'scan-1', + state: 'completed', + observed_items: 613, + unchanged_items: 558, + added_items: 0, + updated_items: 1, + over_limit_items: 54, + missing_items: 0, + planned_uploads: 1, + error_code: '', + created_at: now, + completed_at: now, + }, + ], + total: 1, + limit: 20, + offset: 0, } const detail: SourceScanDetail = { - ...scanPage.items[0], changes: [{ id: 'chg-1', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 2048, created_at: now }], + ...scanPage.items[0], + changes: [ + { id: 'chg-1', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 2048, created_at: now }, + ], } - const html = renderToStaticMarkup() + const html = renderToStaticMarkup( + + ) for (const text of ['扫描历史与变化记录', 'scan-1', '已选择', '变化记录', '内容更新', 'si-safe', '2.0 KiB']) { expect(html).toContain(text) } @@ -289,13 +414,39 @@ describe('SourceConnections scan workbench', () => { it('states explicitly when a selected scan has no changes', () => { const now = '2026-09-06T06:00:00Z' - const scan = { id: 'scan-1', state: 'completed' as const, observed_items: 613, unchanged_items: 559, added_items: 0, updated_items: 0, over_limit_items: 54, missing_items: 0, planned_uploads: 0, error_code: '', created_at: now, completed_at: now } - const html = renderToStaticMarkup() + const scan = { + id: 'scan-1', + state: 'completed' as const, + observed_items: 613, + unchanged_items: 559, + added_items: 0, + updated_items: 0, + over_limit_items: 54, + missing_items: 0, + planned_uploads: 0, + error_code: '', + created_at: now, + completed_at: now, + } + const html = renderToStaticMarkup( + + ) expect(html).toContain('本次扫描未发现新增、更新或不可用变化') }) }) @@ -312,7 +463,7 @@ describe('JobDashboard', () => { loading={false} error={null} onRefresh={vi.fn()} - />, + /> ) expect(html).toContain('同步任务') @@ -329,33 +480,235 @@ describe('ReleaseManagement', () => { const now = '2026-09-06T10:00:00Z' const priorNow = '2026-09-06T09:00:00Z' const reviewPage: ReviewCandidatePage = { - items: [{ - publication_id: 'tp-safe', title: 'Synthetic', source_type: 'manual', current_visibility: 'internal', - knowledge_exists: 'passed', chunks_present: 'passed', retrieval_hit: 'manual_required', - gate_status: 'ready', gate_code: 'ready', review_state: 'pending', decided_visibility: '', decision_code: '', - reviewer_ref: '', reviewed_at: null, updated_at: now, - }], total: 1, limit: 20, offset: 0, + items: [ + { + publication_id: 'tp-safe', + title: 'Synthetic', + source_type: 'manual', + current_visibility: 'internal', + knowledge_exists: 'passed', + chunks_present: 'passed', + retrieval_hit: 'manual_required', + gate_status: 'ready', + gate_code: 'ready', + review_state: 'pending', + decided_visibility: '', + decision_code: '', + reviewer_ref: '', + reviewed_at: null, + updated_at: now, + }, + ], + total: 1, + limit: 20, + offset: 0, } const batchPage: ReleaseBatchPage = { - items: [{ id: 'rb-safe', name: 'Synthetic batch', state: 'draft', policy_version: 'release-gate-v1', created_by: 'engineer-1', sealed_by: '', item_count: 1, created_at: now, sealed_at: null }], - total: 1, limit: 20, offset: 0, + items: [ + { + id: 'rb-safe', + name: 'Synthetic batch', + state: 'draft', + policy_version: 'release-gate-v1', + created_by: 'engineer-1', + sealed_by: '', + item_count: 1, + created_at: now, + sealed_at: null, + }, + ], + total: 1, + limit: 20, + offset: 0, + } + const batchDetail: ReleaseBatchDetail = { + ...batchPage.items[0], + items: [{ publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete' }], } - const batchDetail: ReleaseBatchDetail = { ...batchPage.items[0], items: [{ publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete' }] } const executionPage: ReleaseExecutionPage = { - items: [{ id: 'rx-auto', release_batch_id: 'rb-safe', operation: 'rollback', prior_execution_id: 'rx-safe', state: 'running', target_environment: 'production', authorized_by: 'system:auto-rollback', job_id: 'job-auto', item_count: 1, batch_size: 50, current_batch: 1, total_batches: 1, completed_item_count: 0, failed_item_count: 0, error_code: '', created_at: now, started_at: now, completed_at: null }, { id: 'rx-safe', release_batch_id: 'rb-safe', operation: 'publish', prior_execution_id: '', state: 'failed', target_environment: 'production', authorized_by: 'owner', job_id: 'job-safe', item_count: 2, batch_size: 50, current_batch: 1, total_batches: 1, completed_item_count: 1, failed_item_count: 1, error_code: 'release_item_failed', created_at: priorNow, started_at: priorNow, completed_at: priorNow }], - total: 2, limit: 20, offset: 0, + items: [ + { + id: 'rx-auto', + release_batch_id: 'rb-safe', + operation: 'rollback', + prior_execution_id: 'rx-safe', + state: 'running', + target_environment: 'production', + authorized_by: 'system:auto-rollback', + job_id: 'job-auto', + item_count: 1, + batch_size: 50, + current_batch: 1, + total_batches: 1, + completed_item_count: 0, + failed_item_count: 0, + error_code: '', + created_at: now, + started_at: now, + completed_at: null, + }, + { + id: 'rx-safe', + release_batch_id: 'rb-safe', + operation: 'publish', + prior_execution_id: '', + state: 'failed', + target_environment: 'production', + authorized_by: 'owner', + job_id: 'job-safe', + item_count: 2, + batch_size: 50, + current_batch: 1, + total_batches: 1, + completed_item_count: 1, + failed_item_count: 1, + error_code: 'release_item_failed', + created_at: priorNow, + started_at: priorNow, + completed_at: priorNow, + }, + ], + total: 2, + limit: 20, + offset: 0, } - const executionDetail: ReleaseExecutionDetail = { ...executionPage.items[0], items: [{ publication_id: 'tp-safe', title: 'Synthetic', action: 'delete', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: now, completed_at: now, target_knowledge_base_id: '0b217e8a-2a65-40a3-ab8f-34ac5c7a6f05' }, { publication_id: 'tp-restored', title: 'Restored', action: 'delete', state: 'rolled_back', previous_production_revision: 'prod-v0', production_revision: 'prod-v0', error_code: '', created_at: now, completed_at: now, target_knowledge_base_id: '0b217e8a-2a65-40a3-ab8f-34ac5c7a6f05' }] } - const releasePlan: ReleasePlan = { items: [{ publication_id: 'tp-safe', title: 'B.pdf', target_scope: 'external', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '' }, { publication_id: 'tp-delete', title: 'C.pdf', target_scope: 'internal', action: 'delete', test_state: 'not_required', production_state: 'present', can_release: true, blocker: '' }, { publication_id: '', title: 'D.pdf', target_scope: 'internal', action: 'blocked', test_state: 'ready', production_state: 'present', can_release: false, blocker: 'source_unavailable' }], summary: { add: 1, update: 0, delete: 1, blocked: 1, unchanged: 11284 } } - const html = renderToStaticMarkup() - for (const text of ['来源与目录 → 测试知识库 → 生产知识库','发布计划','新增 1','更新 0','删除 1','未变化 11284','B.pdf','C.pdf','D.pdf','将从生产检索中移除','我确认所选删除项会停止生产检索','待发布(0 + 下架 1)','已选 1 项(删除待确认)','为什么按钮不能点:请确认所选删除项会停止生产检索;至少 1 项动作通过确认;请填写批次名称','至少 1 项动作通过确认','来源当前不可用,保留生产知识','正在执行自动回滚','批次 1 / 1','每批最多 50 项','Snapshot #20260906-090000Z','待你审核', '需人工确认', '批准', '驳回', '创建并锁定清单', '锁定清单(不会上线)', 'Synthetic batch', '删除生产知识', '已从生产检索中移除', '已恢复生产知识', '仍可检查调整', 'Release Worker 默认关闭', '锁定清单 ≠ 上线', '生产确认、发布验证与回滚', '生产操作权限:已阻断', '生产请求门禁已开启', '快照恢复验证未通过', '生产发布已阻断']) { + const executionDetail: ReleaseExecutionDetail = { + ...executionPage.items[0], + items: [ + { + publication_id: 'tp-safe', + title: 'Synthetic', + action: 'delete', + state: 'verified', + previous_production_revision: 'prod-v0', + production_revision: 'absent', + error_code: '', + created_at: now, + completed_at: now, + target_knowledge_base_id: '0b217e8a-2a65-40a3-ab8f-34ac5c7a6f05', + }, + { + publication_id: 'tp-restored', + title: 'Restored', + action: 'delete', + state: 'rolled_back', + previous_production_revision: 'prod-v0', + production_revision: 'prod-v0', + error_code: '', + created_at: now, + completed_at: now, + target_knowledge_base_id: '0b217e8a-2a65-40a3-ab8f-34ac5c7a6f05', + }, + ], + } + const releasePlan: ReleasePlan = { + items: [ + { + publication_id: 'tp-safe', + title: 'B.pdf', + target_scope: 'external', + action: 'add', + test_state: 'ready', + production_state: 'absent', + can_release: true, + blocker: '', + }, + { + publication_id: 'tp-delete', + title: 'C.pdf', + target_scope: 'internal', + action: 'delete', + test_state: 'not_required', + production_state: 'present', + can_release: true, + blocker: '', + }, + { + publication_id: '', + title: 'D.pdf', + target_scope: 'internal', + action: 'blocked', + test_state: 'ready', + production_state: 'present', + can_release: false, + blocker: 'source_unavailable', + }, + ], + summary: { add: 1, update: 0, delete: 1, blocked: 1, unchanged: 11284 }, + } + const html = renderToStaticMarkup( + + ) + for (const text of [ + '来源与目录 → 测试知识库 → 生产知识库', + '发布计划', + '新增 1', + '更新 0', + '删除 1', + '未变化 11284', + 'B.pdf', + 'C.pdf', + 'D.pdf', + '将从生产检索中移除', + '我确认所选删除项会停止生产检索', + '待发布(0 + 下架 1)', + '已选 1 项(删除待确认)', + '为什么按钮不能点:请确认所选删除项会停止生产检索;至少 1 项动作通过确认;请填写批次名称', + '至少 1 项动作通过确认', + '来源当前不可用,保留生产知识', + '正在执行自动回滚', + '批次 1 / 1', + '每批最多 50 项', + 'Snapshot #20260906-090000Z', + '待你审核', + '需人工确认', + '批准', + '驳回', + '创建并锁定清单', + '锁定清单(不会上线)', + 'Synthetic batch', + '删除生产知识', + '已从生产检索中移除', + '已恢复生产知识', + '仍可检查调整', + 'Release Worker 默认关闭', + '锁定清单 ≠ 上线', + '生产确认、发布验证与回滚', + '生产操作权限:已阻断', + '生产请求门禁已开启', + '快照恢复验证未通过', + '生产发布已阻断', + ]) { expect(html).toContain(text) } // 需求(2026-10-10):发布界面要简单——不再显示步骤脚手架/流程编号/引导卡。 @@ -394,7 +747,16 @@ describe('ReleaseManagement', () => { expect(html).toContain('至少 1 项动作通过确认') expect(reviewGateLabel({ review_state: 'approved', gate_status: 'ready' })).toBe('测试已通过') expect(reviewGateLabel({ review_state: 'pending', gate_status: 'ready' })).toBe('可以审核') - for (const technicalValue of ['tp-safe', 'rb-safe', 'rx-safe', 'job-safe', 'release-gate-v1', 'prod-v0', 'prod-v1', '>verified<']) { + for (const technicalValue of [ + 'tp-safe', + 'rb-safe', + 'rx-safe', + 'job-safe', + 'release-gate-v1', + 'prod-v0', + 'prod-v1', + '>verified<', + ]) { expect(html).not.toContain(technicalValue) } expect(html).not.toContain('工程师标识') @@ -404,17 +766,45 @@ describe('ReleaseManagement', () => { describe('release plan pagination (R3)', () => { const baseProps = { reviewPage: { items: [], total: 0, limit: 20, offset: 0 } as any, - reviewLoading: false, reviewError: null, reviewingId: null, + reviewLoading: false, + reviewError: null, + reviewingId: null, batchPage: { items: [], total: 0, limit: 20, offset: 0 } as any, - batchDetail: null, batchLoading: false, batchError: null, mutatingBatchId: null, - onReview: vi.fn(), onReviewRefresh: vi.fn(), onCreateBatch: vi.fn(), onSealBatch: vi.fn(), onSelectBatch: vi.fn(), onBatchRefresh: vi.fn(), - releaseCapabilities: { production_release_requests_enabled: false, production_backup_restore_verified: false, test_auto_review_policy: '' }, + batchDetail: null, + batchLoading: false, + batchError: null, + mutatingBatchId: null, + onReview: vi.fn(), + onReviewRefresh: vi.fn(), + onCreateBatch: vi.fn(), + onSealBatch: vi.fn(), + onSelectBatch: vi.fn(), + onBatchRefresh: vi.fn(), + releaseCapabilities: { + production_release_requests_enabled: false, + production_backup_restore_verified: false, + test_auto_review_policy: '', + }, executionPage: { items: [], total: 0, limit: 20, offset: 0 } as any, - executionDetail: null, executionLoading: false, executionError: null, onSelectExecution: vi.fn(), onExecutionRefresh: vi.fn(), - selectedDeleteIDs: [] as string[], onToggleDelete: vi.fn(), + executionDetail: null, + executionLoading: false, + executionError: null, + onSelectExecution: vi.fn(), + onExecutionRefresh: vi.fn(), + selectedDeleteIDs: [] as string[], + onToggleDelete: vi.fn(), } const planWith = (count: number): ReleasePlan => ({ - items: Array.from({ length: count }, (_, i) => ({ publication_id: `tp-${i}`, title: `文档${i}.pdf`, target_scope: 'internal' as const, action: 'add' as const, test_state: 'ready', production_state: 'absent', can_release: true, blocker: '' })), + items: Array.from({ length: count }, (_, i) => ({ + publication_id: `tp-${i}`, + title: `文档${i}.pdf`, + target_scope: 'internal' as const, + action: 'add' as const, + test_state: 'ready', + production_state: 'absent', + can_release: true, + blocker: '', + })), summary: { add: count, update: 0, delete: 0, blocked: 0, unchanged: 0 }, }) it('renders at most one page (25 rows) instead of the full 618-row plan', () => { @@ -448,51 +838,216 @@ describe('release plan pagination (R3)', () => { describe('R4 rollback levels in the execution timeline', () => { const baseProps = { reviewPage: { items: [], total: 0, limit: 20, offset: 0 } as any, - reviewLoading: false, reviewError: null, reviewingId: null, + reviewLoading: false, + reviewError: null, + reviewingId: null, batchPage: { items: [], total: 0, limit: 20, offset: 0 } as any, - batchDetail: null, batchLoading: false, batchError: null, mutatingBatchId: null, - onReview: vi.fn(), onReviewRefresh: vi.fn(), onCreateBatch: vi.fn(), onSealBatch: vi.fn(), onSelectBatch: vi.fn(), onBatchRefresh: vi.fn(), - releaseCapabilities: { production_release_requests_enabled: true, production_backup_restore_verified: false, test_auto_review_policy: '' }, + batchDetail: null, + batchLoading: false, + batchError: null, + mutatingBatchId: null, + onReview: vi.fn(), + onReviewRefresh: vi.fn(), + onCreateBatch: vi.fn(), + onSealBatch: vi.fn(), + onSelectBatch: vi.fn(), + onBatchRefresh: vi.fn(), + releaseCapabilities: { + production_release_requests_enabled: true, + production_backup_restore_verified: false, + test_auto_review_policy: '', + }, releasePlan: { items: [], summary: { add: 0, update: 0, delete: 0, blocked: 0, unchanged: 0 } } as ReleasePlan, - executionDetail: null, executionLoading: false, executionError: null, onSelectExecution: vi.fn(), onExecutionRefresh: vi.fn(), - selectedDeleteIDs: [] as string[], onToggleDelete: vi.fn(), + executionDetail: null, + executionLoading: false, + executionError: null, + onSelectExecution: vi.fn(), + onExecutionRefresh: vi.fn(), + selectedDeleteIDs: [] as string[], + onToggleDelete: vi.fn(), } - const exec = (over: Record) => ({ - id: 'rx-1', release_batch_id: 'rb-1', operation: 'rollback', prior_execution_id: 'rx-0', - state: 'rolling_back', target_environment: 'production', authorized_by: 'system:auto-rollback', job_id: 'job-1', - item_count: 2, batch_size: 50, current_batch: 1, total_batches: 1, completed_item_count: 1, failed_item_count: 0, - error_code: '', failure_level: '', restore_trigger: 'auto_rollback_after_failure', - created_at: '2026-09-12T09:00:00Z', started_at: '2026-09-12T09:01:00Z', completed_at: null, ...over, - }) as any + const exec = (over: Record) => + ({ + id: 'rx-1', + release_batch_id: 'rb-1', + operation: 'rollback', + prior_execution_id: 'rx-0', + state: 'rolling_back', + target_environment: 'production', + authorized_by: 'system:auto-rollback', + job_id: 'job-1', + item_count: 2, + batch_size: 50, + current_batch: 1, + total_batches: 1, + completed_item_count: 1, + failed_item_count: 0, + error_code: '', + failure_level: '', + restore_trigger: 'auto_rollback_after_failure', + created_at: '2026-09-12T09:00:00Z', + started_at: '2026-09-12T09:01:00Z', + completed_at: null, + ...over, + }) as any it('labels the compensating stage and the escalation after a failed rollback', () => { - const html = renderToStaticMarkup() + const html = renderToStaticMarkup( + + ) expect(html).toContain('正在回滚') expect(html).toContain('正在执行自动回滚') - const failed = renderToStaticMarkup() + const failed = renderToStaticMarkup( + + ) expect(failed).toContain('回滚失败') expect(failed).toContain('整体恢复') - const done = renderToStaticMarkup() + const done = renderToStaticMarkup( + + ) expect(done).toContain('已回滚') expect(done).toContain('已恢复') - const graded = renderToStaticMarkup() + const graded = renderToStaticMarkup( + + ) expect(graded).toContain('本批后续已停止') }) }) // 生产动作(授权发布 / 重排 / 回滚):页面按钮只对管理员出现,且必须逐字输入固定确认语句。 describe('ReleaseManagement production actions', () => { - const authValue = (role: 'admin' | 'engineer') => ({ identity: { id: `${role}-1`, username: role, display_name: role, role, must_change_password: false }, ready: true, login: async () => null, logout: async () => {}, changePassword: async () => null, signedOut: 0, notifySignedOut: () => {} }) + const authValue = (role: 'admin' | 'engineer') => ({ + identity: { id: `${role}-1`, username: role, display_name: role, role, must_change_password: false }, + ready: true, + login: async () => null, + logout: async () => {}, + changePassword: async () => null, + signedOut: 0, + notifySignedOut: () => {}, + }) const now = '2026-10-08T08:00:00Z' - const batchPage: ReleaseBatchPage = { items: [{ id: 'rb-sealed', name: '单文档首发', state: 'sealed', policy_version: 'release-gate-v1', created_by: 'admin', sealed_by: 'admin', item_count: 1, created_at: now, sealed_at: now }], total: 1, limit: 20, offset: 0 } - const executionPage: ReleaseExecutionPage = { items: [{ id: 'rx-done', release_batch_id: 'rb-sealed', operation: 'publish', prior_execution_id: '', state: 'completed', target_environment: 'production', authorized_by: 'admin', job_id: 'job-1', item_count: 1, batch_size: 50, current_batch: 1, total_batches: 1, completed_item_count: 1, failed_item_count: 0, error_code: '', created_at: now, started_at: now, completed_at: now }, { id: 'rx-bad', release_batch_id: 'rb-sealed', operation: 'publish', prior_execution_id: '', state: 'failed', target_environment: 'production', authorized_by: 'admin', job_id: 'job-2', item_count: 1, batch_size: 50, current_batch: 1, total_batches: 1, completed_item_count: 0, failed_item_count: 1, error_code: 'release_item_failed', created_at: now, started_at: now, completed_at: now }], total: 2, limit: 20, offset: 0 } - const base = (extra: Record = {}) => + const batchPage: ReleaseBatchPage = { + items: [ + { + id: 'rb-sealed', + name: '单文档首发', + state: 'sealed', + policy_version: 'release-gate-v1', + created_by: 'admin', + sealed_by: 'admin', + item_count: 1, + created_at: now, + sealed_at: now, + }, + ], + total: 1, + limit: 20, + offset: 0, + } + const executionPage: ReleaseExecutionPage = { + items: [ + { + id: 'rx-done', + release_batch_id: 'rb-sealed', + operation: 'publish', + prior_execution_id: '', + state: 'completed', + target_environment: 'production', + authorized_by: 'admin', + job_id: 'job-1', + item_count: 1, + batch_size: 50, + current_batch: 1, + total_batches: 1, + completed_item_count: 1, + failed_item_count: 0, + error_code: '', + created_at: now, + started_at: now, + completed_at: now, + }, + { + id: 'rx-bad', + release_batch_id: 'rb-sealed', + operation: 'publish', + prior_execution_id: '', + state: 'failed', + target_environment: 'production', + authorized_by: 'admin', + job_id: 'job-2', + item_count: 1, + batch_size: 50, + current_batch: 1, + total_batches: 1, + completed_item_count: 0, + failed_item_count: 1, + error_code: 'release_item_failed', + created_at: now, + started_at: now, + completed_at: now, + }, + ], + total: 2, + limit: 20, + offset: 0, + } + const base = (extra: Record = {}) => ( + + ) it('offers 授权发布 / 重排 / 回滚 to admins only', () => { const admin = renderToStaticMarkup({base()}) @@ -500,7 +1055,9 @@ describe('ReleaseManagement production actions', () => { expect(admin).toContain('重排') expect(admin).toContain('回滚') expect(admin).toContain('生产操作可执行(待确认)') - const engineer = renderToStaticMarkup({base()}) + const engineer = renderToStaticMarkup( + {base()} + ) expect(engineer).not.toContain('授权发布') expect(engineer).not.toContain('') expect(engineer).not.toContain('') @@ -508,15 +1065,49 @@ describe('ReleaseManagement production actions', () => { it('requires the exact confirmation phrase before the action can be submitted', () => { const pending = { kind: 'authorize' as const, id: 'rb-sealed', label: '单文档首发' } - const wrong = renderToStaticMarkup({base({ pendingReleaseAction: pending, releaseActionPhrase: 'publish', onStartReleaseAction: vi.fn(), onReleaseActionPhrase: vi.fn(), onSubmitReleaseAction: vi.fn(), onCancelReleaseAction: vi.fn() })}) + const wrong = renderToStaticMarkup( + + {base({ + pendingReleaseAction: pending, + releaseActionPhrase: 'publish', + onStartReleaseAction: vi.fn(), + onReleaseActionPhrase: vi.fn(), + onSubmitReleaseAction: vi.fn(), + onCancelReleaseAction: vi.fn(), + })} + + ) expect(wrong).toContain('publish-to-production') expect(wrong).toMatch(/ - {error ?

{error}

: null} -
-
-
目标主机
{hostLine}
-
主机 cron
{schedule.host_cron_service ? `服务 ${schedule.host_cron_service}` : '—'}{schedule.host_script_present ? '' : ' · 备份脚本缺失'}
-
最近一次备份
{schedule.last_run_stamp || '—'}{runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''}
-
备份耗时 / 体积
{schedule.last_run_stamp ? `${schedule.last_run_duration_seconds} 秒 · ${formatBackupBytes(schedule.last_run_total_bytes)}` : '—'}
-
-
-
覆盖的库
{schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}
-
失败的库
{schedule.last_run_failed_databases.length ? schedule.last_run_failed_databases.join('、') : '无'}
-
主机上生效的计划
{schedule.host_schedule_enabled ? `每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份` : schedule.host_configured ? '未启用定时' : '—'}
-
与设置是否一致
{schedule.in_sync ? '已一致' : '待下发'}
-
-
- {schedule.host_error ?

主机探测:{schedule.host_error}

: null} - {schedule.last_run_error ?

最近一次结果读取:{schedule.last_run_error}

: null} - {schedule.host_cron_lines.length ?

主机 cron 条目:{schedule.host_cron_lines.join(' ; ')}

: null} - {schedule.last_applied_at ?

最后下发:{formatBackupMoment(schedule.last_applied_at)}{schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''}

: null} -

留档分层:PG 行级留档(发布前,含 ES 文档)+ ES 快照仓 + OSS 版本控制 + 本节的整库逻辑备份 + RDS 托管备份(控制台配置)。详见 docs/PRODUCTION_BACKUP_RECOVERY.md。

- {isAdmin ?
- - - - - {!valid ?

定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。

: null} - - - - {message ?

{message}

: null} - {schedule.running ?

正在备份({formatBackupMoment(schedule.running_started_at)} 开始),完成后自动刷新。

: null} - {schedule.run_last_error && !schedule.running ?

上一次立即备份失败:{schedule.run_last_error}

: null} -
:

定时备份设置仅管理员可修改;当前设置:{schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。

} - + return ( +
+
+
+

存储与备份

+

+ 整库逻辑备份(pg_dump 目录格式)在备份执行主机(同 VPC 直连 RDS) + 上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。 +

+
+ +
+ {error ? ( +

+ {error} +

+ ) : null} +
+
+
目标主机
+
{hostLine}
+
拨号地址
+
{schedule.host_endpoint || '—'}
+
备份脚本
+
{scriptLine}
+
主机 cron
+
+ {schedule.host_cron_service ? `服务 ${schedule.host_cron_service}` : '—'} + {schedule.host_checked_at + ? ` · 状态读取于 ${formatBackupMoment(schedule.host_checked_at)}` + : ' · 状态读取时间未知'} +
+
下次计划(主机读回)
+
+ {schedule.host_next_run + ? schedule.host_next_run + : !schedule.host_configured + ? '未接通备份执行主机:当前计划不会执行' + : schedule.host_schedule_enabled + ? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)` + : '未启用定时或未从主机读到计划'} +
+
最近一次运行
+
+ {schedule.last_run_stamp || '—'} + {runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''} + {schedule.last_run_stamp + ? schedule.last_run_failed_databases.length === 0 && !schedule.last_run_error + ? ' · 成功' + : ' · 有失败/读取错误' + : ''} +
+
最近一次成功
+
未从主机读取(不能用最近一次运行代替成功;失败库/读取错误见下方)
+
备份耗时 / 体积
+
+ {schedule.last_run_stamp + ? `${schedule.last_run_duration_seconds} 秒 · ${formatBackupBytes(schedule.last_run_total_bytes)}` + : '—'} +
+
+
+
覆盖的库
+
{schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}
+
失败的库
+
+ {schedule.last_run_failed_databases.length + ? schedule.last_run_failed_databases.join('、') + : schedule.last_run_stamp + ? '无' + : '未知(还没有读到运行记录,不能据此判断没有失败)'} +
+
主机上生效的计划
+
+ {schedule.host_schedule_enabled + ? `每天 ${schedule.host_schedule_time} · 保留 ${schedule.host_keep_days} 天 · 每月 ${schedule.host_keep_months} 份` + : schedule.host_configured + ? '未启用定时' + : '—'} +
+
与设置是否一致
+
{schedule.in_sync ? '已一致' : '待下发'}
+
+
+ {schedule.host_error ?

主机探测:{schedule.host_error}

: null} + {schedule.last_run_error ?

最近一次结果读取:{schedule.last_run_error}

: null} + {schedule.host_cron_lines.length ? ( +

+ 主机 cron 条目:{schedule.host_cron_lines.join(' ; ')} +

+ ) : null} + {schedule.last_applied_at ? ( +

+ 最后下发:{formatBackupMoment(schedule.last_applied_at)} + {schedule.last_applied_summary ? ` · ${schedule.last_applied_summary}` : ''} +

+ ) : null} +

+ 留档分层:PG 行级留档(发布前,含 ES 文档)+ ES 快照仓 + OSS 版本控制 + 本节的整库逻辑备份 + RDS + 托管备份(控制台配置)。详见 docs/PRODUCTION_BACKUP_RECOVERY.md。 +

+ {isAdmin ? ( +
+ + + + + {!valid ? ( +

定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。

+ ) : null} + + + +

+ 「立即备份一次」执行的是主机上的整库逻辑备份(该主机上全部业务库的 pg_dump 目录), + 不是本次对内/对外 scope 的整库快照;scope 快照在「发布管理 → 整库版本」里封存。 +

+ {message ? ( +

+ {message} +

+ ) : null} + {schedule.running ? ( +

正在备份({formatBackupMoment(schedule.running_started_at)} 开始),完成后自动刷新。

+ ) : null} + {schedule.run_last_error && !schedule.running ? ( +

上一次立即备份失败:{schedule.run_last_error}

+ ) : null} +
+ ) : ( +

+ 定时备份设置仅管理员可修改;当前设置: + {schedule.enabled ? `每天 ${schedule.schedule_time} · 保留 ${schedule.retention_days} 天` : '未启用'}。 +

+ )} +
+ ) } -// 容器:读取 + 下发 + 在途轮询。真正执行备份的是目标库所在主机(同 VPC 直连 RDS)。 +// 容器:读取 + 下发 + 在途轮询。真正执行备份的是备份执行主机(同 VPC 直连 RDS)。 export function BackupScheduleSection() { const auth = useOptionalAuth() const isAdmin = auth?.identity?.role === 'admin' @@ -133,7 +301,8 @@ export function BackupScheduleSection() { }, []) const load = useCallback(async () => { - setLoading(true); setError(null) + setLoading(true) + setError(null) try { adopt(await fetchBackupSchedule()) setProbing(true) @@ -141,83 +310,145 @@ export function BackupScheduleSection() { adopt(await fetchBackupScheduleHost()) } catch (cause) { setError(cause instanceof Error ? cause.message : '读取目标主机上的备份状态失败') - } finally { setProbing(false) } + } finally { + setProbing(false) + } } catch (cause) { setError(cause instanceof Error ? cause.message : '读取备份计划失败') - } finally { setLoading(false) } + } finally { + setLoading(false) + } }, [adopt]) - useEffect(() => { void load() }, [load]) + useEffect(() => { + void load() + }, [load]) // 立即备份约 30~60 秒:在途时轮询主机状态,直到 running 转假并出现新的最近一次结果。 useEffect(() => { if (!schedule?.running) { - if (polling.current !== null) { window.clearInterval(polling.current); polling.current = null } + if (polling.current !== null) { + window.clearInterval(polling.current) + polling.current = null + } return } if (polling.current !== null) return polling.current = window.setInterval(() => { - void fetchBackupScheduleHost().then(adopt).catch(() => undefined) + void fetchBackupScheduleHost() + .then(adopt) + .catch(() => undefined) }, 5000) return () => { - if (polling.current !== null) { window.clearInterval(polling.current); polling.current = null } + if (polling.current !== null) { + window.clearInterval(polling.current) + polling.current = null + } } }, [schedule?.running, adopt]) const save = async () => { - setBusy('save'); setError(null); setMessage('') + setBusy('save') + setError(null) + setMessage('') try { const next = await saveBackupSchedule({ - enabled: enabledDraft, schedule_time: timeDraft, - retention_days: Number(daysDraft), retention_months: Number(monthsDraft), apply: true, + enabled: enabledDraft, + schedule_time: timeDraft, + retention_days: Number(daysDraft), + retention_months: Number(monthsDraft), + apply: true, }) adopt(next) if (!next.host_configured) { setMessage('计划已保存。目标主机凭据未挂载,因此还不能下发到主机上的 cron。') } else if (next.applied) { - setMessage(`计划已保存并下发:每天 ${next.schedule_time} 执行,保留 ${next.retention_days} 天(每月另留 ${next.retention_months} 份)。`) + setMessage( + `计划已保存并下发:每天 ${next.schedule_time} 执行,保留 ${next.retention_days} 天(每月另留 ${next.retention_months} 份)。` + ) } else { setMessage(`计划已保存,但下发失败:${next.apply_error}`) } - } catch (cause) { setError(cause instanceof Error ? cause.message : '保存备份计划失败') } - finally { setBusy(null) } + } catch (cause) { + setError(cause instanceof Error ? cause.message : '保存备份计划失败') + } finally { + setBusy(null) + } } const apply = async () => { - setBusy('apply'); setError(null); setMessage('') + setBusy('apply') + setError(null) + setMessage('') try { const next = await applyBackupSchedule() adopt(next) setMessage(next.applied ? '已按当前设置重新下发到目标主机。' : `下发失败:${next.apply_error}`) - } catch (cause) { setError(cause instanceof Error ? cause.message : '下发备份计划失败') } - finally { setBusy(null) } + } catch (cause) { + setError(cause instanceof Error ? cause.message : '下发备份计划失败') + } finally { + setBusy(null) + } } const runNow = async () => { - setBusy('run'); setError(null); setMessage('') + setBusy('run') + setError(null) + setMessage('') try { const start = await runBackupNow() - setMessage(start.started ? '已在目标主机上开始备份(整库 pg_dump,约 30~60 秒),下方会自动刷新结果。' : '已有一个备份任务在执行中。') + setMessage( + start.started + ? '已在目标主机上开始备份(整库 pg_dump,约 30~60 秒),下方会自动刷新结果。' + : '已有一个备份任务在执行中。' + ) adopt(await fetchBackupScheduleHost()) - } catch (cause) { setError(cause instanceof Error ? cause.message : '触发备份失败') } - finally { setBusy(null) } + } catch (cause) { + setError(cause instanceof Error ? cause.message : '触发备份失败') + } finally { + setBusy(null) + } } if (!schedule) { - return
-

存储与备份

- {error ?

{error}

: null} -

{loading ? '正在读取备份计划…' : '备份计划暂不可用。'}

-
+ return ( +
+
+
+

存储与备份

+
+
+ {error ? ( +

+ {error} +

+ ) : null} +

{loading ? '正在读取备份计划…' : '备份计划暂不可用。'}

+
+ ) } - return void save()} onApply={() => void apply()} onRunNow={() => void runNow()} - onReload={() => void load()} - /> -} \ No newline at end of file + return ( + void save()} + onApply={() => void apply()} + onRunNow={() => void runNow()} + onReload={() => void load()} + /> + ) +} diff --git a/web/src/DWSAccount.mounted.test.tsx b/web/src/DWSAccount.mounted.test.tsx new file mode 100644 index 0000000..cc66cdd --- /dev/null +++ b/web/src/DWSAccount.mounted.test.tsx @@ -0,0 +1,167 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { DWSAccount } from './DWSAccount' +const id = 'a'.repeat(32) +const session = { + id, + state: 'waiting', + verification_url: 'https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE', + user_code: 'TEST-CODE', + expires_at: '2099-01-01T01:00:00Z', +} +const json = (data: unknown, status = 200) => new Response(JSON.stringify({ data }), { status }) +let root: Root +let container: HTMLDivElement +let fetcher: ReturnType Promise>> +const flush = async () => { + await act(async () => { + await Promise.resolve() + }) +} +const click = async (label: string) => { + const button = Array.from(container.querySelectorAll('button')).find((x) => x.textContent === label) + expect(button, label).toBeTruthy() + await act(async () => button!.click()) +} +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + vi.useFakeTimers() + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + fetcher = vi.fn((path: string, init?: RequestInit) => { + if (path.endsWith('credential-status')) + return Promise.resolve(json({ authenticated: false, refresh_token_valid: false })) + if (path === '/api/v1/dws-login') return Promise.resolve(json(session, 202)) + if (path.startsWith('/api/v1/dws-login/')) + return Promise.resolve(json({ ...session, state: init?.method === 'DELETE' ? 'cancelled' : 'waiting' })) + if (path.endsWith('/available')) + return Promise.resolve(json({ knowledge_bases: [], drive_spaces: [], fetched_at: '2026-11-17T09:00:00Z' })) + throw new Error(`unexpected ${path}`) + }) + vi.stubGlobal('fetch', fetcher) +}) +afterEach(async () => { + await act(async () => root.unmount()) + container.remove() + vi.useRealTimers() + vi.unstubAllGlobals() +}) +const mount = async () => { + await act(async () => root.render()) + await flush() +} + +describe('DWS device authorization', () => { + it('opens the official challenge and cancellation removes it', async () => { + await mount() + await click('登录授权') + expect(container.querySelector('[role="dialog"]')).not.toBeNull() + expect(container.querySelector('a')?.href).toBe(session.verification_url) + expect(container.textContent).toContain('TEST-CODE') + await click('取消授权') + expect(container.querySelector('[role="dialog"]')).toBeNull() + expect(fetcher.mock.calls.some(([path, init]) => path.endsWith(id) && init?.method === 'DELETE')).toBe(true) + }) + it('refreshes identity after login and independently reports failed directory access', async () => { + let authorized = false + fetcher.mockImplementation((path: string, init?: RequestInit) => { + if (path.endsWith('credential-status')) + return Promise.resolve( + json({ + authenticated: authorized, + refresh_token_valid: authorized, + corp_name: '测试组织', + user_name: '测试账号', + }) + ) + if (path === '/api/v1/dws-login') return Promise.resolve(json(session, 202)) + if (path.endsWith('/available')) + return Promise.resolve(new Response(JSON.stringify({ error: '目录权限不足' }), { status: 503 })) + if (init?.method === 'DELETE') return Promise.resolve(json({ ...session, state: 'cancelled' })) + authorized = true + return Promise.resolve(json({ ...session, state: 'succeeded', verification_url: '', user_code: '' })) + }) + await mount() + await click('登录授权') + await act(async () => vi.advanceTimersByTimeAsync(1500)) + await flush() + expect(container.querySelector('[role="dialog"]')).toBeNull() + expect(container.textContent).toContain('DWS 登录成功') + expect(container.textContent).toContain('测试账号 · 测试组织') + expect(container.textContent).toContain('目录连接检查未通过:目录权限不足') + expect(container.textContent).not.toContain('目录连接正常') + }) + it('reports partial directory access without claiming full connection success', async () => { + const fallback = fetcher.getMockImplementation()! + fetcher.mockImplementation((path: string, init?: RequestInit) => + path.endsWith('/available') + ? Promise.resolve( + json({ + knowledge_bases: [{}], + drive_spaces: [], + knowledge_notice: '个人知识库权限不足', + fetched_at: '2026-11-17T09:00:00Z', + }) + ) + : fallback(path, init) + ) + await mount() + await click('检查连接') + expect(container.textContent).toContain('目录部分可用') + expect(container.textContent).toContain('个人知识库权限不足') + expect(container.textContent).not.toContain('目录连接正常') + expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false) + }) + it('shows backend startup errors and provides retry', async () => { + const fallback = fetcher.getMockImplementation()! + fetcher.mockImplementation((path: string, init?: RequestInit) => + path === '/api/v1/dws-login' + ? Promise.resolve(new Response(JSON.stringify({ error: '另一位管理员正在授权' }), { status: 409 })) + : fallback(path, init) + ) + await mount() + await click('登录授权') + expect(container.textContent).toContain('另一位管理员正在授权') + expect(Array.from(container.querySelectorAll('button')).some((x) => x.textContent === '重试')).toBe(true) + }) + it('cancels a session returned after its dialog was closed during startup', async () => { + let resolve!: (response: Response) => void + const fallback = fetcher.getMockImplementation()! + fetcher.mockImplementation((path: string, init?: RequestInit) => + path === '/api/v1/dws-login' + ? new Promise((done) => { + resolve = done + }) + : fallback(path, init) + ) + await mount() + await click('登录授权') + await click('取消授权') + await act(async () => resolve(json(session, 202))) + await flush() + expect(container.querySelector('[role="dialog"]')).toBeNull() + expect(fetcher.mock.calls.some(([path, init]) => path.endsWith(id) && init?.method === 'DELETE')).toBe(true) + }) + it('does not reopen a cancelled dialog when a late poll succeeds', async () => { + let resolve!: (response: Response) => void + const fallback = fetcher.getMockImplementation()! + fetcher.mockImplementation((path: string, init?: RequestInit) => + path.endsWith(id) && init?.method === 'GET' + ? new Promise((done) => { + resolve = done + }) + : fallback(path, init) + ) + await mount() + await click('登录授权') + await act(async () => vi.advanceTimersByTimeAsync(1500)) + await click('取消授权') + await act(async () => resolve(json({ ...session, state: 'succeeded' }))) + await flush() + expect(container.querySelector('[role="dialog"]')).toBeNull() + expect(container.textContent).not.toContain('DWS 登录成功') + }) +}) diff --git a/web/src/DWSAccount.test.tsx b/web/src/DWSAccount.test.tsx new file mode 100644 index 0000000..2fd6ffc --- /dev/null +++ b/web/src/DWSAccount.test.tsx @@ -0,0 +1,12 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import { DingtalkAccountStatus } from './SourceManagement' + +describe('DWS account entry', () => { + it('offers device login and a separate connection check beside account status', () => { + const html = renderToStaticMarkup() + expect(html).toContain('登录授权') + expect(html).toContain('检查连接') + expect(html).not.toContain('扫码刷新会话') + }) +}) diff --git a/web/src/DWSAccount.tsx b/web/src/DWSAccount.tsx new file mode 100644 index 0000000..ca9bc6f --- /dev/null +++ b/web/src/DWSAccount.tsx @@ -0,0 +1,313 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + cancelDWSLogin, + checkDWSConnection, + dwsLoginActive, + fetchDWSCredentials, + fetchDWSLogin, + startDWSLogin, +} from './dwsLogin' +import type { DWSCredentials, DWSLogin } from './dwsLogin' + +const messageOf = (cause: unknown) => (cause instanceof Error ? cause.message : '请求失败,请重试') +const moment = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false }) + +export function DWSAccount({ + autoStart = false, + onAuthorized, + onCredentials, + onCancel, +}: { + autoStart?: boolean + onAuthorized?: (credentials: DWSCredentials) => void + onCredentials?: (credentials: DWSCredentials) => void + onCancel?: () => void +} = {}) { + const callbacks = useRef({ onAuthorized, onCredentials, onCancel }) + callbacks.current = { onAuthorized, onCredentials, onCancel } + const startedAutomatically = useRef(false) + const [credentials, setCredentials] = useState(null) + const [loading, setLoading] = useState(true) + const [error, setError] = useState('') + const [notice, setNotice] = useState('') + const [connection, setConnection] = useState> | null>(null) + const [checking, setChecking] = useState(false) + const [session, setSession] = useState(null) + const [open, setOpen] = useState(false) + const [starting, setStarting] = useState(false) + const [loginError, setLoginError] = useState('') + const id = useRef('') + const generation = useRef(0) + const mounted = useRef(false) + const handled = useRef('') + const action = useRef(null) + const checkAction = useRef(null) + + useEffect(() => { + mounted.current = true + const controller = new AbortController() + void fetchDWSCredentials(controller.signal) + .then((fresh) => { + setCredentials(fresh) + callbacks.current.onCredentials?.(fresh) + }) + .catch((cause) => { + if (!controller.signal.aborted) setError(messageOf(cause)) + }) + .finally(() => { + if (!controller.signal.aborted) setLoading(false) + }) + return () => { + mounted.current = false + controller.abort() + action.current?.abort() + checkAction.current?.abort() + generation.current++ + if (id.current) void cancelDWSLogin(id.current).catch(() => undefined) + } + }, []) + + const check = useCallback(async () => { + checkAction.current?.abort() + const controller = new AbortController() + checkAction.current = controller + setChecking(true) + setConnection(null) + setError('') + try { + const result = await checkDWSConnection(controller.signal) + const fresh = await fetchDWSCredentials(controller.signal) + if (!controller.signal.aborted && mounted.current) { + setConnection(result) + setCredentials(fresh) + } + } catch (cause) { + if (!controller.signal.aborted && mounted.current) setError(`目录连接检查未通过:${messageOf(cause)}`) + } finally { + if (!controller.signal.aborted && mounted.current) setChecking(false) + } + }, []) + + const start = async () => { + const current = ++generation.current + action.current?.abort() + checkAction.current?.abort() + setChecking(false) + const controller = new AbortController() + action.current = controller + setOpen(true) + setStarting(true) + setSession(null) + setLoginError('') + setNotice('') + setConnection(null) + setError('') + try { + const next = await startDWSLogin(controller.signal) + if (!mounted.current || current !== generation.current) { + void cancelDWSLogin(next.id).catch(() => undefined) + return + } + id.current = next.id + setSession(next) + } catch (cause) { + if (mounted.current && current === generation.current) setLoginError(messageOf(cause)) + } finally { + if (mounted.current && current === generation.current) setStarting(false) + } + } + + useEffect(() => { + if (autoStart && !startedAutomatically.current) { + startedAutomatically.current = true + void start() + } + }, [autoStart]) + + const close = async () => { + const current = generation.current + const sessionID = id.current + setLoginError('') + if (!sessionID && starting) { + // Keep the POST alive so its returned session can be cancelled by ID. + ++generation.current + setOpen(false) + setStarting(false) + callbacks.current.onCancel?.() + return + } + if (sessionID && session && dwsLoginActive(session.state)) { + try { + await cancelDWSLogin(sessionID) + } catch (cause) { + if (mounted.current && generation.current === current) setLoginError(`取消未完成:${messageOf(cause)}`) + return + } + } + if (mounted.current && generation.current === current) { + ++generation.current + id.current = '' + setOpen(false) + setSession(null) + callbacks.current.onCancel?.() + } + } + + useEffect(() => { + if (!session || !dwsLoginActive(session.state) || loginError) return + const controller = new AbortController() + const current = generation.current + const timer = window.setTimeout(() => { + void fetchDWSLogin(session.id, controller.signal) + .then((next) => { + if (!controller.signal.aborted && current === generation.current) setSession(next) + }) + .catch((cause) => { + if (!controller.signal.aborted && current === generation.current) setLoginError(messageOf(cause)) + }) + }, 1500) + return () => { + window.clearTimeout(timer) + controller.abort() + } + }, [session, loginError]) + + useEffect(() => { + if (session?.state !== 'succeeded' || handled.current === session.id) return + handled.current = session.id + const current = generation.current + id.current = '' + setOpen(false) + setNotice('DWS 登录成功,正在检查目录连接…') + void fetchDWSCredentials() + .then((fresh) => { + if (!mounted.current || current !== generation.current) return + setCredentials(fresh) + setNotice('DWS 登录成功') + callbacks.current.onCredentials?.(fresh) + void check() + callbacks.current.onAuthorized?.(fresh) + }) + .catch((cause) => { + if (mounted.current && current === generation.current) setError(`授权成功,状态刷新失败:${messageOf(cause)}`) + }) + }, [session, check]) + + const status = loading + ? '读取中…' + : error && !credentials + ? '状态读取失败' + : !credentials?.status_known + ? '登录状态待核验' + : !credentials.authenticated + ? '未登录' + : credentials.refresh_token_valid + ? '已登录' + : '凭证需更新' + const busy = starting || Boolean(session && dwsLoginActive(session.state)) + const labels: Record = { + starting: '正在生成授权入口…', + waiting: '请打开钉钉授权页,确认本次登录。完成后此页会自动更新。', + verifying: '已收到授权,正在验证并保存登录状态…', + succeeded: '登录成功', + expired: '授权已过期,请重新发起。', + failed: '授权未完成,请重试。', + cancelled: '授权已取消。', + } + return ( +
+
+
+ 钉钉账号(DWS) · {status} + {credentials?.authenticated ? ( +
+ {[credentials.user_name, credentials.corp_name].filter(Boolean).join(' · ') || '账号信息暂未返回'} +
+ ) : null} + {credentials?.authenticated && credentials.refresh_expires_at ? ( + 授权有效期至 {moment(credentials.refresh_expires_at)} + ) : null} +
+
+ + +
+
+ 所有钉钉来源共用此账号。登录后检查知识库与钉盘的实际访问权限。 + {notice ? ( +

+ {notice} +

+ ) : null} + {error ? ( +

+ {error} +

+ ) : null} + {connection ? ( +
+

+ {connection.notices.length ? '目录部分可用' : '目录连接正常'}:{connection.message} · 检查于{' '} + {moment(connection.checkedAt)} +

+ {connection.notices.map((value) => ( +

+ {value} +

+ ))} +
+ ) : null} + {open ? ( +
+
+

DWS 登录授权

+

{starting ? '正在生成授权入口…' : session ? labels[session.state] : '授权入口生成失败'}

+ {session?.state === 'waiting' && session.verification_url ? ( + <> + + 打开钉钉授权页 + +

+ 若授权页要求输入授权码:{session.user_code} +

+ 本次授权有效期至 {moment(session.expires_at)} + + ) : null} + {session?.error ? ( +

+ {session.error} +

+ ) : null} + {loginError ? ( +

+ {loginError} +

+ ) : null} +
+ {session && !dwsLoginActive(session.state) ? ( + + ) : null} + {loginError && session && dwsLoginActive(session.state) ? ( + + ) : null} + {!starting && !session ? : null} + +
+
+
+ ) : null} +
+ ) +} diff --git a/web/src/DingtalkSessionControl.test.tsx b/web/src/DingtalkSessionControl.test.tsx index 42a181c..9ee6821 100644 --- a/web/src/DingtalkSessionControl.test.tsx +++ b/web/src/DingtalkSessionControl.test.tsx @@ -1,12 +1,12 @@ import { renderToStaticMarkup } from 'react-dom/server' -import { describe,expect,it,vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { DingtalkSessionControl } from './DingtalkSessionControl' -describe('DingtalkSessionControl',()=>{ - it('renders the admin scan button without firing any request',()=>{ - const fetchMock=vi.fn() - vi.stubGlobal('fetch',fetchMock) - const markup=renderToStaticMarkup() +describe('DingtalkSessionControl', () => { + it('renders the admin scan button without firing any request', () => { + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + const markup = renderToStaticMarkup() expect(markup).toContain('扫码刷新会话') expect(markup).not.toContain('modal-backdrop') expect(fetchMock).not.toHaveBeenCalled() diff --git a/web/src/DingtalkSessionControl.tsx b/web/src/DingtalkSessionControl.tsx index 5429388..0e2d467 100644 --- a/web/src/DingtalkSessionControl.tsx +++ b/web/src/DingtalkSessionControl.tsx @@ -18,7 +18,14 @@ interface DingtalkSessionControlProps { onClose?: () => void } -export function DingtalkSessionControl({ autoStart = false, hideTrigger = false, space, onSuccess, onClose, triggerLabel = '扫码刷新会话' }: DingtalkSessionControlProps = {}) { +export function DingtalkSessionControl({ + autoStart = false, + hideTrigger = false, + space, + onSuccess, + onClose, + triggerLabel = '扫码刷新会话', +}: DingtalkSessionControlProps = {}) { const [session, setSession] = useState(null) const [failure, setFailure] = useState(null) const [starting, setStarting] = useState(false) @@ -28,29 +35,43 @@ export function DingtalkSessionControl({ autoStart = false, hideTrigger = false, const autoStartedRef = useRef(false) const successHandledRef = useRef(false) - useEffect(() => () => { if (idRef.current) void cancelDingtalkSession(idRef.current) }, []) + useEffect( + () => () => { + if (idRef.current) void cancelDingtalkSession(idRef.current) + }, + [] + ) useEffect(() => { if (!session || finished.has(session.state)) return const timer = setInterval(() => { - fetchDingtalkSession(session.id).then(setSession).catch(() => undefined) + fetchDingtalkSession(session.id) + .then(setSession) + .catch(() => undefined) }, 1500) return () => clearInterval(timer) }, [session?.id, session?.state]) - const close = useCallback((cancel = true) => { - if (cancel && idRef.current) void cancelDingtalkSession(idRef.current) - idRef.current = null - setSession(null) - setStarting(false) - setOpen(false) - onClose?.() - }, [onClose]) + const close = useCallback( + (cancel = true) => { + if (cancel && idRef.current) void cancelDingtalkSession(idRef.current) + idRef.current = null + setSession(null) + setStarting(false) + setOpen(false) + onClose?.() + }, + [onClose] + ) const start = useCallback(async () => { // Show the dialog immediately. Launching Chromium and rendering the QR can // take several seconds and must never look like an ignored click. - setOpen(true); setStarting(true); setFailure(null); setSession(null); setLastSuccess(false) + setOpen(true) + setStarting(true) + setFailure(null) + setSession(null) + setLastSuccess(false) successHandledRef.current = false try { const fresh = await startDingtalkSession(space) @@ -81,35 +102,82 @@ export function DingtalkSessionControl({ autoStart = false, hideTrigger = false, }, [session?.state, onSuccess, close]) const stateLabel: Record = { - starting: '正在生成二维码,请稍候…', qr: '请用钉钉 App 扫码登录', scanned: '已扫码,正在验证并继续…', - reusing: '检测到有效浏览器会话,正在验证…', success: '✅ 钉钉扫码会话已刷新,扫描任务可继续使用', - expired: '二维码已过期,请重新发起', failed: '会话验证失败,请重试或联系管理员', closed: '会话已关闭', + starting: '正在生成二维码,请稍候…', + qr: '请用钉钉 App 扫码登录', + scanned: '已扫码,正在验证并继续…', + reusing: '检测到有效浏览器会话,正在验证…', + success: '✅ 钉钉扫码会话已刷新,扫描任务可继续使用', + expired: '二维码已过期,请重新发起', + failed: '会话验证失败,请重试或联系管理员', + closed: '会话已关闭', } const generating = open && !failure && (starting || !session || session.state === 'starting') - return
- {!hideTrigger ? : null} - {lastSuccess && !hideTrigger ?

✅ 钉钉会话已刷新

: null} - {failure && !open ?

{failure}

: null} - {open ?
-
-

刷新钉钉扫码会话

-

- {generating ? '正在生成二维码,请稍候…' : session ? (stateLabel[session.state] ?? session.state) : '二维码生成失败,请重试'} + return ( +

+ {!hideTrigger ? ( + + ) : null} + {lastSuccess && !hideTrigger ? ( +

+ ✅ 钉钉会话已刷新

- {generating ? : null} - {session?.qr_png && session.state === 'qr' ? 钉钉登录二维码 : null} - {session?.error ?

{session.error}

: null} - {failure ?

{failure}

: null} -
- {session && finished.has(session.state) - ? - : } + ) : null} + {failure && !open ? ( +

+ {failure} +

+ ) : null} + {open ? ( +
+
+

刷新钉钉扫码会话

+

+ {generating + ? '正在生成二维码,请稍候…' + : session + ? (stateLabel[session.state] ?? session.state) + : '二维码生成失败,请重试'} +

+ {generating ? ( + + ) : null} + {session?.qr_png && session.state === 'qr' ? ( + 钉钉登录二维码 + ) : null} + {session?.error ? ( +

+ {session.error} +

+ ) : null} + {failure ? ( +

+ {failure} +

+ ) : null} +
+ {session && finished.has(session.state) ? ( + + ) : ( + + )} +
+
-
-
: null} -
+ ) : null} +
+ ) } diff --git a/web/src/DingtalkSourceDiscovery.test.tsx b/web/src/DingtalkSourceDiscovery.test.tsx index b90b05e..76c95cf 100644 --- a/web/src/DingtalkSourceDiscovery.test.tsx +++ b/web/src/DingtalkSourceDiscovery.test.tsx @@ -8,11 +8,18 @@ describe('DingtalkSourceDiscovery', () => { const html = renderToStaticMarkup( ) - for (const text of ['dws 导入(钉钉)', '刷新列表', '加入为来源(选中 0)', '已是来源']) { + for (const text of ['添加数据源向导', '类型', '授权', '范围', '校验', '保存', '钉钉知识库', '钉盘']) { expect(html).toContain(text) } // 需求(2026-10-10):数据源配置这里不再做文件格式筛选——格式归目录级标注决定。 - for (const removed of ['文件格式筛选', '未勾选的一律不取件', '保存保留格式', '恢复继承上级规则']) { + for (const removed of [ + '文件格式筛选', + '未勾选的一律不取件', + '保存保留格式', + '恢复继承上级规则', + '扫码会话', + '弹二维码', + ]) { expect(html).not.toContain(removed) } }) diff --git a/web/src/DingtalkSourceDiscovery.tsx b/web/src/DingtalkSourceDiscovery.tsx index 307789b..637701a 100644 --- a/web/src/DingtalkSourceDiscovery.tsx +++ b/web/src/DingtalkSourceDiscovery.tsx @@ -1,21 +1,6 @@ -import { useCallback, useEffect, useState } from 'react' - -import { DingtalkRequestError, registerDingtalkSpace } from './dingtalkSession' -import { DingtalkSessionControl } from './DingtalkSessionControl' -import { - discoveryCandidates, - fetchAvailableDingtalkSources, - type AvailableDingtalkSources, - type DiscoveryCandidate, -} from './dingtalkSources' - -// 「系统设置 → 数据源配置」里的数据源发现面板(管理员): -// ① 列出当前钉钉账号(dws)能看到的钉钉知识库; -// ② 列出钉盘空间(我的文件 / 组织空间); -// ③ 勾选后加入为来源(登记走既有路径,首次目录扫描自动排队); -// ④ 登记需要有效的钉钉扫码会话:会话失效时直接弹二维码,扫完自动重试本次登记。 -// 这里不显示文件格式筛选:格式由目录级标注决定,不在这张卡上做。 +import { SourceWizard } from './SourceWizard' +// Keep historical callers on the same DWS authorization and recovery path. export function DingtalkSourceDiscovery({ registeredNames, onRegistered, @@ -23,171 +8,5 @@ export function DingtalkSourceDiscovery({ registeredNames: string[] onRegistered: () => void }) { - const [list, setList] = useState(null) - const [loading, setLoading] = useState(false) - const [loadError, setLoadError] = useState(null) - const [checked, setChecked] = useState([]) - const [busy, setBusy] = useState(false) - const [message, setMessage] = useState(null) - const [failure, setFailure] = useState(null) - const [loginRequired, setLoginRequired] = useState(false) - - const load = useCallback(async (signal?: AbortSignal) => { - setLoading(true) - setLoadError(null) - try { - const next = await fetchAvailableDingtalkSources(signal) - setList(next) - // 已登记的默认不再勾选:避免重复登记。 - setChecked([]) - } catch (cause) { - if (cause instanceof DOMException && cause.name === 'AbortError') return - setLoadError(cause instanceof Error ? cause.message : '列举数据源失败') - setList(null) - } finally { - setLoading(false) - } - }, []) - - useEffect(() => { - const controller = new AbortController() - void load(controller.signal) - return () => controller.abort() - }, [load]) - - const candidates = discoveryCandidates(list, registeredNames) - const knowledgeBases = candidates.filter((item) => item.kind === 'knowledge_base') - const driveSpaces = candidates.filter((item) => item.kind === 'drive_space') - const selected = candidates.filter((item) => checked.includes(item.key)) - const toggle = (key: string) => - setChecked((current) => (current.includes(key) ? current.filter((item) => item !== key) : [...current, key])) - - const submit = async (retryAfterLogin = false) => { - setBusy(true) - setFailure(null) - setMessage(null) - const added: string[] = [] - const failed: string[] = [] - let needLogin = false - for (const candidate of selected) { - try { - const result = await registerDingtalkSpace(candidate.url) - added.push(result.name || candidate.name) - } catch (cause) { - // 扫码会话失效:登记本身没问题,直接弹二维码,扫完自动重试剩下的。 - if (cause instanceof DingtalkRequestError && cause.code === 'login_required' && !retryAfterLogin) { - needLogin = true - break - } - failed.push(`${candidate.name}:${cause instanceof Error ? cause.message : '登记失败'}`) - } - } - setBusy(false) - if (needLogin) { - setLoginRequired(true) - setFailure('钉钉扫码会话已失效:请扫码登录,登录成功后会自动继续这次登记。') - return - } - if (added.length) { - setMessage(`已加入 ${added.length} 个来源:${added.join('、')}。首次目录扫描已在后台排队。`) - onRegistered() - void load() - } - if (failed.length) setFailure(failed.join(';')) - } - - const resumeAfterLogin = () => { - setLoginRequired(false) - setFailure(null) - void submit(true) - } - - const renderRow = (candidate: DiscoveryCandidate) => { - const already = candidate.alreadyRegistered - return ( -
  • - - {already ? 已是来源 : null} -
  • - ) - } - - return ( -
    -
    -
    - dws 导入(钉钉) - 按当前钉钉账号列出能访问的知识库与钉盘空间;勾选后加入为来源,首次目录扫描自动排队。 -
    - -
    - {loadError ? ( -

    - {loadError} -

    - ) : null} - {list ? ( -
    -
    -

    知识库({knowledgeBases.length})

    - {list.knowledge_notice ? ( - 知识库列表可能不全:{list.knowledge_notice} - ) : null} - {knowledgeBases.length ? ( -
      {knowledgeBases.map(renderRow)}
    - ) : ( - 当前账号下没有可访问的知识库。 - )} -
    -
    -

    钉盘({driveSpaces.length})

    - {list.drive_notice ? 钉盘这次列不出来:{list.drive_notice} : null} - {!list.drive_notice && !driveSpaces.length ? ( - 当前账号下没有可见的钉盘空间。 - ) : null} - {driveSpaces.length ?
      {driveSpaces.map(renderRow)}
    : null} -
    -
    - ) : null} -
    - - 勾选的知识库会登记为来源连接;已登记的条目标为「已是来源」,不会重复登记。 -
    - {message ? ( -

    - {message} -

    - ) : null} - {failure ? ( -

    - {failure} -

    - ) : null} - {loginRequired ? ( - setLoginRequired(false)} - /> - ) : null} -
    - ) + return } diff --git a/web/src/DocumentWorkbench.test.tsx b/web/src/DocumentWorkbench.test.tsx index caa456e..5816acf 100644 --- a/web/src/DocumentWorkbench.test.tsx +++ b/web/src/DocumentWorkbench.test.tsx @@ -4,30 +4,80 @@ import { DocumentWorkbenchView } from './DocumentWorkbench' import { document } from './documentFixture' describe('document engineer workbench', () => { - it('shows real file names, source categories and scope without technical identifiers', () => { - const manual={...document,id:'manual',title:'P3 验收文档',source_type:'manual' as const,connection_id:'manual-1'} - const html = renderToStaticMarkup() - for (const text of ['来源与目录','手册.pdf','使用指南','对外','解析完成','PP分类','未接通目录','文件名','显示 1 份验收文档']) expect(html).toContain(text) - expect(html).not.toContain('P3 验收文档') - expect(html).not.toContain('a') - expect(html).not.toContain('只走这 8 步') - }) - it('shows monitoring and no fabricated page progress or production availability', () => { - const html = renderToStaticMarkup() - expect(html).toContain('解析监控') - expect(html).toContain('来源处理概览') - expect(html).toContain('已就绪 1 / 2') - expect(html).toContain('独立解析') - expect(html).toContain('内容复用') - expect(html).toContain('处理中 1') - expect(html).toContain('解析完成不代表已上线') - expect(html).not.toContain('100%') - expect(html).not.toContain('生产可用') - }) - it('does not display zero as a successful load when the request failed', () => { - const html = renderToStaticMarkup() - expect(html).toContain('加载失败') - expect(html).not.toContain('aria-label="当前目录统计"') - expect(html).not.toContain('没有符合条件的文件') - }) + it('shows real file names, source categories and scope without technical identifiers', () => { + const manual = { + ...document, + id: 'manual', + title: 'P3 验收文档', + source_type: 'manual' as const, + connection_id: 'manual-1', + } + const html = renderToStaticMarkup( + + ) + for (const text of [ + '来源与目录', + '手册.pdf', + '使用指南', + '对外', + '解析完成', + 'PP分类', + '未接通目录', + '文件名', + '显示 1 份验收文档', + ]) + expect(html).toContain(text) + expect(html).not.toContain('P3 验收文档') + expect(html).not.toContain('a') + expect(html).not.toContain('只走这 8 步') + }) + it('shows monitoring and no fabricated page progress or production availability', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('解析监控') + expect(html).toContain('来源处理概览') + expect(html).toContain('已就绪 1 / 2') + expect(html).toContain('独立解析') + expect(html).toContain('内容复用') + expect(html).toContain('处理中 1') + expect(html).toContain('解析完成不代表已上线') + expect(html).not.toContain('100%') + expect(html).not.toContain('生产可用') + }) + it('does not display zero as a successful load when the request failed', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('加载失败') + expect(html).not.toContain('aria-label="当前目录统计"') + expect(html).not.toContain('没有符合条件的文件') + }) }) diff --git a/web/src/DocumentWorkbench.tsx b/web/src/DocumentWorkbench.tsx index f6afc34..a1d6f2e 100644 --- a/web/src/DocumentWorkbench.tsx +++ b/web/src/DocumentWorkbench.tsx @@ -6,155 +6,583 @@ import { clearScopeRule, fetchScopeRules, setScopeRule } from './scopeRules' import type { ClearScopeRuleDecision, ScopeRule, ScopeRuleDecision } from './scopeRules' import { ScopeRuleEditor } from './ScopeRuleEditor' import { WorkspaceContextTabsSetter } from './workspaceContext' -import { connectionKey, directoryGroups, documentPipeline, documentProblem, documentStage, fetchDocumentCatalog, filterDocuments, operationalDocuments, sourceProgress, stageLabels, visibilityOrigin } from './documentWorkbench' +import { + connectionKey, + directoryGroups, + documentPipeline, + documentProblem, + documentStage, + fetchDocumentCatalog, + filterDocuments, + operationalDocuments, + sourceProgress, + stageLabels, + visibilityOrigin, +} from './documentWorkbench' import type { DocumentStage } from './documentWorkbench' import './documentWorkbench.css' type Mode = 'directory' | 'monitor' | 'attention' -const sourceNames: Record = {pp:'PP公开文档', alist:'AList文件源', dingtalk:'钉钉知识库', manual:'手工验收文档'} -const activeStages: DocumentStage[] = ['downloading','uploading','parsing','indexing'] +const sourceNames: Record = { + pp: 'PP公开文档', + alist: 'AList文件源', + dingtalk: '钉钉知识库', + manual: '手工验收文档', +} +const activeStages: DocumentStage[] = ['downloading', 'uploading', 'parsing', 'indexing'] interface ViewProps { - items: SourceAsset[] - connections: SourceConnectionPage['items'] - mode: Mode - loading: boolean - error: string | null - onRefresh: () => void - onRetry: (id:string) => void - retryingId: string | null + items: SourceAsset[] + connections: SourceConnectionPage['items'] + mode: Mode + loading: boolean + error: string | null + onRefresh: () => void + onRetry: (id: string) => void + retryingId: string | null } -const time = (value:string) => new Date(value).toLocaleString('zh-CN', {hour12:false}) -const bytes = (value:number) => value >= 1048576 ? `${(value/1048576).toFixed(1)} MB` : `${(value/1024).toFixed(1)} KB` +const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false }) +const bytes = (value: number) => + value >= 1048576 ? `${(value / 1048576).toFixed(1)} MB` : `${(value / 1024).toFixed(1)} KB` -export function DocumentWorkbenchView({items, connections, mode, loading, error, onRefresh, onRetry, retryingId}: ViewProps) { - const [connection, setConnection] = useState('') - const [directory, setDirectory] = useState(null) - const [query, setQuery] = useState('') - const [visibility, setVisibility] = useState('') - const [stage, setStage] = useState('') - const [page, setPage] = useState(0) - const [selectedID, setSelectedID] = useState(null) - const [showTestDocuments,setShowTestDocuments]=useState(false) - const [scopeRules,setScopeRules]=useState([]) - const [scopeLoading,setScopeLoading]=useState(false) - const [scopeError,setScopeError]=useState(null) - const setWorkspaceContextTabs=useContext(WorkspaceContextTabsSetter) - const visibleItems=useMemo(()=>operationalDocuments(items,showTestDocuments),[items,showTestDocuments]) - const groups = useMemo(()=>directoryGroups(visibleItems),[visibleItems]) - const sources = useMemo(()=> { - const map = new Map(connections.filter(c=>showTestDocuments||c.source_type!=='manual').map(c=>[c.id, {id:c.id,type:c.source_type,name:c.name}])) - for (const item of visibleItems) if (!map.has(connectionKey(item))) map.set(connectionKey(item), {id:connectionKey(item),type:item.source_type,name:item.connection_name}) - return [...map.values()] - },[visibleItems,connections,showTestDocuments]) - const scoped = filterDocuments(visibleItems,{connection,directory,query:'',visibility:'',stage:''}) - const filtered = filterDocuments(visibleItems,{connection,directory,query,visibility,stage}).filter(item => mode !== 'attention' || ['blocked','failed'].includes(documentStage(item))) - const shownPage = Math.min(page,Math.max(0,Math.ceil(filtered.length/40)-1)) - const selected = filtered.find(item=>item.id===selectedID) - const reset = () => {setPage(0);setSelectedID(null)} - const selectFolder = (id:string,path:string|null) => {setConnection(id);setDirectory(path);reset()} - const title = mode === 'monitor' ? '解析监控' : mode === 'attention' ? '待处理文件' : '来源与目录' - const unavailable = items.length === 0 && Boolean(loading || error) - const progress=sourceProgress(visibleItems) - const manualCount=items.filter(item=>item.source_type==='manual').length - const directDirectoryRule=scopeRules.find(rule=>rule.target_type==='directory'&&rule.connection_id===connection&&rule.directory_path===(directory??'')) - const selectedItemRule=scopeRules.find(rule=>rule.target_type==='item'&&rule.source_item_id===selectedID) - const selectedSourceLabel=sourceNames[sources.find(item=>item.id===connection)?.type||'']||'当前来源' - useEffect(()=>{ - if(!connection){setScopeRules([]);setScopeError(null);return} - const controller=new AbortController() - setScopeLoading(true) - void fetchScopeRules(connection,controller.signal).then(setScopeRules).catch(cause=>{if(!controller.signal.aborted)setScopeError(cause instanceof Error?cause.message:'加载范围规则失败')}).finally(()=>{if(!controller.signal.aborted)setScopeLoading(false)}) - return()=>controller.abort() - },[connection]) - useEffect(()=>{ - if(!connection){setWorkspaceContextTabs([]);return} - const tabs=[{key:'source',label:selectedSourceLabel,onActivate:()=>{setDirectory(null);setSelectedID(null);setPage(0)}}] - if(directory!==null)tabs.push({key:'directory',label:directory||'分类待补齐',onActivate:()=>setSelectedID(null)}) - if(selected)tabs.push({key:'file',label:selected.title||'当前文件',onActivate:()=>setSelectedID(selected.id)}) - setWorkspaceContextTabs(tabs) - return()=>setWorkspaceContextTabs([]) - },[connection,directory,selected,selectedSourceLabel,setWorkspaceContextTabs]) - const mutateScope=async(decision:ScopeRuleDecision|ClearScopeRuleDecision,clear:boolean)=>{ - if(scopeLoading)return - setScopeLoading(true);setScopeError(null) - try{if(clear)await clearScopeRule(decision as ClearScopeRuleDecision);else await setScopeRule(decision as ScopeRuleDecision);setScopeRules(await fetchScopeRules(connection));onRefresh()}catch(cause){setScopeError(cause instanceof Error?cause.message:'保存范围规则失败')}finally{setScopeLoading(false)} - } - return
    -

    文档工作台

    {title}

    {mode === 'monitor' ? '看每份文件处理到哪一步。解析完成不代表已上线。' : mode === 'attention' ? '只列出超限、失败或来源不可访问的文件。内容审核请进入发布管理。' : '先选来源和目录,再看文件、对内/对外和处理状态。'}

    - {error ?
    {error}(旧数据仅供参考)
    : null} - {mode==='monitor'&&!unavailable?
    来源处理概览直接看各来源完成、处理中和异常数量
    {progress.map(item=>{const source=sources.find(value=>value.id===item.connection);return })}
    :null} -
    - -
    - - {!unavailable ?
    - 文件 {scoped.length} - {mode==='monitor'?<>独立解析 {scoped.filter(x=>documentStage(x)==='completed').length}内容复用 {scoped.filter(x=>documentStage(x)==='reused').length}处理中 {scoped.filter(x=>activeStages.includes(documentStage(x))).length}等待 {scoped.filter(x=>documentStage(x)==='waiting').length}需处理(含超限) {scoped.filter(x=>['blocked','failed'].includes(documentStage(x))).length}:<>对内 {scoped.filter(x=>x.visibility==='internal').length}对外 {scoped.filter(x=>x.visibility==='external').length}处理中 {scoped.filter(x=>activeStages.includes(documentStage(x))).length}已解析 {scoped.filter(x=>documentStage(x)==='completed').length}需处理 {scoped.filter(x=>['blocked','failed'].includes(documentStage(x))).length}} -
    :

    文件数量尚未核实

    } - {mode==='directory'&&connection&&directory!==''?void mutateScope(decision,false)} onClear={decision=>void mutateScope(decision,true)} />:mode==='directory'&&connection&&directory===''?

    “分类待补齐”不是可靠目录,不能单独设置范围。请先补齐来源目录,或返回来源级设置。

    :null} -
    - - - -
    -
    {!connection?'全部来源':sourceNames[sources.find(s=>s.id===connection)?.type || ''] || '当前来源'} / {directory === null?'全部文件':directory || '目录待补齐'} {!unavailable ? 筛选结果 {filtered.length} 份 : null}
    - {loading && !items.length ?
    正在核对完整文档清单…
    : null} - {!loading && !error && !filtered.length ?
    没有符合条件的文件。
    : null} - {filtered.length ?
    - {filtered.slice(shownPage*40,(shownPage+1)*40).map(item=> - - - - )} -
    文件名对内/对外处理状态大小状态更新时间
    {sourceNames[item.source_type]} / {item.directory_path || '目录待补齐'}{item.visibility==='external'?'对外':'对内'}{visibilityOrigin(item)}{stageLabels[documentStage(item)]}{bytes(item.size_bytes)}
    : null} -
    第 {shownPage+1} / {Math.max(1,Math.ceil(filtered.length/40))} 页
    - {mode === 'monitor' ?

    每15秒自动刷新。当前接口未提供页数或逐页百分比,因此只显示真实阶段。时间为状态更新时间,不是源文件修改时间。

    : null} -
    -
    - {selected ?

    {selected.title || '文件名待补齐'}

    -
    来源位置
    {sourceNames[selected.source_type]} / {selected.directory_path || '目录待补齐'}
    对内/对外
    {selected.visibility==='external'?'对外':'对内'} · {visibilityOrigin(selected)}
    当前进度
    {stageLabels[documentStage(selected)]}
    - {documentProblem(selected) ?

    {documentProblem(selected)}

    : null} -
    文件大小 {bytes(selected.size_bytes)}状态更新时间 {time(selected.updated_at)}来源变化 {selected.source_change==='unchanged'?'无变化':'需要核对'}检索状态 {selected.retrieval_state==='enabled'?'测试环境已启用':'未证明已启用'}
    -
    {documentPipeline(selected).map(step=>
    )}
    -

    原文与版本差异尚未接通,请在源系统核对内容;不要仅凭“解析完成”批准发布。

    - {mode==='directory'?void mutateScope(decision,false)} onClear={decision=>void mutateScope(decision,true)} />:null} - {selected.can_retry && selected.publication_id ? : null} - {selected.last_error ?
    错误详情{selected.last_error}
    : null} -
    : null} -
    +export function DocumentWorkbenchView({ + items, + connections, + mode, + loading, + error, + onRefresh, + onRetry, + retryingId, +}: ViewProps) { + const [connection, setConnection] = useState('') + const [directory, setDirectory] = useState(null) + const [query, setQuery] = useState('') + const [visibility, setVisibility] = useState('') + const [stage, setStage] = useState('') + const [page, setPage] = useState(0) + const [selectedID, setSelectedID] = useState(null) + const [showTestDocuments, setShowTestDocuments] = useState(false) + const [scopeRules, setScopeRules] = useState([]) + const [scopeLoading, setScopeLoading] = useState(false) + const [scopeError, setScopeError] = useState(null) + const setWorkspaceContextTabs = useContext(WorkspaceContextTabsSetter) + const visibleItems = useMemo(() => operationalDocuments(items, showTestDocuments), [items, showTestDocuments]) + const groups = useMemo(() => directoryGroups(visibleItems), [visibleItems]) + const sources = useMemo(() => { + const map = new Map( + connections + .filter((c) => showTestDocuments || c.source_type !== 'manual') + .map((c) => [c.id, { id: c.id, type: c.source_type, name: c.name }]) + ) + for (const item of visibleItems) + if (!map.has(connectionKey(item))) + map.set(connectionKey(item), { id: connectionKey(item), type: item.source_type, name: item.connection_name }) + return [...map.values()] + }, [visibleItems, connections, showTestDocuments]) + const scoped = filterDocuments(visibleItems, { connection, directory, query: '', visibility: '', stage: '' }) + const filtered = filterDocuments(visibleItems, { connection, directory, query, visibility, stage }).filter( + (item) => mode !== 'attention' || ['blocked', 'failed'].includes(documentStage(item)) + ) + const shownPage = Math.min(page, Math.max(0, Math.ceil(filtered.length / 40) - 1)) + const selected = filtered.find((item) => item.id === selectedID) + const reset = () => { + setPage(0) + setSelectedID(null) + } + const selectFolder = (id: string, path: string | null) => { + setConnection(id) + setDirectory(path) + reset() + } + const title = mode === 'monitor' ? '解析监控' : mode === 'attention' ? '待处理文件' : '来源与目录' + const unavailable = items.length === 0 && Boolean(loading || error) + const progress = sourceProgress(visibleItems) + const manualCount = items.filter((item) => item.source_type === 'manual').length + const directDirectoryRule = scopeRules.find( + (rule) => + rule.target_type === 'directory' && rule.connection_id === connection && rule.directory_path === (directory ?? '') + ) + const selectedItemRule = scopeRules.find((rule) => rule.target_type === 'item' && rule.source_item_id === selectedID) + const selectedSourceLabel = sourceNames[sources.find((item) => item.id === connection)?.type || ''] || '当前来源' + useEffect(() => { + if (!connection) { + setScopeRules([]) + setScopeError(null) + return + } + const controller = new AbortController() + setScopeLoading(true) + void fetchScopeRules(connection, controller.signal) + .then(setScopeRules) + .catch((cause) => { + if (!controller.signal.aborted) setScopeError(cause instanceof Error ? cause.message : '加载范围规则失败') + }) + .finally(() => { + if (!controller.signal.aborted) setScopeLoading(false) + }) + return () => controller.abort() + }, [connection]) + useEffect(() => { + if (!connection) { + setWorkspaceContextTabs([]) + return + } + const tabs = [ + { + key: 'source', + label: selectedSourceLabel, + onActivate: () => { + setDirectory(null) + setSelectedID(null) + setPage(0) + }, + }, + ] + if (directory !== null) + tabs.push({ key: 'directory', label: directory || '分类待补齐', onActivate: () => setSelectedID(null) }) + if (selected) + tabs.push({ key: 'file', label: selected.title || '当前文件', onActivate: () => setSelectedID(selected.id) }) + setWorkspaceContextTabs(tabs) + return () => setWorkspaceContextTabs([]) + }, [connection, directory, selected, selectedSourceLabel, setWorkspaceContextTabs]) + const mutateScope = async (decision: ScopeRuleDecision | ClearScopeRuleDecision, clear: boolean) => { + if (scopeLoading) return + setScopeLoading(true) + setScopeError(null) + try { + if (clear) await clearScopeRule(decision as ClearScopeRuleDecision) + else await setScopeRule(decision as ScopeRuleDecision) + setScopeRules(await fetchScopeRules(connection)) + onRefresh() + } catch (cause) { + setScopeError(cause instanceof Error ? cause.message : '保存范围规则失败') + } finally { + setScopeLoading(false) + } + } + return ( +
    +
    +
    +

    文档工作台

    +

    {title}

    +

    + {mode === 'monitor' + ? '看每份文件处理到哪一步。解析完成不代表已上线。' + : mode === 'attention' + ? '只列出超限、失败或来源不可访问的文件。内容审核请进入发布管理。' + : '先选来源和目录,再看文件、对内/对外和处理状态。'} +

    +
    + +
    + {error ? ( +
    + {error}(旧数据仅供参考) +
    + ) : null} + {mode === 'monitor' && !unavailable ? ( +
    +
    + 来源处理概览 + 直接看各来源完成、处理中和异常数量 +
    +
    + {progress.map((item) => { + const source = sources.find((value) => value.id === item.connection) + return ( + + ) + })} +
    +
    + ) : null} +
    + +
    + {!unavailable ? ( +
    + + 文件 {scoped.length} + + {mode === 'monitor' ? ( + <> + + 独立解析 {scoped.filter((x) => documentStage(x) === 'completed').length} + + + 内容复用 {scoped.filter((x) => documentStage(x) === 'reused').length} + + + 处理中 {scoped.filter((x) => activeStages.includes(documentStage(x))).length} + + + 等待 {scoped.filter((x) => documentStage(x) === 'waiting').length} + + + 需处理(含超限){' '} + {scoped.filter((x) => ['blocked', 'failed'].includes(documentStage(x))).length} + + + ) : ( + <> + + 对内 {scoped.filter((x) => x.visibility === 'internal').length} + + + 对外 {scoped.filter((x) => x.visibility === 'external').length} + + + 处理中 {scoped.filter((x) => activeStages.includes(documentStage(x))).length} + + + 已解析 {scoped.filter((x) => documentStage(x) === 'completed').length} + + + 需处理 {scoped.filter((x) => ['blocked', 'failed'].includes(documentStage(x))).length} + + + )} +
    + ) : ( +

    文件数量尚未核实

    + )} + {mode === 'directory' && connection && directory !== '' ? ( + void mutateScope(decision, false)} + onClear={(decision) => void mutateScope(decision, true)} + /> + ) : mode === 'directory' && connection && directory === '' ? ( +

    + “分类待补齐”不是可靠目录,不能单独设置范围。请先补齐来源目录,或返回来源级设置。 +

    + ) : null} +
    + + + +
    +
    + {!connection ? '全部来源' : sourceNames[sources.find((s) => s.id === connection)?.type || ''] || '当前来源'}{' '} + / {directory === null ? '全部文件' : directory || '目录待补齐'}{' '} + {!unavailable ? 筛选结果 {filtered.length} 份 : null} +
    + {loading && !items.length ?
    正在核对完整文档清单…
    : null} + {!loading && !error && !filtered.length ?
    没有符合条件的文件。
    : null} + {filtered.length ? ( +
    + + + + + + + + + + + + {filtered.slice(shownPage * 40, (shownPage + 1) * 40).map((item) => ( + + + + + + + + ))} + +
    文件名对内/对外处理状态大小状态更新时间
    + + + {sourceNames[item.source_type]} / {item.directory_path || '目录待补齐'} + + + + {item.visibility === 'external' ? '对外' : '对内'} + + {visibilityOrigin(item)} + + + {stageLabels[documentStage(item)]} + + {bytes(item.size_bytes)} + +
    +
    + ) : null} +
    + + 第 {shownPage + 1} / {Math.max(1, Math.ceil(filtered.length / 40))} 页 + +
    + + +
    +
    + {mode === 'monitor' ? ( +

    + 每15秒自动刷新。当前接口未提供页数或逐页百分比,因此只显示真实阶段。时间为状态更新时间,不是源文件修改时间。 +

    + ) : null} +
    +
    + {selected ? ( +
    +
    +

    {selected.title || '文件名待补齐'}

    + +
    +
    +
    +
    来源位置
    +
    + {sourceNames[selected.source_type]} / {selected.directory_path || '目录待补齐'} +
    +
    对内/对外
    +
    + {selected.visibility === 'external' ? '对外' : '对内'} · {visibilityOrigin(selected)} +
    +
    当前进度
    +
    {stageLabels[documentStage(selected)]}
    +
    + {documentProblem(selected) ?

    {documentProblem(selected)}

    : null} +
    + + 文件大小 {bytes(selected.size_bytes)} + + + 状态更新时间 {time(selected.updated_at)} + + + 来源变化 {selected.source_change === 'unchanged' ? '无变化' : '需要核对'} + + + 检索状态 {selected.retrieval_state === 'enabled' ? '测试环境已启用' : '未证明已启用'} + +
    +
    + {documentPipeline(selected).map((step) => ( +
    +
    + ))} +
    +

    原文与版本差异尚未接通,请在源系统核对内容;不要仅凭“解析完成”批准发布。

    + {mode === 'directory' ? ( + void mutateScope(decision, false)} + onClear={(decision) => void mutateScope(decision, true)} + /> + ) : null} + {selected.can_retry && selected.publication_id ? ( + + ) : null} + {selected.last_error ? ( +
    + 错误详情 + {selected.last_error} +
    + ) : null} +
    +
    + ) : null} +
    + ) } -export function DocumentWorkbench({mode,connections}: {mode:Mode;connections:SourceConnectionPage['items']}) { - const [items,setItems] = useState([]) - const [loading,setLoading] = useState(true) - const [error,setError] = useState(null) - const [revision,setRevision] = useState(0) - const [retryingId,setRetryingId] = useState(null) - useEffect(()=>{ - const controller = new AbortController() - setLoading(true) - void fetchDocumentCatalog(controller.signal).then(data=>{if (!controller.signal.aborted) {setItems(data);setError(null)}}).catch(cause=>{if (!controller.signal.aborted) setError(cause instanceof Error?cause.message:'加载文件失败')}).finally(()=>{if (!controller.signal.aborted) setLoading(false)}) - return ()=>controller.abort() - },[revision]) - useEffect(()=>{ - if (mode!=='monitor' || loading) return - const timer = window.setTimeout(()=>setRevision(r=>r+1),15000) - return ()=>window.clearTimeout(timer) - },[mode,loading,revision]) - const retry = async(id:string)=>{ - if (retryingId) return - if (!window.confirm('仅重试这份失败文件,不影响已成功文件或生产。继续吗?')) return - setRetryingId(id) - try {await retryPublication(id);setRevision(r=>r+1)} catch(cause) {setError(cause instanceof Error?cause.message:'重试失败')} finally {setRetryingId(null)} - } - return setRevision(r=>r+1)} onRetry={id=>void retry(id)} retryingId={retryingId} /> +export function DocumentWorkbench({ mode, connections }: { mode: Mode; connections: SourceConnectionPage['items'] }) { + const [items, setItems] = useState([]) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + const [revision, setRevision] = useState(0) + const [retryingId, setRetryingId] = useState(null) + useEffect(() => { + const controller = new AbortController() + setLoading(true) + void fetchDocumentCatalog(controller.signal) + .then((data) => { + if (!controller.signal.aborted) { + setItems(data) + setError(null) + } + }) + .catch((cause) => { + if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载文件失败') + }) + .finally(() => { + if (!controller.signal.aborted) setLoading(false) + }) + return () => controller.abort() + }, [revision]) + useEffect(() => { + if (mode !== 'monitor' || loading) return + const timer = window.setTimeout(() => setRevision((r) => r + 1), 15000) + return () => window.clearTimeout(timer) + }, [mode, loading, revision]) + const retry = async (id: string) => { + if (retryingId) return + if (!window.confirm('仅重试这份失败文件,不影响已成功文件或生产。继续吗?')) return + setRetryingId(id) + try { + await retryPublication(id) + setRevision((r) => r + 1) + } catch (cause) { + setError(cause instanceof Error ? cause.message : '重试失败') + } finally { + setRetryingId(null) + } + } + return ( + setRevision((r) => r + 1)} + onRetry={(id) => void retry(id)} + retryingId={retryingId} + /> + ) } diff --git a/web/src/FilenameFilterEditor.test.tsx b/web/src/FilenameFilterEditor.test.tsx index 2039e22..897f240 100644 --- a/web/src/FilenameFilterEditor.test.tsx +++ b/web/src/FilenameFilterEditor.test.tsx @@ -5,20 +5,22 @@ import { FilenameFilterEditorView } from './FilenameFilterEditor' describe('FilenameFilterEditorView', () => { it('renders format groups with the allow-mode preselection', () => { - const html = renderToStaticMarkup( undefined} - options={['pdf', 'zip', 'mp4']} - selected={['pdf']} - onToggle={() => undefined} - busy={false} - hasOwnRule={false} - message="已保留 .pdf" - error={null} - onSave={() => undefined} - onClear={() => undefined} - />) + const html = renderToStaticMarkup( + undefined} + options={['pdf', 'zip', 'mp4']} + selected={['pdf']} + onToggle={() => undefined} + busy={false} + hasOwnRule={false} + message="已保留 .pdf" + error={null} + onSave={() => undefined} + onClear={() => undefined} + /> + ) expect(html).toContain('文件格式筛选') expect(html).toContain('勾选保留') expect(html).toContain('勾选排除') diff --git a/web/src/FilenameFilterEditor.tsx b/web/src/FilenameFilterEditor.tsx index 888b587..d971da8 100644 --- a/web/src/FilenameFilterEditor.tsx +++ b/web/src/FilenameFilterEditor.tsx @@ -1,6 +1,13 @@ import { useEffect, useMemo, useState } from 'react' -import { clearFilenameFilter, DEFAULT_ALLOWED_EXTENSIONS, DEFAULT_EXCLUDED_EXTENSIONS, fetchFilenameFilters, parseExtensionDraft, saveFilenameFilter } from './filenameFilters' +import { + clearFilenameFilter, + DEFAULT_ALLOWED_EXTENSIONS, + DEFAULT_EXCLUDED_EXTENSIONS, + fetchFilenameFilters, + parseExtensionDraft, + saveFilenameFilter, +} from './filenameFilters' import type { FilenameFilterRule } from './filenameFilters' import './systemSettings.css' @@ -40,41 +47,129 @@ function groupOf(extension: string): string { return DEFAULT_EXCLUDED_EXTENSIONS.includes(extension) ? '排除项' : '其他' } -export function FilenameFilterEditorView({ label, mode, onModeChange, options, selected, onToggle, busy, hasOwnRule, message, error, onSave, onClear }: ViewProps) { +export function FilenameFilterEditorView({ + label, + mode, + onModeChange, + options, + selected, + onToggle, + busy, + hasOwnRule, + message, + error, + onSave, + onClear, +}: ViewProps) { const selectedSet = useMemo(() => new Set(selected), [selected]) const unknown = selected.filter((extension) => !options.includes(extension)) - return
    -
    文件格式筛选{label} · 选择要入库的文件格式,未勾选的一律不取件
    -
    - - + return ( +
    +
    +
    + 文件格式筛选 + {label} · 选择要入库的文件格式,未勾选的一律不取件 +
    +
    + + +
    -
    -
    - {FORMAT_GROUPS.map((group) =>
    - {group.label} -
    {group.extensions.map((extension) => )}
    -
    )} -
    - {unknown.length ?
    规则含未知格式{unknown.map((extension) => .{extension})}
    : null} -
    - { - if (event.key !== 'Enter') return - event.preventDefault() - const target = event.currentTarget - for (const extension of parseExtensionDraft(target.value)) onToggle(extension) - target.value = '' - }} aria-label="手动补充格式" /> - - {hasOwnRule ? : null} -
    - {mode === 'allow' ? '白名单:无扩展名的文件不受限制;目录级规则就近覆盖上级。' : '黑名单:仅排除勾选格式,其余可入库。'} - {message ?

    {message}

    : null} - {error ?

    {error}

    : null} -
    +
    + {FORMAT_GROUPS.map((group) => ( +
    + {group.label} +
    + {group.extensions.map((extension) => ( + + ))} +
    +
    + ))} +
    + {unknown.length ? ( +
    + 规则含未知格式 + {unknown.map((extension) => ( + .{extension} + ))} +
    + ) : null} +
    + { + if (event.key !== 'Enter') return + event.preventDefault() + const target = event.currentTarget + for (const extension of parseExtensionDraft(target.value)) onToggle(extension) + target.value = '' + }} + aria-label="手动补充格式" + /> + + {hasOwnRule ? ( + + ) : null} +
    + + {mode === 'allow' + ? '白名单:无扩展名的文件不受限制;目录级规则就近覆盖上级。' + : '黑名单:仅排除勾选格式,其余可入库。'} + + {message ? ( +

    + {message} +

    + ) : null} + {error ? ( +

    + {error} +

    + ) : null} + + ) } -export function FilenameFilterEditor({ connectionID, directoryPath = '', label, onChanged }: { connectionID: string; directoryPath?: string; label: string; onChanged?: () => void }) { +export function FilenameFilterEditor({ + connectionID, + directoryPath = '', + label, + onChanged, +}: { + connectionID: string + directoryPath?: string + label: string + onChanged?: () => void +}) { const [rules, setRules] = useState([]) const [mode, setMode] = useState('allow') const [selected, setSelected] = useState(DEFAULT_ALLOWED_EXTENSIONS) @@ -104,41 +199,82 @@ export function FilenameFilterEditor({ connectionID, directoryPath = '', label, setSelected(current.excluded_extensions) } else if (!touched) { setMode('allow') - setSelected(directoryPath === '' ? DEFAULT_ALLOWED_EXTENSIONS : [...new Set([...(inheritedHas('allow') ? inheritedValues('allow') : DEFAULT_ALLOWED_EXTENSIONS)])]) + setSelected( + directoryPath === '' + ? DEFAULT_ALLOWED_EXTENSIONS + : [...new Set([...(inheritedHas('allow') ? inheritedValues('allow') : DEFAULT_ALLOWED_EXTENSIONS)])] + ) } } const inheritedHas = (want: string) => [...inherited].some((value) => value.endsWith(`:${want}`)) - const inheritedValues = (want: string) => [...inherited].filter((value) => value.endsWith(`:${want}`)).map((value) => value.split(':')[0]) + const inheritedValues = (want: string) => + [...inherited].filter((value) => value.endsWith(`:${want}`)).map((value) => value.split(':')[0]) useEffect(() => { const controller = new AbortController() - void load(controller.signal).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载文件格式筛选失败') }) + void load(controller.signal).catch((cause) => { + if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载文件格式筛选失败') + }) return () => controller.abort() }, [connectionID, directoryPath]) const toggle = (extension: string) => { setTouched(true) - setSelected((previous) => previous.includes(extension) ? previous.filter((value) => value !== extension) : [...previous, extension].sort()) + setSelected((previous) => + previous.includes(extension) ? previous.filter((value) => value !== extension) : [...previous, extension].sort() + ) } const save = async () => { - setBusy(true); setError(null); setMessage(null) + setBusy(true) + setError(null) + setMessage(null) try { await saveFilenameFilter(connectionID, directoryPath, mode, selected) await load() - setMessage(mode === 'allow' ? `已保留 ${selected.map((value) => `.${value}`).join('、')};其余格式不再取件入库。` : `已排除 ${selected.map((value) => `.${value}`).join('、')}。`) + setMessage( + mode === 'allow' + ? `已保留 ${selected.map((value) => `.${value}`).join('、')};其余格式不再取件入库。` + : `已排除 ${selected.map((value) => `.${value}`).join('、')}。` + ) onChanged?.() - } catch (cause) { setError(cause instanceof Error ? cause.message : '保存文件格式筛选失败') } - finally { setBusy(false) } + } catch (cause) { + setError(cause instanceof Error ? cause.message : '保存文件格式筛选失败') + } finally { + setBusy(false) + } } const clear = async () => { - setBusy(true); setError(null); setMessage(null) + setBusy(true) + setError(null) + setMessage(null) try { await clearFilenameFilter(connectionID, directoryPath) await load() setMessage('已移除本级规则,恢复继承上级。') onChanged?.() - } catch (cause) { setError(cause instanceof Error ? cause.message : '清除文件格式筛选失败') } - finally { setBusy(false) } + } catch (cause) { + setError(cause instanceof Error ? cause.message : '清除文件格式筛选失败') + } finally { + setBusy(false) + } } - return { setTouched(true); setMode(next) }} options={options} selected={selected} onToggle={toggle} busy={busy} hasOwnRule={Boolean(direct)} message={message} error={error} onSave={() => void save()} onClear={() => void clear()} /> + return ( + { + setTouched(true) + setMode(next) + }} + options={options} + selected={selected} + onToggle={toggle} + busy={busy} + hasOwnRule={Boolean(direct)} + message={message} + error={error} + onSave={() => void save()} + onClear={() => void clear()} + /> + ) } diff --git a/web/src/LegacySourceAssociation.test.tsx b/web/src/LegacySourceAssociation.test.tsx new file mode 100644 index 0000000..50274ad --- /dev/null +++ b/web/src/LegacySourceAssociation.test.tsx @@ -0,0 +1,45 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { renderToStaticMarkup } from 'react-dom/server' +import { associateLegacySource, LegacySourceAssociation } from './LegacySourceAssociation' + +afterEach(() => vi.unstubAllGlobals()) +const reply = (status: number, data: unknown) => new Response(JSON.stringify(data), { status }) + +it('only sends exact snapshot and scope; association is not publishing', async () => { + const fetchMock = vi + .fn() + .mockResolvedValue( + reply(200, { associated: true, published: false, snapshot_id: 'snapshot', source_id: 'a'.repeat(64) }) + ) + vi.stubGlobal('fetch', fetchMock) + expect(await associateLegacySource('internal', 'snapshot')).toBe('a'.repeat(64)) + expect(fetchMock.mock.calls).toHaveLength(1) + expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/library/source-associations') + expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ scope: 'internal', snapshot_id: 'snapshot' }) +}) + +it('rejects wrong-snapshot and incomplete readback, and shows evidence errors', async () => { + for (const value of [ + { associated: true, published: false, snapshot_id: 'wrong', source_id: 'a'.repeat(64) }, + { associated: true, snapshot_id: 'snapshot' }, + ]) { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply(200, value))) + await expect(associateLegacySource('internal', 'snapshot')).rejects.toThrow('来源关联回执') + } + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(reply(409, { error: 'original capture identity mismatch' }))) + await expect(associateLegacySource('internal', 'snapshot')).rejects.toThrow('original capture identity mismatch') +}) + +it('hides association controls from non-admin and distinguishes it from publication', () => { + expect( + renderToStaticMarkup( + {}} /> + ) + ).toBe('') + const html = renderToStaticMarkup( + {}} /> + ) + expect(html).toContain('只追加治理关联') + expect(html).toContain('disabled') + expect(html).toContain('核验原证据并关联') +}) diff --git a/web/src/LegacySourceAssociation.tsx b/web/src/LegacySourceAssociation.tsx new file mode 100644 index 0000000..5d0a872 --- /dev/null +++ b/web/src/LegacySourceAssociation.tsx @@ -0,0 +1,83 @@ +import { useState } from 'react' +import type { LibrarySnapshot } from './librarySnapshots' + +export async function associateLegacySource(scope: string, snapshotID: string): Promise { + const response = await fetch('/api/v1/library/source-associations', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ scope, snapshot_id: snapshotID }), + }) + const value = (await response.json().catch(() => null)) as Record | null + if (!response.ok) + throw new Error(typeof value?.error === 'string' ? value.error : `来源关联失败(HTTP ${response.status})`) + if ( + value?.associated !== true || + value.published !== false || + value.snapshot_id !== snapshotID || + typeof value.source_id !== 'string' || + !/^[a-f0-9]{64}$/.test(value.source_id) + ) { + throw new Error('来源关联回执不完整或快照身份不符') + } + return value.source_id +} + +export function LegacySourceAssociation({ + scope, + snapshots, + admin, + onBound, +}: { + scope: string + snapshots: LibrarySnapshot[] + admin: boolean + onBound: () => Promise +}) { + const [snapshotID, setSnapshotID] = useState('') + const [pending, setPending] = useState(false) + const [notice, setNotice] = useState('') + if (!admin) return null + const choices = snapshots.filter((item) => item.scope === scope) + const bind = async () => { + if (pending || !choices.some((item) => item.snapshot_id === snapshotID)) return + setPending(true) + setNotice('') + try { + const sourceID = await associateLegacySource(scope, snapshotID) + setNotice(`来源证据已核验关联:${sourceID}。没有发布内容;发布授权与写入闸门仍独立检查。`) + await onBound() + } catch (error) { + setNotice(error instanceof Error ? error.message : '来源关联失败') + } finally { + setPending(false) + } + } + return ( +
    + 关联旧封存的原始来源证据(管理员) +

    + 只追加治理关联,保留原快照与摘要。服务端核对原捕获响应、执行器指纹及清单;备份、来源不符或证据缺失均拒绝,不凭同一范围认领。 +

    + + + {notice ?

    {notice}

    : null} +
    + ) +} diff --git a/web/src/LibraryStorageSection.tsx b/web/src/LibraryStorageSection.tsx index d3a78e3..ef340e2 100644 --- a/web/src/LibraryStorageSection.tsx +++ b/web/src/LibraryStorageSection.tsx @@ -89,78 +89,82 @@ export function LibraryStorageSection() { )}
    -
    -

    保留与依赖保护

    -

    - {policyConfigured - ? `策略:${[ - plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '', - plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '', - ] - .filter(Boolean) - .join(' + ')}` - : '策略:未设置(不生成清理候选)'} -

    -

    - 受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、在飞作业引用, - 不论多久都不会进入候选。 -

    - {data.versions.filter((item) => item.protected).length > 0 ? ( -
      - {data.versions - .filter((item) => item.protected) - .map((item) => ( -
    • - {item.id.slice(0, 12)} {item.kind} · {(item.protected_by ?? []).join('、')} -
    • - ))} -
    - ) : null} -
    - -
    -

    清理预览

    - {policyConfigured ? ( - plan && plan.candidates.length > 0 ? ( - <> -

    - 按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '} - {formatBytes(plan.reclaim_preview_bytes)}(共享 blob 不会因此释放,这不是可回收空间)。 -

    -
      - {plan.candidates.map((item) => ( +
      + 保留策略与清理预览(未设置时按“全部保留”处理) +
      +

      保留与依赖保护

      +

      + {policyConfigured + ? `策略:${[ + plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '', + plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '', + ] + .filter(Boolean) + .join(' + ')}` + : '策略:未设置(不生成清理候选)'} +

      +

      + 受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、运行中作业引用, + 不论多久都不会进入候选。 +

      + {data.versions.filter((item) => item.protected).length > 0 ? ( +
        + {data.versions + .filter((item) => item.protected) + .map((item) => (
      • - {item.id.slice(0, 12)} {item.kind} · {item.reason.join(';')} ·{' '} - {formatBytes(item.exclusive_bytes)} + {item.id.slice(0, 12)} {item.kind} · {(item.protected_by ?? []).join('、')}
      • ))} -
      - - ) : ( -

      按当前策略没有可清理的候选版本。

      - ) - ) : ( -

      - 保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。 -

      - )} - {plan?.blocked.length ? ( -
        - {plan.blocked.map((item) => ( -
      • {item}
      • - ))} -
      - ) : null} -
      +
    + ) : null} +
    -
      -
    • 自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)
    • -
    • 实际删除需要单独授权,本页只给预览
    • -
    • 以上数字都不是「可回收空间」,不能用来估算清理收益
    • - {data.notes.map((note) => ( -
    • {note}
    • - ))} -
    +
    +

    清理预览

    + {policyConfigured ? ( + plan && plan.candidates.length > 0 ? ( + <> +

    + 按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '} + {formatBytes(plan.reclaim_preview_bytes)}(共享归档文件不会因此释放,这不是可回收空间)。 +

    +
      + {plan.candidates.map((item) => ( +
    • + {item.id.slice(0, 12)} {item.kind} · {item.reason.join(';')} ·{' '} + {formatBytes(item.exclusive_bytes)} +
    • + ))} +
    + + ) : ( +

    按当前策略没有可清理的候选版本。

    + ) + ) : ( +

    + 保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。 +

    + )} + {plan?.blocked.length ? ( +
      + {plan.blocked.map((item) => ( +
    • {item}
    • + ))} +
    + ) : null} +
    + +
      +
    • 自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)
    • +
    • 实际删除需要单独授权,本页只给预览
    • +
    • 以上数字都不是「可回收空间」,不能用来估算清理收益
    • + {data.notes.map((note) => ( + // 服务端注记里的 blob 指归档文件:页面统一术语,不把实现细节甩给操作者。 +
    • {note.replace(/blob/gi, '归档文件')}
    • + ))} +
    + ) : null} diff --git a/web/src/MembersSection.tsx b/web/src/MembersSection.tsx index ba32ec2..10a5441 100644 --- a/web/src/MembersSection.tsx +++ b/web/src/MembersSection.tsx @@ -1,5 +1,11 @@ import { useCallback, useEffect, useState } from 'react' -import { createManagedUser, fetchManagedUsers, resetManagedUserPassword, setManagedUserRole, setManagedUserState } from './members' +import { + createManagedUser, + fetchManagedUsers, + resetManagedUserPassword, + setManagedUserRole, + setManagedUserState, +} from './members' import type { ManagedUser } from './members' import { roleLabels, useOptionalAuth } from './auth' import { PasswordInput } from './PasswordInput' @@ -17,66 +23,258 @@ export function MembersSection() { const [busy, setBusy] = useState(null) const [error, setError] = useState(null) const [message, setMessage] = useState(null) - const [form, setForm] = useState({ username: '', display_name: '', role: 'engineer' as ManagedUser['role'], password: '' }) + // 重置密码用受控对话框(遮罩输入),不再借浏览器 prompt 显示明文。 + const [resetTarget, setResetTarget] = useState<{ id: string; username: string } | null>(null) + const [resetValue, setResetValue] = useState('') + const [form, setForm] = useState({ + username: '', + display_name: '', + role: 'engineer' as ManagedUser['role'], + password: '', + }) const load = useCallback(async () => { - setLoading(true); setError(null) - try { setUsers(await fetchManagedUsers()) } - catch (cause) { setError(friendly(cause, '加载成员失败')) } - finally { setLoading(false) } + setLoading(true) + setError(null) + try { + setUsers(await fetchManagedUsers()) + } catch (cause) { + setError(friendly(cause, '加载成员失败')) + } finally { + setLoading(false) + } }, []) - useEffect(() => { void load() }, [load]) + useEffect(() => { + void load() + }, [load]) const run = async (key: string, action: () => Promise, success: string) => { - setBusy(key); setError(null); setMessage(null) - try { await action(); setMessage(success); await load() } - catch (cause) { setError(friendly(cause, '操作失败')) } - finally { setBusy(null) } + setBusy(key) + setError(null) + setMessage(null) + try { + await action() + setMessage(success) + await load() + } catch (cause) { + setError(friendly(cause, '操作失败')) + } finally { + setBusy(null) + } } - const create = () => run('create', async () => { - await createManagedUser(form) - setForm({ username: '', display_name: '', role: 'engineer', password: '' }) - }, `成员 ${form.username} 已创建,初始密码只用于首次登录`) + const create = () => + run( + 'create', + async () => { + await createManagedUser(form) + setForm({ username: '', display_name: '', role: 'engineer', password: '' }) + }, + `成员 ${form.username} 已创建,初始密码只用于首次登录` + ) const formValid = /^[a-z0-9][a-z0-9._-]{1,63}$/.test(form.username.trim()) && form.password.length >= 8 - return
    -

    成员与角色

    登录后的一切操作自动记录在成员名下;角色决定谁能审核、封批和行使生产授权。

    - {loading ?

    加载成员…

    : null} - {error ?

    {error}

    : null} - {message ?

    {message}

    : null} -
    - {users.map((user) => { - const self = user.id === identity?.id - return - - - - - - - })} -
    成员角色状态最近登录操作
    {user.display_name || user.username}{user.username}{user.must_change_password ? ' · 待设置新密码' : ''}{self ? {memberRoleLabels[user.role]} : ( - - )}{user.state === 'active' ? '启用' : '已停用'}{user.last_login_at ? new Date(user.last_login_at).toLocaleString('zh-CN', { hour12: false }) : '从未登录'}
    - {!self ? : null} - {!self ? : 当前登录人} -
    -
    - - - - - -
    - 停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。 -
    + return ( +
    +
    +
    +

    成员与角色

    +

    登录后的一切操作自动记录在成员名下;角色决定谁能审核、封批和行使生产授权。

    +
    +
    + {loading ?

    加载成员…

    : null} + {error ? ( +

    + {error} +

    + ) : null} + {message ? ( +

    + {message} +

    + ) : null} +
    + + + + + + + + + + + + {users.map((user) => { + const self = user.id === identity?.id + return ( + + + + + + + + ) + })} + +
    成员角色状态最近登录操作
    + {user.display_name || user.username} + + {user.username} + {user.must_change_password ? ' · 待设置新密码' : ''} + + + {self ? ( + {memberRoleLabels[user.role]} + ) : ( + + )} + + + {user.state === 'active' ? '启用' : '已停用'} + + + {user.last_login_at + ? new Date(user.last_login_at).toLocaleString('zh-CN', { hour12: false }) + : '从未登录'} + +
    + {!self ? ( + + ) : null} + {!self ? ( + + ) : ( + 当前登录人 + )} +
    +
    +
    +
    + + + + + +
    + 停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。 + {resetTarget ? ( +
    +

    重置 {resetTarget.username} 的临时密码

    +

    至少 8 位;对方首次登录必须更换,旧会话会立即失效。

    + setResetValue(event.target.value)} + /> +
    + + +
    +
    + ) : null} +
    + ) } diff --git a/web/src/PPConnection.css b/web/src/PPConnection.css new file mode 100644 index 0000000..f290949 --- /dev/null +++ b/web/src/PPConnection.css @@ -0,0 +1,93 @@ +.pp-connection { + border: 1px solid var(--border, #dce3eb); + border-radius: 10px; + padding: 16px; + margin: 12px 0; + background: var(--surface, #fff); +} +.pp-heading, +.pp-actions, +.pp-password { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} +.pp-heading { + justify-content: space-between; +} +.pp-heading h3 { + margin: 0; + font-size: 15px; +} +.pp-state { + color: var(--text-muted, #66758a); + font-size: 13px; +} +.pp-connection dl { + margin: 12px 0; +} +.pp-connection dl > div { + display: flex; + gap: 12px; + margin: 6px 0; + font-size: 13px; +} +.pp-connection dt { + flex: 0 0 76px; + color: var(--text-muted, #66758a); +} +.pp-connection dd { + margin: 0; + overflow-wrap: anywhere; +} +.pp-connection form { + display: grid; + gap: 12px; + margin-top: 14px; +} +.pp-connection label { + display: grid; + gap: 5px; + font-size: 13px; +} +.pp-connection input { + width: 100%; + max-width: 540px; + box-sizing: border-box; + padding: 9px 11px; + border: 1px solid var(--border, #cdd7e4); + border-radius: 6px; + background: var(--surface, #fff); + color: inherit; +} +.pp-connection button { + padding: 7px 12px; + border: 1px solid var(--border, #cdd7e4); + border-radius: 6px; + background: var(--surface, #fff); + color: inherit; + cursor: pointer; +} +.pp-connection button.primary { + background: #2563eb; + color: #fff; + border-color: #2563eb; +} +.pp-connection button:disabled { + opacity: 0.5; + cursor: default; +} +.pp-connection [role='alert'] { + color: #a93835; +} +.pp-connection [role='status'] { + font-size: 13px; +} +.pp-connection.compact { + margin-top: 0; +} +.pp-test-result { + padding-top: 8px; + border-top: 1px solid var(--border, #dce3eb); +} diff --git a/web/src/PPConnection.mounted.test.tsx b/web/src/PPConnection.mounted.test.tsx new file mode 100644 index 0000000..bb9839a --- /dev/null +++ b/web/src/PPConnection.mounted.test.tsx @@ -0,0 +1,76 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { PPConnection } from './PPConnection' +let root: Root, host: HTMLDivElement +let fetcher: ReturnType Promise>> +const active = { + id: 'active-one', + base_url: 'https://api.example.invalid', + username: 'example', + password_configured: true, +} +const view = { + revision: 1, + active, + pending: null, + observation: { state: 'valid', message: '认证有效 · 目录可读', checked_at: '2026-11-17T10:00:00Z' }, + pending_observation: null, +} +const json = (data: unknown) => new Response(JSON.stringify({ data })) +const click = async (label: string) => { + const b = [...host.querySelectorAll('button')].find((x) => x.textContent?.trim() === label) + expect(b, label).toBeTruthy() + await act(async () => b!.click()) +} +const type = async (label: string, value: string) => { + const input = [...host.querySelectorAll('label')] + .find((x) => x.textContent?.startsWith(label)) + ?.querySelector('input') + expect(input, label).toBeTruthy() + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value) + input!.dispatchEvent(new Event('input', { bubbles: true })) + }) +} +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + fetcher = vi.fn(async (_p: string, init?: RequestInit) => + json(init?.method === 'PUT' ? { ...view, revision: 2 } : view) + ) + vi.stubGlobal('fetch', fetcher) +}) +afterEach(async () => { + await act(async () => root.unmount()) + host.remove() + vi.unstubAllGlobals() +}) +describe('PP configuration editor', () => { + it('keeps the stored password without sending a masked replacement or launching scans', async () => { + await act(async () => root.render()) + await click('配置') + expect(host.querySelector('input[type=password]')).toBeNull() + await click('保存并校验') + const writes = fetcher.mock.calls.filter(([, i]) => i?.method === 'PUT') + expect(writes).toHaveLength(1) + const data = JSON.parse(String(writes[0][1]?.body)) + expect(data).toEqual({ base_url: active.base_url, username: 'example', revision: 1 }) + expect(host.textContent).toContain('已保存并生效') + expect(fetcher.mock.calls.every(([p]) => p.startsWith('/api/v1/pp-connection'))).toBe(true) + }) + it('sends a newly entered password only on explicit replacement and clears it after save', async () => { + await act(async () => root.render()) + await click('配置') + await click('更新密码') + await type('新密码', 'example-replacement') + await click('保存并校验') + const write = fetcher.mock.calls.find(([, i]) => i?.method === 'PUT') + expect(JSON.parse(String(write?.[1]?.body)).password).toBe('example-replacement') + expect(host.querySelector('input[type=password]')).toBeNull() + expect(host.textContent).not.toContain('example-replacement') + }) +}) diff --git a/web/src/PPConnection.test.tsx b/web/src/PPConnection.test.tsx new file mode 100644 index 0000000..ad7b8cb --- /dev/null +++ b/web/src/PPConnection.test.tsx @@ -0,0 +1,13 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import { PPConnection } from './PPConnection' +describe('PP connection card', () => { + it('starts with an observation gap and exposes configuration without inventing validity', () => { + const html = renderToStaticMarkup() + expect(html).toContain('PP 连接') + expect(html).toContain('读取中') + expect(html).toContain('配置') + expect(html).not.toContain('认证有效') + expect(html).not.toContain('公开只读可达') + }) +}) diff --git a/web/src/PPConnection.tsx b/web/src/PPConnection.tsx new file mode 100644 index 0000000..070e2f7 --- /dev/null +++ b/web/src/PPConnection.tsx @@ -0,0 +1,288 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + readPPConnection, + savePPConnection, + testPPConnection, + type PPDraft, + type PPObservation, + type PPView, +} from './ppConnection' +import './PPConnection.css' +const errorText = (e: unknown) => (e instanceof Error ? e.message : '请求失败,请重试') +const when = (s: string) => new Date(s).toLocaleString('zh-CN', { hour12: false }) +export function PPConnection({ compact = false }: { compact?: boolean }) { + const [view, setView] = useState(null) + const [loading, setLoading] = useState(true) + const [error, setError] = useState('') + const [notice, setNotice] = useState('') + const [editing, setEditing] = useState(false) + const [draft, setDraft] = useState({ base_url: 'https://api.dobot.cn', username: '', revision: 0 }) + const [password, setPassword] = useState('') + const [replacing, setReplacing] = useState(false) + const [busy, setBusy] = useState('') + const [tested, setTested] = useState(null) + const mounted = useRef(false) + const sequence = useRef(0) + const action = useRef(null) + const formState = useRef({ editing: false, busy: '' }) + formState.current = { editing, busy } + const load = useCallback(async () => { + const current = ++sequence.current + try { + const next = await readPPConnection() + if (mounted.current && sequence.current === current) { + setView(next) + setError('') + } + } catch (e) { + if (mounted.current && sequence.current === current) setError(errorText(e)) + } finally { + if (mounted.current && sequence.current === current) setLoading(false) + } + }, []) + useEffect(() => { + mounted.current = true + void load() + const refresh = () => { + if (!formState.current.editing && !formState.current.busy) void load() + } + window.addEventListener('pp-config-updated', refresh) + return () => { + mounted.current = false + sequence.current++ + action.current?.abort() + window.removeEventListener('pp-config-updated', refresh) + } + }, [load]) + const open = () => { + if (!view) return + const source = view.pending ?? view.active + setDraft({ + base_url: source?.base_url ?? 'https://api.dobot.cn', + username: source?.username ?? '', + revision: view.revision, + ...(view.pending ? { pending_id: view.pending.id } : {}), + }) + setPassword('') + setReplacing(false) + setTested(null) + setNotice('') + setError('') + setEditing(true) + } + const resetTest = () => { + setTested(null) + setNotice('') + } + const run = async (save: boolean) => { + if (!view) return + setBusy(save ? 'saving' : 'testing') + setError('') + setNotice('') + setTested(null) + const controller = new AbortController() + action.current = controller + const current = ++sequence.current + const payload: PPDraft = editing + ? { ...draft, ...(password ? { password } : {}) } + : { + base_url: view.active?.base_url ?? 'https://api.dobot.cn', + username: view.active?.username ?? '', + revision: view.revision, + } + try { + if (save) { + const next = await savePPConnection(payload, controller.signal) + if (!mounted.current || sequence.current !== current) return + setView(next) + setPassword('') + setReplacing(false) + setEditing(false) + setNotice(next.pending ? '修改已保存为待验证;原生效配置保留。' : 'PP 配置已保存并生效。') + window.dispatchEvent(new Event('pp-config-updated')) + } else { + const result = await testPPConnection(payload, controller.signal) + if (!mounted.current || sequence.current !== current) return + setTested(result) + const next = await readPPConnection(controller.signal) + if (mounted.current && sequence.current === current) setView(next) + } + } catch (e) { + if (!controller.signal.aborted && mounted.current && sequence.current === current) { + setError(errorText(e)) + try { + const next = await readPPConnection(controller.signal) + if (mounted.current && sequence.current === current) setView(next) + } catch { + /* Keep the last observation with the visible error. */ + } + } + } finally { + if (mounted.current && sequence.current === current) setBusy('') + } + } + const observation = view?.observation + const status = loading + ? '读取中…' + : error && !view + ? '状态读取失败' + : !view?.active + ? '未配置' + : !observation + ? '未检查' + : observation.state === 'valid' + ? '认证有效 · 目录可读' + : observation.message + return ( +
    +
    +

    PP 连接

    + {status} +
    + {!editing && ( + <> +
    +
    +
    API 地址
    +
    {view?.active?.base_url || '未配置'}
    +
    +
    +
    账号
    +
    {view?.active?.username || '未配置'}
    +
    +
    +
    密码
    +
    {view?.active?.password_configured ? '已配置' : '未配置'}
    +
    +
    +
    最近检查
    +
    {observation ? `${when(observation.checked_at)} · ${observation.message}` : '尚无检查记录'}
    +
    +
    + {observation?.previous && ( +

    + 上次结果(旧):{observation.previous.message} · {when(observation.previous.checked_at)} +

    + )} + {view?.pending && ( +

    存在待验证修改;{view.active ? '当前仍使用原生效配置。' : '尚无生效配置。'}

    + )} +
    + + + {error && ( + + )} +
    + + )} + {editing && ( +
    { + e.preventDefault() + void run(true) + }} + > + + +
    + 密码:{(view?.pending ?? view?.active)?.password_configured ? '已配置' : '未配置'} + +
    + {replacing && ( + + )} +
    + + + +
    +
    + )} + {tested && ( +

    + {editing ? '未保存配置测试:' : '当前配置检查:'} + {tested.message}({when(tested.checked_at)}) +

    + )} + {notice &&

    {notice}

    } + {error && ( +

    + {error} + {view && ';上次读取的配置与检查结果仍保留。'} +

    + )} +
    + ) +} +export function PPAuthorizationStep() { + return +} diff --git a/web/src/PasswordInput.test.tsx b/web/src/PasswordInput.test.tsx index 2eaff9f..fb78d4f 100644 --- a/web/src/PasswordInput.test.tsx +++ b/web/src/PasswordInput.test.tsx @@ -4,14 +4,18 @@ import { PasswordInput } from './PasswordInput' describe('PasswordInput', () => { it('masks the field by default and offers a visibility toggle', () => { - const markup = renderToStaticMarkup( undefined} />) + const markup = renderToStaticMarkup( + undefined} /> + ) expect(markup).toContain('type="password"') expect(markup).toContain('显示密码') expect(markup).toContain('aria-pressed="false"') }) it('renders revealed when initiallyRevealed is set', () => { - const markup = renderToStaticMarkup( undefined} />) + const markup = renderToStaticMarkup( + undefined} /> + ) expect(markup).toContain('type="text"') expect(markup).toContain('隐藏密码') expect(markup).toContain('aria-pressed="true"') diff --git a/web/src/ProductionBindingsSection.test.tsx b/web/src/ProductionBindingsSection.test.tsx new file mode 100644 index 0000000..c47e664 --- /dev/null +++ b/web/src/ProductionBindingsSection.test.tsx @@ -0,0 +1,101 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it, vi } from 'vitest' + +import { ProductionBindingsView } from './ProductionBindingsSection' +import type { ProductionBindings } from './productionBindings' + +const bindings = (overrides: Partial = {}): ProductionBindings => ({ + internal_kb_id: '0b217e8a-2a65-40a3-ab8f-34ac5c7a6f05', + external_kb_id: '9a1e5c11-0000-4000-8000-000000000002', + internal_kb_name: '对内知识库-wiki', + external_kb_name: '对外知识库-wiki', + updated_by: 'yaozhanghao', + production_base_url: 'https://weknora-test.dobot.cn', + production_connected: true, + production_message: '', + legacy_scope: '文档级发布(单篇文档写生产)· 旧路径', + whole_target: { + configured: true, + source: '部署环境 LIBRARY_PRODUCTION_*', + tenant_id: 10000, + internal_kb_id: 'a8e9c8ad-411c-4c53-8421-599d29e9b179', + external_kb_id: '2e980686-2233-4c4e-b5a6-8b0069477b8e', + database: 'pgm-wz9ohr9gk919pr1q.pg.rds.aliyuncs.com:5432/weknora_test', + elastic_index: 'weknora_test_chunks', + object_bucket: 'dobot-weknora-test', + missing_reason: '', + }, + ...overrides, +}) + +const view = (value: ProductionBindings | null, admin = true) => + renderToStaticMarkup( + + ) + +describe('ProductionBindingsView', () => { + it('把实际整库目标(完整 ID + 端点)显示出来,而不是只显示可编辑的文档级绑定', () => { + const html = view(bindings()) + expect(html).toContain('整库发布目标(实际写入,只读)') + // 完整 ID 必须可读:截断会让操作者核对不了 a8e9c8ad 与 0b217e8a 的区别。 + expect(html).toContain('a8e9c8ad-411c-4c53-8421-599d29e9b179') + expect(html).toContain('2e980686-2233-4c4e-b5a6-8b0069477b8e') + expect(html).toContain('pgm-wz9ohr9gk919pr1q.pg.rds.aliyuncs.com:5432/weknora_test') + expect(html).toContain('weknora_test_chunks') + expect(html).toContain('dobot-weknora-test') + expect(html).toContain('部署环境 LIBRARY_PRODUCTION_*') + }) + + it('旧文档级绑定标成旧路径,不再声称"发布写入此库"', () => { + const html = view(bindings()) + expect(html).toContain('文档级发布(单篇文档写生产)· 旧路径') + expect(html).toContain('整库封存/同步/恢复不读取这组配置') + expect(html).toContain('对内文档级目标') + expect(html).not.toContain('发布写入此库') + }) + + it('整库目标缺配置:点名缺哪个环境变量,且不拿文档级绑定顶上去', () => { + const html = view( + bindings({ + whole_target: { + configured: false, + source: '部署环境 LIBRARY_PRODUCTION_*', + tenant_id: 0, + internal_kb_id: '', + external_kb_id: '', + database: '(未配置)', + elastic_index: '', + object_bucket: '', + missing_reason: '未配置:LIBRARY_PRODUCTION_DATABASE_URL、LIBRARY_PRODUCTION_KB_INTERNAL', + }, + }) + ) + expect(html).toContain('LIBRARY_PRODUCTION_DATABASE_URL') + expect(html).toContain('整库目标配置不全') + // 文档级绑定仍然显示,但必须仍是"文档级"身份,不能冒充整库目标。 + expect(html).toContain('对内文档级目标') + }) + + it('非管理员看得到目标,但没有保存入口', () => { + const html = view(bindings(), false) + expect(html).toContain('a8e9c8ad-411c-4c53-8421-599d29e9b179') + expect(html).not.toContain('保存文档级目标') + expect(html).toContain('仅管理员可修改文档级发布目标') + }) +}) diff --git a/web/src/ProductionBindingsSection.tsx b/web/src/ProductionBindingsSection.tsx index 79b8f5d..251d841 100644 --- a/web/src/ProductionBindingsSection.tsx +++ b/web/src/ProductionBindingsSection.tsx @@ -5,8 +5,185 @@ import { fetchProductionBindingOptions, fetchProductionBindings, saveProductionB import type { ProductionBindings } from './productionBindings' import type { KnowledgeBaseOption } from './routingBindings' -// 「生产知识库绑定」:发布链路的 源库 → 目标库 映射。这里选的是发布要写入的 -// 生产(目标)知识库,与上面的「测试知识库绑定」(测试端收件库)是两件事。 +// 「生产知识库绑定」:这里同时涉及两条独立路径,页面必须分开写清楚: +// 1) 整库发布目标(封存/同步/恢复真正写入的库与端点)——来自部署配置,只读; +// 2) 文档级绑定(旧流程:单篇文档发布写哪个库)——可在这里编辑。 +// 把 2 写成"发布写入此库"会让操作者以为整库发布会写进 0b217e8a 这类 2000+ 文档库。 + +export interface ProductionBindingsViewProps { + bindings: ProductionBindings | null + options: KnowledgeBaseOption[] + internalDraft: string + externalDraft: string + isAdmin: boolean + loading: boolean + saving: boolean + error: string | null + message: string + dirty: boolean + sameSelection: boolean + onInternalChange: (next: string) => void + onExternalChange: (next: string) => void + onSave: () => void + onReload: () => void +} + +export function ProductionBindingsView(props: ProductionBindingsViewProps) { + const { + bindings, + options, + internalDraft, + externalDraft, + isAdmin, + loading, + saving, + error, + message, + dirty, + sameSelection, + onInternalChange, + onExternalChange, + onSave, + onReload, + } = props + const optionLabel = (base: KnowledgeBaseOption) => `${base.name}(${base.knowledge_count} 文档)` + const renderSide = (label: string, boundID: string, boundName: string) => ( +
    + {label} + + {boundID ? boundName || `${boundID.slice(0, 8)}…` : '未绑定 · 按同 ID 语义发布(目标端须存在同 ID 库)'} + + {boundID ? '文档级绑定 · 只影响单篇文档发布,不改整库目标' : '未绑定:沿用测试库 ID'} +
    + ) + const whole = bindings?.whole_target + const wholeRows: [string, string][] = whole + ? [ + ['对内目标知识库', whole.internal_kb_id || '未配置'], + ['对外目标知识库', whole.external_kb_id || '未配置'], + ['目标数据库', whole.database || '—'], + ['检索索引', whole.elastic_index || '—'], + ['对象存储桶', whole.object_bucket || '—'], + ['租户', whole.tenant_id ? String(whole.tenant_id) : '—'], + ['配置来源', whole.source || '—'], + ] + : [] + const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) => + options.length > 0 ? ( + + ) : ( + onChange(event.target.value.trim())} + placeholder={`${placeholder}(输入生产知识库 ID)`} + aria-label={placeholder} + /> + ) + + return ( +
    +
    +
    +

    生产知识库绑定

    +

    + 这里有两件不同的事,页面分开显示:整库发布目标(封存/同步/恢复真正写入的目标, + 由部署配置决定,只读)与文档级绑定(旧流程:单篇文档发布写哪个库,可在这里改)。 +

    +
    + +
    + {error ? ( +

    + {/api key file/i.test(error) + ? '生产 API 读取凭据未配置:无法在此列出生产知识库。整库同步走独立执行器通道,不受这条读取凭据影响。' + : error} +

    + ) : null} + {bindings ? ( +
    +

    整库发布目标(实际写入,只读)

    + {whole?.configured === false ? ( +

    + 整库目标配置不全:{whole.missing_reason}。整库封存/同步/恢复在补齐部署配置前会被拒绝, + 页面不会用下面的文档级绑定顶上。 +

    + ) : null} + {wholeRows.length ? ( +
    + {wholeRows.map(([label, value]) => ( +
    +
    {label}
    +
    + {value} +
    +
    + ))} +
    + ) : null} +

    + 这份目标来自部署环境,不在页面上编辑;改它需要改部署配置并重启 api/worker,不会由本页保存。 +

    +
    + ) : null} + {bindings ? ( +
    + + {bindings.legacy_scope || '文档级发布(单篇文档写生产)· 旧路径'} + · 展开编辑;整库封存/同步/恢复不读取这组配置 + +
    + {renderSide('对内文档级目标', bindings.internal_kb_id, bindings.internal_kb_name)} + {renderSide('对外文档级目标', bindings.external_kb_id, bindings.external_kb_name)} +
    +
    + ) : null} + {bindings && !bindings.production_connected ? ( +

    + 生产端核对不可用: + {/api key file/i.test(bindings.production_message) + ? '生产 API 读取凭据未配置(不影响整库执行器;整库同步走独立数据库/索引/存储通道)' + : bindings.production_message} + 。{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''} +

    + ) : null} + {bindings && bindings.production_connected && bindings.production_base_url ? ( +

    + 生产端:{bindings.production_base_url} + {bindings.updated_by ? ` · 最近修改:${bindings.updated_by}` : ''} +

    + ) : null} + {isAdmin && bindings ? ( +
    + + +

    保存时只改文档级绑定;整库发布目标由部署配置决定,本页不改它。

    +

    保存时会向生产端核对所选的库是否真实存在;对不上会拒收,生产端不可达则只提示。

    + {sameSelection ?

    对内与对外必须绑定不同的生产知识库

    : null} + + {message ? ( +

    + {message} +

    + ) : null} +
    + ) : null} + {!isAdmin ?

    仅管理员可修改文档级发布目标。

    : null} +
    + ) +} + +// 容器:读取 + 保存。整库目标只读展示,保存动作只写文档级绑定。 export function ProductionBindingsSection() { const auth = useOptionalAuth() const isAdmin = auth?.identity?.role === 'admin' @@ -20,68 +197,69 @@ export function ProductionBindingsSection() { const [message, setMessage] = useState('') const load = useCallback(async () => { - setLoading(true); setError(null) + setLoading(true) + setError(null) try { const next = await fetchProductionBindings() setBindings(next) setInternalDraft(next.internal_kb_id) setExternalDraft(next.external_kb_id) - try { setOptions(await fetchProductionBindingOptions()) } catch { setOptions([]) } - } catch (cause) { setError(cause instanceof Error ? cause.message : '读取生产知识库绑定失败') } - finally { setLoading(false) } + try { + setOptions(await fetchProductionBindingOptions()) + } catch { + setOptions([]) + } + } catch (cause) { + setError(cause instanceof Error ? cause.message : '读取生产知识库绑定失败') + } finally { + setLoading(false) + } }, []) - useEffect(() => { void load() }, [load]) + useEffect(() => { + void load() + }, [load]) - const dirty = bindings !== null && (internalDraft !== bindings.internal_kb_id || externalDraft !== bindings.external_kb_id) + const dirty = + bindings !== null && (internalDraft !== bindings.internal_kb_id || externalDraft !== bindings.external_kb_id) const sameSelection = internalDraft !== '' && internalDraft === externalDraft const save = async () => { - setSaving(true); setError(null); setMessage('') + setSaving(true) + setError(null) + setMessage('') try { const next = await saveProductionBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft }) setBindings(next) const where = `对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}` - setMessage(next.production_connected - ? `发布目标已更新:${where}。之后新发布的“对内/对外”内容会写入这两个生产库(已发布过的条目仍回到原目标)。` - : `发布目标已保存:${where};但当前核对不了生产端(${next.production_message}),下次发布前请确认。`) - } catch (cause) { setError(cause instanceof Error ? cause.message : '保存生产知识库绑定失败') } - finally { setSaving(false) } + setMessage( + next.production_connected + ? `文档级发布目标已更新:${where}。只影响单篇文档发布;整库发布写的是上面那份「整库发布目标」。` + : `文档级发布目标已保存:${where};但当前核对不了生产端(${next.production_message}),下次发布前请确认。` + ) + } catch (cause) { + setError(cause instanceof Error ? cause.message : '保存生产知识库绑定失败') + } finally { + setSaving(false) + } } - const optionLabel = (base: KnowledgeBaseOption) => `${base.name}(${base.knowledge_count} 文档)` - const renderSide = (label: string, boundID: string, boundName: string) => ( -
    - {label} - {boundID ? (boundName || `${boundID.slice(0, 8)}…`) : '未绑定 · 按同 ID 语义发布(目标端须存在同 ID 库)'} - {boundID ? 'UI 绑定 · 发布写入此库' : '未绑定:沿用测试库 ID'} -
    + return ( + void save()} + onReload={() => void load()} + /> ) - const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) => ( - options.length > 0 - ? - : onChange(event.target.value.trim())} placeholder={`${placeholder}(输入生产知识库 ID)`} aria-label={placeholder} /> - ) - - return
    -

    生产知识库绑定

    发布链路的“源库 → 目标库”:新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库。留空表示未绑定,按同 ID 语义发布。

    - {error ?

    {error}

    : null} - {bindings ?
    - {renderSide('对内生产知识库', bindings.internal_kb_id, bindings.internal_kb_name)} - {renderSide('对外生产知识库', bindings.external_kb_id, bindings.external_kb_name)} -
    : null} - {bindings && !bindings.production_connected ?

    生产端核对不可用:{bindings.production_message}。{bindings.production_base_url ? `(生产地址:${bindings.production_base_url})` : ''}

    : null} - {bindings && bindings.production_connected && bindings.production_base_url ?

    生产端:{bindings.production_base_url}{bindings.updated_by ? ` · 最近修改:${bindings.updated_by}` : ''}

    : null} - {isAdmin && bindings ?
    - - -

    保存时会向生产端核对所选的库是否真实存在;对不上会拒收,生产端不可达则只提示。

    - {sameSelection ?

    对内与对外必须绑定不同的生产知识库

    : null} - - {message ?

    {message}

    : null} -
    : null} - {!isAdmin ?

    仅管理员可修改发布目标。

    : null} -
    -} \ No newline at end of file +} diff --git a/web/src/QAAI.tsx b/web/src/QAAI.tsx index ed22b3c..04c2bbc 100644 --- a/web/src/QAAI.tsx +++ b/web/src/QAAI.tsx @@ -288,7 +288,7 @@ export function QAAIWorkbench({ {status ? ( {status.worker_ready ? '执行器在线' : '执行器未在线,任务会持久保留'} - {!ready ? ';请先在系统设置 → 服务配置完成模型核验' : ''} + {!ready ? ';请先在系统设置 → AI 模型连接完成模型核验' : ''} ) : ( 读取后台状态… diff --git a/web/src/QAMirrorSync.tsx b/web/src/QAMirrorSync.tsx index 4f691d9..8651982 100644 --- a/web/src/QAMirrorSync.tsx +++ b/web/src/QAMirrorSync.tsx @@ -16,7 +16,7 @@ export function QAMirrorSyncView(p: ViewProps) {
    + {confirmation?.current ? ( + + ) : null} {confirmation?.has_image && !stale ? ( + +
    + + ) : null} {settings ? (

    {settings.enabled ? '自动发送已启用' : '自动发送未启用'} ·{' '} @@ -187,6 +260,7 @@ export function QAWeeklyMail({ week, busy }: { week: string; busy: boolean }) { {send.week} · 第{send.draft_revision}版 ·{' '} {{ sending: '发送中', sent: '已发送', failed: '发送失败' }[send.status]} · {stamp(send.updated_at)} {send.last_error ? ` · ${send.last_error}` : ''} + {send.message_id ? ` · ${send.message_id}` : ''} ))} diff --git a/web/src/ReleasePlanner.test.tsx b/web/src/ReleasePlanner.test.tsx index 87c3ff6..9d378ab 100644 --- a/web/src/ReleasePlanner.test.tsx +++ b/web/src/ReleasePlanner.test.tsx @@ -1,20 +1,62 @@ import { renderToStaticMarkup } from 'react-dom/server' -import { describe,expect,it,vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { ReleasePlannerView } from './ReleasePlanner' import { simulatedReleaseCandidates } from './releasePlanner' -describe('ReleasePlannerView',()=>{ - it('shows a four-step document release plan with explicit closure and production gates',()=>{ - const html=renderToStaticMarkup() - for(const text of ['本地模拟发布准备','1. 选择文档','2. 检查数据闭包','3. 锁定清单','4. 生产负责人授权','[模拟] CR5用户手册.pdf','切片 186','向量 186','Wiki 完整','图谱 完整','闭包完整','文档级:','闭包可独立验证','整知识库:','Wiki或图谱共享','推荐方式','文档级同步','生产发布已关闭','生产备份到OSS:尚未配置'])expect(html).toContain(text) - expect(html).not.toContain('>授权生产发布') - }) - it('forces whole knowledge-base mode for shared graph data and blocks failed parsing',()=>{ - const whole=renderToStaticMarkup() - expect(whole).toContain('整知识库同步') - expect(whole).toContain('图谱 共享,需整库') - const failed=renderToStaticMarkup() - expect(failed).toContain('当前清单不能同步') - expect(failed).toContain('闭包不完整') - }) +describe('ReleasePlannerView', () => { + it('shows a four-step document release plan with explicit closure and production gates', () => { + const html = renderToStaticMarkup( + + ) + for (const text of [ + '本地模拟发布准备', + '1. 选择文档', + '2. 检查数据闭包', + '3. 锁定清单', + '4. 生产负责人授权', + '[模拟] CR5用户手册.pdf', + '切片 186', + '向量 186', + 'Wiki 完整', + '图谱 完整', + '闭包完整', + '文档级:', + '闭包可独立验证', + '整知识库:', + 'Wiki或图谱共享', + '推荐方式', + '文档级同步', + '生产发布已关闭', + '生产备份到OSS:尚未配置', + ]) + expect(html).toContain(text) + expect(html).not.toContain('>授权生产发布') + }) + it('forces whole knowledge-base mode for shared graph data and blocks failed parsing', () => { + const whole = renderToStaticMarkup( + + ) + expect(whole).toContain('整知识库同步') + expect(whole).toContain('图谱 共享,需整库') + const failed = renderToStaticMarkup( + + ) + expect(failed).toContain('当前清单不能同步') + expect(failed).toContain('闭包不完整') + }) }) diff --git a/web/src/ReleasePlanner.tsx b/web/src/ReleasePlanner.tsx index d7fe553..2e55329 100644 --- a/web/src/ReleasePlanner.tsx +++ b/web/src/ReleasePlanner.tsx @@ -1,26 +1,183 @@ import { useState } from 'react' -import { evaluateReleaseSelection,simulatedReleaseCandidates } from './releasePlanner' -import type { ClosureState,ReleaseCandidate } from './releasePlanner' +import { evaluateReleaseSelection, simulatedReleaseCandidates } from './releasePlanner' +import type { ClosureState, ReleaseCandidate } from './releasePlanner' import './releasePlanner.css' -const closure=(value:ClosureState)=>value==='ready'?'完整':value==='shared'?'共享,需整库':value==='missing'?'缺失':'不适用' -const modeLabel={none:'尚未选择',document:'文档级同步',knowledge_base:'整知识库同步',blocked:'当前清单不能同步'} as const -interface Props{candidates:ReleaseCandidate[];selectedIDs:string[];onToggle:(id:string)=>void;onClear:()=>void;onGenerate?:()=>void;generated?:boolean} -export function ReleasePlannerView({candidates,selectedIDs,onToggle,onClear,onGenerate=()=>undefined,generated=false}:Props){ - const selected=candidates.filter(item=>selectedIDs.includes(item.id));const plan=evaluateReleaseSelection(selected);const totals=selected.reduce((sum,item)=>({chunks:sum.chunks+item.chunks,vectors:sum.vectors+item.vectors,assets:sum.assets+item.assets}),{chunks:0,vectors:0,assets:0}) - return

    -

    同步准备

    发布管理

    确认测试环境哪些文档具备完整数据,再决定文档级或整知识库同步。

    生产发布已关闭
    -
    本地模拟发布准备候选文档和闭包数量均为模拟,用于确认工作流程;不会连接生产。
    -
    1. 1. 选择文档
    2. 2. 检查数据闭包
    3. 3. 锁定清单
    4. 4. 生产负责人授权
    -
    -

    测试环境候选文档

    解析失败或核心数据缺失的文件不可加入
    -
    {candidates.map(item=>{const blocked=item.parse_status!=='completed'||item.chunks<1||item.vectors!==item.chunks||item.assets<1||item.wiki==='missing'||item.graph==='missing';const shared=item.wiki==='shared'||item.graph==='shared';return })}
    -
    - -
    -
    +const closure = (value: ClosureState) => + value === 'ready' ? '完整' : value === 'shared' ? '共享,需整库' : value === 'missing' ? '缺失' : '不适用' +const modeLabel = { + none: '尚未选择', + document: '文档级同步', + knowledge_base: '整知识库同步', + blocked: '当前清单不能同步', +} as const +interface Props { + candidates: ReleaseCandidate[] + selectedIDs: string[] + onToggle: (id: string) => void + onClear: () => void + onGenerate?: () => void + generated?: boolean } -export function ReleasePlanner(){ - const [selectedIDs,setSelectedIDs]=useState([]);const [generated,setGenerated]=useState(false) - const toggle=(id:string)=>{setGenerated(false);setSelectedIDs(current=>current.includes(id)?current.filter(value=>value!==id):[...current,id])} - return {setSelectedIDs([]);setGenerated(false)}} onGenerate={()=>setGenerated(true)} generated={generated} /> +export function ReleasePlannerView({ + candidates, + selectedIDs, + onToggle, + onClear, + onGenerate = () => undefined, + generated = false, +}: Props) { + const selected = candidates.filter((item) => selectedIDs.includes(item.id)) + const plan = evaluateReleaseSelection(selected) + const totals = selected.reduce( + (sum, item) => ({ + chunks: sum.chunks + item.chunks, + vectors: sum.vectors + item.vectors, + assets: sum.assets + item.assets, + }), + { chunks: 0, vectors: 0, assets: 0 } + ) + return ( +
    +
    +
    +

    同步准备

    +

    发布管理

    +

    确认测试环境哪些文档具备完整数据,再决定文档级或整知识库同步。

    +
    + 生产发布已关闭 +
    +
    + 本地模拟发布准备 + 候选文档和闭包数量均为模拟,用于确认工作流程;不会连接生产。 +
    +
      +
    1. 1. 选择文档
    2. +
    3. 2. 检查数据闭包
    4. +
    5. 3. 锁定清单
    6. +
    7. 4. 生产负责人授权
    8. +
    +
    +
    +
    +
    +

    测试环境候选文档

    + 解析失败或核心数据缺失的文件不可加入 +
    + +
    +
    + {candidates.map((item) => { + const blocked = + item.parse_status !== 'completed' || + item.chunks < 1 || + item.vectors !== item.chunks || + item.assets < 1 || + item.wiki === 'missing' || + item.graph === 'missing' + const shared = item.wiki === 'shared' || item.graph === 'shared' + return ( + + ) + })} +
    +
    + +
    +
    + ) +} +export function ReleasePlanner() { + const [selectedIDs, setSelectedIDs] = useState([]) + const [generated, setGenerated] = useState(false) + const toggle = (id: string) => { + setGenerated(false) + setSelectedIDs((current) => (current.includes(id) ? current.filter((value) => value !== id) : [...current, id])) + } + return ( + { + setSelectedIDs([]) + setGenerated(false) + }} + onGenerate={() => setGenerated(true)} + generated={generated} + /> + ) } diff --git a/web/src/ReleaseTargets.mount.test.tsx b/web/src/ReleaseTargets.mount.test.tsx new file mode 100644 index 0000000..26b28ed --- /dev/null +++ b/web/src/ReleaseTargets.mount.test.tsx @@ -0,0 +1,474 @@ +// @vitest-environment jsdom +// +// 同一挂载上的真实刷新/切换行为:ReleaseTargets 自己走 load() + fetch。 +// 旧测试拿三次 renderToStaticMarkup 当成"刷新",那是三个互不相关的静态输入, +// 既不执行 effect 也不发请求,证明不了刷新后不残留旧状态(G1)。 +// 这里只用一个挂载 + 可控 fetch,覆盖: +// - 首次读取未返回 / 请求失败 / 当前范围没有 overview:都不许说"目标非空"; +// - 空 → 不可读 → 恢复(同一挂载上的真实重新读取); +// - 刷新失败保留旧观测时必须标成上次观测,恢复后清掉; +// - 对内/对外切换不串用,overview 属于别的范围时也不借用。 +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import type { Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { AuthContext } from './auth' +import type { LibraryOverview } from './librarySnapshots' +import { ReleaseTargets } from './ReleaseTargets' + +const adminValue = { + identity: { + id: 'u-admin', + username: 'admin', + display_name: '管理员', + role: 'admin' as const, + must_change_password: false, + }, + ready: true, + login: async () => null, + logout: async () => undefined, + changePassword: async () => null, + signedOut: 0, + notifySignedOut: () => undefined, +} + +type Scope = 'internal' | 'external' +type Reply = { status: number; body: unknown; hold?: Promise } + +const emptyTarget: LibraryOverview['production'] = { + state: 'unknown', + empty_baseline: true, + reason: '生产目标可读且为空:本次是首次发布,写入前仍会生成完整预备份', +} +const unreadableTarget: LibraryOverview['production'] = { + state: 'unreachable', + reason: '无法读取目标整库状态:请检查目标连接后重试,不能据此判定空库或建立基线', +} + +const snapshot = { + snapshot_id: 'f992d64ea45bf737a0721a465b5aef2b150ef7757157eb84f3aaf8b6972d98f9', + scope: 'internal', + knowledge_base_id: '0c84a098-d3ed-4b82-a165-e6de9691d6a8', + tenant_id: 10000, + created_at: '2026-11-02T02:00:00Z', + validation_policy: 'artifact-acceptance-v1', + format: 'weknora-library-snapshot/v1', + compatibility: { + weknora_version: 'v0.7.1', + schema_version: 74, + retriever_engine: 'elasticsearch_v8', + embedding_model: 'text-embedding-v4', + embedding_dimension: 1024, + index_mapping_sha256: 'a'.repeat(64), + }, + parts: [], + logical_bytes: 0, + unique_bytes: 0, + shared_bytes: 0, + totals: { documents: 0, chunks: 0, index_documents: 0, resources: 0, wiki_pages: 0 }, +} + +const overviewBody = (scope: string, production: LibraryOverview['production']) => ({ + scope, + test_sealed: { ...snapshot, scope }, + production, + prebackup: { state: 'unknown', reason: '本次目标快照还没有生产预备份' }, + diff: { state: 'unknown', reason: '生产与测试的文档级差异读取未接线', added: [], updated: [], removed: [] }, + jobs: [], + gate: { sync_allowed: false, reasons: ['没有与目标快照匹配的有效发布授权'] }, + authorization: { state: 'none', reason: '没有与目标快照匹配的有效发布授权' }, + capture_available: false, + now: '2026-11-02T02:05:00Z', +}) + +const snapshotsBody = { + available: true, + reason: '', + archive_root: '/tmp/archive', + snapshots: [], + versions: 0, + content_bytes: 0, + blob_file_bytes: 0, + blob_allocated_bytes: 0, + unreferenced_blobs: 0, + unreferenced_bytes: 0, + manifest_file_bytes: 0, + manifest_allocated_bytes: 0, + capture_note: '', + capture_available: false, + capture_reason: '', +} + +const reply = (body: unknown, status = 200): Reply => ({ status, body }) +const json = (body: unknown, status: number) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) + +let overviews: Record +// 维护窗口与持有作业详情:默认没有窗口;需要时按测试覆盖。 +let maintenanceBody: Record = {} +let jobDetails: Record = {} +let jobDetailFailures: Record = {} +let recoveryCalls: { scope: string; window_job_id: string }[] = [] +let verificationBySnapshot: Record = {} +let container: HTMLDivElement +let root: Root +let originalFetch: typeof fetch + +const mount = async () => { + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + await act(async () => { + root.render( + + + + ) + }) + await settle() +} + +// load() 是几层 await(fetch → json → setState);按微任务轮次推进到稳定。 +const settle = async () => { + for (let round = 0; round < 6; round += 1) { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + } +} + +const text = () => container.textContent ?? '' +const buttonLabels = () => Array.from(container.querySelectorAll('button')).map((node) => node.textContent ?? '') + +const click = async (label: string) => { + const target = Array.from(container.querySelectorAll('button')).find((node) => + (node.textContent ?? '').includes(label) + ) + if (!target) throw new Error(`没有找到按钮:${label}(现有:${buttonLabels().join(' / ')})`) + await act(async () => { + target.dispatchEvent(new window.MouseEvent('click', { bubbles: true })) + }) + await settle() +} + +beforeEach(() => { + originalFetch = globalThis.fetch + overviews = { + internal: reply(overviewBody('internal', emptyTarget)), + external: reply(overviewBody('external', unreadableTarget)), + } + maintenanceBody = {} + jobDetails = {} + jobDetailFailures = {} + recoveryCalls = [] + verificationBySnapshot = {} + snapshotsBody.snapshots = [] + snapshotsBody.versions = 0 + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input) + if (url.startsWith('/api/v1/library/verifications')) { + const snapshotID = new URL(url, 'http://candidate.invalid').searchParams.get('snapshot_id') ?? '' + return json( + { + scope: 'internal', + target: { + instance: 'test', + project: 'test', + internal_kb: 'kb', + external_kb: 'kb-external', + index: 'idx', + s3_bucket: 'bucket', + tenant_id: 10000, + database_configured: true, + }, + snapshot_latest: verificationBySnapshot[snapshotID] ?? null, + }, + 200 + ) + } + if (url.startsWith('/api/v1/library/snapshots')) return json(snapshotsBody, 200) + if (url.startsWith('/api/v1/library/captures')) return json({ jobs: [] }, 200) + if (url.startsWith('/api/v1/library/maintenance/recover')) { + const body = JSON.parse(String(init?.body ?? '{}')) as { scope: string; window_job_id: string } + recoveryCalls.push(body) + return json({ accepted: true, recovery_job: 'q-recover' }, 200) + } + if (url.startsWith('/api/v1/library/maintenance')) return json(maintenanceBody, 200) + if (url.startsWith('/api/v1/library/jobs/')) { + const id = decodeURIComponent(url.slice('/api/v1/library/jobs/'.length)) + const status = jobDetailFailures[id] + if (status) return json({ error: '作业详情读取失败' }, status) + const job = jobDetails[id] + return job ? json({ available: true, job }, 200) : json({ available: false, reason: '作业不存在' }, 404) + } + if (url.startsWith('/api/v1/library/overview')) { + const scope = new URL(url, 'http://candidate.invalid').searchParams.get('scope') + const answer = overviews[scope === 'external' ? 'external' : 'internal'] + if (answer.hold) await answer.hold + return json(answer.body, answer.status) + } + return json({ error: '测试未声明该请求' }, 404) + }) as typeof fetch +}) + +afterEach(async () => { + if (root) { + await act(async () => { + root.unmount() + }) + } + container?.remove() + globalThis.fetch = originalFetch +}) + +describe('ReleaseTargets 同一挂载上的目标观测(F1/G1)', () => { + it('首次读取未返回时只说正在读取,不说目标非空', async () => { + let release: () => void = () => undefined + const hold = new Promise((resolve) => { + release = resolve + }) + overviews.internal = { ...reply(overviewBody('internal', emptyTarget)), hold } + await mount() + expect(text()).toContain('正在读取目标状态') + expect(text()).not.toContain('目标非空') + expect(text()).not.toContain('目标已读且为空') + release() + await settle() + expect(text()).toContain('目标已读且为空') + expect(text()).not.toContain('正在读取目标状态') + }) + + it('空 → 不可读 → 恢复:同一挂载按每次真实读取重新分类', async () => { + await mount() + expect(text()).toContain('目标已读且为空') + expect(text()).not.toContain('目标非空') + // 管理员 + 已封存时基线入口本来会出现,但空目标不该给(后端会 409)。 + expect(buttonLabels()).not.toContain('建立目标权威基线(维护隔离)') + + overviews.internal = reply(overviewBody('internal', unreadableTarget)) + await click('刷新') + expect(text()).toContain('无法读取目标整库状态') + expect(text()).not.toContain('目标已读且为空') + expect(text()).not.toContain('目标非空') + expect(buttonLabels()).not.toContain('建立目标权威基线(维护隔离)') + + overviews.internal = reply(overviewBody('internal', emptyTarget)) + await click('刷新') + expect(text()).toContain('目标已读且为空') + expect(text()).not.toContain('无法读取目标整库状态') + expect(text()).not.toContain('目标非空') + }) + + it('刷新失败保留旧观测时标成上次观测,恢复读取后清除', async () => { + await mount() + expect(text()).toContain('目标已读且为空') + expect(text()).not.toContain('上次观测') + + overviews.internal = reply({ error: '上游不可用' }, 502) + await click('刷新') + expect(text()).toContain('读取失败') + // 旧观测仍在,但不能冒充刚验证。 + expect(text()).toContain('目标已读且为空') + expect(text()).toContain('上次观测 · 刷新失败,可能已过期') + expect(text()).not.toContain('目标非空') + + overviews.internal = reply(overviewBody('internal', emptyTarget)) + await click('刷新') + expect(text()).not.toContain('上次观测') + expect(text()).not.toContain('读取失败') + expect(text()).toContain('目标已读且为空') + }) + + it('内外切换不串用:对外的不可读不会被内对的空顶替', async () => { + await mount() + expect(text()).toContain('目标已读且为空') + + await click('对外知识库') + expect(text()).toContain('无法读取目标整库状态') + expect(text()).not.toContain('目标已读且为空') + expect(text()).not.toContain('目标非空') + expect(buttonLabels()).not.toContain('建立目标权威基线(维护隔离)') + + overviews.external = reply(overviewBody('external', emptyTarget)) + await click('刷新') + expect(text()).toContain('目标已读且为空') + expect(text()).not.toContain('无法读取目标整库状态') + + await click('对内知识库') + expect(text()).toContain('目标已读且为空') + }) + + it('同一挂载的封存作业运行→失败仍只显示只读导出,不切成生产步骤', async () => { + const runningSeal = { + id: 'libseal-ui-running', + scope: 'internal', + kind: 'seal', + state: 'running', + stage: 'export', + request_digest: 's', + queue_job_id: 'q-seal', + snapshot_id: '', + target_snapshot_id: '', + actor: 'admin', + error: '', + recovery: '', + created_at: '2026-11-05T05:41:58Z', + updated_at: '2026-11-05T05:42:00Z', + finished_at: null, + stages: [ + { + stage: 'export', + state: 'running', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '正在导出', + updated_at: '2026-11-05T05:42:00Z', + }, + ], + } + overviews.internal = reply({ ...overviewBody('internal', emptyTarget), job: runningSeal, jobs: [runningSeal] }) + await mount() + expect(text()).toContain('只读导出测试版本') + expect(text()).not.toContain('生产生效') + expect(text()).not.toContain('目标在维护中') + + const failedSeal = { + ...runningSeal, + state: 'failed', + error: 'unverified legacy library chunk index coverage', + finished_at: '2026-11-05T05:42:13Z', + stages: [{ ...runningSeal.stages[0], state: 'failed', detail: '封存校验失败' }], + } + overviews.internal = reply({ ...overviewBody('internal', emptyTarget), job: failedSeal, jobs: [failedSeal] }) + await click('刷新') + expect(text()).toContain('封存校验失败') + expect(text()).toContain('unverified legacy library chunk index coverage') + expect(text()).not.toContain('生产生效') + expect(text()).not.toContain('目标在维护中') + }) + + it('版本列表按选中快照的精确验证记录显示,不借用同 scope 最新 passed', async () => { + ;(snapshotsBody as { snapshots: unknown[] }).snapshots = [snapshot] + snapshotsBody.versions = 1 + verificationBySnapshot[snapshot.snapshot_id] = { + id: 'libverify-internal-exact', + scope: 'internal', + status: 'passed', + snapshot_id: snapshot.snapshot_id, + job_id: 'libverify-internal-exact-job', + finished_at: '2026-11-05T06:00:00Z', + } + await mount() + await click('版本与快照') + await click('全部归档') + expect(text()).toContain('恢复验证通过 · libverify-internal-exact-job') + expect(text()).not.toContain('分项完整 · 未做生产恢复验证') + }) + + it('当前范围没有自己的 overview 时不借用别的范围分类', async () => { + // 服务端把对内的 overview 回给了对外请求:scope 不匹配,等于没有观测。 + overviews.external = reply(overviewBody('internal', emptyTarget)) + await mount() + await click('对外知识库') + expect(text()).toContain('还没有读到') + expect(text()).not.toContain('目标已读且为空') + expect(text()).not.toContain('目标非空') + expect(buttonLabels()).not.toContain('建立目标权威基线(维护隔离)') + }) +}) + +// 真实事故复现(2026-11-03 22:48 CST):needs_restore 的持有作业 A 被同 scope 较新的 +// 成功封存 B 覆盖,页面写成“导出 · 已完成”。页面级必须按 owner_job_id 读作业, +// 并且恢复只投递到持有 scope 的那一个窗口。 +describe('维护窗口按持有作业展示(页面级)', () => { + const ownerA = { + id: 'libverify-internal-A', + scope: 'internal', + kind: 'verify', + state: 'failed', + stage: 'verify', + request_digest: 'v', + queue_job_id: 'qv', + snapshot_id: '', + target_snapshot_id: '', + actor: 'admin', + error: '恢复验证失败:canary 校验不一致', + recovery: '预备份保留;按归档人工核验', + created_at: '2026-11-03T09:20:00Z', + updated_at: '2026-11-03T09:24:00Z', + finished_at: '2026-11-03T09:24:00Z', + stages: [], + } + const sealB = { + ...ownerA, + id: 'libseal-lib-internal-20261103T092352', + kind: 'seal', + state: 'succeeded', + stage: 'export', + error: '', + recovery: '', + finished_at: '2026-11-03T09:23:52Z', + } + const instanceHeld = { + held: true, + instance: 'kgmaint-weknora', + instance_maintenance: { + instance: 'kgmaint-weknora', + owner_scope: 'internal', + scope: 'internal', + owner_job_id: 'libverify-internal-A', + level: 'instance', + services: ['app'], + ingress_state: 'closed', + state: 'needs_restore', + acquired_at: '2026-11-03T09:20:00Z', + updated_at: '2026-11-03T09:24:00Z', + released_at: null, + }, + } + + it('较新封存 B 成功不覆盖 needs_restore 窗口,恢复按 A 投递到持有 scope', async () => { + maintenanceBody = instanceHeld + jobDetails = { 'libverify-internal-A': ownerA } + overviews.internal = reply({ ...overviewBody('internal', emptyTarget), job: sealB }) + await mount() + expect(text()).toContain('libverify-internal-A') + expect(text()).toContain('canary 校验不一致') + expect(text()).toContain('维护记录,未实时探测') + expect(text()).not.toContain('导出 · 已完成') + + await click('按预备份恢复') + expect(recoveryCalls).toEqual([{ scope: 'internal', window_job_id: 'libverify-internal-A' }]) + }) + + it('持有作业详情 5xx 时明确“读取失败”,不显示 B 的进度也不给强制成功', async () => { + maintenanceBody = instanceHeld + jobDetailFailures = { 'libverify-internal-A': 503 } + overviews.internal = reply({ ...overviewBody('internal', emptyTarget), job: sealB }) + await mount() + expect(text()).toContain('持有作业状态读取失败') + expect(text()).toContain('HTTP 503') + expect(text()).not.toContain('导出 · 已完成') + expect(text()).not.toContain('强制成功') + }) + + it('持有作业 404 时写“不存在”,不退回最新作业', async () => { + maintenanceBody = instanceHeld + overviews.internal = reply({ ...overviewBody('internal', emptyTarget), job: sealB }) + await mount() + expect(text()).toContain('不存在(维护记录引用了未登记的作业)') + expect(text()).not.toContain('导出 · 已完成') + }) + + it('切到另一个 scope 不向错误 scope 投递恢复', async () => { + maintenanceBody = instanceHeld + jobDetails = { 'libverify-internal-A': ownerA } + await mount() + await click('对外知识库') + expect(text()).toContain('维护窗口属于 internal') + expect(buttonLabels()).not.toContain('按预备份恢复') + expect(recoveryCalls).toEqual([]) + }) +}) diff --git a/web/src/ReleaseTargets.test.tsx b/web/src/ReleaseTargets.test.tsx index b5394eb..f3d72e0 100644 --- a/web/src/ReleaseTargets.test.tsx +++ b/web/src/ReleaseTargets.test.tsx @@ -1,12 +1,14 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it, vi } from 'vitest' -import { ReleaseTargetsView } from './ReleaseTargets' +import { ReleaseTargetsView, libraryPollingActive } from './ReleaseTargets' import type { LibraryCaptureJob, LibraryJobRecord, + LibraryMaintenanceView, LibraryOverview, LibrarySnapshot, LibrarySnapshotList, + LibraryStageRow, } from './librarySnapshots' const internalSnapshot: LibrarySnapshot = { @@ -97,6 +99,26 @@ const overview: LibraryOverview = { ], }, authorization: { state: 'none', reason: '没有与目标快照匹配的有效发布授权' }, + // 测试夹具把两份归档登记为测试封存:默认筛选「已登记版本」会隐藏未登记文件, + // 但仍可由用户切到「全部归档」显式查看。 + versions: [ + { + id: 'ver-internal', + kind: 'test_sealed', + snapshot_id: internalSnapshot.snapshot_id, + version_label: '封存 f992d64ea45b', + source_job_id: '', + created_at: internalSnapshot.created_at, + }, + { + id: 'ver-external', + kind: 'test_sealed', + snapshot_id: externalSnapshot.snapshot_id, + version_label: '封存 01343b0b310b', + source_job_id: '', + created_at: externalSnapshot.created_at, + }, + ], capture_available: true, now: '2026-10-28T03:40:00Z', } @@ -149,9 +171,13 @@ const base: ViewProps = { pendingCapture: false, canCapture: true, canWrite: true, + canReconcileCapture: false, + pendingReconcileCapture: '', + onReconcileCapture: vi.fn(), canRestore: false, sync: { canSign: false, pendingGrant: false, onGrant: vi.fn(), canStart: false, pending: false, onStart: vi.fn() }, baseline: { canStart: false, pending: false, onStart: vi.fn() }, + verification: { onAccepted: vi.fn(), onComplete: vi.fn() }, restore: null, restoreNotice: null, pendingRestore: false, @@ -182,8 +208,9 @@ describe('ReleaseTargetsView(确认稿布局)', () => { it('未接入项显示“未接入/未知”,不用 0 / 无变化冒充', () => { const html = render() expect(html).toContain('生产当前') - // 生产没有权威版本时必须写未知,不能拿测试快照顶替 - expect(html).toContain('未知(尚未建立权威版本)') + // 生产没有权威版本时必须写"非空且尚无权威版本",不能拿测试快照顶替, + // 也不能把所有非 known 一律写成"未知"(空目标与读不到是另外两类)。 + expect(html).toContain('目标非空,尚无权威版本') expect(html).toContain('尚无记录 · 生产与测试的文档级差异读取未接线') expect(html).toContain('未接入') }) @@ -305,29 +332,486 @@ describe('ReleaseTargetsView(确认稿布局)', () => { }) it('抽屉只展示当前选中库的历史', () => { - const html = render({ drawerOpen: true, scope: 'external' }) - expect(html).toContain('封存 01343b0b310b') - expect(html).not.toContain('封存 f992d64ea45b') + const html = render({ + drawerOpen: true, + scope: 'external', + overviews: { + internal: overview, + external: { ...overview, scope: 'external', versions: [overview.versions![1]] }, + }, + }) + const drawer = html.slice(html.indexOf('aria-label="版本与快照"')) + expect(drawer).toContain('快照 01343b0b310b') + expect(drawer).not.toContain('快照 f992d64ea45b') }) - it('同步中布局显示四类数据卡与明细,且不编造百分比', () => { + // E3:归档里同时躺着测试封存、目标基线与每次预备份。旧页面把每一行都写"测试封存", + // 于是预备份/基线被当成了"可以发布的候选"。类型只能来自版本登记。 + it('抽屉按版本登记标注每份归档,不把预备份/基线写成测试封存', () => { + const html = render({ + drawerOpen: true, + overview: { + ...overview, + versions: [ + { + id: 'libver-sealed', + kind: 'test_sealed', + snapshot_id: internalSnapshot.snapshot_id, + version_label: '', + source_job_id: 'libseal-1', + created_at: internalSnapshot.created_at, + }, + { + id: 'libver-pre', + kind: 'production_prebackup', + snapshot_id: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', + version_label: '', + source_job_id: 'librestore-internal-1', + created_at: '2026-10-29T16:59:39Z', + }, + ], + }, + page: { + ...page, + snapshots: [ + internalSnapshot, + { + ...internalSnapshot, + snapshot_id: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', + created_at: '2026-10-29T16:59:39Z', + }, + ], + }, + }) + expect(html).toContain('测试封存') + expect(html).toContain('生产预备份') + // 没有被登记过的归档文件也不能冒充测试封存 + expect(html).not.toContain('测试封存 { + const html = render({ + drawerOpen: true, + overview: { + ...overview, + prebackup: { + state: 'known', + version: { + id: 'libver-pre', + kind: 'production_prebackup', + snapshot_id: '089676a09107ceab3bf5e88651f443da26e5d9b2d0de380840c5ec24941a07c2', + version_label: '', + source_job_id: 'librestore-internal-1793293164573204381', + evidence: {}, + created_by: 'worker', + created_at: '2026-10-29T16:59:39Z', + }, + bound_to_target: false, + }, + }, + }) + expect(html).toContain('已登记预备份') + expect(html).not.toContain('尚未创建') + expect(html).toContain('作业 librestore-internal-1793293164573204381') + expect(html).toContain('不是当前拟发布目标的快照') + expect(html).toContain('最近一次生产预备份') + expect(html).not.toContain('无记录(尚未为本次目标创建)') + }) + + // E1:作业已经成功,页面不能还说"尚未启动/此时尚未运行"。 + it('已完成的同步不再写“尚未启动”,阶段按本次作业打勾', () => { + const succeeded: LibraryJobRecord = { + ...persistedSeal, + id: 'libsync-internal-1793292008635856030', + kind: 'sync', + state: 'succeeded', + stage: 'finalize', + snapshot_id: '4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73', + target_snapshot_id: internalSnapshot.snapshot_id, + finished_at: '2026-10-29T16:40:36Z', + updated_at: '2026-10-29T16:40:36Z', + stages: [ + { + stage: 'prebackup', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '', + updated_at: '2026-10-29T16:40:21Z', + }, + { + stage: 'database', + state: 'succeeded', + total: 67, + completed: 67, + bytes_total: 88086, + bytes_done: 88086, + detail: '', + updated_at: '2026-10-29T16:40:22Z', + }, + { + stage: 'verify', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '', + updated_at: '2026-10-29T16:40:26Z', + }, + { + stage: 'finalize', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '已登记生效版本', + updated_at: '2026-10-29T16:40:26Z', + }, + ], + } + const html = render({ overview: { ...overview, job: succeeded, jobs: [succeeded] } }) + expect(html).not.toContain('尚未启动,不修改生产') + expect(html).not.toContain('此时尚未运行') + expect(html).toContain('生产同步已完成') + expect(html).toContain('生产同步 · 已完成') + const stageBar = html.slice(html.indexOf('aria-label="作业阶段"'), html.indexOf('rel-steps-note')) + expect(stageBar).toContain('✓') + }) + + // E4:基线/恢复不是"生产同步",也不是"封存进行中"。 + it('建立基线进行中不写成同步中,也不写成封存进行中', () => { + const baseline: LibraryJobRecord = { + ...persistedSeal, + id: 'libbase-internal-1', + kind: 'baseline', + state: 'running', + stage: 'database', + finished_at: null, + } + const html = render({ overview: { ...overview, job: baseline, jobs: [baseline] } }) + expect(html).toContain('建立目标基线进行中') + expect(html).toContain('建立目标基线作业') + expect(html).toContain('建基线中') + expect(html).not.toContain('封存进行中') + expect(html).not.toContain('生产同步作业') + expect(html).not.toContain('同步中') + }) + + it('恢复作业用“按版本恢复”而不是“生产同步”,并说明已回到该快照', () => { + const stages: LibraryStageRow[] = [ + { + stage: 'prebackup', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '', + updated_at: '2026-10-29T16:59:39Z', + }, + { + stage: 'database', + state: 'succeeded', + total: 5, + completed: 5, + bytes_total: 7138, + bytes_done: 7138, + detail: '', + updated_at: '2026-10-29T16:59:40Z', + }, + { + stage: 'resources', + state: 'succeeded', + total: 1, + completed: 1, + bytes_total: 507, + bytes_done: 507, + detail: '', + updated_at: '2026-10-29T16:59:40Z', + }, + { + stage: 'index', + state: 'succeeded', + total: 2, + completed: 2, + bytes_total: 28563, + bytes_done: 28563, + detail: '', + updated_at: '2026-10-29T16:59:40Z', + }, + { + stage: 'wiki', + state: 'succeeded', + total: 10, + completed: 10, + bytes_total: 23144, + bytes_done: 23144, + detail: '', + updated_at: '2026-10-29T16:59:40Z', + }, + { + stage: 'verify', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '', + updated_at: '2026-10-29T16:59:40Z', + }, + { + stage: 'finalize', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '已登记生效版本', + updated_at: '2026-10-29T16:59:40Z', + }, + ] + const restoreRunning: LibraryJobRecord = { + ...persistedSeal, + id: 'librestore-internal-1793293164573204381', + kind: 'restore', + state: 'running', + stage: 'wiki', + target_snapshot_id: '4b720eb42fca75de40aa862f2b53d0751e648d760dafaca309aaee08771f2c73', + finished_at: null, + stages, + } + const running = render({ overview: { ...overview, job: restoreRunning, jobs: [restoreRunning] } }) + expect(running).toContain('按版本恢复作业') + expect(running).toContain('恢复到 4b720eb42fca') + expect(running).toContain('恢复进行中(目标在维护中)') + expect(running).not.toContain('生产同步作业') + + const restoreDone: LibraryJobRecord = { + ...restoreRunning, + state: 'succeeded', + finished_at: '2026-10-29T16:59:51Z', + } + const html = render({ overview: { ...overview, job: restoreDone, jobs: [restoreDone] } }) + expect(html).toContain('按版本恢复') + expect(html).toContain('按版本恢复已完成') + const stageBar = html.slice(html.indexOf('aria-label="作业阶段"'), html.indexOf('rel-steps-note')) + expect(stageBar).toContain('目标已回到该快照') + }) + + it('恢复验证使用自己的阶段,不把登记证据说成新版本生效', () => { + const verifyJob: LibraryJobRecord = { + ...persistedSeal, + id: 'libverify-internal-1', + kind: 'verify', + state: 'running', + stage: 'restore', + stages: [ + { + stage: 'capture', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '已捕获', + updated_at: '2026-11-05T01:00:00Z', + }, + { + stage: 'verify', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '基线校验通过', + updated_at: '2026-11-05T01:01:00Z', + }, + { + stage: 'canary', + state: 'succeeded', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: 'canary 通过', + updated_at: '2026-11-05T01:02:00Z', + }, + { + stage: 'restore', + state: 'running', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '正在恢复', + updated_at: '2026-11-05T01:03:00Z', + }, + { + stage: 'finalize', + state: 'pending', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '', + updated_at: '2026-11-05T01:04:00Z', + }, + ], + } + const html = render({ overview: { ...overview, job: verifyJob, jobs: [verifyJob] } }) + expect(html).toContain('恢复验证阶段') + expect(html).toContain('捕获目标') + expect(html).toContain('登记验证证据') + expect(html).not.toContain('新版本生效') + }) + + it('快照抽屉默认隐藏未登记归档,并给出全部归档入口', () => { + const html = render({ + drawerOpen: true, + overview: { ...overview, versions: [] }, + }) + const drawer = html.slice(html.indexOf('aria-label="版本与快照"')) + expect(drawer).toContain('已登记版本') + expect(drawer).toContain('全部归档(含未登记)') + expect(drawer).not.toContain('快照 f992d64ea45b') + expect(drawer).toContain('当前筛选下没有已登记版本') + }) + + it('统计数据只取当前作业快照,并按真实阶段状态展示', () => { + const jobSnapshot: LibrarySnapshot = { + ...internalSnapshot, + snapshot_id: 'old-job-snapshot', + totals: { + documents: 4, + chunks: 38, + resources: 21, + bindings: 4, + wiki_pages: 31, + wiki_folders: 21, + wiki_log_entries: 11, + }, + } + const job: LibraryJobRecord = { + ...persistedSeal, + id: 'libsync-old', + kind: 'sync', + target_snapshot_id: jobSnapshot.snapshot_id, + stage: 'database', + stages: [ + { + stage: 'database', + state: 'running', + total: null, + completed: null, + bytes_total: null, + bytes_done: null, + detail: '', + updated_at: '2026-11-05T01:00:00Z', + }, + ], + } + const html = render({ + page: { ...page, snapshots: [internalSnapshot, jobSnapshot] }, + overview: { ...overview, job, jobs: [job], test_sealed: internalSnapshot }, + }) + expect(html).toContain('文档 4 · 分块 38 · 资源 21 · 绑定 4') + expect(html).toContain('页面 31 · 目录 21 · 日志 11') + expect(html).toContain('执行中;执行器尚未提供该分项明细') + expect(html).not.toContain('已完成 0 / 0') + }) + + it('封存已完成但终态未回写时,管理员看到核对入口;工程师不显示', () => { + const reconciled: LibraryJobRecord = { + ...persistedSeal, + stages: [{ ...persistedSeal.stages[0], state: 'succeeded', detail: '已封存快照 f992d64ea45b' }], + } + const admin = render({ + canReconcileCapture: true, + onReconcileCapture: vi.fn(), + overview: { ...overview, job: reconciled, jobs: [reconciled] }, + }) + expect(admin).toContain('核对封存结果') + const engineer = render({ + canReconcileCapture: false, + overview: { ...overview, job: reconciled, jobs: [reconciled] }, + }) + expect(engineer).not.toContain('核对封存结果') + }) + + it('系统误判的封存作业(已完成队列+成功导出)仍可由管理员核对;真实失败不显示', () => { + const misclassified: LibraryJobRecord = { + ...persistedSeal, + state: 'failed', + stage: '', + snapshot_id: '', + error: '队列中已无对应作业,业务作业未收到结果', + recovery: '封存作业由 agent 恢复来源;确认来源 healthy 后可重发', + stages: [{ ...persistedSeal.stages[0], state: 'succeeded' }], + } + const admin = render({ + canReconcileCapture: true, + overview: { ...overview, job: misclassified, jobs: [misclassified] }, + }) + expect(admin).toContain('核对封存结果') + const realFailure = render({ + canReconcileCapture: true, + overview: { + ...overview, + job: { ...misclassified, error: '真实导出失败' }, + jobs: [{ ...misclassified, error: '真实导出失败' }], + }, + }) + expect(realFailure).not.toContain('核对封存结果') + }) + + it('封存作业只显示只读导出步骤,不冒充生产备份/同步/生效或目标维护', () => { const html = render({ jobs: [runningJob], overview: { ...overview, job: persistedSeal, jobs: [persistedSeal] }, }) expect(html).toContain('测试库封存作业') - expect(html).toContain('数据库 · 文档与分块') - expect(html).toContain('原文件 · 图片 · 附件') - expect(html).toContain('检索索引 · 向量') - expect(html).toContain('Wiki · 完整快照') - expect(html).toContain('同步明细') - // 唯一允许出现的百分比是免责声明里的「100% ≠ 作业完成」,没有任何进度主张 - expect(html.match(/[1-9]\d*%/g) ?? []).toEqual(['100%']) - expect(html).toContain('文件传输 100% ≠ 作业完成') - expect(html).toContain('不编造百分比') - // 没有真实总量时只写"未知总量",不画百分比 - expect(html).toContain('未知总量') + // F06: 运行中主按钮只能查看当前任务,不能再次启动。 + expect(html).toContain('查看当前任务') + expect(html).not.toContain('▶ 启动同步') + expect(html).toContain('只读导出测试版本') + expect(html).toContain('只读导出测试库快照 → 不修改目标生产') + expect(html).toContain('封存进行中(只读导出测试版本,不修改目标生产)') + expect(html).toContain('封存范围') expect(html).toContain('主机侧正在暂停写入者、导出并恢复') + expect(html).not.toContain('>备份生产<') + expect(html).not.toContain('>同步数据与 Wiki<') + expect(html).not.toContain('>生产验证<') + expect(html).not.toContain('>生产生效<') + expect(html).not.toContain('目标在维护中') + expect(html).not.toContain('各类数据同步情况') + expect(html).not.toContain('同步明细') + }) + + it('失败封存保留失败阶段与原因,不切成生产步骤', () => { + const failedSeal: LibraryJobRecord = { + ...persistedSeal, + state: 'failed', + error: 'unverified legacy library chunk index coverage', + stages: [{ ...persistedSeal.stages[0], state: 'failed', detail: '封存校验失败' }], + } + const html = render({ + overview: { ...overview, job: failedSeal, jobs: [failedSeal] }, + }) + expect(html).toContain('只读导出测试版本') + expect(html).toContain('封存校验失败') + expect(html).toContain('unverified legacy library chunk index coverage') + expect(html).toContain('测试封存失败') + expect(html).not.toContain('目标在维护中') + expect(html).not.toContain('>备份生产<') + expect(html).not.toContain('>同步数据与 Wiki<') + expect(html).not.toContain('>生产生效<') + expect(html).not.toContain('目标在维护中') }) it('无权限时不给封存入口;不可发起时给出接口返回的真实原因与执行器身份', () => { @@ -446,3 +930,210 @@ describe('ReleaseTargetsView(确认稿布局)', () => { expect(unknown).not.toContain('也没有维护能力配置') }) }) + +// 后端 /api/v1/library/overview 已经区分四类生产目标状态(library_flow.go unknownLibraryTarget、 +// library_baseline.go:81 的空目标 409)。页面此前只判断 state === 'known',于是"已证空"和 +// "读不到"都被写成"未知"、并给出必然 409 的"建立目标权威基线"入口。 +describe('生产目标四类状态:known / 空 / 非空 / 不可读', () => { + const baseline = { canStart: true, pending: false, onStart: vi.fn() } + const emptyTarget: LibraryOverview['production'] = { + state: 'unknown', + empty_baseline: true, + reason: '生产目标可读且为空:本次是首次发布,写入前仍会生成完整预备份', + } + const nonEmptyTarget: LibraryOverview['production'] = { + state: 'unknown', + reason: '目标非空且尚无权威版本', + } + const unreadableTarget: LibraryOverview['production'] = { + state: 'unreachable', + reason: '无法读取目标整库状态:请检查目标连接后重试,不能据此判定空库或建立基线', + } + const knownTarget: LibraryOverview['production'] = { + state: 'known', + version: { + id: 'v-known', + kind: 'production_effective', + snapshot_id: 'c'.repeat(64), + version_label: '生效 20261030-01', + source_job_id: 'libsync-known', + evidence: {}, + created_by: 'admin', + created_at: '2026-10-30T09:00:00Z', + }, + } + + it('空目标:写明"已读且为空/首次发布/写前仍预备份",且不给会 409 的建基线入口', () => { + const html = render({ + baseline, + overview: { + ...overview, + production: emptyTarget, + // 接口在空基线上不再给"建立基线"缺项(librarySyncGateWithGrant:657-661) + gate: { sync_allowed: false, reasons: ['没有与目标快照匹配的有效发布授权'] }, + }, + }) + expect(html).toContain('目标已读且为空') + expect(html).toContain('首次发布') + expect(html).toContain('写前仍会生成完整预备份') + // 页面不能把"已证空"写成未知,也不能引导去建一个必然被 409 拒绝的基线。 + expect(html).not.toContain('未知(尚未建立权威版本)') + expect(html).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/) + }) + + it('非空且无生效版本:仍指向既有基线入口,不谎称空库', () => { + const html = render({ + baseline, + overview: { + ...overview, + production: nonEmptyTarget, + gate: { + sync_allowed: false, + reasons: [ + '目标非空且没有生效版本记录:先建立目标权威基线(维护隔离下捕获整库并逐类校验),或确认目标确实是空库', + ], + }, + }, + }) + expect(html).toContain('目标非空') + expect(html).toMatch(/建立目标权威基线(维护隔离)<\/button>/) + expect(html).not.toContain('目标已读且为空') + }) + + it('不可读:照实说读取失败,既不认定空也不认定非空,更不引导建基线', () => { + const html = render({ + baseline, + overview: { + ...overview, + production: unreadableTarget, + gate: { sync_allowed: false, reasons: [unreadableTarget.reason!] }, + }, + }) + expect(html).toContain('无法读取目标整库状态') + expect(html).not.toContain('目标已读且为空') + expect(html).not.toContain('目标非空') + expect(html).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/) + }) + + it('known:显示权威生效版本与快照摘要,不再写未知', () => { + const html = render({ baseline, overview: { ...overview, production: knownTarget } }) + expect(html).toContain('生效 20261030-01') + expect(html).toContain(knownTarget.version!.snapshot_id.slice(0, 12)) + expect(html).not.toContain('未知(尚未建立权威版本)') + expect(html).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/) + }) + + // 真正的一次挂载刷新由 ReleaseTargets.mount.test.tsx 覆盖:三次 renderToStaticMarkup + // 只是三个互不相关的静态输入,不执行 load/effect/fetch,不能算刷新证据。 + + // F1:没有读到 overview 时,页面自己造的 {state:'unknown'} 与后端"已探测且非空" + // 在 JSON 上长得一模一样。缺观测的三条真实路径都不能落进 nonempty 分支, + // 也不能提供会返回 409 的建基线入口。 + it('没有目标观测时不冒充非空:初始加载 / 整体读取失败 / 范围不匹配', () => { + const cases: Array<[string, Partial, string]> = [ + ['初始加载中', { loading: true, overview: null }, '正在读取目标状态'], + ['初始 overview 请求失败', { error: '发布状态读取失败(HTTP 503)', overview: null }, '不能据此判定空或非空'], + [ + '选中对外但只有对内 overview', + { scope: 'external', overview: { ...overview, scope: 'internal' } }, + '还没有读到', + ], + ] + for (const [name, overrides, expected] of cases) { + const html = render({ baseline, ...overrides }) + expect(html, name).toContain(expected) + expect(html, name).not.toContain('目标非空') + expect(html, name).not.toContain('目标已读且为空') + expect(html, name).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/) + } + }) + + it('刷新失败但保留旧观测时标成上次观测,不冒充刚验证', () => { + const html = render({ + baseline, + error: '发布状态读取失败(HTTP 502)', + overview: { ...overview, production: emptyTarget }, + }) + expect(html).toContain('目标已读且为空') + expect(html).toContain('上次观测 · 刷新失败,可能已过期') + expect(html).not.toContain('正在读取目标状态') + expect(html).not.toMatch(/建立目标权威基线(维护隔离)<\/button>/) + }) + + it('空目标但没有测试封存:启动同步保持禁用并说明缺候选', () => { + const html = render({ + baseline, + overview: { + ...overview, + production: emptyTarget, + test_sealed: undefined, + test_sealed_reason: '还没有该目标的测试封存', + }, + }) + expect(html).toMatch(/]*class="rel-primary"[^>]*disabled/) + expect(html).toContain('尚无测试封存') + }) +}) + +// E5:轮询必须覆盖"投递 → 终态读回"。 +// 旧实现只按封存队列的作业判断,于是点了同步/恢复/建立基线之后页面根本不刷新, +// 看上去像"还没启动";要么反过来,一个失败作业被永远轮询下去。 +describe('libraryPollingActive(轮询范围)', () => { + const idle = { internal: null, external: null } as Record<'internal' | 'external', LibraryOverview | null> + const withJob = (state: LibraryJobRecord['state'], kind: LibraryJobRecord['kind']) => + ({ + internal: { ...overview, job: { ...persistedSeal, state, kind }, jobs: [] }, + external: null, + }) as Record<'internal' | 'external', LibraryOverview | null> + + it('投递中就已经在轮询,不必等到作业出现在列表里', () => { + expect(libraryPollingActive({ captures: [], overviews: idle, pending: true })).toBe(true) + }) + + it('持久作业在飞(同步/恢复/基线)也轮询', () => { + expect(libraryPollingActive({ captures: [], overviews: withJob('running', 'sync'), pending: false })).toBe(true) + expect(libraryPollingActive({ captures: [], overviews: withJob('pending', 'restore'), pending: false })).toBe(true) + expect(libraryPollingActive({ captures: [], overviews: withJob('running', 'baseline'), pending: false })).toBe(true) + }) + + it('封存队列里的作业同样算在飞', () => { + expect(libraryPollingActive({ captures: [runningJob], overviews: idle, pending: false })).toBe(true) + }) + + it('终态必须停下来:失败作业不许被无限轮询', () => { + expect(libraryPollingActive({ captures: [], overviews: withJob('succeeded', 'sync'), pending: false })).toBe(false) + expect(libraryPollingActive({ captures: [], overviews: withJob('failed', 'sync'), pending: false })).toBe(false) + expect(libraryPollingActive({ captures: [], overviews: withJob('cancelled', 'restore'), pending: false })).toBe( + false + ) + expect( + libraryPollingActive({ captures: [{ ...runningJob, state: 'failed' }], overviews: idle, pending: false }) + ).toBe(false) + }) +}) + +// F12:按预备份恢复是独立队列作业(不产生新的 library_jobs 行), +// 页面必须自己记住"还在等恢复",并在维护窗口关闭后停止。 +describe('libraryPollingActive(恢复轮询)', () => { + const idle = { internal: null, external: null } as Record<'internal' | 'external', LibraryOverview | null> + + it('恢复投递后即使没有任何作业行也要继续读回', () => { + expect(libraryPollingActive({ captures: [], overviews: idle, pending: false, recoveryPending: true })).toBe(true) + }) + + it('维护窗口仍被持有时继续读回(恢复/收尾未结束)', () => { + const held = { + internal: { held: true } as unknown as LibraryMaintenanceView, + external: null, + } + expect(libraryPollingActive({ captures: [], overviews: idle, pending: false, maintenances: held })).toBe(true) + }) + + it('维护窗口关闭且没有在飞动作时停止', () => { + const released = { + internal: { held: false } as unknown as LibraryMaintenanceView, + external: null, + } + expect(libraryPollingActive({ captures: [], overviews: idle, pending: false, maintenances: released })).toBe(false) + }) +}) diff --git a/web/src/ReleaseTargets.tsx b/web/src/ReleaseTargets.tsx index 0988204..3fb729f 100644 --- a/web/src/ReleaseTargets.tsx +++ b/web/src/ReleaseTargets.tsx @@ -1,4 +1,5 @@ -import { useCallback, useEffect, useState } from 'react' +import { LegacySourceAssociation } from './LegacySourceAssociation' +import { useCallback, useEffect, useRef, useState } from 'react' import { createLibraryRestoreAuthorization, createLibrarySyncAuthorization, @@ -8,13 +9,17 @@ import { enqueueLibraryRestore, enqueueLibrarySync, fetchLibraryCaptures, + fetchLibraryJobDetail, fetchLibraryMaintenance, + maintenanceOwnerJobID, fetchLibraryOverview, fetchLibraryRestoreAvailability, fetchLibrarySnapshots, + reconcileLibraryCapture, formatBytes, scopeLabel, type LibraryCaptureJob, + type LibraryJobLookup, type LibraryJobRecord, type LibraryMaintenanceView, type LibraryOverview, @@ -22,9 +27,12 @@ import { type LibrarySnapshot, type LibrarySnapshotList, type LibraryStageRow, + type LibraryVersionRef, } from './librarySnapshots' import { useOptionalAuth } from './auth' import './releaseTargets.css' +import { RestoreVerificationSection } from './RestoreVerificationSection' +import { fetchSnapshotVerification } from './restoreVerification' // 发布管理:按已确认稿实现——顶部两个知识库页签,下面是**一个**作业区。 // @@ -110,10 +118,20 @@ interface ViewProps { pendingCapture: boolean canCapture: boolean canWrite: boolean + // 管理员核对已完成 queue/精确版本/归档后修复 pending 封存作业终态。 + canReconcileCapture: boolean + pendingReconcileCapture: string + onReconcileCapture: (jobID: string) => void // 发布动作:签发授权(管理员)与启动同步是两个独立步骤,页面绝不自动签发。 sync: ReleaseSyncActions // 目标非空又没有生效版本时,唯一入口是"建立目标权威基线"(管理员)。 baseline: ReleaseBaselineActions + // 恢复验证(真实作业)的接受/终态要回到父页面:父级据此启动轮询并在终态读回 + // overview/维护/闸口,不能只在子面板里刷新自己。 + verification: { + onAccepted: (jobId: string) => void + onComplete: (jobId: string) => void + } // 按版本恢复是管理员动作:工程师看得到条件,但拿不到恢复入口。 canRestore: boolean restore: LibraryRestoreAvailability | null @@ -123,7 +141,11 @@ interface ViewProps { onGrantRestore: () => void onRestore: () => void overview: LibraryOverview | null + /** F09: 每个 scope 的独立观测;不能拿当前 scope 的 overview 重算另一个页签。 */ + overviews?: Record maintenance: LibraryMaintenanceView | null + // 维护记录里 owner_job_id 对应的作业详情;缺失就是“未读取”,不能用 overview.job 顶替。 + maintenanceOwnerJob?: LibraryJobLookup now: number onRefresh: () => void onCapture: () => void @@ -139,8 +161,10 @@ function scopeView( const history = (page?.snapshots ?? []).filter((item) => item.scope === scope) const scoped = jobs.filter((job) => job.scope === scope) const persisted = overview?.jobs ?? [] + // F02/F06: 顶部阶段必须跟当前在飞作业;只有没有在飞作业时才显示最近终态。 + // 同一个 overview 里可能有刚完成的封存和正在跑的同步,不能用"最近一条"覆盖当前阶段。 const job = - overview?.job ?? persisted.find((item) => item.state === 'pending' || item.state === 'running') ?? persisted[0] + persisted.find((item) => item.state === 'pending' || item.state === 'running') ?? overview?.job ?? persisted[0] return { scope, // 候选只认接口给的 test_sealed(来自版本登记):归档里还有生产预备份与 @@ -157,6 +181,32 @@ function scopeView( const scopeName = (scope: Scope) => (scope === 'internal' ? '对内知识库' : '对外知识库') +// 生产目标必须按接口的四类状态原样呈现:把"已读且为空"和"读不到"都写成"未知", +// 会让人去点一个必然被拒绝的"建立基线"(后端对空目标返回 409 library_baseline_target_empty, +// 对读不到的目标返回 503 library_baseline_unprobeable)。 +type ProductionTargetClass = 'known' | 'empty' | 'nonempty' | 'unreachable' | 'no-observation' + +// 只有真正读到的 overview 才能分类。页面自己补的 {state:'unknown'} 与后端 +// "已探测且非空"在 JSON 上无法区分,所以缺观测必须单列一类(no-observation), +// 否则首次加载、整体读取失败、当前范围没数据都会被误报成"目标非空"(F1)。 +function productionTargetClass(production: LibraryOverview['production'] | null | undefined): ProductionTargetClass { + if (!production) return 'no-observation' + if (production.state === 'known' && production.version) return 'known' + if (production.state === 'unreachable') return 'unreachable' + // unknown 有两种:可读且空(空基线,首次发布合法起点)与可读但非空(缺权威版本)。 + return production.empty_baseline ? 'empty' : 'nonempty' +} + +// 刷新失败时页面会保留上一次的 overview:那份观测仍是当时的真实结果, +// 但已经不是刚刚验证过的状态,必须标出来,不能混作当前结论。 +const STALE_NOTE = '上次观测 · 刷新失败,可能已过期' + +function noObservationText(loading: boolean, error: string | null): string { + if (loading) return '正在读取目标状态(尚未确认空或非空)' + if (error) return '读取失败,还没有读到目标状态(不能据此判定空或非空)' + return '还没有读到该范围的目标状态' +} + // 不可发起时必须说清是哪一条不满足:读的是接口给出的真实原因(执行器不可达、 // 指向别的实例、降级、观测过期),不是一句写死的"通道未接线"。 function captureHint(view: ScopeView, canWrite: boolean): string { @@ -174,7 +224,17 @@ function captureHint(view: ScopeView, canWrite: boolean): string { function statusOf(view: ScopeView) { const job = view.job if (job && (job.state === 'running' || job.state === 'pending')) { - return { text: job.kind === 'seal' ? '封存中' : '同步中', tone: 'blue' as const } + // 页签徽标也要说清是哪一类作业在跑:把"建立基线"写成"同步中"会让人 + // 以为生产正在被写入。 + const text = + job.kind === 'seal' + ? '封存中' + : job.kind === 'restore' + ? '恢复中' + : job.kind === 'baseline' + ? '建基线中' + : '同步中' + return { text, tone: 'blue' as const } } if (view.overview?.production.state === 'known') return { text: '生产已记录版本', tone: 'green' as const } if (view.overview?.test_sealed || view.snapshot) return { text: '已有封存', tone: 'green' as const } @@ -215,6 +275,72 @@ function jobStateText(job: LibraryJobRecord): string { return map[job.state] ?? job.state } +// 作业类型必须逐类写清:基线不是同步,恢复也不是同步。混写会让人以为 +// "建立基线"正在把测试内容写进生产,或者把恢复当成一次正式发布。 +export function jobKindText(kind?: string): string { + if (kind === 'seal') return '测试封存' + if (kind === 'sync') return '生产同步' + if (kind === 'restore') return '按版本恢复' + if (kind === 'baseline') return '建立目标基线' + if (kind === 'verify') return '恢复验证' + return kind ? kind : '—' +} + +// 归档里的每一份快照属于哪一类版本:只能来自版本登记,不能一律写"测试封存"。 +export function snapshotVersionLabel(refs: LibraryVersionRef[] | undefined, snapshotID: string): string { + const kinds = new Set((refs ?? []).filter((item) => item.snapshot_id === snapshotID).map((item) => item.kind)) + const labels: string[] = [] + if (kinds.has('test_sealed')) labels.push('测试封存') + if (kinds.has('production_effective')) labels.push('生产生效') + if (kinds.has('production_prebackup')) labels.push('生产预备份') + return labels.length > 0 ? labels.join(' · ') : '未登记(归档文件,不作为发布候选)' +} + +// 生产写入的当前状态:不能用一句写死的"尚未启动"顶替已经完成的作业。 +export function publishStateText(job?: LibraryJobRecord): string { + if (!job) return '尚未启动,不修改生产' + if (job.state === 'pending' || job.state === 'running') { + return job.kind === 'seal' + ? '封存进行中(只读导出测试版本,不修改目标生产)' + : job.kind === 'restore' + ? '恢复进行中(目标在维护中)' + : job.kind === 'baseline' + ? '建立基线进行中(只读捕获目标,不写内容)' + : job.kind === 'verify' + ? '恢复验证进行中(目标在维护中)' + : '同步进行中(目标在维护中)' + } + if (job.state === 'succeeded') return `${jobKindText(job.kind)}已完成 · ${stamp(job.finished_at ?? job.updated_at)}` + if (job.state === 'failed') return `${jobKindText(job.kind)}失败 · ${stamp(job.finished_at ?? job.updated_at)}` + return `${jobKindText(job.kind)}已取消 · ${stamp(job.finished_at ?? job.updated_at)}` +} + +// 轮询范围 = 投递中 + 有在飞作业(封存队列与持久作业都算)。 +// 终态(成功/失败/取消)必须停下来:无限轮询一个失败作业既没意义, +// 也会把"作业已经结束"这个事实淹没在不停刷新的页面里。 +export function libraryPollingActive(input: { + captures: LibraryCaptureJob[] + overviews: Record + pending: boolean + /** 按预备份恢复是一次队列作业,不产生新的 library_jobs 行:必须单独记住"还在等它"。 */ + recoveryPending?: boolean + /** 维护窗口仍被持有 ⇒ 恢复/收尾还没结束,页面必须继续读回。 */ + maintenances?: Record +}): boolean { + if (input.pending) return true + if (input.recoveryPending) return true + if (input.captures.some((job) => ACTIVE_STATES.includes(job.state))) return true + const maintenanceHeld = (['internal', 'external'] as Scope[]).some((scope) => { + const view = input.maintenances?.[scope] + return Boolean(view?.held) + }) + if (maintenanceHeld) return true + return (['internal', 'external'] as Scope[]).some((scope) => { + const job = input.overviews[scope]?.job + return Boolean(job && ACTIVE_STATES.includes(job.state)) + }) +} + // ---- 目标维护窗口:级别 / 进度 / 恢复错误 ---- // // 维护窗口有两种级别:实例级(跨 scope 共用一把锁,真正挡住写入者)和库级。 @@ -231,7 +357,13 @@ export interface MaintenanceSummary { releasedAt: string progress: string recoveryError: string + // 作业失败但维护窗口已释放:只保留失败记录,不能再说"目标保持维护"。 + releasedFailure: string recoveryNote: string + // 窗口未释放但持有作业已经是终态成功:对账缺口,页面不提供强制成功。 + unreconciledNote: string + // 实例级窗口属于另一个 scope:不在此投递恢复,提示切回持有 scope。 + scopeNote: string canRecover: boolean } @@ -252,11 +384,32 @@ const stageLabel: Record = { } const ingressText = (state?: string) => - state === 'closed' ? '已关闭(排空后等待写入)' : state === 'open' ? '打开' : state ? state : '未知' + state === 'closed' + ? '已关闭(排空后等待写入)' + : state === 'none' + ? '无闸门(测试模式)' + : state === 'open' + ? '打开' + : state + ? state + : '未知' +// 持有作业详情没读到时只写未读取/未知,绝不拿同 scope 最新作业顶替。 +const ownerJobText = (lookup: LibraryJobLookup | undefined, ownerJobID: string) => { + const id = ownerJobID || '—' + if (lookup?.state === 'error') return `持有作业状态读取失败:${lookup.reason}(不使用其他作业推断)` + if (lookup?.state === 'missing') return `持有作业 ${id} 不存在(维护记录引用了未登记的作业)` + if (lookup?.state === 'loaded') + return `持有作业状态未读取/未知(维护记录为 ${id},读取到的是 ${lookup.job.id},不采用)` + return `持有作业状态未读取/未知(owner_job_id=${id};不使用最新作业代替)` +} + +// 维护卡只消费“维护记录里的持有作业”。同 scope 最新作业可能是一次无关封存: +// 拿它当窗口进度会把 needs_restore 显示成“导出 · 已完成”(真实事故 2026-11-03)。 export function maintenanceSummary( maintenance: LibraryMaintenanceView | null | undefined, - job: LibraryJobRecord | undefined + ownerJob?: LibraryJobLookup, + scope?: string ): MaintenanceSummary { const record = maintenance?.instance_maintenance ?? maintenance?.maintenance ?? null const level = !record @@ -267,36 +420,64 @@ export function maintenanceSummary( ? '库级' : record.level || '未知' const held = Boolean(maintenance?.held) - const failed = job?.state === 'failed' - const ownerScope = maintenance?.instance_maintenance?.owner_scope ?? record?.scope ?? '—' + const ownerScope = maintenance?.instance_maintenance?.owner_scope ?? record?.scope ?? '' + const ownerJobID = record?.owner_job_id ?? '' + // 只有 id 与维护记录一致的作业才是本窗口的进度;其余按“未读取”处理。 + const owner = ownerJob?.state === 'loaded' && ownerJob.job.id === ownerJobID ? ownerJob.job : undefined + const failed = owner?.state === 'failed' + const progress = owner + ? `${stageLabel[owner.stage] ?? owner.stage ?? '—'} · ${jobStateText(owner)}` + : record + ? ownerJobText(ownerJob, ownerJobID) + : '尚无作业进度' + // 实例级窗口跨 scope 共用:只有持有 scope 才能投递恢复,否则后端必然 409。 + const sameScope = !scope || !ownerScope || ownerScope === scope + const scopeNote = + held && !sameScope + ? `维护窗口属于 ${ownerScope},当前查看 ${scope}:页面不向另一个 scope 投递恢复,请切回 ${ownerScope} 再处理` + : '' + // 恢复只由“维护仍持有 + 本窗口作业未收口”决定,与无关的最新作业无关。 + const unsettled = owner + ? owner.state === 'failed' || owner.state === 'cancelled' + : record?.state === 'needs_restore' || record?.state === 'failed' || record?.state === 'held' return { level, held, - owner: record ? `${ownerScope} · ${record.owner_job_id || '—'}` : '—', + owner: record ? `${ownerScope || '—'} · ${record.owner_job_id || '—'}` : '—', state: record?.state || '—', ingress: record ? ingressText(record.ingress_state) : '—', services: (record?.services ?? []).join('、') || '—', acquiredAt: record?.acquired_at ? stamp(record.acquired_at) : '—', releasedAt: record?.released_at ? stamp(record.released_at) : '', - progress: job ? `${stageLabel[job.stage] ?? job.stage ?? '—'} · ${jobStateText(job)}` : '尚无作业进度', - recoveryError: failed ? job?.error || '作业失败但没有留下错误明细' : '', - recoveryNote: job?.recovery || '', - canRecover: held && (failed || !job || job.state === 'cancelled'), + progress, + // 只有仍然 held 的失败才配 held 处置说明;窗口已释放时那段文案是假的。 + recoveryError: failed && held ? owner?.error || '作业失败但没有留下错误明细' : '', + releasedFailure: failed && !held ? owner?.error || '作业失败但没有留下错误明细' : '', + recoveryNote: owner?.recovery || '', + unreconciledNote: + held && owner && owner.state === 'succeeded' + ? '持有作业已完成但维护窗口仍未释放:维护记录与作业终态未对账,页面不提供强制成功,需按窗口记录人工核验' + : '', + scopeNote, + canRecover: held && Boolean(record) && sameScope && Boolean(unsettled), } } export function MaintenanceCard({ maintenance, - job, + ownerJob, + scope, canWrite, onRecover, }: { maintenance: LibraryMaintenanceView | null | undefined - job: LibraryJobRecord | undefined + // 只收“按 owner_job_id 读到的持有作业”,不是 scope 的最新作业。 + ownerJob?: LibraryJobLookup + scope?: string canWrite: boolean onRecover: (windowJobID: string) => void }) { - const summary = maintenanceSummary(maintenance, job) + const summary = maintenanceSummary(maintenance, ownerJob, scope) const record = maintenance?.instance_maintenance ?? maintenance?.maintenance // "没有窗口记录"不等于"没有维护能力":能力是配置事实,接口单独返回。 // 接口没给能力信息时也不能猜,明确写"未知"。 @@ -350,7 +531,11 @@ export function MaintenanceCard({ {summary.state}
  • - 入口 {summary.ingress} + 入口(维护记录,未实时探测) + {summary.ingress} +
  • +
  • + 服务 {summary.services}
  • @@ -366,13 +551,44 @@ export function MaintenanceCard({ 进度:{summary.progress} {summary.releasedAt ? ` · 窗口已于 ${summary.releasedAt} 释放` : ''}

    + {summary.scopeNote ?

    {summary.scopeNote}

    : null} + {summary.held ? ( +

    + 窗口仍被持有:只有维护记录本身释放才算结束,其他作业的完成或失败不改变本窗口。 +

    + ) : null} + {summary.unreconciledNote ? ( +
    + 维护记录未对账 +

    {summary.unreconciledNote}

    +
    + ) : null} + {summary.releasedFailure ? ( +
    + 作业失败(维护窗口已释放) +

    {summary.releasedFailure}

    + {summary.recoveryNote ?

    处理记录:{summary.recoveryNote}

    : null} +

    + 窗口已释放,维护记录中的入口状态:{summary.ingress}(未实时探测):这里是历史失败记录,不再按 held + 处置,也不提供强制成功。 +

    +
    + ) : null} {summary.recoveryError ? (
    恢复错误

    {summary.recoveryError}

    {summary.recoveryNote ?

    处理记录:{summary.recoveryNote}

    : null} +

    + 内容可能已写入并通过校验,但收尾没有完成:目标保持维护、入口未开。请按本作业的预备份与校验证据人工核验后再放行; + 页面不提供“强制成功”,也不会因为“看起来已经写进去了”就开门。 +

    ) : null} +

    + 发布或恢复完成后,Wiki 与日志页面需要刷新再翻页:发布前的分页游标在发布后失效(本地编号会被重新编排), + 用旧标签页继续翻页会得到错位的结果,这不是数据损坏。 +

    {canWrite && summary.canRecover && record ? ( - ) : null} - {baseline.canStart && baselineNeeded ? ( - - ) : null} - +

    + {gate.reasons.length > 0 + ? `启动与恢复条件还有 ${gate.reasons.length} 项未满足,见上方“发布前检查”。` + : '启动与恢复条件已满足。'} +

    {authorization.state !== 'active' && !sync.canSign ? (

    同步授权只能由管理员按目标+快照签发;工程师看不到签发入口。

    ) : null} -

    同步启动后,这里显示本次生产恢复点及备份进度,可直接查看对应快照。

    - -

    恢复版本会恢复一整套生产知识状态,不回退测试知识库。

    +

    恢复会回退整套生产知识状态,不回退测试知识库。

    ) } @@ -663,7 +974,10 @@ function ProtectionCard({ interface ReadyProps { view: ScopeView diff: LibraryOverview['diff'] - production: LibraryOverview['production'] + production: LibraryOverview['production'] | null + // 缺观测时的说明与"旧观测"标记都由上层按 loading/error 判定,子组件只负责显示。 + productionNote: string + stale: boolean prebackup: LibraryOverview['prebackup'] gate: LibraryOverview['gate'] authorization: LibraryOverview['authorization'] @@ -674,17 +988,24 @@ interface ReadyProps { onOpen: () => void sync: ReleaseSyncActions baseline: ReleaseBaselineActions + verification: { + onAccepted: (jobId: string) => void + onComplete: (jobId: string) => void + } } function ReadyBody({ view, diff, production, + productionNote, + stale, prebackup, gate, authorization, sync, baseline, + verification, canCapture, canWrite, pendingCapture, @@ -695,22 +1016,30 @@ function ReadyBody({ return ( <>
    -

    启动后的作业进度

    - 此时尚未运行 + {/* 作业跑完/失败后不能还说"此时尚未运行":这个徽标说的是**最近一次作业**的终态。 */} + + {view.job + ? `${jobKindText(view.job.kind)} · ${jobStateText(view.job)} · ${stamp(view.job.finished_at ?? view.job.updated_at)}` + : '此时尚未运行'} +
    @@ -723,35 +1052,82 @@ function ReadyBody({ : '还没有测试库封存。封存会短暂停住测试写入者,导出完整版本后恢复。'}

    - {canCapture ? ( - - ) : ( - {captureHint(view, canWrite)} - )} + {canCapture ? '封存入口在页面顶部“下一步”。' : captureHint(view, canWrite)} ) } -function ProgressBody({ view, now, onOpen }: { view: ScopeView; now: number; onOpen: () => void }) { +function ProgressBody({ + view, + now, + onOpen, + canReconcileCapture, + pendingReconcileCapture, + onReconcileCapture, +}: { + view: ScopeView + now: number + onOpen: () => void + canReconcileCapture: boolean + pendingReconcileCapture: string + onReconcileCapture: (jobID: string) => void +}) { const job = view.job const sealJob = job?.kind === 'seal' ? job : undefined - const syncJob = job?.kind === 'sync' ? job : undefined + // 四类数据阶段对同步/恢复/基线都成立:分项读的是这份作业自己的阶段, + // 不是"只有 sync 才有"。写死 sync 会让恢复作业的分项全显示"未接入"。 + const dataJob = job && job.kind !== 'seal' ? job : undefined const running = job?.state === 'running' || job?.state === 'pending' - const stage = (name: string) => syncJob?.stages.find((item) => item.stage === name) + // Startup reconciliation used to rewrite a completed capture as "队列不存在". + // Only that exact legacy shape gets an admin reconcile action; real failures do not. + const legacyOrphan = + sealJob?.state === 'failed' && + sealJob.stage === '' && + sealJob.snapshot_id === '' && + sealJob.error === '队列中已无对应作业,业务作业未收到结果' && + sealJob.recovery === '封存作业由 agent 恢复来源;确认来源 healthy 后可重发' + const stage = (name: string) => (dataJob ?? sealJob)?.stages.find((item) => item.stage === name) + // F11: counts must belong to the snapshot this job actually used. A newly + // sealed test version must not decorate an older sync/restore/verify job. + const jobSnapshotID = job?.target_snapshot_id || job?.snapshot_id || '' + const sealed = jobSnapshotID + ? view.history.find((item) => item.snapshot_id === jobSnapshotID) + : job + ? undefined + : view.overview?.test_sealed + const breakdown = (keys: [string, string][]) => + sealed + ? keys + .map(([key, label]) => `${label} ${typeof sealed.totals[key] === 'number' ? sealed.totals[key] : '未知'}`) + .join(' · ') + : '' const cards = [ - { title: '数据库 · 文档与分块', row: stage('database'), axis: '文档 / 分块' }, - { title: '原文件 · 图片 · 附件', row: stage('resources'), axis: '对象 / 字节' }, - { title: '检索索引 · 向量', row: stage('index'), axis: '索引文档' }, - { title: 'Wiki · 完整快照', row: stage('wiki'), axis: 'Wiki 页' }, + // F11: these totals are storage rows, not business document/page counts. + { + title: '数据库 · 存储行', + row: stage('database'), + axis: '行(文档/分块/标签/关系)', + counts: breakdown([ + ['documents', '文档'], + ['chunks', '分块'], + ['resources', '资源'], + ['bindings', '绑定'], + ]), + }, + { title: '原文件 · 图片 · 附件', row: stage('resources'), axis: '对象 / 字节', counts: '' }, + { title: '检索索引 · 向量', row: stage('index'), axis: '索引文档', counts: '' }, + { + title: 'Wiki · 存储行', + row: stage('wiki'), + axis: '页面 / 目录 / 日志', + counts: breakdown([ + ['wiki_pages', '页面'], + ['wiki_folders', '目录'], + ['wiki_log_entries', '日志'], + ]), + }, ].map((card) => ({ ...card, // 只有真实的 total 才画进度;没有 total 就是"未知总量",绝不按 0 或 100% 画。 @@ -764,18 +1140,29 @@ function ProgressBody({ view, now, onOpen }: { view: ScopeView; now: number; onO return ( <> -
    +

    - {sealJob ? '测试库封存作业' : syncJob ? '生产同步作业' : '本次作业'} + {sealJob ? '测试库封存作业' : dataJob ? `${jobKindText(dataJob.kind)}作业` : '本次作业'} - 测试封存 {view.overview?.test_sealed?.snapshot_id.slice(0, 12) ?? '未接入'} → 生产当前{' '} - - {view.overview?.production.state === 'known' && view.overview.production.version - ? view.overview.production.version.version_label || - view.overview.production.version.snapshot_id.slice(0, 12) - : '未知'} - + {sealJob ? ( + <>只读导出测试库快照 → 不修改目标生产 + ) : ( + <> + {dataJob?.kind === 'restore' + ? `恢复到 ${dataJob.target_snapshot_id.slice(0, 12) || '—'}` + : dataJob?.kind === 'baseline' + ? `目标基线 ${dataJob.target_snapshot_id.slice(0, 12) || '(本次捕获后登记)'}` + : `测试封存 ${view.overview?.test_sealed?.snapshot_id.slice(0, 12) ?? '未接入'}`}{' '} + → 目标当前{' '} + + {view.overview?.production.state === 'known' && view.overview.production.version + ? view.overview.production.version.version_label || + view.overview.production.version.snapshot_id.slice(0, 12) + : '未知'} + + + )}

    @@ -783,11 +1170,27 @@ function ProgressBody({ view, now, onOpen }: { view: ScopeView; now: number; onO

    - 作业 {job?.id ?? '未接入'} · 类型 {job ? (job.kind === 'seal' ? '测试封存' : '生产同步') : '—'} · - 操作人 {job?.actor || '—'} · 最近进展 {job ? stamp(job.updated_at) : '—'} + 作业 {job?.id ?? '未接入'} · 类型 {job ? jobKindText(job.kind) : '—'} · 操作人{' '} + {job?.actor || '—'} · 最近进展 {job ? stamp(job.updated_at) : '—'} {job?.recovery ? ` · 恢复:${job.recovery}` : ''}

    + {sealJob && + canReconcileCapture && + (sealJob.state === 'pending' || sealJob.state === 'running' || legacyOrphan) && + stage('export')?.state === 'succeeded' ? ( +
    + 队列已完成、导出阶段已成功,但作业终态尚未回写。 + +
    + ) : null}
    当前: @@ -805,118 +1208,235 @@ function ProgressBody({ view, now, onOpen }: { view: ScopeView; now: number; onO
    -
    -
    -

    各类数据同步情况

    - 没有真实总量与完成量的项目只显示状态,不编造百分比 -
    -
    - {cards.map((card) => ( -
    -
    -

    {card.title}

    - - {card.row - ? card.row.state === 'succeeded' - ? '已完成' - : card.row.state === 'running' - ? '执行中' - : card.row.state === 'failed' - ? '失败' - : '等待' - : '未接入'} - -
    -

    - {card.count} · {card.axis} -

    -
    - -
    -

    - {card.row?.detail - ? card.row.detail - : syncJob - ? '该分项还没有上报数据' - : '生产同步执行链未接通,分项不会产生数据'} -

    -
    - ))} + {sealJob ? ( +
    +
    +

    封存范围

    + 只读 +
    +

    + 本作业只读取测试库并导出快照,不备份生产、不写目标、不做生产验证,也不持有目标维护窗口。 + 快照完成后在“版本与快照”查看;没有真实导出总量时显示未知,不补零或 100%。 +

    -
    + ) : ( + <> +
    +
    +

    各类数据同步情况

    + 没有真实总量与完成量的项目只显示状态,不编造百分比 +
    +
    + {cards.map((card) => ( +
    +
    +

    {card.title}

    + + {card.row + ? card.row.state === 'succeeded' + ? '已完成' + : card.row.state === 'running' + ? '执行中' + : card.row.state === 'failed' + ? '失败' + : '等待' + : '未接入'} + +
    +

    + {card.count} · {card.axis} +

    + {card.counts ?

    封存快照分项:{card.counts}

    : null} +
    + +
    +

    + {card.row?.detail + ? card.row.detail + : card.row + ? card.row.state === 'running' + ? '执行中;执行器尚未提供该分项明细' + : card.row.state === 'pending' + ? '等待执行;不能按完成展示' + : card.row.state === 'failed' + ? '失败;没有可核对完成量' + : card.row.state === 'succeeded' + ? card.row.total != null + ? `已完成 ${card.row.completed ?? card.row.total} / ${card.row.total} 条存储行` + : '该分项已完成,执行器未提供可核对总量' + : '状态未知;不按完成展示' + : dataJob + ? '本次作业没有产生该分项阶段记录' + : '目标同步执行链未接通,分项不会产生数据'} +

    +
    + ))} +
    +
    -
    -
    -

    同步明细

    - 行来自持久作业阶段,worker 重启后仍可读 -
    - - - - - - - - - - - - {(job?.stages ?? []).length === 0 ? ( - - - - ) : ( - job!.stages.map((row) => ( - - - - - - +
    +
    +

    同步明细

    + 行来自持久作业阶段,worker 重启后仍可读 +
    +
    任务 / 对象阶段进度状态说明
    - 尚无阶段记录 -
    {row.stage}{row.stage === 'export' ? '测试封存' : row.stage} - {row.total != null ? `${row.completed ?? '—'} / ${row.total}` : '未知总量'} - {row.bytes_total != null - ? ` · ${formatBytes(row.bytes_done ?? 0)} / ${formatBytes(row.bytes_total)}` - : ''} - - {row.state === 'succeeded' - ? '已完成' - : row.state === 'running' - ? '执行中' - : row.state === 'failed' - ? '失败' - : row.state === 'skipped' - ? '已跳过' - : '等待'} - {row.detail || '—'}
    + + + + + + + - )) - )} - -
    任务 / 对象阶段进度状态说明
    -
    - - 最近事件: - {job?.error - ? job.error.slice(0, 120) - : running - ? '作业执行中;无错误。' - : job - ? `作业${jobStateText(job)};无错误。` - : sealJob - ? '封存作业已结束。' - : '尚无作业记录。'} - - 文件传输 100% ≠ 作业完成;生产验证通过前不显示“完成”。 -
    -
    + + + {(job?.stages ?? []).length === 0 ? ( + + + 尚无阶段记录 + + + ) : ( + job!.stages.map((row) => ( + + {row.stage} + {row.stage === 'export' ? '测试封存' : row.stage} + + {row.total != null ? `${row.completed ?? '—'} / ${row.total}` : '未知总量'} + {row.bytes_total != null + ? ` · ${formatBytes(row.bytes_done ?? 0)} / ${formatBytes(row.bytes_total)}` + : ''} + + + {row.state === 'succeeded' + ? '已完成' + : row.state === 'running' + ? '执行中' + : row.state === 'failed' + ? '失败' + : row.state === 'skipped' + ? '已跳过' + : '等待'} + + {row.detail || '—'} + + )) + )} + + +
    + + 最近事件: + {job?.error + ? job.error.slice(0, 120) + : running + ? '作业执行中;无错误。' + : job + ? `作业${jobStateText(job)};无错误。` + : sealJob + ? '封存作业已结束。' + : '尚无作业记录。'} + + 文件传输 100% ≠ 作业完成;生产验证通过前不显示“完成”。 +
    +
    + + )} ) } +// F03: list rows must use the same exact snapshot query as the detail. The +// scope-wide latest passed record is never allowed to color another snapshot. +function SnapshotVerificationBadge({ scope, snapshotID }: { scope: Scope; snapshotID: string }) { + const [state, setState] = useState<'loading' | 'loaded' | 'error'>('loading') + const [record, setRecord] = useState>['snapshot_latest']>(null) + const [error, setError] = useState('') + useEffect(() => { + const controller = new AbortController() + setState('loading') + setRecord(null) + setError('') + fetchSnapshotVerification(scope, snapshotID, controller.signal) + .then((value) => { + setRecord(value.snapshot_latest ?? null) + setState('loaded') + }) + .catch((reason: unknown) => { + if ((reason as Error)?.name === 'AbortError') return + setError(reason instanceof Error ? reason.message : '读取该快照的恢复验证记录失败') + setState('error') + }) + return () => controller.abort() + }, [scope, snapshotID]) + if (state === 'loading') return 读取验证记录… + if (state === 'error') + return ( + + 验证状态读取失败 + + ) + if (!record) return 未做生产恢复验证 + return record.status === 'passed' ? ( + 恢复验证通过 · {record.job_id} + ) : ( + 恢复验证未通过 · {record.job_id} + ) +} + +// F03: exact snapshot evidence. This component deliberately reads +// snapshot_latest, not latest: a passed record for another snapshot must not +// make this one look verified. +function SnapshotVerification({ scope, snapshotID }: { scope: Scope; snapshotID: string }) { + const [state, setState] = useState<'loading' | 'loaded' | 'error'>('loading') + const [record, setRecord] = useState>['snapshot_latest']>(null) + const [error, setError] = useState('') + useEffect(() => { + const controller = new AbortController() + setState('loading') + setRecord(null) + setError('') + fetchSnapshotVerification(scope, snapshotID, controller.signal) + .then((value) => { + setRecord(value.snapshot_latest ?? null) + setState('loaded') + }) + .catch((reason: unknown) => { + if ((reason as Error)?.name === 'AbortError') return + setError(reason instanceof Error ? reason.message : '读取该快照的恢复验证记录失败') + setState('error') + }) + return () => controller.abort() + }, [scope, snapshotID]) + return ( +
    + 查看校验记录 + {state === 'loading' ?

    正在读取该快照的恢复验证记录…

    : null} + {state === 'error' ?

    {error}

    : null} + {state === 'loaded' && !record ? ( +

    该快照没有真实恢复验证记录;未验证,原因不是加载失败。

    + ) : null} + {record ? ( +
    +

    + 该快照最近一次:{record.status === 'passed' ? '通过' : '未通过'} · {record.finished_at} · 作业{' '} + {record.job_id} +

    + {record.failure ?

    原因:{record.failure}

    : null} + {record.report ? ( +
    + 本次恢复验证报告 +
    {JSON.stringify(record.report, null, 2)}
    +
    + ) : null} +
    + ) : null} +
    + ) +} + interface DrawerProps { view: ScopeView page: LibrarySnapshotList | null @@ -957,16 +1477,41 @@ function Drawer({ onGrantRestore, onRestore, }: DrawerProps) { - if (!open) return null const listing = view.history + const [kindFilter, setKindFilter] = useState<'registered' | 'all' | 'test' | 'production'>('registered') + const [historyPage, setHistoryPage] = useState(0) + const [confirmRestore, setConfirmRestore] = useState(false) + const selectedRef = useRef(null) + useEffect(() => { + setKindFilter('registered') + setHistoryPage(0) + setConfirmRestore(false) + }, [view.scope, open]) + useEffect(() => { + if (expanded) selectedRef.current?.scrollIntoView?.({ block: 'nearest' }) + }, [expanded]) + const versionLabelOf = (snapshot: LibrarySnapshot) => + snapshotVersionLabel(view.overview?.versions, snapshot.snapshot_id) + const filtered = listing.filter((snapshot) => { + const label = versionLabelOf(snapshot) + if (kindFilter === 'all') return true + if (kindFilter === 'test') return label.includes('测试封存') + if (kindFilter === 'production') return label.includes('生产生效') + return !label.startsWith('未登记') + }) + const pageSize = 8 + const pageCount = Math.max(1, Math.ceil(filtered.length / pageSize)) + const currentPage = Math.min(historyPage, pageCount - 1) + const pageItems = filtered.slice(currentPage * pageSize, currentPage * pageSize + pageSize) const selected = listing.find((item) => item.snapshot_id === expanded) + if (!open) return null return (
    + ) : null} {restore?.allowed ? (

    条件已满足:生产写入闸口打开、这份快照有恢复授权 @@ -1193,6 +1808,7 @@ export function ReleaseTargetsView(props: ViewProps) { page, jobs, overview, + overviews, loading, error, notice, @@ -1205,8 +1821,12 @@ export function ReleaseTargetsView(props: ViewProps) { pendingCapture, canCapture, canWrite, + canReconcileCapture, + pendingReconcileCapture, + onReconcileCapture, sync, baseline, + verification, canRestore, restore, restoreNotice, @@ -1216,17 +1836,41 @@ export function ReleaseTargetsView(props: ViewProps) { onRestore, now, maintenance, + maintenanceOwnerJob, onRefresh, onCapture, onRecover, } = props - const internal = scopeView(page, jobs, 'internal', overview?.scope === 'internal' ? overview : null) - const external = scopeView(page, jobs, 'external', overview?.scope === 'external' ? overview : null) + // A response with a different scope is not an observation for this tab. + const scopedOverview = (target: Scope): LibraryOverview | null => { + const candidate = overviews?.[target] ?? overview + return candidate?.scope === target ? candidate : null + } + const internal = scopeView(page, jobs, 'internal', scopedOverview('internal')) + const external = scopeView(page, jobs, 'external', scopedOverview('external')) const view = scope === 'internal' ? internal : external - const active = Boolean(view.activeJob) || view.job?.state === 'running' || view.job?.state === 'pending' + const legacyOrphanJob = Boolean( + view.job && + view.job.kind === 'seal' && + view.job.state === 'failed' && + view.job.stage === '' && + view.job.snapshot_id === '' && + view.job.error === '队列中已无对应作业,业务作业未收到结果' && + view.job.recovery === '封存作业由 agent 恢复来源;确认来源 healthy 后可重发' + ) + const active = + Boolean(view.activeJob) || view.job?.state === 'running' || view.job?.state === 'pending' || legacyOrphanJob + // F06: 运行中禁止再次启动,也禁止把主按钮继续显示成可启动的绿色动作。 + const runningJob = active && view.job ? view.job : undefined // 三类版本严格分开:target 是测试封存,production 是生产权威版本,prebackup 是本次预备份。 const target = view.overview?.test_sealed - const production = view.overview?.production ?? { state: 'unknown' as const } + // 没有 overview 时不能补一个 {state:'unknown'} 再当成"已探测且非空": + // production 保持 null,分类走 no-observation。 + const production = view.overview?.production ?? null + const productionClass = productionTargetClass(production) + // 刷新失败但仍保留上一份 overview:显示可以继续,但必须标成上次观测。 + const productionStale = Boolean(error) && production !== null + const productionNote = noObservationText(loading, error) const prebackup = view.overview?.prebackup ?? { state: 'unknown' as const } const diff = view.overview?.diff ?? { state: 'unknown' as const, @@ -1238,17 +1882,69 @@ export function ReleaseTargetsView(props: ViewProps) { const gate = view.overview?.gate ?? { sync_allowed: false, reasons: ['整库状态接口不可用'] } const authorization = view.overview?.authorization ?? { state: 'none' as const, reason: '整库状态接口不可用' } + const sealed = Boolean(view.snapshot) + const authorizationActive = authorization.state === 'active' + // 主按钮永远是"同步"或"查看当前任务";准备动作(封存/基线/恢复验证/授权) + // 作为次要按钮按状态出现,页面因此只有一个前进方向。 + const primaryAction = runningJob + ? { + label: '查看当前任务', + hint: `${jobKindText(runningJob.kind)}正在执行,不要重复启动。`, + disabled: false, + run: () => document.getElementById('rel-progress')?.scrollIntoView?.({ behavior: 'smooth', block: 'start' }), + } + : { + label: sync.pending ? '投递中…' : '▶ 启动同步', + hint: sync.canStart + ? '先固定测试版本,再备份目标并写入;失败会停在维护窗口。' + : `暂不能启动:${gate.reasons.join(';') || '条件未满足'}`, + disabled: !sync.canStart || sync.pending, + run: sync.onStart, + } + const prepAction = !sealed + ? canCapture + ? { + label: pendingCapture ? '封存中…' : '封存测试版本', + hint: '只读导出测试库,生成一份可发布的整库版本。', + disabled: pendingCapture, + run: onCapture, + } + : { label: '尚无封存', hint: captureHint(view, canWrite), disabled: true, run: () => {} } + : productionClass === 'nonempty' && baseline.canStart + ? { + label: baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)', + hint: '生产目标非空但还没有权威版本,先登记一份基线。', + disabled: baseline.pending, + run: baseline.onStart, + } + : !authorizationActive && sync.canSign + ? { + label: sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)', + hint: '授权后才允许写生产;一次授权只对当前目标+快照有效。', + disabled: sync.pendingGrant, + run: sync.onGrant, + } + : null + + const productionText = + productionClass === 'known' && production?.version + ? production.version.version_label || `生效 ${production.version.snapshot_id.slice(0, 12)}` + : productionClass === 'empty' + ? '目标已读且为空' + : productionClass === 'unreachable' + ? '读取失败' + : productionClass === 'nonempty' + ? '目标非空,尚无权威版本' + : '未读取' + return (

    -
    +
    -

    发布管理

    -

    测试维护与验证,生产按知识库版本同步。

    +

    发布管理

    +

    测试封存 → 生产同步:每一步只保留一个入口。

    -
    - +
    @@ -1289,87 +1985,87 @@ export function ReleaseTargetsView(props: ViewProps) { ) : null} {notice ?

    {notice}

    : null} -
    -
    -

    - {scopeName(scope)} · {active ? '封存进行中' : view.snapshot ? '已封存,同步按条件放行' : '尚无测试封存'} -

    -
    - - -
    -
    -

    - 生产当前{' '} - {production.state === 'known' && production.version ? ( - {production.version.version_label || `生效 ${production.version.snapshot_id.slice(0, 12)}`} - ) : ( - 未知(尚未建立权威版本) - )}{' '} - → 拟发布{' '} - {target ? `封存 ${target.snapshot_id.slice(0, 12)} · ${stamp(target.created_at)}` : '还没有测试封存'} · - 尚未启动,不修改生产 +

    +

    + {scopeName(scope)} ·{' '} + {active ? `${jobKindText(view.job?.kind)}进行中` : sealed ? '已封存,同步按条件放行' : '尚无测试封存'} + {sealed ? '(需要新版本时点上方“封存测试版本”)' : ''}

    -
    +
    -
    新增文档
    -
    - {diff.state === 'computed' ? diff.added.length : '未接入'} +
    测试封存
    +
    + {sealed ? `快照 ${view.snapshot!.snapshot_id.slice(0, 12)}` : '尚无'}
    + {sealed ? stamp(view.snapshot!.created_at) : '先封存测试版本'}
    -
    更新文档
    -
    - {diff.state === 'computed' ? diff.updated.length : '未接入'} -
    +
    生产当前
    +
    {productionText}
    + {publishStateText(view.job)}
    -
    删除文档
    -
    - {diff.state === 'computed' ? diff.removed.length : '未接入'} -
    +
    发布授权
    +
    {authorizationActive ? '已签发' : '未签发'}
    + + {authorizationActive + ? `有效至 ${stamp(authorization.expires_at ?? '')}` + : sync.canSign + ? '可在下方签发' + : '需管理员签发'} +
    -
    Wiki 发布方式
    -
    {target ? '完整快照' : '未接入'}
    +
    最近预备份
    +
    + {prebackup.state === 'known' ? '已登记' : '无'} +
    + + {prebackup.state === 'known' && prebackup.version + ? stamp(prebackup.version.created_at) + : '同步时自动生成'} +
    -
      -
    • - {target - ? `✓ 文档解析与索引完整(${target.totals.chunks ?? 0} 分块 / ${target.totals.index_documents ?? 0} 索引)` - : '○ 文档解析与索引:未接入'} - {target ? ( - - 依据 {stamp(target.created_at)} 封存的测试库全库快照,不代表实时测试库已就绪 - - ) : null} -
    • -
    • - {target ? `✓ Wiki 快照完整(${target.totals.wiki_pages ?? 0} 页)` : '○ Wiki 快照:未接入'} - {target ? 同一份封存快照,不是实时 Wiki 队列状态 : null} -
    • -
    • - {target ? `✓ 清单与摘要登记:${target.parts.length} 项部件摘要已记录` : '○ 数据完整性:尚无封存可核验'} - {target ? ( - 封存时逐项哈希登记;列表只校验清单自身,字节级复核在同步/恢复执行前进行 - ) : null} -
    • -
    +
    +

    + 下一步 + {prepAction && prepAction.disabled === false && !runningJob ? prepAction.hint : primaryAction.hint} +

    + {prepAction && !runningJob ? ( + + ) : null} + + +
    + {gate.reasons.length > 0 ? ( +

    还差 {gate.reasons.length} 项条件,展开“发布前检查”查看原因。

    + ) : null} +
    + +
    0}> + + 发布前检查 + {gate.reasons.length > 0 ? `(${gate.reasons.length} 项未满足)` : '(已满足)'} + {gate.reasons.length > 0 ? (
      {gate.reasons.map((reason) => ( @@ -1377,23 +2073,60 @@ export function ReleaseTargetsView(props: ViewProps) { ))}
    ) : null} -

    启动后先固定测试版本,再备份生产。备份失败或恢复条件不满足,不进入生产写入。

    -
    - - +
      +
    • + {target + ? `✓ 文档解析与索引完整(${target.totals.chunks ?? 0} 分块 / ${target.totals.index_documents ?? 0} 索引)` + : '○ 文档解析与索引:未接入(尚无封存)'} + {target ? ( + + 依据 {stamp(target.created_at)} 封存的测试库全库快照,不代表实时测试库已就绪 + + ) : null} +
    • +
    • + {target ? `✓ Wiki 快照完整(${target.totals.wiki_pages ?? 0} 页)` : '○ Wiki 快照:未接入(尚无封存)'} + {target ? 同一份封存快照,不是实时 Wiki 队列状态 : null} +
    • +
    • + {target ? `✓ 清单与摘要登记:${target.parts.length} 项部件摘要` : '○ 数据完整性:未接入(尚无封存可核验)'} + {target ? ( + 封存时逐项哈希登记;列表只校验清单自身,字节级复核在同步/恢复执行前进行 + ) : null} +
    • +
    + + {active ? ( - onDrawer(true)} /> +
    + onDrawer(true)} + canReconcileCapture={canReconcileCapture} + pendingReconcileCapture={pendingReconcileCapture} + onReconcileCapture={onReconcileCapture} + /> +
    ) : ( )} +
    + 高级与历史(目标维护、差异明细、来源身份) + + +

    + 目标实例 {view.overview?.target_instance || view.overview?.executor?.instance || '未读取'} · 项目{' '} + {view.overview?.target_project || view.overview?.executor?.project || '未读取'} · 知识库{' '} + {view.overview?.target_knowledge_base_id || target?.knowledge_base_id || '未读取'}({scopeName(scope)}) + {productionStale ? ({STALE_NOTE}) : null} +

    + {target?.source_identity ? ( +
    + 来源身份与完整摘要 +

    + 来源实例:{target.source_identity.project} / {target.source_identity.app} +

    +

    + 来源租户 / 知识库:{target.source_identity.tenant_id} / {target.source_identity.knowledge_base_id} +

    +

    来源身份:{target.source_id}

    +

    快照摘要:{target.snapshot_id}

    +
    + ) : null} +

    同步会先固定测试版本,再备份生产;备份失败或恢复条件不满足时不进入生产写入。

    +
    + >({ + internal: { state: 'unread' }, + external: { state: 'unread' }, + }) + // 轮询会并发多次 load:晚到的旧响应不许覆盖更新的维护窗口/作业。 + const loadSeq = useRef(0) const [scope, setScope] = useState('internal') const [drawerOpen, setDrawerOpen] = useState(false) const [expandedSnapshot, setExpandedSnapshot] = useState(null) const [pendingCapture, setPendingCapture] = useState(false) + const [pendingReconcileCapture, setPendingReconcileCapture] = useState('') const [now, setNow] = useState(() => Date.now()) const load = useCallback(async (signal?: AbortSignal) => { + const seq = ++loadSeq.current setLoading(true) try { const [snapshots, captures, internalOverview, externalOverview, internalMaintenance, externalMaintenance] = @@ -1458,17 +2232,35 @@ export function ReleaseTargets() { fetchLibraryMaintenance('internal', signal), fetchLibraryMaintenance('external', signal), ]) + // 只读既有作业详情接口,按维护记录的 owner_job_id 精确取;读不到就记下来, + // 不用 overview 的最新作业兜底(那是另一件事,会把失败窗口显示成已完成)。 + const ownerIDs = { + internal: maintenanceOwnerJobID(internalMaintenance), + external: maintenanceOwnerJobID(externalMaintenance), + } + const [internalOwnerJob, externalOwnerJob] = await Promise.all([ + ownerIDs.internal + ? fetchLibraryJobDetail(ownerIDs.internal, signal) + : Promise.resolve({ state: 'unread' }), + ownerIDs.external + ? fetchLibraryJobDetail(ownerIDs.external, signal) + : Promise.resolve({ state: 'unread' }), + ]) + // 晚回包直接丢掉:不覆盖更新的窗口,也不把旧窗口的作业挂到新窗口上。 + if (seq !== loadSeq.current) return setPage(snapshots) setJobs(captures) setOverviews({ internal: internalOverview, external: externalOverview }) setMaintenances({ internal: internalMaintenance, external: externalMaintenance }) + setMaintenanceJobs({ internal: internalOwnerJob, external: externalOwnerJob }) setNow(Date.now()) setError(null) } catch (loadError) { if ((loadError as Error).name === 'AbortError') return + if (seq !== loadSeq.current) return setError(loadError instanceof Error ? loadError.message : '加载发布状态失败') } finally { - setLoading(false) + if (seq === loadSeq.current) setLoading(false) } }, []) @@ -1478,16 +2270,6 @@ export function ReleaseTargets() { return () => controller.abort() }, [load]) - const busy = jobs.some((job) => ACTIVE_STATES.includes(job.state)) - useEffect(() => { - if (!busy) return - const timer = window.setInterval(() => { - setNow(Date.now()) - void load().catch(() => undefined) - }, 3000) - return () => window.clearInterval(timer) - }, [busy, load]) - const role = auth?.identity?.role const canWrite = role === 'engineer' || role === 'admin' // 恢复写的是整套生产知识状态,接口只认管理员;页面必须与它一致。 @@ -1523,14 +2305,14 @@ export function ReleaseTargets() { } const startSync = async () => { - if (!targetSnapshot) { - setNotice('还没有可发布的测试封存') + if (!targetSnapshot || !current?.test_sealed?.source_id) { + setNotice('还没有与当前来源绑定的可发布封存,请刷新状态') return } setPendingSync(true) setNotice(null) try { - const accepted = await enqueueLibrarySync(scope, targetSnapshot) + const accepted = await enqueueLibrarySync(scope, targetSnapshot, current?.test_sealed?.source_id ?? '') setNotice(`已投递同步:${accepted.job_id}(先固定测试版本并生成预备份,再写目标)`) await load() } catch (syncError) { @@ -1558,7 +2340,48 @@ export function ReleaseTargets() { const [restore, setRestore] = useState(null) const [restoreNotice, setRestoreNotice] = useState(null) const [pendingRestore, setPendingRestore] = useState(false) + // 按预备份恢复(library.recover)是独立的队列作业,不会产生新的 library_jobs 行: + // 只靠 jobs/overview 判断会让页面在投递后立刻停止轮询,恢复完成也停在旧状态(F12)。 + const [pendingRecovery, setPendingRecovery] = useState(false) + const recoveryStartedAt = useRef(0) + // 恢复验证是独立业务作业:投递后父页面必须自己轮询 overview/维护/闸口, + // 只在子面板刷新证据会让页面停在点击前的状态(审核 B4)。 + const [activeVerifyJob, setActiveVerifyJob] = useState('') const [pendingGrant, setPendingGrant] = useState(false) + // 轮询覆盖"投递 → 终态读回":投递中的动作也算在跑(点完到 worker 落库之间 + // 有一次空窗,只看已有作业会让页面停在"尚未启动")。终态(成功/失败/取消) + // 再做一次读回就停,不会无限轮询失败作业。 + const polling = libraryPollingActive({ + captures: jobs, + overviews, + pending: + pendingCapture || + pendingSync || + pendingBaseline || + pendingRestore || + pendingSyncGrant || + pendingGrant || + activeVerifyJob !== '', + recoveryPending: pendingRecovery, + maintenances, + }) + const wasPolling = useRef(false) + useEffect(() => { + if (polling) { + wasPolling.current = true + const timer = window.setInterval(() => { + setNow(Date.now()) + void load().catch(() => undefined) + }, 3000) + return () => window.clearInterval(timer) + } + if (wasPolling.current) { + wasPolling.current = false + // 终态读回:拿最后一次的 finished_at / 阶段终值,然后停下。 + void load().catch(() => undefined) + } + return undefined + }, [polling, load]) const [restoreRound, setRestoreRound] = useState(0) const restoreSnapshot = expandedSnapshot ?? '' useEffect(() => { @@ -1625,62 +2448,125 @@ export function ReleaseTargets() { } } + const reconcileCapture = async (jobID: string) => { + setPendingReconcileCapture(jobID) + setNotice(null) + try { + const result = await reconcileLibraryCapture(jobID) + setNotice( + result.already_succeeded + ? `封存作业 ${jobID} 已是成功终态,未重复写入` + : `已核对封存结果:${jobID} → ${result.snapshot_id.slice(0, 12)}(审计 ${result.audit_operation_id ?? '已记录'})` + ) + await load() + } catch (reconcileError) { + setNotice(reconcileError instanceof Error ? reconcileError.message : '核对封存结果失败') + } finally { + setPendingReconcileCapture('') + } + } + const recover = async (windowJobID: string) => { setNotice(null) try { const accepted = await enqueueLibraryRecovery(scope, windowJobID) - setNotice(`已投递按预备份恢复:${accepted.recovery_job || '(未返回作业号)'}`) + // 从这里开始页面必须持续读回,直到维护窗口真的关闭(成功)或恢复失败被记下来。 + recoveryStartedAt.current = Date.now() + setPendingRecovery(true) + setNotice(`已投递按预备份恢复:${accepted.recovery_job || '(未返回作业号)'};正在等待恢复与校验完成`) await load() } catch (recoveryError) { + setPendingRecovery(false) setNotice(recoveryError instanceof Error ? recoveryError.message : '恢复请求失败') } } + // 恢复轮询的收尾:维护窗口不再被持有 ⇒ 读到终态,停止等待并给出结论。 + // 超时不是"成功":只停止轮询并把状态留给页面显示(恢复失败会继续 held + needs_restore)。 + useEffect(() => { + if (!pendingRecovery) return + const held = Boolean(maintenances[scope]?.held) + const timedOut = Date.now() - recoveryStartedAt.current > 15 * 60 * 1000 + if (!held || timedOut) { + setPendingRecovery(false) + if (timedOut) setNotice('恢复轮询超时:请查看维护窗口状态(仍在维护说明恢复/校验未通过)') + void load().catch(() => undefined) + } + }, [pendingRecovery, maintenances, scope, load]) + return ( - { - setScope(next) - setExpandedSnapshot(null) - }} - drawerOpen={drawerOpen} - onDrawer={setDrawerOpen} - expandedSnapshot={expandedSnapshot} - onExpandSnapshot={setExpandedSnapshot} - pendingCapture={pendingCapture} - canCapture={canCapture} - canWrite={canWrite} - sync={{ - canSign: canSignSync, - pendingGrant: pendingSyncGrant, - onGrant: () => void grantSync(), - canStart: current?.gate.sync_allowed === true, - pending: pendingSync, - onStart: () => void startSync(), - }} - baseline={{ - canStart: canSignSync, - pending: pendingBaseline, - onStart: () => void startBaseline(), - }} - canRestore={canRestore} - restore={restore} - restoreNotice={restoreNotice} - pendingRestore={pendingRestore} - pendingGrant={pendingGrant} - onGrantRestore={() => void grantRestore()} - onRestore={() => void startRestore()} - maintenance={maintenances[scope]} - now={now} - onRefresh={() => void load()} - onCapture={() => void startCapture()} - onRecover={(windowJobID) => void recover(windowJobID)} - /> + <> + { + setScope(next) + setExpandedSnapshot(null) + // F10: 旧操作通知属于旧作业/旧对象,切范围后不得继续挂在页顶。 + setNotice(null) + }} + drawerOpen={drawerOpen} + onDrawer={setDrawerOpen} + expandedSnapshot={expandedSnapshot} + onExpandSnapshot={setExpandedSnapshot} + pendingCapture={pendingCapture} + canCapture={canCapture} + canWrite={canWrite} + canReconcileCapture={role === 'admin'} + pendingReconcileCapture={pendingReconcileCapture} + onReconcileCapture={(jobID) => void reconcileCapture(jobID)} + sync={{ + canSign: canSignSync, + pendingGrant: pendingSyncGrant, + onGrant: () => void grantSync(), + canStart: current?.gate.sync_allowed === true && Boolean(current?.test_sealed?.source_id), + pending: pendingSync, + onStart: () => void startSync(), + }} + baseline={{ + canStart: canSignSync, + pending: pendingBaseline, + onStart: () => void startBaseline(), + }} + verification={{ + onAccepted: (jobId) => { + // F10: 新验证作业开始时清掉上一次封存/同步的旧通知。 + setNotice(null) + setActiveVerifyJob(jobId) + void load() + }, + onComplete: () => { + setActiveVerifyJob('') + void load() + }, + }} + canRestore={canRestore} + restore={restore} + restoreNotice={restoreNotice} + pendingRestore={pendingRestore} + pendingGrant={pendingGrant} + onGrantRestore={() => void grantRestore()} + onRestore={() => void startRestore()} + maintenance={maintenances[scope]} + maintenanceOwnerJob={maintenanceJobs[scope]} + now={now} + onRefresh={() => void load()} + onCapture={() => void startCapture()} + onRecover={(windowJobID) => void recover(windowJobID)} + /> + load()} + /> + ) } diff --git a/web/src/RestoreVerificationSection.mounted.test.tsx b/web/src/RestoreVerificationSection.mounted.test.tsx new file mode 100644 index 0000000..d4ad4f7 --- /dev/null +++ b/web/src/RestoreVerificationSection.mounted.test.tsx @@ -0,0 +1,217 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import type { Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { RestoreVerificationSection } from './RestoreVerificationSection' + +// 审核 B4/B5 的挂载级回归(GPT-6 的离线挂载反例转成通过断言): +// 全部 fetch 都是 fake,不发任何 8088/云请求;这不是页面验收。 +const target = { + instance: 'fixture', + project: 'fixture', + internal_kb: 'fixture-internal', + external_kb: 'fixture-external', + index: 'fixture-index', + s3_bucket: 'fixture-bucket', + tenant_id: 1, + database_configured: true, +} + +const passed = { + id: 'e', + scope: 'internal', + status: 'passed', + snapshot_id: 'a'.repeat(64), + job_id: 'old-internal-job', + started_at: '2026-01-01T00:00:00Z', + finished_at: '2026-01-01T00:01:00Z', +} + +const internalView = { + scope: 'internal', + verified: true, + reason: '', + target, + latest: passed, + history: [passed], + running: false, +} + +const externalView = { + scope: 'external', + verified: false, + reason: '还没有对当前目标做过恢复验证', + target, + latest: null, + history: [], + running: false, +} + +let container: HTMLDivElement +let root: Root + +const jsonResponse = (body: unknown, status = 200) => ({ + ok: status >= 200 && status < 300, + status, + json: async () => body, +}) + +const press = async (label: string) => { + const button = [...container.querySelectorAll('button')].find((item) => item.textContent === label) + if (!button) throw new Error(`button ${label} not found: ${container.textContent}`) + await act(async () => { + button.click() + }) +} + +beforeEach(() => { + ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + vi.unstubAllGlobals() +}) + +describe('RestoreVerificationSection mounted (offline fixtures)', () => { + it('刷新失败时旧证据标成过期,不再显示"已验证(当前目标)"', async () => { + let mode: 'ok' | 'fail' = 'ok' + vi.stubGlobal('fetch', async () => { + if (mode === 'fail') throw new Error('offline fixture read failed') + return jsonResponse(internalView) + }) + await act(async () => { + root.render() + }) + expect(container.textContent).toContain('已验证(当前目标)') + mode = 'fail' + await press('刷新验证状态') + expect(container.textContent).not.toContain('已验证(当前目标)') + expect(container.textContent).toContain('上次观测已过期') + expect(container.textContent).toContain('刷新失败') + expect(container.textContent).toContain('offline fixture read failed') + }) + + it('切 scope 不沿用旧 scope 的通过证据', async () => { + vi.stubGlobal('fetch', async (url: string) => { + if (String(url).includes('scope=external')) return new Promise(() => undefined) + return jsonResponse(internalView) + }) + await act(async () => { + root.render() + }) + expect(container.textContent).toContain('old-internal-job') + await act(async () => { + root.render() + }) + // 新 scope 的观测还没回来:宁可显示"还没读到",也不能沿用旧 scope 的证据。 + expect(container.textContent).toContain('还没有读到验证状态') + expect(container.textContent).not.toContain('fixture-internal') + expect(container.textContent).not.toContain('old-internal-job') + expect(container.textContent).not.toContain('已验证(当前目标)') + }) + + it('接受作业后父页面收到 onAccepted,终态收到 onComplete', async () => { + const onAccepted = vi.fn() + const onComplete = vi.fn() + let started = false + vi.stubGlobal('fetch', async (url: string, init?: { method?: string }) => { + if (init?.method === 'POST') { + started = true + return jsonResponse({ job: { id: 'libverify-internal-1', scope: 'internal' }, reused: false }, 202) + } + if (String(url).includes('scope=internal')) { + if (!started) return jsonResponse({ ...internalView, verified: false, latest: null, history: [] }) + if (container.textContent?.includes('验证执行中')) { + return jsonResponse({ + ...externalView, + scope: 'internal', + latest: { ...passed, status: 'passed', job_id: 'libverify-internal-1' }, + running: false, + }) + } + return jsonResponse({ + ...externalView, + scope: 'internal', + running: true, + job_id: 'libverify-internal-1', + stage: 'restore', + }) + } + return jsonResponse(externalView) + }) + await act(async () => { + root.render( + + ) + }) + await press('跑一次恢复验证(维护隔离)') + expect(onAccepted).not.toHaveBeenCalled() + await press('确认并投递') + expect(onAccepted).toHaveBeenCalledWith('libverify-internal-1') + expect(container.textContent).toContain('验证执行中') + await press('刷新验证状态') + expect(onComplete).toHaveBeenCalledWith('libverify-internal-1') + }) + + it('切 scope 后迟到的旧 POST 不能污染新目标或触发父级旧作业回调', async () => { + const onAccepted = vi.fn() + const onComplete = vi.fn() + let resolvePost: ((value: unknown) => void) | null = null + vi.stubGlobal('fetch', async (url: string, init?: { method?: string }) => { + if (init?.method === 'POST') { + return new Promise((resolve) => { + resolvePost = resolve + }) + } + return jsonResponse(String(url).includes('scope=external') ? externalView : internalView) + }) + await act(async () => { + root.render( + + ) + }) + // 旧 internal POST 挂起时切到 external:external 的真实观测已经完成。 + await act(async () => { + ;[...container.querySelectorAll('button')].find((item) => item.textContent?.includes('跑一次恢复验证'))!.click() + }) + await act(async () => { + ;[...container.querySelectorAll('button')].find((item) => item.textContent === '确认并投递')!.click() + }) + await act(async () => { + root.render( + + ) + }) + expect(container.textContent).toContain('fixture-external') + expect(container.textContent).not.toContain('已验证(当前目标)') + expect(container.textContent).not.toContain('old-internal-job') + // 放行旧 internal POST:它的 then/onAccepted/reload 必须全部失效。 + await act(async () => { + resolvePost?.(jsonResponse({ job: { id: 'verify-internal-new', scope: 'internal' }, reused: false }, 202)) + }) + expect(container.textContent).toContain('fixture-external') + expect(container.textContent).not.toContain('已验证(当前目标)') + expect(container.textContent).not.toContain('old-internal-job') + expect(container.textContent).not.toContain('verify-internal-new') + expect(onAccepted).not.toHaveBeenCalled() + expect(onComplete).not.toHaveBeenCalled() + }) + + it('HTTP 失败按失败显示,不把响应当通过证据', async () => { + vi.stubGlobal('fetch', async () => + jsonResponse({ scope: 'internal', verified: true, reason: '证据读取失败', target, history: [] }, 503) + ) + await act(async () => { + root.render() + }) + expect(container.textContent).toContain('读取验证状态失败') + expect(container.textContent).not.toContain('已验证(当前目标)') + }) +}) diff --git a/web/src/RestoreVerificationSection.test.tsx b/web/src/RestoreVerificationSection.test.tsx new file mode 100644 index 0000000..da3be68 --- /dev/null +++ b/web/src/RestoreVerificationSection.test.tsx @@ -0,0 +1,173 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' + +import { RestoreVerificationView } from './RestoreVerificationSection' +import type { LibraryVerificationView } from './restoreVerification' + +const target = { + instance: 'weknora-test', + project: 'weknora', + internal_kb: 'a8e9c8ad-411c-4c53-8421-599d29e9b179', + external_kb: '2e980686-2233-4c4e-b5a6-8b0069477b8e', + index: 'weknora_test_chunks', + s3_bucket: 'dobot-weknora-test', + tenant_id: 10000, + database_configured: true, +} + +const view = (overrides: Partial = {}): LibraryVerificationView => ({ + scope: 'internal', + target, + verified: false, + reason: '还没有对当前目标做过恢复验证', + latest: null, + history: [], + ...overrides, +}) + +const render = ( + value: LibraryVerificationView | null, + isAdmin = true, + pending = false, + error: string | null = null, + stale = false +) => + renderToStaticMarkup( + undefined} + onReload={() => undefined} + /> + ) + +describe('RestoreVerificationView', () => { + it('没有证据时显示"还没有验证记录"并给出下一步,不显示已验证', () => { + const html = render(view()) + expect(html).toContain('还没有验证记录') + expect(html).toContain('跑一次恢复验证') + expect(html).not.toContain('已验证(当前目标)') + }) + + it('管理员能看到发起按钮,工程师只看到证据与原因', () => { + expect(render(view(), true)).toContain('跑一次恢复验证') + const engineer = render(view(), false) + expect(engineer).not.toContain('跑一次恢复验证') + expect(engineer).toContain('仅管理员可发起') + }) + + it('通过后显示已验证、快照与完整目标', () => { + const html = render( + view({ + verified: true, + reason: '', + latest: { + id: 'libverify-internal-job1', + scope: 'internal', + status: 'passed', + snapshot_id: '0f9b39a16738', + job_id: 'libverify-internal-1', + report: { status: 'passed', checks: ['database', 'index', 'objects', 'wiki'] }, + started_at: '2026-11-03T01:00:00Z', + finished_at: '2026-11-03T01:02:00Z', + }, + }) + ) + expect(html).toContain('已验证(当前目标)') + // F03: a passed record with empty API reason must not print "还没有读到验证状态". + expect(html).toContain('当前目标的最近一次真实恢复验证已通过') + expect(html).not.toContain('还没有读到验证状态') + expect(html).toContain('查看本次恢复验证报告') + expect(html).toContain('0f9b39a16738') + expect(html).toContain('a8e9c8ad-411c-4c53-8421-599d29e9b179') + expect(html).toContain('weknora_test_chunks') + }) + + it('高影响恢复验证先给出目标/影响/恢复方式的一次确认', () => { + const html = renderToStaticMarkup( + undefined} + onConfirm={() => undefined} + onCancel={() => undefined} + onReload={() => undefined} + /> + ) + expect(html).toContain('恢复验证影响确认') + expect(html).toContain('目标:对内知识库 · weknora-test') + expect(html).toContain('短暂停止目标写入者并关闭入口') + expect(html).toContain('确认并投递') + expect(html).toContain('取消') + }) + + it('失败时把失败原因写出来,按钮仍可重试', () => { + const html = render( + view({ + latest: { + id: 'libverify-internal-job2', + scope: 'internal', + status: 'failed', + snapshot_id: 'snap-2', + job_id: 'libverify-internal-2', + failure: '恢复后内容仍与预备份不一致', + started_at: '2026-11-03T01:00:00Z', + finished_at: '2026-11-03T01:05:00Z', + }, + }) + ) + expect(html).toContain('最近一次未通过') + expect(html).toContain('恢复后内容仍与预备份不一致') + expect(html).toContain('跑一次恢复验证') + }) + + // 审核 B5:刷新失败时旧证据必须明确标成过期,不能再显示"已验证(当前目标)"。 + it('stale 观测不得显示当前已通过,并给出刷新失败说明', () => { + const html = render( + view({ + verified: true, + reason: '', + latest: { + id: 'libverify-internal-job1', + scope: 'internal', + status: 'passed', + snapshot_id: '0f9b39a16738', + job_id: 'libverify-internal-1', + started_at: '2026-11-03T01:00:00Z', + finished_at: '2026-11-03T01:02:00Z', + }, + }), + true, + false, + '读取验证状态失败:offline fixture read failed', + true + ) + expect(html).not.toContain('已验证(当前目标)') + expect(html).toContain('上次观测已过期') + expect(html).toContain('刷新失败') + expect(html).toContain('offline fixture read failed') + }) + + // 审核 B4:在飞作业必须体现在按钮/状态上。 + it('running 时显示执行中并禁用发起按钮', () => { + const html = render(view({ running: true, job_id: 'libverify-internal-9', stage: 'restore' })) + expect(html).toContain('验证执行中') + expect(html).toContain('disabled') + }) + + it('投递被拒时显示后端逐条原因', () => { + const html = render(view(), true, false, '恢复验证被拒绝:生产写入闸口关闭') + expect(html).toContain('生产写入闸口关闭') + }) +}) diff --git a/web/src/RestoreVerificationSection.tsx b/web/src/RestoreVerificationSection.tsx new file mode 100644 index 0000000..7524aa8 --- /dev/null +++ b/web/src/RestoreVerificationSection.tsx @@ -0,0 +1,284 @@ +import { useCallback, useEffect, useRef, useState } from 'react' + +import { + enqueueLibraryVerification, + fetchLibraryVerification, + verificationReasonText, + verificationStatusText, + verificationTargetLines, +} from './restoreVerification' +import type { LibraryVerificationView } from './restoreVerification' + +// 「恢复验证」面板:同步闸口认的"生产可恢复"证据只能由这里发起的一次真实演练产生。 +// +// 为什么要有这个入口:以前只有 CLI(现为 internal/libraryverify 的薄封装)能跑演练, +// 页面只能看到一个 env 开关。运维在页面上看到"缺 1 项",却没有任何可点的下一步。 +// 这里把"跑一次真实演练"变成正常流程:它会停写入者、写 canary、按预备份恢复, +// 全过程由 worker 执行并登记真实终态;页面只显示结果,不提供手填开关。 + +export interface RestoreVerificationViewProps { + view: LibraryVerificationView | null + scope: string + isAdmin: boolean + pending: boolean + error: string | null + notice: string + // stale 表示这份 view 是上一次成功读取的结果,本次刷新失败,不能当当前结论。 + stale: boolean + onRun: () => void + onReload: () => void + confirming?: boolean + onConfirm?: () => void + onCancel?: () => void +} + +const stampText = (value: string): string => { + if (!value) return '—' + const parsed = new Date(value) + return Number.isNaN(parsed.getTime()) ? value : parsed.toLocaleString() +} + +export function RestoreVerificationView(props: RestoreVerificationViewProps) { + const { + view, + scope, + isAdmin, + pending, + error, + notice, + stale, + onRun, + onReload, + confirming = false, + onConfirm, + onCancel, + } = props + const status = verificationStatusText(view, stale) + const latest = view?.latest ?? null + const running = Boolean(view?.running) + const tone = stale ? 'gray' : view?.verified ? 'green' : latest?.status === 'failed' ? 'red' : 'gray' + return ( +
    +
    +

    恢复验证(当前整库目标)

    + {status} +
    + {stale ? ( +

    + 刷新失败:下面是上一次成功读取的观测,已过期,不能代表当前目标;在刷新成功之前不得据此判断"已验证"。 +

    + ) : null} + {view ? ( +
      + {verificationTargetLines(view.target, scope).map((line) => ( +
    • {line}
    • + ))} +
    + ) : null} +

    {verificationReasonText(view, stale)}

    + {latest ? ( +

    + 最近一次:{latest.status === 'passed' ? '通过' : '未通过'} · 快照 {latest.snapshot_id.slice(0, 12) || '—'} ·{' '} + {stampText(latest.finished_at)} · 作业 {latest.job_id} +

    + ) : null} + {latest?.failure ?

    未通过原因:{latest.failure}

    : null} + {latest?.report ? ( +
    + 查看本次恢复验证报告 +
    {JSON.stringify(latest.report, null, 2)}
    +
    + ) : null} + {error ?

    {error}

    : null} + {notice ?

    {notice}

    : null} + {confirming ? ( +
    + 确认停写并执行恢复验证? +

    + 目标:{scope === 'internal' ? '对内知识库' : '对外知识库'} · {view?.target?.instance || '目标实例未配置'} +

    +

    + 影响:短暂停止目标写入者并关闭入口,在目标写入 canary,再按预备份恢复并逐类复核;完成后按原运行状态收尾。 +

    +

    恢复方式:本次作业自己的预备份与写前镜像;不是测试封存,也不会登记新版本。

    +
    + + +
    +
    + ) : null} +
    + {isAdmin ? ( + + ) : ( + 恢复验证仅管理员可发起;工程师可以看到证据与原因。 + )} + +
    +

    + 验证会停住目标写入者、写一个隔离 canary 证明校验有效、再按预备份恢复并逐类复核; + 通过后证据按当前目标登记,换库/换索引/换桶后自动失效。 +

    +
    + ) +} + +// 容器:挂载即读一次,之后每 3 秒刷新(验证作业在 worker 里跑,页面只读证据)。 +// +// 两个身份必须分开: +// - 观测身份 = scope + 请求代次:切 scope 立即清旧结果,晚到的旧响应被丢弃; +// - 作业身份 = 投递返回的 job_id:它驱动父页面的 load/轮询,终态再通知一次。 +export function RestoreVerificationSection({ + scope, + isAdmin, + onAccepted, + onComplete, +}: { + scope: string + isAdmin: boolean + onAccepted?: (jobId: string) => void + onComplete?: (jobId: string) => void +}) { + const [view, setView] = useState(null) + const [stale, setStale] = useState(false) + const [pending, setPending] = useState(false) + const [error, setError] = useState(null) + const [notice, setNotice] = useState('') + const [confirming, setConfirming] = useState(false) + const mounted = useRef(true) + const generation = useRef(0) + const viewScopeRef = useRef('') + // scopeRef 是"当前渲染的 scope":异步回调必须同时核对 scope 与世代, + // 只比 GET generation 会被迟到的旧 POST 重新递增而失效(审核 B5-R1)。 + const scopeRef = useRef(scope) + const scopeEpoch = useRef(0) + const actionSeq = useRef(0) + const acceptedJob = useRef('') + const sawRunning = useRef(false) + const onAcceptedRef = useRef(onAccepted) + onAcceptedRef.current = onAccepted + const onCompleteRef = useRef(onComplete) + onCompleteRef.current = onComplete + + const reload = useCallback((targetScope: string, signal?: AbortSignal) => { + const request = ++generation.current + return fetchLibraryVerification(targetScope, signal) + .then((next) => { + // 晚到的旧 scope/旧代次响应一律丢弃:它不能改写当前 scope 的观测。 + if (!mounted.current || request !== generation.current || targetScope !== scopeRef.current) return + setView(next) + viewScopeRef.current = next.scope + setStale(false) + setError(null) + const job = acceptedJob.current + if (!job) return + if (next.running) { + sawRunning.current = true + return + } + // 终态:本作业不再出现在在飞集合里(或被证据行点名),通知父页面做最后一次读回。 + if (sawRunning.current || next.job_id === job || next.latest?.job_id === job) { + acceptedJob.current = '' + sawRunning.current = false + onCompleteRef.current?.(job) + } + }) + .catch((err: unknown) => { + if (!mounted.current || request !== generation.current || targetScope !== scopeRef.current) return + if ((err as Error)?.name === 'AbortError') return + // 刷新失败:同 scope 的旧结果保留但明确标成过期;别的 scope 的旧结果直接丢掉。 + setStale(true) + setView((current) => (viewScopeRef.current === targetScope ? current : null)) + setError(err instanceof Error ? err.message : '读取恢复验证状态失败') + }) + }, []) + + useEffect(() => { + mounted.current = true + scopeRef.current = scope + // 切 scope 使所有在飞动作失效:旧 scope 的 POST/回调不能写回新目标。 + scopeEpoch.current += 1 + actionSeq.current = 0 + setPending(false) + // 切 scope:旧 scope 的证据不能继续显示为"当前目标已验证"。 + setView(null) + viewScopeRef.current = '' + setStale(false) + setError(null) + setNotice('') + setConfirming(false) + acceptedJob.current = '' + sawRunning.current = false + const controller = new AbortController() + void reload(scope, controller.signal) + const timer = setInterval(() => void reload(scope, controller.signal), 3000) + return () => { + mounted.current = false + controller.abort() + clearInterval(timer) + } + // reload 依赖 viewScope(用于判断旧结果是否同 scope),不能让它的身份变化重启轮询。 + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [scope]) + + const onRun = useCallback(() => { + const actionScope = scope + const actionEpoch = scopeEpoch.current + const action = ++actionSeq.current + // 动作仍然有效 = 组件挂着 + 还是同一个 scope 世代 + 仍是最新一次点击。 + const current = () => + mounted.current && + scopeEpoch.current === actionEpoch && + scopeRef.current === actionScope && + actionSeq.current === action + setPending(true) + setError(null) + setNotice('') + enqueueLibraryVerification(actionScope) + .then((accepted) => { + if (!current() || accepted.scope !== actionScope) return + acceptedJob.current = accepted.job_id + sawRunning.current = false + setNotice(`已投递恢复验证作业 ${accepted.job_id};页面会自动刷新进度与终态,父级作业/维护/闸口同步更新。`) + // 父页面必须立刻知道"有一个验证在跑":否则它不会轮询 overview/维护。 + onAcceptedRef.current?.(accepted.job_id) + void reload(actionScope) + }) + .catch((err: unknown) => { + if (!current()) return + setError(err instanceof Error ? err.message : '投递恢复验证失败') + }) + .finally(() => { + // 旧动作的 finally 不能清掉新 scope 新动作的 pending。 + if (current()) setPending(false) + }) + }, [scope, reload]) + + return ( + setConfirming(true)} + onConfirm={() => { + setConfirming(false) + onRun() + }} + onCancel={() => setConfirming(false)} + onReload={() => void reload(scope)} + /> + ) +} diff --git a/web/src/RoutingBindingsSection.tsx b/web/src/RoutingBindingsSection.tsx index 3b5322d..16c0400 100644 --- a/web/src/RoutingBindingsSection.tsx +++ b/web/src/RoutingBindingsSection.tsx @@ -17,67 +17,174 @@ export function RoutingBindingsSection() { const [message, setMessage] = useState('') const load = useCallback(async () => { - setLoading(true); setError(null) + setLoading(true) + setError(null) try { const next = await fetchRoutingBindings() setBindings(next) setInternalDraft(next.internal_bound_by_ui ? next.internal_kb_id : '') setExternalDraft(next.external_bound_by_ui ? next.external_kb_id : '') - try { setOptions(await fetchRoutingBindingOptions()) } catch { setOptions([]) } - } catch (cause) { setError(cause instanceof Error ? cause.message : '读取测试知识库绑定失败') } - finally { setLoading(false) } + try { + setOptions(await fetchRoutingBindingOptions()) + } catch { + setOptions([]) + } + } catch (cause) { + setError(cause instanceof Error ? cause.message : '读取测试知识库绑定失败') + } finally { + setLoading(false) + } }, []) - useEffect(() => { void load() }, [load]) + useEffect(() => { + void load() + }, [load]) - const dirty = bindings !== null && (internalDraft !== (bindings.internal_bound_by_ui ? bindings.internal_kb_id : '') || externalDraft !== (bindings.external_bound_by_ui ? bindings.external_kb_id : '')) + const dirty = + bindings !== null && + (internalDraft !== (bindings.internal_bound_by_ui ? bindings.internal_kb_id : '') || + externalDraft !== (bindings.external_bound_by_ui ? bindings.external_kb_id : '')) const sameSelection = internalDraft !== '' && internalDraft === externalDraft const save = async () => { - setSaving(true); setError(null); setMessage('') + setSaving(true) + setError(null) + setMessage('') try { const next = await saveRoutingBindings({ internal_kb_id: internalDraft, external_kb_id: externalDraft }) setBindings(next) - const replan = next.replanned || next.retired_duplicates - ? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}` - : '' - setMessage(`绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}。此后“来源与目录”的标记按新绑定路由${replan}。`) - } catch (cause) { setError(cause instanceof Error ? cause.message : '保存测试知识库绑定失败') } - finally { setSaving(false) } + const replan = + next.replanned || next.retired_duplicates + ? `;同时把 ${next.replanned} 项还没上传的待入库重新指向新库${next.retired_duplicates ? `,${next.retired_duplicates} 项因新库里已有同篇而被退休` : ''}` + : '' + setMessage( + `绑定已生效:对内 ${next.internal_kb_name || next.internal_kb_id.slice(0, 8) || '未绑定'} · 对外 ${next.external_kb_name || next.external_kb_id.slice(0, 8) || '未绑定'}。此后“来源与目录”的标记按新绑定路由${replan}。` + ) + } catch (cause) { + setError(cause instanceof Error ? cause.message : '保存测试知识库绑定失败') + } finally { + setSaving(false) + } } - const optionLabel = (base: KnowledgeBaseOption) => `${base.name}(${base.knowledge_count} 文档 · ${base.id.slice(0, 8)}…)` + const optionLabel = (base: KnowledgeBaseOption) => + `${base.name}(${base.knowledge_count} 文档 · ${base.id.slice(0, 8)}…)` const renderSide = (label: string, boundID: string, boundName: string, fromEnv: boolean, boundByUI: boolean) => (
    {label} - {boundID ? (boundName || `${boundID.slice(0, 8)}…`) : '未绑定 · 该方向的标记会被拒绝'} - {boundID ? (boundByUI ? (boundName ? `UI 绑定 · ${boundID.slice(0, 8)}…` : 'UI 绑定') : fromEnv ? '来自部署默认值(env)' : '') : '请绑定一个测试知识库'} + {boundID ? boundName || `${boundID.slice(0, 8)}…` : '未绑定 · 该方向的标记会被拒绝'} + + {boundID + ? boundByUI + ? boundName + ? `UI 绑定 · ${boundID.slice(0, 8)}…` + : 'UI 绑定' + : fromEnv + ? '来自部署默认值(env)' + : '' + : '请绑定一个测试知识库'} +
    ) - const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) => ( - options.length > 0 - ? - : onChange(event.target.value.trim())} placeholder={`${placeholder}(输入知识库 ID)`} aria-label={placeholder} /> - ) + const editorFor = (value: string, onChange: (next: string) => void, placeholder: string) => + options.length > 0 ? ( + + ) : ( + onChange(event.target.value.trim())} + placeholder={`${placeholder}(输入知识库 ID)`} + aria-label={placeholder} + /> + ) - return
    -

    测试知识库绑定

    “来源与目录”里的对内 / 对外标记按这里的绑定分发到对应的测试 WeKnora 知识库;保存后立即生效,无需重启。发布写入的生产知识库见「生产知识库绑定」。

    - {error ?

    {error}

    : null} - {bindings ?
    - {renderSide('对内知识库', bindings.internal_kb_id, bindings.internal_kb_name, bindings.internal_env_fallback, bindings.internal_bound_by_ui)} - {renderSide('对外知识库', bindings.external_kb_id, bindings.external_kb_name, bindings.external_env_fallback, bindings.external_bound_by_ui)} -
    : null} - {bindings && !bindings.weknora_connected ?

    当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。

    : null} - {isAdmin && bindings ?
    - - -

    留空 = 取消 UI 绑定,回退到部署默认值;对内与对外必须是不同的库。

    - {sameSelection ?

    对内与对外必须绑定不同的知识库

    : null} - - {message ?

    {message}

    : null} -
    : null} - {!isAdmin ?

    仅管理员可修改测试知识库绑定。

    : null} -
    + return ( +
    +
    +
    +

    测试知识库绑定

    +

    + “来源与目录”里的对内 / 对外标记按这里的绑定分发到对应的测试 WeKnora + 知识库;保存后立即生效,无需重启。发布写入的生产知识库见「生产知识库绑定」。 +

    +
    + +
    + {error ? ( +

    + {error} +

    + ) : null} + {bindings ? ( + <> +
    + {(['internal', 'external'] as const).map((scope) => { + const binding = scope === 'internal' ? bindings.internal_kb_id : bindings.external_kb_id + const source = + scope === 'internal' ? bindings.library_source_internal_kb : bindings.library_source_external_kb + const state = scope === 'internal' ? bindings.internal_source_state : bindings.external_source_state + return ( +
    + {scope === 'internal' ? '对内' : '对外'} + 入库目标 {binding ? `${binding.slice(0, 8)}…` : '未绑定'} + 封存源 {source ? `${source.slice(0, 8)}…` : '未配置(LIBRARY_SOURCE_KB_*)'} + + {state === 'consistent' + ? '一致' + : state === 'mismatch' + ? '不一致:改绑定不会改封存源,封存仍导出旧库' + : '未配置:整库封存无法定位来源'} + +
    + ) + })} +
    +
    + {renderSide( + '对内知识库', + bindings.internal_kb_id, + bindings.internal_kb_name, + bindings.internal_env_fallback, + bindings.internal_bound_by_ui + )} + {renderSide( + '对外知识库', + bindings.external_kb_id, + bindings.external_kb_name, + bindings.external_env_fallback, + bindings.external_bound_by_ui + )} +
    + + ) : null} + {bindings && !bindings.weknora_connected ? ( +

    当前读不到 WeKnora 的库列表,只能按 ID 填写;连接恢复后可改为下拉选择。

    + ) : null} + {isAdmin && bindings ? ( +
    + + +

    留空 = 取消 UI 绑定,回退到部署默认值;对内与对外必须是不同的库。

    + {sameSelection ?

    对内与对外必须绑定不同的知识库

    : null} + + {message ? ( +

    + {message} +

    + ) : null} +
    + ) : null} + {!isAdmin ?

    仅管理员可修改测试知识库绑定。

    : null} +
    + ) } diff --git a/web/src/ScopeRuleEditor.test.tsx b/web/src/ScopeRuleEditor.test.tsx index 091e102..5437304 100644 --- a/web/src/ScopeRuleEditor.test.tsx +++ b/web/src/ScopeRuleEditor.test.tsx @@ -2,18 +2,48 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it, vi } from 'vitest' import { ScopeRuleEditor } from './ScopeRuleEditor' -describe('ScopeRuleEditor',()=>{ - it('explains directory inheritance and keeps production publication separate',()=>{ - const html=renderToStaticMarkup() - for(const text of ['此目录及子目录','当前设置:对内','由 engineer 设置','移除本级设置,恢复继承','不会自动发布到生产']) expect(html).toContain(text) - expect(html).not.toContain('操作人{ - const html=renderToStaticMarkup() - expect(html).toContain('整个来源') - expect(html).toContain('当前没有本级设置') - expect(html).toContain('拟修改为') - expect(html).toContain('选择新范围') - expect(html).not.toContain('移除本级设置') - }) +describe('ScopeRuleEditor', () => { + it('explains directory inheritance and keeps production publication separate', () => { + const html = renderToStaticMarkup( + + ) + for (const text of [ + '此目录及子目录', + '当前设置:对内', + '由 engineer 设置', + '移除本级设置,恢复继承', + '不会自动发布到生产', + ]) + expect(html).toContain(text) + expect(html).not.toContain('操作人 { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('整个来源') + expect(html).toContain('当前没有本级设置') + expect(html).toContain('拟修改为') + expect(html).toContain('选择新范围') + expect(html).not.toContain('移除本级设置') + }) }) diff --git a/web/src/ScopeRuleEditor.tsx b/web/src/ScopeRuleEditor.tsx index 9b66843..4cb9226 100644 --- a/web/src/ScopeRuleEditor.tsx +++ b/web/src/ScopeRuleEditor.tsx @@ -2,30 +2,78 @@ import { useState } from 'react' import type { ClearScopeRuleDecision, ScopeRule, ScopeRuleDecision, ScopeRuleTarget, Visibility } from './scopeRules' interface Props { - target: ScopeRuleTarget - currentRule?: ScopeRule - saving: boolean - error?: string|null - onSave: (decision:ScopeRuleDecision)=>void - onClear: (decision:ClearScopeRuleDecision)=>void + target: ScopeRuleTarget + currentRule?: ScopeRule + saving: boolean + error?: string | null + onSave: (decision: ScopeRuleDecision) => void + onClear: (decision: ClearScopeRuleDecision) => void } -export function ScopeRuleEditor({target,currentRule,saving,error,onSave,onClear}:Props){ - const [visibility,setVisibility]=useState(currentRule?.visibility||'') - const [reason,setReason]=useState('') - const reasonReady=reason.trim()!==''&&!saving - const saveReady=reasonReady&&visibility!=='' - const label=target.target_type==='item'?'仅此文件':target.directory_path?'此目录及子目录':'整个来源' - const base={...target,reason:reason.trim()} - return
    -
    对内/对外设置{label}
    {currentRule?当前设置:{currentRule.visibility==='external'?'对外':'对内'}:当前没有本级设置}
    - {currentRule?

    由 {currentRule.updated_by} 设置 · 原因:{currentRule.reason}

    :

    当前继承上级规则或来源原始标记。

    } -
    - - -
    - {error?

    {error}

    :null} -
    {currentRule?:null}
    - 这里只更新治理规则并记录审计,操作自动记在当前登录人名下;不会修改源文件,也不会自动发布到生产。 -
    +export function ScopeRuleEditor({ target, currentRule, saving, error, onSave, onClear }: Props) { + const [visibility, setVisibility] = useState(currentRule?.visibility || '') + const [reason, setReason] = useState('') + const reasonReady = reason.trim() !== '' && !saving + const saveReady = reasonReady && visibility !== '' + const label = target.target_type === 'item' ? '仅此文件' : target.directory_path ? '此目录及子目录' : '整个来源' + const base = { ...target, reason: reason.trim() } + return ( +
    +
    +
    + 对内/对外设置 + {label} +
    + {currentRule ? ( + + 当前设置:{currentRule.visibility === 'external' ? '对外' : '对内'} + + ) : ( + 当前没有本级设置 + )} +
    + {currentRule ? ( +

    + 由 {currentRule.updated_by} 设置 · 原因:{currentRule.reason} +

    + ) : ( +

    当前继承上级规则或来源原始标记。

    + )} +
    + + +
    + {error ? ( +

    + {error} +

    + ) : null} +
    + + {currentRule ? ( + + ) : null} +
    + 这里只更新治理规则并记录审计,操作自动记在当前登录人名下;不会修改源文件,也不会自动发布到生产。 +
    + ) } diff --git a/web/src/SnapshotHistory.test.tsx b/web/src/SnapshotHistory.test.tsx index 5693d02..8b52025 100644 --- a/web/src/SnapshotHistory.test.tsx +++ b/web/src/SnapshotHistory.test.tsx @@ -1,34 +1,115 @@ import { renderToStaticMarkup } from 'react-dom/server' -import { describe,expect,it,vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { SnapshotHistoryView } from './SnapshotHistory' import type { CatalogSnapshot } from './sourceCatalog' -const head:CatalogSnapshot={snapshot_id:'ss-new',connection_id:'conn-1',root_node_id:'root',source_name:'国内工业',node_count:2,folder_count:1,file_count:1,observed_at:'2026-09-11T00:00:00Z',created_at:'2026-09-11T00:00:05Z',is_head:true} -const older:CatalogSnapshot={...head,snapshot_id:'ss-old',observed_at:'2026-09-10T00:00:00Z',is_head:false} -const fileNode={node_id:'file-old',parent_node_id:'root',node_type:'file' as const,name:'手册.pdf',direct_child_count:0,subtree_file_count:1,subtree_bytes:20,size_bytes:20,modified_at:'2026-09-09T00:00:00Z',content_sha256:'ab'.repeat(32),visibility:'unknown' as const,imported_count:0,parsed_count:0,active_count:0,failed_count:0,routable_count:0} -const page={current:{node_id:'root',node_type:'folder' as const,name:'国内工业',direct_child_count:1,subtree_file_count:1,subtree_bytes:20,visibility:'unknown' as const,imported_count:0,parsed_count:0,active_count:0,failed_count:0,routable_count:0},breadcrumbs:[{node_id:'root',name:'国内工业'}],items:[fileNode],total:1,limit:50,offset:0} +const head: CatalogSnapshot = { + snapshot_id: 'ss-new', + connection_id: 'conn-1', + root_node_id: 'root', + source_name: '国内工业', + node_count: 2, + folder_count: 1, + file_count: 1, + observed_at: '2026-09-11T00:00:00Z', + created_at: '2026-09-11T00:00:05Z', + is_head: true, +} +const older: CatalogSnapshot = { ...head, snapshot_id: 'ss-old', observed_at: '2026-09-10T00:00:00Z', is_head: false } +const fileNode = { + node_id: 'file-old', + parent_node_id: 'root', + node_type: 'file' as const, + name: '手册.pdf', + direct_child_count: 0, + subtree_file_count: 1, + subtree_bytes: 20, + size_bytes: 20, + modified_at: '2026-09-09T00:00:00Z', + content_sha256: 'ab'.repeat(32), + visibility: 'unknown' as const, + imported_count: 0, + parsed_count: 0, + active_count: 0, + failed_count: 0, + routable_count: 0, +} +const page = { + current: { + node_id: 'root', + node_type: 'folder' as const, + name: '国内工业', + direct_child_count: 1, + subtree_file_count: 1, + subtree_bytes: 20, + visibility: 'unknown' as const, + imported_count: 0, + parsed_count: 0, + active_count: 0, + failed_count: 0, + routable_count: 0, + }, + breadcrumbs: [{ node_id: 'root', name: '国内工业' }], + items: [fileNode], + total: 1, + limit: 50, + offset: 0, +} -describe('SnapshotHistoryView',()=>{ - it('lists snapshot history, flags head and opens a historical snapshot read-only',()=>{ - const html=renderToStaticMarkup() - expect(html).toContain('历史快照') - expect(html).toContain('当前') - expect(html).toContain('只读') - expect(html).toContain('手册.pdf') - expect(html).toContain('内容Hash') - expect(html).toContain('abababababab') - // hash is displayable but never turns into an interactive policy checkbox/button - expect(html).not.toContain('checkbox') - expect(html).not.toContain('policy-button') - }) - it('shows 内容Hash未获取 instead of faking a hash',()=>{ - const missing={...page,items:[{...fileNode,content_sha256:undefined}]} - const html=renderToStaticMarkup() - expect(html).toContain('内容Hash未获取') - }) - it('lists snapshots without an active page and offers opening each one',()=>{ - const html=renderToStaticMarkup() - expect((html.match(/查看该快照/g)||[]).length).toBe(2) - expect(html).toContain('份文件') - }) +describe('SnapshotHistoryView', () => { + it('lists snapshot history, flags head and opens a historical snapshot read-only', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('历史快照') + expect(html).toContain('当前') + expect(html).toContain('只读') + expect(html).toContain('手册.pdf') + expect(html).toContain('内容Hash') + expect(html).toContain('abababababab') + // hash is displayable but never turns into an interactive policy checkbox/button + expect(html).not.toContain('checkbox') + expect(html).not.toContain('policy-button') + }) + it('shows 内容Hash未获取 instead of faking a hash', () => { + const missing = { ...page, items: [{ ...fileNode, content_sha256: undefined }] } + const html = renderToStaticMarkup( + + ) + expect(html).toContain('内容Hash未获取') + }) + it('lists snapshots without an active page and offers opening each one', () => { + const html = renderToStaticMarkup( + + ) + expect((html.match(/查看该快照/g) || []).length).toBe(2) + expect(html).toContain('份文件') + }) }) diff --git a/web/src/SnapshotHistory.tsx b/web/src/SnapshotHistory.tsx index 4ff1513..71e9ef1 100644 --- a/web/src/SnapshotHistory.tsx +++ b/web/src/SnapshotHistory.tsx @@ -1,32 +1,107 @@ import type { CatalogNodePage, CatalogSnapshot } from './sourceCatalog' import './sourceCatalogBrowser.css' -const stamp=(value:string)=>new Date(value).toLocaleString('zh-CN',{hour12:false}) -const shortHash=(value:string)=>`${value.slice(0,12)}…${value.slice(-8)}` +const stamp = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false }) +const shortHash = (value: string) => `${value.slice(0, 12)}…${value.slice(-8)}` -interface Props{snapshots:CatalogSnapshot[];active:CatalogSnapshot|null;page:CatalogNodePage|null;loading:boolean;error:string|null - onClose:()=>void;onOpenSnapshot:(snapshot:CatalogSnapshot)=>void;onOpenFolder:(snapshot:CatalogSnapshot,nodeID:string)=>void} - -export function SnapshotHistoryView({snapshots,active,page,loading,error,onClose,onOpenSnapshot,onOpenFolder}:Props){ - return
    -

    历史快照

    只读查看不可变快照;切换查看不会改变当前生效版本。

    - {error?
    {error}
    :null} -
      {snapshots.map(snapshot=>
    • -
      {stamp(snapshot.observed_at)}{snapshot.is_head?当前:null}{snapshot.node_count} 个节点 · {snapshot.file_count} 份文件 · 入库 {stamp(snapshot.created_at)}
      - -
    • )}
    - {loading?
    正在读取历史快照目录…
    :null} - {active&&page?
    {active.source_name}只读历史快照
    - - {page.items.map(node=> - - - - - - )}
    名称类型大小更新时间内容Hash
    {node.node_type==='folder'?:<>📄 {node.name}}{node.node_type==='folder'?'文件夹':'文件'}{typeof node.size_bytes==='number'?`${node.size_bytes} B`:'—'}{node.modified_at?stamp(node.modified_at):'—'}{node.content_sha256?shortHash(node.content_sha256):'内容Hash未获取'}
    - {page.total>page.limit?

    共 {page.total} 项 · 每页 {page.limit} 项

    :null} -
    :null} - {!loading&&active&&!page&&!error?
    该快照暂无可见内容。
    :null} -
    +interface Props { + snapshots: CatalogSnapshot[] + active: CatalogSnapshot | null + page: CatalogNodePage | null + loading: boolean + error: string | null + onClose: () => void + onOpenSnapshot: (snapshot: CatalogSnapshot) => void + onOpenFolder: (snapshot: CatalogSnapshot, nodeID: string) => void +} + +export function SnapshotHistoryView({ + snapshots, + active, + page, + loading, + error, + onClose, + onOpenSnapshot, + onOpenFolder, +}: Props) { + return ( +
    +
    +

    历史快照

    +

    只读查看不可变快照;切换查看不会改变当前生效版本。

    + +
    + {error ? ( +
    + {error} +
    + ) : null} +
      + {snapshots.map((snapshot) => ( +
    • +
      + {stamp(snapshot.observed_at)} + {snapshot.is_head ? 当前 : null} + + {snapshot.node_count} 个节点 · {snapshot.file_count} 份文件 · 入库 {stamp(snapshot.created_at)} + +
      + +
    • + ))} +
    + {loading ?
    正在读取历史快照目录…
    : null} + {active && page ? ( +
    +
    + {active.source_name} + 只读历史快照 +
    + + + + + + + + + + + + {page.items.map((node) => ( + + + + + + + + ))} + +
    名称类型大小更新时间内容Hash
    + {node.node_type === 'folder' ? ( + + ) : ( + <>📄 {node.name} + )} + {node.node_type === 'folder' ? '文件夹' : '文件'}{typeof node.size_bytes === 'number' ? `${node.size_bytes} B` : '—'}{node.modified_at ? stamp(node.modified_at) : '—'}{node.content_sha256 ? shortHash(node.content_sha256) : '内容Hash未获取'}
    + {page.total > page.limit ? ( +

    + + 共 {page.total} 项 · 每页 {page.limit} 项 + +

    + ) : null} +
    + ) : null} + {!loading && active && !page && !error ?
    该快照暂无可见内容。
    : null} +
    + ) } diff --git a/web/src/SourceCatalogBrowser.focus.test.tsx b/web/src/SourceCatalogBrowser.focus.test.tsx new file mode 100644 index 0000000..ccd7cbe --- /dev/null +++ b/web/src/SourceCatalogBrowser.focus.test.tsx @@ -0,0 +1,155 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import type { Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { SourceCatalogBrowser } from './SourceCatalogBrowser' +import type { CatalogNode, CatalogSource } from './sourceCatalog' + +// F14:定位是“一次性导航请求”。旧请求不得在目录刷新/来源重载时重放, +// 手工换目录后必须留在原地;新的显式请求仍要能定位。 +const source: CatalogSource = { + connection_id: 'conn-atom', + source_type: 'dingtalk', + name: 'ATOM知识库', + root_node_id: 'root-1', + folder_count: 2, + file_count: 2, + observed_at: '2026-11-05T00:00:00Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 0, +} +const node = (id: string, name: string, type: 'folder' | 'file', parent: string): CatalogNode => ({ + node_id: id, + parent_node_id: parent, + node_type: type, + name, + direct_child_count: type === 'folder' ? 1 : 0, + subtree_file_count: 1, + subtree_bytes: 1024, + size_bytes: type === 'file' ? 1024 : undefined, + visibility: 'internal', + imported_count: type === 'file' ? 1 : 0, + parsed_count: type === 'file' ? 1 : 0, + active_count: 0, + failed_count: 0, + routable_count: 1, +}) +const page = (parent: string) => { + const crumbs = + parent === 'root-1' + ? [{ node_id: 'root-1', name: 'ATOM知识库' }] + : [ + { node_id: 'root-1', name: 'ATOM知识库' }, + { node_id: parent, name: parent === 'folder-1' ? '售后机器出厂问题整改' : '常见问题汇总' }, + ] + return { + current: node(parent, crumbs[crumbs.length - 1].name, 'folder', parent === 'root-1' ? '' : 'root-1'), + breadcrumbs: crumbs, + items: + parent === 'root-1' + ? [ + node('folder-1', '售后机器出厂问题整改', 'folder', 'root-1'), + node('folder-2', '常见问题汇总', 'folder', 'root-1'), + ] + : [node(parent === 'folder-1' ? 'file-1' : 'file-2', '人形常见问题.adoc', 'file', parent)], + total: 1, + limit: 50, + offset: 0, + } +} + +let container: HTMLDivElement +let root: Root +let requested: string[] +const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200 }) + +beforeEach(() => { + ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + requested = [] + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input), 'http://localhost') + if (url.pathname === '/api/v1/source-catalog/sources') return json({ data: [source] }) + if (url.pathname === '/api/v1/source-catalog/routing-capabilities') + return json({ data: { internal_enabled: true, external_enabled: true } }) + if (url.pathname === '/api/v1/source-catalog/nodes') { + const parent = url.searchParams.get('parent_id') || '' + requested.push(parent) + return json(page(parent)) + } + if (url.pathname === '/api/v1/jobs') return json({ data: [] }) + if (url.pathname === '/api/v1/source-catalog/route') + return json({ + data: { + selected_files: 1, + intents_recorded: 1, + fetch_queued: 1, + planned_publications: 1, + blocked_items: 0, + unbound_files: 0, + }, + }) + return new Response('{}', { status: 404 }) + }) + ) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + vi.unstubAllGlobals() +}) + +const settle = async () => { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +describe('one-shot source location', () => { + it('keeps the manually chosen directory when the old request is re-rendered', async () => { + const focus = { connectionID: 'conn-atom', nodeID: 'folder-1' } + const applied = vi.fn() + await act(async () => root.render()) + await settle() + expect(applied).toHaveBeenCalledTimes(1) + expect(requested.at(-1)).toBe('folder-1') + + // 用户手工返回根目录并进入另一个目录(不经过新旧定位请求)。 + const back = [...container.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === '返回上一级') + await act(async () => back?.click()) + await settle() + const other = [...container.querySelectorAll('button')].find((b) => b.textContent?.includes('常见问题汇总')) + await act(async () => other?.click()) + await settle() + expect(requested.at(-1)).toBe('folder-2') + + // 在当前目录保存一次策略:revision 会让 sources 重新加载,旧 focus 不得重放。 + const checkbox = container.querySelector('input[aria-label="选择人形常见问题.adoc"]') as HTMLInputElement | null + await act(async () => checkbox?.click()) + const route = [...container.querySelectorAll('button')].find((b) => b.textContent === '对内') + await act(async () => route?.click()) + await settle() + expect(requested.at(-1)).toBe('folder-2') + + // 同一旧请求对象因父重渲染再次传入(模拟 revision/sources 刷新):不得拽回 folder-1。 + await act(async () => root.render()) + await settle() + expect(requested.at(-1)).toBe('folder-2') + + // 新的显式定位请求必须仍然有效。 + const next = { connectionID: 'conn-atom', nodeID: 'folder-1' } + await act(async () => root.render()) + await settle() + expect(requested.at(-1)).toBe('folder-1') + expect(applied).toHaveBeenCalledTimes(2) + }) +}) diff --git a/web/src/SourceCatalogBrowser.locator.test.tsx b/web/src/SourceCatalogBrowser.locator.test.tsx new file mode 100644 index 0000000..4d53023 --- /dev/null +++ b/web/src/SourceCatalogBrowser.locator.test.tsx @@ -0,0 +1,96 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import type { Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { SourceCatalogBrowserView } from './SourceCatalogBrowser' +import type { CatalogNode, CatalogNodePage, CatalogSource } from './sourceCatalog' + +// F14 的界面入口:已导入的文件能从这里直接跳到解析监控(不再靠手抄文件名)。 +const source: CatalogSource = { + connection_id: 'conn-atom', + source_type: 'dingtalk', + name: 'ATOM知识库', + root_node_id: 'root-1', + folder_count: 1, + file_count: 1, + observed_at: '2026-10-26T10:41:01Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 0, +} +const file: CatalogNode = { + node_id: 'node-atom-file', + parent_node_id: 'node-atom-folder', + node_type: 'file', + name: '末端航插线序问题.adoc.docx', + direct_child_count: 0, + subtree_file_count: 1, + subtree_bytes: 1024, + size_bytes: 1024, + visibility: 'internal', + imported_count: 1, + parsed_count: 1, + active_count: 0, + failed_count: 0, + routable_count: 1, +} +const page: CatalogNodePage = { + current: { + ...file, + node_id: 'node-atom-folder', + node_type: 'folder', + name: '售后机器出厂问题整改', + parent_node_id: undefined, + }, + breadcrumbs: [ + { node_id: 'root-1', name: 'ATOM知识库' }, + { node_id: 'node-atom-folder', name: '售后机器出厂问题整改' }, + ], + items: [file], + total: 1, + limit: 50, + offset: 0, +} + +let container: HTMLDivElement +let root: Root +beforeEach(() => { + ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) +afterEach(() => { + act(() => root.unmount()) + container.remove() +}) + +describe('source directory to processing handoff', () => { + it('offers 查看处理 for an imported file and passes the exact node identity', () => { + const onViewProcessing = vi.fn() + act(() => + root.render( + + ) + ) + const button = [...container.querySelectorAll('button')].find((item) => item.textContent === '查看处理') + expect(button).toBeTruthy() + act(() => button?.click()) + expect(onViewProcessing).toHaveBeenCalledWith(file) + }) +}) diff --git a/web/src/SourceCatalogBrowser.refreshState.test.tsx b/web/src/SourceCatalogBrowser.refreshState.test.tsx new file mode 100644 index 0000000..5087af2 --- /dev/null +++ b/web/src/SourceCatalogBrowser.refreshState.test.tsx @@ -0,0 +1,100 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import type { Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { SourceCatalogBrowserView } from './SourceCatalogBrowser' +import type { CatalogSource } from './sourceCatalog' +import type { Job } from './jobs' + +// F16 的挂载级回归:同一个组件从 running 走到 failed/completed, +// 终态不能残留“后台运行”,失败要能看到时间/旧快照/原因/作业号并可重试。 +const source: CatalogSource = { + connection_id: 'conn-atom', + source_type: 'dingtalk', + name: 'ATOM知识库', + root_node_id: 'root-1', + folder_count: 1, + file_count: 191, + observed_at: '2026-10-26T10:41:01Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 12000, +} + +const job = (state: Job['state'], extra: Partial = {}): Job => ({ + id: 'job-6e18ea86dce10d5472978573a4022a1a', + type: 'source.catalog.refresh', + payload: { connection_id: 'conn-atom', progress: 0, stage: 'queued', message: '等待后台刷新' }, + state, + priority: 0, + available_at: '2026-11-04T14:00:00Z', + attempt: 3, + max_attempts: 3, + last_error: 'ModuleNotFoundError: dws_dingtalk_scan', + idempotency_key: 'source.catalog.refresh:conn-atom', + created_at: '2026-11-04T14:00:00Z', + updated_at: '2026-11-04T14:03:30Z', + ...extra, +}) + +let container: HTMLDivElement +let root: Root +const render = (refreshJob: Job) => + act(() => + root.render( + + ) + ) + +beforeEach(() => { + ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() +}) + +describe('SourceCatalogBrowser refresh terminal states', () => { + it('drops the background-running text when the same card turns failed', () => { + render(job('running')) + expect(container.textContent).toContain('后台运行') + render(job('failed')) + expect(container.textContent).not.toContain('后台运行') + expect(container.textContent).toContain('实时刷新失败') + expect(container.textContent).toContain('job-6e18ea86dce10d5472978573a4022a1a') + expect(container.textContent).toContain('旧快照') + expect(container.textContent).toContain('dws_dingtalk_scan') + const retry = [...container.querySelectorAll('button')].find((button) => button.textContent === '重试刷新') + expect(retry).toBeTruthy() + }) + + it('keeps the retry entry disabled while running and hides it when completed', () => { + render(job('running')) + const retryRunning = [...container.querySelectorAll('button')].find((button) => button.textContent === '重试刷新') + expect(retryRunning?.disabled).toBe(true) + render(job('completed', { last_error: '' })) + expect(container.textContent).not.toContain('后台运行') + expect([...container.querySelectorAll('button')].some((button) => button.textContent === '重试刷新')).toBe(false) + expect(container.textContent).toContain('实时快照已完成') + }) +}) diff --git a/web/src/SourceCatalogBrowser.test.tsx b/web/src/SourceCatalogBrowser.test.tsx index c5d7610..e6d76be 100644 --- a/web/src/SourceCatalogBrowser.test.tsx +++ b/web/src/SourceCatalogBrowser.test.tsx @@ -1,141 +1,535 @@ import { renderToStaticMarkup } from 'react-dom/server' -import { describe,expect,it,vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { SourceCatalogBrowserView } from './SourceCatalogBrowser' -import type { CatalogNode,CatalogNodePage,CatalogSource } from './sourceCatalog' +import type { CatalogNode, CatalogNodePage, CatalogSource } from './sourceCatalog' import type { Job } from './jobs' -const source:CatalogSource={connection_id:'conn-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:1080,file_count:3468,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:12000} -const node=(name:string,type:'folder'|'file',id:string)=>({node_id:id,parent_node_id:'root-1',node_type:type,name,direct_child_count:type==='folder'?2:0,subtree_file_count:type==='folder'?10:1,subtree_bytes:1024,size_bytes:type==='file'?1024:undefined,visibility:type==='folder'?'internal' as const:'unknown' as const,imported_count:type==='folder'?8:0,parsed_count:type==='folder'?7:0,active_count:1,failed_count:0,routable_count:type==='file'?1:8}) -const page:CatalogNodePage={current:{...node('公司级技术支持知识库','folder','root-1'),parent_node_id:undefined},breadcrumbs:[{node_id:'root-1',name:'公司级技术支持知识库'}],items:[node('01|产品总览与定位','folder','folder-1'),node('根目录说明.pdf','file','file-1')],total:2,limit:50,offset:0} - -describe('SourceCatalogBrowserView',()=>{ - - it('shows a source that is still doing its first scan, with progress',()=>{ - const scanning:CatalogSource={...source,connection_id:'conn-scan',name:'公司级营销资料管理',root_node_id:'',folder_count:1153,file_count:1428,snapshot_status:'scanning',scan_progress:36,scan_message:'正在扫描目录:已完成 470 个文件夹,待处理 683 个',last_refresh_duration_ms:0} - const html=renderToStaticMarkup() - // 新来源不必等快照落地就出现在列表里,并且带百分比。 - for(const text of ['公司级营销资料管理','首次扫描中 36%','首次扫描中 · 36%','正在扫描目录:已完成 470 个文件夹,待处理 683 个','已发现约 1428 份文件'])expect(html).toContain(text) - // 还没有目录:不渲染空目录、也不提供标注/格式筛选入口。 - expect(html).not.toContain('当前目录为空。') - expect(html).not.toContain('禁止导入') - }) - - it('uses a Windows-style path bar instead of a directory tree',()=>{ - const html=renderToStaticMarkup() - expect(html).toContain('aria-label="当前目录路径"') - expect(html).toContain('aria-label="目录面包屑"') - expect(html).toContain('aria-label="返回上一级"') - expect(html).not.toContain('role="tree"') - expect(html).not.toContain('目录树') - for(const text of ['禁止导入即生效','大小','大小未提供','总大小','已知合计'])expect(html).not.toContain(text) - expect(html).toContain('
    ') - expect(html).toContain('文件格式筛选') - expect(html).not.toMatch(/]*class="catalog-format-filter"[^>]*open/) - }) - - it('looks like a folder browser and shows only direct children',()=>{ - const html=renderToStaticMarkup() - for(const text of ['各个知识源头的资料总览与标注','公司级技术支持知识库','01|产品总览与定位','文件夹','已解析 7 / 已导入 8','本地只读快照','含所有子目录文件'])expect(html).toContain(text) - expect(html).not.toContain('真实目录') - expect(html).toContain('根目录说明.pdf') - expect(html).not.toContain('显示根目录文件') - expect(html).toContain('aria-label="当前目录路径"') - expect(html).not.toContain('第 1 / 1 页') - expect(html).not.toContain('PP分类 · 不代表完整原始目录') - expect(html).toContain('快照时间') - expect(html).toContain('快照就绪') - expect(html).toContain('上次刷新耗时 12秒') - expect(html).toContain('实时刷新目录') - expect(html).not.toContain('aria-label="处理策略01|产品总览与定位"') - expect(html).not.toContain('递归作用于全部子目录') - }) - it('shows current directory, discovered file counts and the estimate marker during refresh',()=>{ - const job:Job={id:'job-scan',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'scanning',progress:43,message:'正在扫描目录:已完成 125 个文件夹,待处理 55 个',processed:125,total:180,current_directory:'产品资料/CR系列',scanned_files:2438,estimated_total_files:5662,total_is_estimate:true},state:'running',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:1,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'} - const html=renderToStaticMarkup() - expect(html).toContain('当前目录:产品资料/CR系列') - expect(html).toContain('已发现 2438 份文件') - expect(html).toContain('(估算)') - }) - it('hides the running refresh to a compact pill that expands back on click without blocking browsing',()=>{ - const job:Job={id:'job-hide',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'scanning',progress:60,message:'正在扫描目录:已完成 1000 个文件夹',processed:1000,total:1339,current_directory:'产品资料/CR系列',scanned_files:2438},state:'running',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:1,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'} - const common={sources:[source],selectedSource:source,page,loading:false,error:null,refreshJob:job,onSelectSource:vi.fn(),onOpenFolder:vi.fn(),onNavigateTo:vi.fn(),onBack:vi.fn(),onPageChange:vi.fn(),onRefresh:vi.fn()} - const full=renderToStaticMarkup() - expect(full).toContain('隐藏到后台') - expect(full).toContain('实时快照进度') - expect(full).toContain('产品资料/CR系列') - const hidden=renderToStaticMarkup() - expect(hidden).not.toContain('实时快照进度') - expect(hidden).toContain('catalog-refresh-pill') - expect(hidden).toContain('60%') - expect(hidden).toContain('公司级技术支持知识库') // pill still names the source - // browsing and annotation stay interactive in hidden mode (only a duplicate refresh is blocked) - expect(hidden).toContain('aria-label="选择01|产品总览与定位"') - expect(hidden).toContain('aria-label="选择根目录说明.pdf"') - expect(hidden).toContain('全选当前页') - expect(hidden).toContain('实时刷新中…') - }) - it('announces failure safely and keeps old snapshot usable',()=>{ - const job:Job={id:'job-fail',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'failed',progress:0,message:'AList API Token 未配置,请联系管理员更新来源凭据;旧快照仍然保留',processed:0,total:0},state:'failed',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:3,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'} - const html=renderToStaticMarkup() - expect(html).toContain('实时刷新失败') - expect(html).toContain('刷新失败;旧快照仍然保留,目录浏览与标注不受影响。') - expect(html).toContain('快照就绪') - expect(html).toContain('01|产品总览与定位') - }) - it('keeps the progress bar free of directory details when the scanner reports none',()=>{ - const job:Job={id:'job-plain',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'building',progress:80,message:'正在校验目录结构',processed:10,total:10},state:'running',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:1,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'} - const html=renderToStaticMarkup() - expect(html).toContain('正在校验目录结构') - expect(html).not.toContain('刷新明细') - }) - it('uses durable background refresh progress and the current stage message',()=>{ - const job:Job={id:'job-refresh',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'scanning',progress:50,message:'正在扫描目录:已完成 50 个',processed:50,total:100},state:'running',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:1,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'} - const html=renderToStaticMarkup() - expect(html).toContain('实时刷新中') - expect(html).toContain('正在扫描目录:已完成 50 个') - expect(html).toContain('value="50"') - }) - it('uses clickable breadcrumbs and an explicit back action below the source root',()=>{ - const nested={...page,current:{...page.current,node_id:'folder-1',parent_node_id:'root-1',name:'01|产品总览与定位'},breadcrumbs:[...page.breadcrumbs,{node_id:'folder-1',name:'01|产品总览与定位'}]} - const html=renderToStaticMarkup() - expect(html).toContain('aria-label="返回上一级"') - expect(html).toContain('公司级技术支持知识库') - expect(html).toContain('01|产品总览与定位') - }) - it('shows policy as a read-only table state and offers top-level policy buttons',()=>{ - const nested={...page,current:{...page.current,node_id:'folder-1',parent_node_id:'root-1',name:'01|产品总览与定位'},breadcrumbs:[...page.breadcrumbs,{node_id:'folder-1',name:'01|产品总览与定位'}],items:[node('可入队.pdf','file','file-ready'),node('已知目录','folder','folder-known'),{...node('大小未知目录','folder','folder-unknown'),subtree_bytes:0},{...node('只有元数据.pdf','file','file-meta'),size_bytes:undefined,routable_count:0}],total:4} - const html=renderToStaticMarkup() - for(const text of ['名称','处理策略','全选当前页','对内','对外','禁止导入','aria-label="选择可入队.pdf"'])expect(html).toContain(text) - for(const text of ['class="catalog-policy-actions"','class="internal-policy-button"','class="external-policy-button"','class="blocked-policy-button"','class="selected-count"'])expect(html).toContain(text) - for(const text of ['操作人','判断原因','名称与处理策略','当前策略','选择策略','批量处理策略','应用策略','对内 + 对外','{ - const nested={...page,current:{...page.current,node_id:'folder-1'},breadcrumbs:[...page.breadcrumbs,{node_id:'folder-1',name:'01|产品总览与定位'}],items:[node('可入队.pdf','file','file-ready'),node('已知目录','folder','folder-known')],total:2} - const html=renderToStaticMarkup() - // exactly three top-level policy buttons: 对内 / 对外 / 禁止导入 (docs/SOURCE_SCOPE_POLICY.md rules 4-6) - expect((html.match(/class="[a-z-]+-policy-button"/g)||[]).length).toBe(3) - // rule 2: only current-page select-all exists - expect(html).toContain('全选当前页') - expect(html).not.toContain('递归全选') - // rule 1: both file and folder rows expose selection checkboxes - expect(html).toContain('aria-label="选择可入队.pdf"') - expect(html).toContain('aria-label="选择已知目录"') - // rules 5-6: no batch entry for historical 对内 + 对外 or for unset state - expect(html).not.toContain('对内 + 对外') - expect(html).not.toContain('批量未选择') - }) - it('lets an engineer select a directory without opening it',()=>{ - const html=renderToStaticMarkup() - expect(html).toContain('aria-label="选择01|产品总览与定位"') - }) - it('does not claim an empty source loaded when the request failed',()=>{ - const html=renderToStaticMarkup() - expect(html).toContain('加载失败') - expect(html).not.toContain('尚无来源目录') - }) +const source: CatalogSource = { + connection_id: 'conn-1', + source_type: 'dingtalk', + name: '公司级技术支持知识库', + root_node_id: 'root-1', + folder_count: 1080, + file_count: 3468, + observed_at: '2026-09-08T00:00:00Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 12000, +} +const node = (name: string, type: 'folder' | 'file', id: string) => ({ + node_id: id, + parent_node_id: 'root-1', + node_type: type, + name, + direct_child_count: type === 'folder' ? 2 : 0, + subtree_file_count: type === 'folder' ? 10 : 1, + subtree_bytes: 1024, + size_bytes: type === 'file' ? 1024 : undefined, + visibility: type === 'folder' ? ('internal' as const) : ('unknown' as const), + imported_count: type === 'folder' ? 8 : 0, + parsed_count: type === 'folder' ? 7 : 0, + active_count: 1, + failed_count: 0, + routable_count: type === 'file' ? 1 : 8, +}) +const page: CatalogNodePage = { + current: { ...node('公司级技术支持知识库', 'folder', 'root-1'), parent_node_id: undefined }, + breadcrumbs: [{ node_id: 'root-1', name: '公司级技术支持知识库' }], + items: [node('01|产品总览与定位', 'folder', 'folder-1'), node('根目录说明.pdf', 'file', 'file-1')], + total: 2, + limit: 50, + offset: 0, +} + +describe('SourceCatalogBrowserView', () => { + it('shows a source that is still doing its first scan, with progress', () => { + const scanning: CatalogSource = { + ...source, + connection_id: 'conn-scan', + name: '公司级营销资料管理', + root_node_id: '', + folder_count: 1153, + file_count: 1428, + snapshot_status: 'scanning', + scan_progress: 36, + scan_message: '正在扫描目录:已完成 470 个文件夹,待处理 683 个', + last_refresh_duration_ms: 0, + } + const html = renderToStaticMarkup( + + ) + // 新来源不必等快照落地就出现在列表里,并且带百分比。 + for (const text of [ + '公司级营销资料管理', + '首次扫描中 36%', + '首次扫描中 · 36%', + '正在扫描目录:已完成 470 个文件夹,待处理 683 个', + '已发现约 1428 份文件', + ]) + expect(html).toContain(text) + // 还没有目录:不渲染空目录、也不提供标注/格式筛选入口。 + expect(html).not.toContain('当前目录为空。') + expect(html).not.toContain('禁止导入') + }) + + it('uses a Windows-style path bar instead of a directory tree', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('aria-label="当前目录路径"') + expect(html).toContain('aria-label="目录面包屑"') + expect(html).toContain('aria-label="返回上一级"') + expect(html).not.toContain('role="tree"') + expect(html).not.toContain('目录树') + for (const text of ['禁止导入即生效', '大小', '大小未提供', '总大小', '已知合计']) + expect(html).not.toContain(text) + expect(html).toContain('
    ') + expect(html).toContain('文件格式筛选') + expect(html).not.toMatch(/]*class="catalog-format-filter"[^>]*open/) + }) + + it('looks like a folder browser and shows only direct children', () => { + const html = renderToStaticMarkup( + + ) + for (const text of [ + '各个知识源头的资料总览与标注', + '公司级技术支持知识库', + '01|产品总览与定位', + '文件夹', + '已解析 7 / 已导入 8', + '本地只读快照', + '含所有子目录文件', + ]) + expect(html).toContain(text) + expect(html).not.toContain('真实目录') + expect(html).toContain('根目录说明.pdf') + expect(html).not.toContain('显示根目录文件') + expect(html).toContain('aria-label="当前目录路径"') + expect(html).not.toContain('第 1 / 1 页') + expect(html).not.toContain('PP分类 · 不代表完整原始目录') + expect(html).toContain('快照时间') + expect(html).toContain('快照就绪') + expect(html).toContain('上次刷新耗时 12秒') + expect(html).toContain('实时刷新目录') + expect(html).not.toContain('aria-label="处理策略01|产品总览与定位"') + expect(html).not.toContain('递归作用于全部子目录') + }) + it('shows current directory, discovered file counts and the estimate marker during refresh', () => { + const job: Job = { + id: 'job-scan', + type: 'source.catalog.refresh', + payload: { + connection_id: 'conn-1', + stage: 'scanning', + progress: 43, + message: '正在扫描目录:已完成 125 个文件夹,待处理 55 个', + processed: 125, + total: 180, + current_directory: '产品资料/CR系列', + scanned_files: 2438, + estimated_total_files: 5662, + total_is_estimate: true, + }, + state: 'running', + priority: 20, + available_at: '2026-09-09T00:00:00Z', + attempt: 1, + max_attempts: 3, + idempotency_key: 'safe', + created_at: '2026-09-09T00:00:00Z', + updated_at: '2026-09-09T00:00:00Z', + } + const html = renderToStaticMarkup( + + ) + expect(html).toContain('当前目录:产品资料/CR系列') + expect(html).toContain('已发现 2438 份文件') + expect(html).toContain('(估算)') + }) + it('hides the running refresh to a compact pill that expands back on click without blocking browsing', () => { + const job: Job = { + id: 'job-hide', + type: 'source.catalog.refresh', + payload: { + connection_id: 'conn-1', + stage: 'scanning', + progress: 60, + message: '正在扫描目录:已完成 1000 个文件夹', + processed: 1000, + total: 1339, + current_directory: '产品资料/CR系列', + scanned_files: 2438, + }, + state: 'running', + priority: 20, + available_at: '2026-09-09T00:00:00Z', + attempt: 1, + max_attempts: 3, + idempotency_key: 'safe', + created_at: '2026-09-09T00:00:00Z', + updated_at: '2026-09-09T00:00:00Z', + } + const common = { + sources: [source], + selectedSource: source, + page, + loading: false, + error: null, + refreshJob: job, + onSelectSource: vi.fn(), + onOpenFolder: vi.fn(), + onNavigateTo: vi.fn(), + onBack: vi.fn(), + onPageChange: vi.fn(), + onRefresh: vi.fn(), + } + const full = renderToStaticMarkup( + + ) + expect(full).toContain('隐藏到后台') + expect(full).toContain('实时快照进度') + expect(full).toContain('产品资料/CR系列') + const hidden = renderToStaticMarkup( + + ) + expect(hidden).not.toContain('实时快照进度') + expect(hidden).toContain('catalog-refresh-pill') + expect(hidden).toContain('60%') + expect(hidden).toContain('公司级技术支持知识库') // pill still names the source + // browsing and annotation stay interactive in hidden mode (only a duplicate refresh is blocked) + expect(hidden).toContain('aria-label="选择01|产品总览与定位"') + expect(hidden).toContain('aria-label="选择根目录说明.pdf"') + expect(hidden).toContain('全选当前页') + expect(hidden).toContain('实时刷新中…') + }) + it('announces failure safely and keeps old snapshot usable', () => { + const job: Job = { + id: 'job-fail', + type: 'source.catalog.refresh', + payload: { + connection_id: 'conn-1', + stage: 'failed', + progress: 0, + message: 'AList API Token 未配置,请联系管理员更新来源凭据;旧快照仍然保留', + processed: 0, + total: 0, + }, + state: 'failed', + priority: 20, + available_at: '2026-09-09T00:00:00Z', + attempt: 3, + max_attempts: 3, + idempotency_key: 'safe', + created_at: '2026-09-09T00:00:00Z', + updated_at: '2026-09-09T00:00:00Z', + } + const html = renderToStaticMarkup( + + ) + expect(html).toContain('实时刷新失败') + expect(html).toContain('刷新失败;旧快照仍然保留,目录浏览与标注不受影响。') + expect(html).toContain('快照就绪') + expect(html).toContain('01|产品总览与定位') + }) + it('keeps the progress bar free of directory details when the scanner reports none', () => { + const job: Job = { + id: 'job-plain', + type: 'source.catalog.refresh', + payload: { + connection_id: 'conn-1', + stage: 'building', + progress: 80, + message: '正在校验目录结构', + processed: 10, + total: 10, + }, + state: 'running', + priority: 20, + available_at: '2026-09-09T00:00:00Z', + attempt: 1, + max_attempts: 3, + idempotency_key: 'safe', + created_at: '2026-09-09T00:00:00Z', + updated_at: '2026-09-09T00:00:00Z', + } + const html = renderToStaticMarkup( + + ) + expect(html).toContain('正在校验目录结构') + expect(html).not.toContain('刷新明细') + }) + it('uses durable background refresh progress and the current stage message', () => { + const job: Job = { + id: 'job-refresh', + type: 'source.catalog.refresh', + payload: { + connection_id: 'conn-1', + stage: 'scanning', + progress: 50, + message: '正在扫描目录:已完成 50 个', + processed: 50, + total: 100, + }, + state: 'running', + priority: 20, + available_at: '2026-09-09T00:00:00Z', + attempt: 1, + max_attempts: 3, + idempotency_key: 'safe', + created_at: '2026-09-09T00:00:00Z', + updated_at: '2026-09-09T00:00:00Z', + } + const html = renderToStaticMarkup( + + ) + expect(html).toContain('实时刷新中') + expect(html).toContain('正在扫描目录:已完成 50 个') + expect(html).toContain('value="50"') + }) + it('uses clickable breadcrumbs and an explicit back action below the source root', () => { + const nested = { + ...page, + current: { ...page.current, node_id: 'folder-1', parent_node_id: 'root-1', name: '01|产品总览与定位' }, + breadcrumbs: [...page.breadcrumbs, { node_id: 'folder-1', name: '01|产品总览与定位' }], + } + const html = renderToStaticMarkup( + + ) + expect(html).toContain('aria-label="返回上一级"') + expect(html).toContain('公司级技术支持知识库') + expect(html).toContain('01|产品总览与定位') + }) + it('shows policy as a read-only table state and offers top-level policy buttons', () => { + const nested = { + ...page, + current: { ...page.current, node_id: 'folder-1', parent_node_id: 'root-1', name: '01|产品总览与定位' }, + breadcrumbs: [...page.breadcrumbs, { node_id: 'folder-1', name: '01|产品总览与定位' }], + items: [ + node('可入队.pdf', 'file', 'file-ready'), + node('已知目录', 'folder', 'folder-known'), + { ...node('大小未知目录', 'folder', 'folder-unknown'), subtree_bytes: 0 }, + { ...node('只有元数据.pdf', 'file', 'file-meta'), size_bytes: undefined, routable_count: 0 }, + ], + total: 4, + } + const html = renderToStaticMarkup( + + ) + for (const text of ['名称', '处理策略', '全选当前页', '对内', '对外', '禁止导入', 'aria-label="选择可入队.pdf"']) + expect(html).toContain(text) + for (const text of [ + 'class="catalog-policy-actions"', + 'class="internal-policy-button"', + 'class="external-policy-button"', + 'class="blocked-policy-button"', + 'class="selected-count"', + ]) + expect(html).toContain(text) + for (const text of [ + '操作人', + '判断原因', + '名称与处理策略', + '当前策略', + '选择策略', + '批量处理策略', + '应用策略', + '对内 + 对外', + ' { + const nested = { + ...page, + current: { ...page.current, node_id: 'folder-1' }, + breadcrumbs: [...page.breadcrumbs, { node_id: 'folder-1', name: '01|产品总览与定位' }], + items: [node('可入队.pdf', 'file', 'file-ready'), node('已知目录', 'folder', 'folder-known')], + total: 2, + } + const html = renderToStaticMarkup( + + ) + // exactly three top-level policy buttons: 对内 / 对外 / 禁止导入 (docs/SOURCE_SCOPE_POLICY.md rules 4-6) + expect((html.match(/class="[a-z-]+-policy-button"/g) || []).length).toBe(3) + // rule 2: only current-page select-all exists + expect(html).toContain('全选当前页') + expect(html).not.toContain('递归全选') + // rule 1: both file and folder rows expose selection checkboxes + expect(html).toContain('aria-label="选择可入队.pdf"') + expect(html).toContain('aria-label="选择已知目录"') + // rules 5-6: no batch entry for historical 对内 + 对外 or for unset state + expect(html).not.toContain('对内 + 对外') + expect(html).not.toContain('批量未选择') + }) + it('lets an engineer select a directory without opening it', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('aria-label="选择01|产品总览与定位"') + }) + it('does not claim an empty source loaded when the request failed', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('加载失败') + expect(html).not.toContain('尚无来源目录') + }) }) diff --git a/web/src/SourceCatalogBrowser.tsx b/web/src/SourceCatalogBrowser.tsx index 5eec0fd..965bfa7 100644 --- a/web/src/SourceCatalogBrowser.tsx +++ b/web/src/SourceCatalogBrowser.tsx @@ -1,6 +1,20 @@ -import { useContext,useEffect,useState } from 'react' -import { fetchCatalogNodes,fetchCatalogRoutingCapabilities,fetchCatalogSnapshotNodes,fetchCatalogSnapshots,fetchCatalogSources,routeCatalogFiles } from './sourceCatalog' -import type { CatalogNode,CatalogNodePage,CatalogPolicy,CatalogRoutingCapabilities,CatalogSnapshot,CatalogSource } from './sourceCatalog' +import { useContext, useEffect, useRef, useState } from 'react' +import { + fetchCatalogNodes, + fetchCatalogRoutingCapabilities, + fetchCatalogSnapshotNodes, + fetchCatalogSnapshots, + fetchCatalogSources, + routeCatalogFiles, +} from './sourceCatalog' +import type { + CatalogNode, + CatalogNodePage, + CatalogPolicy, + CatalogRoutingCapabilities, + CatalogSnapshot, + CatalogSource, +} from './sourceCatalog' import { SnapshotHistoryView } from './SnapshotHistory' import { triggerCatalogRefresh } from './sourceCatalog' import { fetchJobs } from './jobs' @@ -9,113 +23,811 @@ import { WorkspaceContextTabsSetter } from './workspaceContext' import { FilenameFilterEditor } from './FilenameFilterEditor' import './sourceCatalogBrowser.css' -const sourceLabels:Record={dingtalk:'钉钉知识库',pp:'PP资料下载中心',alist:'AList文件源'} -const duration=(milliseconds:number)=>milliseconds<=0?'未记录':milliseconds<1000?`${milliseconds}毫秒`:milliseconds<60000?`${Math.round(milliseconds/1000)}秒`:`${Math.floor(milliseconds/60000)}分${Math.round(milliseconds%60000/1000)}秒` -const scope=(value:string)=>value==='internal'?'对内':value==='external'?'对外':value==='both'?'对内 + 对外':value==='blocked'?'禁止导入':value==='mixed'?'混合':'未选择' -const progress=(node:CatalogNode)=>node.imported_count?`已解析 ${node.parsed_count} / 已导入 ${node.imported_count}`:'尚未导入' +const sourceLabels: Record = { dingtalk: '钉钉知识库', pp: 'PP资料下载中心', alist: 'AList文件源' } +const duration = (milliseconds: number) => + milliseconds <= 0 + ? '未记录' + : milliseconds < 1000 + ? `${milliseconds}毫秒` + : milliseconds < 60000 + ? `${Math.round(milliseconds / 1000)}秒` + : `${Math.floor(milliseconds / 60000)}分${Math.round((milliseconds % 60000) / 1000)}秒` +const scope = (value: string) => + value === 'internal' + ? '对内' + : value === 'external' + ? '对外' + : value === 'both' + ? '对内 + 对外' + : value === 'blocked' + ? '禁止导入' + : value === 'mixed' + ? '混合' + : '未选择' +const progress = (node: CatalogNode) => + node.imported_count ? `已解析 ${node.parsed_count} / 已导入 ${node.imported_count}` : '尚未导入' +const time = (value?: string) => (value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '未记录') +// 失败原因可能带来源地址或凭据路径;界面只展示脱敏摘要,详细值留在作业表。 +const sanitizeRefreshReason = (value?: string) => + (value || '') + .replace(/https?:\/\/\S+/g, '[地址已隐藏]') + .replace(/\/run\/source-secrets\/\S+/g, '[凭据路径已隐藏]') + .replace(/\b(?:token|api[-_]?key|password|authorization|cookie|secret)=\S+/gi, '[凭据已隐藏]') + .slice(0, 160) -interface ViewProps{ - sources:CatalogSource[];selectedSource:CatalogSource|null;page:CatalogNodePage|null;loading:boolean;error:string|null - routingCapabilities?:CatalogRoutingCapabilities;routingMessage?:string;routingLoading?:boolean - refreshJob?:Job|null - onSelectSource:(source:CatalogSource)=>void;onOpenFolder:(node:CatalogNode)=>void;onNavigateTo:(nodeID:string)=>void;onBack:()=>void;onPageChange:(offset:number)=>void;onRefresh:()=>void;onRoute?:(nodeIDs:string[],policy:CatalogPolicy)=>Promise - history?:{open:boolean;snapshots:CatalogSnapshot[];active:CatalogSnapshot|null;page:CatalogNodePage|null;loading:boolean;error:string|null;onOpen:()=>void;onClose:()=>void;onOpenSnapshot:(snapshot:CatalogSnapshot)=>void;onOpenFolder:(snapshot:CatalogSnapshot,nodeID:string)=>void} - refreshHidden?:boolean;onToggleRefreshHidden?:()=>void;onFiltersChanged?:()=>void +interface ViewProps { + sources: CatalogSource[] + selectedSource: CatalogSource | null + page: CatalogNodePage | null + loading: boolean + error: string | null + routingCapabilities?: CatalogRoutingCapabilities + routingMessage?: string + routingLoading?: boolean + refreshJob?: Job | null + onSelectSource: (source: CatalogSource) => void + onOpenFolder: (node: CatalogNode) => void + onNavigateTo: (nodeID: string) => void + onBack: () => void + onPageChange: (offset: number) => void + onRefresh: () => void + onRoute?: (nodeIDs: string[], policy: CatalogPolicy) => Promise + history?: { + open: boolean + snapshots: CatalogSnapshot[] + active: CatalogSnapshot | null + page: CatalogNodePage | null + loading: boolean + error: string | null + onOpen: () => void + onClose: () => void + onOpenSnapshot: (snapshot: CatalogSnapshot) => void + onOpenFolder: (snapshot: CatalogSnapshot, nodeID: string) => void + } + refreshHidden?: boolean + onToggleRefreshHidden?: () => void + onFiltersChanged?: () => void + onViewProcessing?: (node: CatalogNode) => void } -export function SourceCatalogBrowserView({sources,selectedSource,page,loading,error,routingCapabilities={internal_enabled:false,external_enabled:false},routingMessage='',routingLoading=false,refreshJob=null,onSelectSource,onOpenFolder,onNavigateTo,onBack,onPageChange,onRefresh,onRoute=async()=>false,history,refreshHidden=false,onToggleRefreshHidden,onFiltersChanged}:ViewProps){ - const [selectedIDs,setSelectedIDs]=useState([]) - const [appliedPolicies,setAppliedPolicies]=useState>({}) - const atSourceRoot=Boolean(page&&page.breadcrumbs.length===1) - const visibleItems=page?.items||[] - useEffect(()=>{setSelectedIDs([]);setAppliedPolicies({})},[selectedSource?.connection_id,page?.current.node_id]) - useEffect(()=>{if(routingMessage)setSelectedIDs([])},[routingMessage]) - const selectableNodes=visibleItems - const selectedNodeIDs=selectedIDs - const selectedCount=selectedIDs.length - const routeReady=!routingLoading - const policyEnabled=(policy:CatalogPolicy)=>policy==='blocked'||policy==='both'?(policy==='blocked'||routingCapabilities.internal_enabled&&routingCapabilities.external_enabled):policy==='internal'?routingCapabilities.internal_enabled:routingCapabilities.external_enabled - const toggleNode=(id:string)=>setSelectedIDs(current=>current.includes(id)?current.filter(value=>value!==id):[...current,id]) - const applyPolicy=async(policy:CatalogPolicy)=>{if(!selectedNodeIDs.length)return;const changed=await onRoute(selectedNodeIDs,policy);if(changed)setAppliedPolicies(current=>({...current,...Object.fromEntries(selectedNodeIDs.map(id=>[id,policy]))}))} - const refreshPayload=refreshJob?.payload&&typeof refreshJob.payload==='object'?refreshJob.payload as Record:{} - const refreshProgress=typeof refreshPayload.progress==='number'?refreshPayload.progress:0 - const refreshMessage=typeof refreshPayload.message==='string'?refreshPayload.message:'等待后台刷新' - const refreshDirectory=typeof refreshPayload.current_directory==='string'&&refreshPayload.current_directory?refreshPayload.current_directory:'' - const refreshFiles=typeof refreshPayload.scanned_files==='number'&&refreshPayload.scanned_files>0?refreshPayload.scanned_files:0 - const refreshEstimate=refreshPayload.total_is_estimate===true - const stageLabels:Record={queued:'排队中',connecting:'连接来源',scanning:'扫描目录',building:'构建快照',activating:'写入快照',completed:'完成',failed:'失败'} - const refreshStageLabel=typeof refreshPayload.stage==='string'?stageLabels[refreshPayload.stage]||refreshPayload.stage:'排队中' - const pillSource=typeof refreshPayload.source_name==='string'?refreshPayload.source_name:'' - const refreshPillSource=pillSource||selectedSource?.name||'' - const refreshActive=refreshJob?.state==='pending'||refreshJob?.state==='running'||refreshJob?.state==='retry' - return
    -

    来源与目录

    各个知识源头的资料总览与标注

    - {error?
    {error}
    :null} - {refreshJob&&refreshActive&&refreshHidden?:null} - {refreshJob&&!(refreshActive&&refreshHidden)?<>
    {refreshActive?'实时刷新中':refreshJob.state==='completed'?'实时快照已完成':'实时刷新失败'}{selectedSource?selectedSource.name+' · ':''}{refreshStageLabel}{refreshMessage}
    {refreshProgress}%{refreshEstimate?'(估算)':''} · 后台运行,可以切换页面{refreshActive&&onToggleRefreshHidden?:null}
    {refreshActive&&(refreshDirectory||refreshFiles)?
    {refreshDirectory?当前目录:{refreshDirectory}:null}{refreshFiles?已发现 {refreshFiles} 份文件:null}
    :null}{refreshJob.state==='failed'?

    刷新失败;旧快照仍然保留,目录浏览与标注不受影响。

    :null}:null} -
    - -
    - {selectedSource&&selectedSource.snapshot_status==='scanning'?
    -
    首次扫描中 · {selectedSource.scan_progress??0}%{selectedSource.name}
    - -

    {selectedSource.scan_message||'正在从源头扫描目录…'}

    - 已发现约 {selectedSource.file_count} 份文件(文件夹 {selectedSource.folder_count} 个)。扫完这一页会自动出现目录;现在可以先去做别的。 -
    :selectedSource&&page?<> -
    - - -
    -
    {page.current.name}{selectedSource.snapshot_only?'本地只读快照,不代表实时连接':'实时目录'}
    {atSourceRoot?`第一层目录 ${page.items.filter(node=>node.node_type==='folder').length}`:`当前子项 ${page.total}`}含所有子目录文件 {page.current.subtree_file_count}
    -
    - 文件格式筛选 - item.name).join('/')} label={atSourceRoot?'整个来源':'当前目录'} onChanged={onFiltersChanged} /> -
    +export function SourceCatalogBrowserView({ + sources, + selectedSource, + page, + loading, + error, + routingCapabilities = { internal_enabled: false, external_enabled: false }, + routingMessage = '', + routingLoading = false, + refreshJob = null, + onSelectSource, + onOpenFolder, + onNavigateTo, + onBack, + onPageChange, + onRefresh, + onRoute = async () => false, + history, + refreshHidden = false, + onToggleRefreshHidden, + onFiltersChanged, + onViewProcessing, +}: ViewProps) { + const [selectedIDs, setSelectedIDs] = useState([]) + const [appliedPolicies, setAppliedPolicies] = useState>({}) + const atSourceRoot = Boolean(page && page.breadcrumbs.length === 1) + const visibleItems = page?.items || [] + useEffect(() => { + setSelectedIDs([]) + setAppliedPolicies({}) + }, [selectedSource?.connection_id, page?.current.node_id]) + useEffect(() => { + if (routingMessage) setSelectedIDs([]) + }, [routingMessage]) + const selectableNodes = visibleItems + const selectedNodeIDs = selectedIDs + const selectedCount = selectedIDs.length + const routeReady = !routingLoading + const policyEnabled = (policy: CatalogPolicy) => + policy === 'blocked' || policy === 'both' + ? policy === 'blocked' || (routingCapabilities.internal_enabled && routingCapabilities.external_enabled) + : policy === 'internal' + ? routingCapabilities.internal_enabled + : routingCapabilities.external_enabled + const toggleNode = (id: string) => + setSelectedIDs((current) => (current.includes(id) ? current.filter((value) => value !== id) : [...current, id])) + const applyPolicy = async (policy: CatalogPolicy) => { + if (!selectedNodeIDs.length) return + const changed = await onRoute(selectedNodeIDs, policy) + if (changed) + setAppliedPolicies((current) => ({ + ...current, + ...Object.fromEntries(selectedNodeIDs.map((id) => [id, policy])), + })) + } + const refreshPayload = + refreshJob?.payload && typeof refreshJob.payload === 'object' ? (refreshJob.payload as Record) : {} + const refreshProgress = typeof refreshPayload.progress === 'number' ? refreshPayload.progress : 0 + const refreshMessage = typeof refreshPayload.message === 'string' ? refreshPayload.message : '等待后台刷新' + const refreshDirectory = + typeof refreshPayload.current_directory === 'string' && refreshPayload.current_directory + ? refreshPayload.current_directory + : '' + const refreshFiles = + typeof refreshPayload.scanned_files === 'number' && refreshPayload.scanned_files > 0 + ? refreshPayload.scanned_files + : 0 + const refreshEstimate = refreshPayload.total_is_estimate === true + const stageLabels: Record = { + queued: '排队中', + connecting: '连接来源', + scanning: '扫描目录', + building: '构建快照', + activating: '写入快照', + completed: '完成', + failed: '失败', + } + const refreshStageLabel = + typeof refreshPayload.stage === 'string' ? stageLabels[refreshPayload.stage] || refreshPayload.stage : '排队中' + const pillSource = typeof refreshPayload.source_name === 'string' ? refreshPayload.source_name : '' + const refreshPillSource = pillSource || selectedSource?.name || '' + const refreshActive = + refreshJob?.state === 'pending' || refreshJob?.state === 'running' || refreshJob?.state === 'retry' + return ( +
    +
    +
    +

    来源与目录

    +

    各个知识源头的资料总览与标注

    +
    + +
    + {error ? ( +
    + {error} +
    + ) : null} + {refreshJob && refreshActive && refreshHidden ? ( + + ) : null} + {refreshJob && !(refreshActive && refreshHidden) ? ( + <> +
    +
    + + {refreshActive ? '实时刷新中' : refreshJob.state === 'completed' ? '实时快照已完成' : '实时刷新失败'} + + + {selectedSource ? selectedSource.name + ' · ' : ''} + {refreshStageLabel} + + {refreshMessage} +
    + + + {refreshActive + ? `${refreshProgress}%${refreshEstimate ? '(估算)' : ''} · 后台运行,可以切换页面` + : refreshJob.state === 'completed' + ? `完成于 ${time(refreshJob.updated_at)}` + : `失败于 ${time(refreshJob.updated_at)} · 旧快照 ${time(selectedSource?.observed_at)}`} + + {refreshActive && onToggleRefreshHidden ? ( + + ) : null} + {refreshJob.state !== 'completed' ? ( + + ) : null} +
    + {refreshActive && (refreshDirectory || refreshFiles) ? ( +
    + {refreshDirectory ? 当前目录:{refreshDirectory} : null} + {refreshFiles ? 已发现 {refreshFiles} 份文件 : null} +
    + ) : null} + {refreshJob.state === 'failed' ? ( +

    + 刷新失败;旧快照仍然保留,目录浏览与标注不受影响。原因: + {sanitizeRefreshReason(refreshJob.last_error) || '未提供'} · 作业 {refreshJob.id} +

    + ) : null} + + ) : null} +
    + +
    + {selectedSource && selectedSource.snapshot_status === 'scanning' ? ( +
    +
    + 首次扫描中 · {selectedSource.scan_progress ?? 0}% + {selectedSource.name} +
    + +

    {selectedSource.scan_message || '正在从源头扫描目录…'}

    + + 已发现约 {selectedSource.file_count} 份文件(文件夹 {selectedSource.folder_count}{' '} + 个)。扫完这一页会自动出现目录;现在可以先去做别的。 + +
    + ) : selectedSource && page ? ( + <> +
    + + +
    +
    +
    + {page.current.name} + {selectedSource.snapshot_only ? '本地只读快照,不代表实时连接' : '实时目录'} +
    + + {atSourceRoot + ? `第一层目录 ${page.items.filter((node) => node.node_type === 'folder').length}` + : `当前子项 ${page.total}`} + + 含所有子目录文件 {page.current.subtree_file_count} +
    +
    + 文件格式筛选 + item.name) + .join('/')} + label={atSourceRoot ? '整个来源' : '当前目录'} + onChanged={onFiltersChanged} + /> +
    - {visibleItems.length?
    -
    - -
    已选 {selectedCount} 项
    + {visibleItems.length ? ( +
    +
    + + 已选 {selectedCount} 项 +
    + + + +
    +
    + {routingMessage ?

    {routingMessage}

    : null} +
    + ) : null} + {visibleItems.length ? ( +
    + + + + + + + + + + + + + {visibleItems.map((node) => { + const visibility = appliedPolicies[node.node_id] || node.visibility + return ( + + + + + + + + + ) + })} + +
    名称类型处理策略文件数量导入与解析更新时间
    + {node.node_type === 'folder' ? ( +
    + toggleNode(node.node_id)} + /> + +
    + ) : ( + + )} +
    {node.node_type === 'folder' ? '文件夹' : '文件'} +
    + {scope(visibility)} +
    +
    {node.node_type === 'folder' ? `${node.subtree_file_count} 份` : '—'} + {progress(node)} + {node.active_count ? 处理中 {node.active_count} : null} + {node.failed_count ? ( + 失败 {node.failed_count} + ) : null} + {onViewProcessing && node.node_type === 'file' && node.imported_count > 0 ? ( + + ) : null} + + {node.modified_at + ? new Date(node.modified_at).toLocaleString('zh-CN', { hour12: false }) + : '—'} +
    +
    + ) : ( +
    当前目录为空。
    + )} + {page.total > page.limit ? ( +
    + + 第 {Math.floor(page.offset / page.limit) + 1} / {Math.max(1, Math.ceil(page.total / page.limit))} 页 + +
    + + +
    +
    + ) : null} +
    + 快照就绪 + 快照时间:{new Date(selectedSource.observed_at).toLocaleString('zh-CN', { hour12: false })} + 上次刷新耗时 {duration(selectedSource.last_refresh_duration_ms)} + {history ? ( + + ) : null} +
    + {history && history.open ? ( + + ) : null} + + ) : loading ? ( +
    正在读取第一层目录…
    + ) : !error ? ( +
    请选择一个内容来源。
    + ) : null} +
    - {routingMessage?

    {routingMessage}

    :null} -
    :null} - {visibleItems.length?
    {visibleItems.map(node=>{const visibility=appliedPolicies[node.node_id]||node.visibility;return })}
    名称类型处理策略文件数量导入与解析更新时间
    {node.node_type==='folder'?
    toggleNode(node.node_id)} />
    :}
    {node.node_type==='folder'?'文件夹':'文件'}
    {scope(visibility)}
    {node.node_type==='folder'?`${node.subtree_file_count} 份`:'—'}{progress(node)}{node.active_count?处理中 {node.active_count}:null}{node.failed_count?失败 {node.failed_count}:null}{node.modified_at?new Date(node.modified_at).toLocaleString('zh-CN',{hour12:false}):'—'}
    :
    当前目录为空。
    } - {page.total>page.limit?
    第 {Math.floor(page.offset/page.limit)+1} / {Math.max(1,Math.ceil(page.total/page.limit))} 页
    :null} -
    快照就绪快照时间:{new Date(selectedSource.observed_at).toLocaleString('zh-CN',{hour12:false})}上次刷新耗时 {duration(selectedSource.last_refresh_duration_ms)}{history?:null}
    - {history&&history.open?:null} - :loading?
    正在读取第一层目录…
    :!error?
    请选择一个内容来源。
    :null} -
    -
    - + + ) } -export function SourceCatalogBrowser(){ - const [sources,setSources]=useState([]);const [selected,setSelected]=useState(null);const [parentID,setParentID]=useState('');const [page,setPage]=useState(null);const [offset,setOffset]=useState(0);const [revision,setRevision]=useState(0);const [loading,setLoading]=useState(true);const [error,setError]=useState(null);const setContextTabs=useContext(WorkspaceContextTabsSetter) - const [routingCapabilities,setRoutingCapabilities]=useState({internal_enabled:false,external_enabled:false});const [routingMessage,setRoutingMessage]=useState('');const [routingLoading,setRoutingLoading]=useState(false) - const [refreshJob,setRefreshJob]=useState(null) - const [historySnapshots,setHistorySnapshots]=useState([]);const [historyActive,setHistoryActive]=useState(null);const [historyPage,setHistoryPage]=useState(null);const [historyLoading,setHistoryLoading]=useState(false);const [historyError,setHistoryError]=useState(null);const [historyOpen,setHistoryOpen]=useState(false) - const [refreshHidden,setRefreshHidden]=useState(false) +export function SourceCatalogBrowser({ + focus, + onViewProcessing, + onFocusApplied, +}: { + focus?: { connectionID: string; nodeID: string } | null + onViewProcessing?: (source: CatalogSource, node: CatalogNode) => void + onFocusApplied?: () => void +} = {}) { + const [sources, setSources] = useState([]) + const [selected, setSelected] = useState(null) + const [parentID, setParentID] = useState('') + const [page, setPage] = useState(null) + const [offset, setOffset] = useState(0) + const [revision, setRevision] = useState(0) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + const setContextTabs = useContext(WorkspaceContextTabsSetter) + const [routingCapabilities, setRoutingCapabilities] = useState({ + internal_enabled: false, + external_enabled: false, + }) + const [routingMessage, setRoutingMessage] = useState('') + const [routingLoading, setRoutingLoading] = useState(false) + const [refreshJob, setRefreshJob] = useState(null) + const [historySnapshots, setHistorySnapshots] = useState([]) + const [historyActive, setHistoryActive] = useState(null) + const [historyPage, setHistoryPage] = useState(null) + const [historyLoading, setHistoryLoading] = useState(false) + const [historyError, setHistoryError] = useState(null) + const [historyOpen, setHistoryOpen] = useState(false) + const [refreshHidden, setRefreshHidden] = useState(false) - const openHistory=async()=>{if(!selected||historyLoading)return;if(historyOpen){closeHistory();return}setHistoryOpen(true);setHistoryLoading(true);setHistoryError(null);try{const result=await fetchCatalogSnapshots(selected.connection_id,20,0);setHistorySnapshots(result.items);const head=result.items.find(item=>item.is_head)||result.items[0]||null;setHistoryActive(head);if(head)setHistoryPage(await fetchCatalogSnapshotNodes(selected.connection_id,head.snapshot_id,head.root_node_id));else setHistoryPage(null)}catch(cause){setHistoryError(cause instanceof Error?cause.message:'加载快照历史失败')}finally{setHistoryLoading(false)}} - const openHistorySnapshot=async(snapshot:CatalogSnapshot)=>{if(!selected||historyLoading)return;setHistoryLoading(true);setHistoryError(null);try{setHistoryActive(snapshot);setHistoryPage(await fetchCatalogSnapshotNodes(selected.connection_id,snapshot.snapshot_id,snapshot.root_node_id))}catch(cause){setHistoryError(cause instanceof Error?cause.message:'加载历史快照目录失败')}finally{setHistoryLoading(false)}} - const openHistoryFolder=async(snapshot:CatalogSnapshot,nodeID:string)=>{if(!selected||historyLoading)return;setHistoryLoading(true);setHistoryError(null);try{setHistoryPage(await fetchCatalogSnapshotNodes(selected.connection_id,snapshot.snapshot_id,nodeID))}catch(cause){setHistoryError(cause instanceof Error?cause.message:'加载历史快照目录失败')}finally{setHistoryLoading(false)}} - const closeHistory=()=>{setHistoryOpen(false);setHistoryActive(null);setHistoryPage(null);setHistoryError(null)} + const openHistory = async () => { + if (!selected || historyLoading) return + if (historyOpen) { + closeHistory() + return + } + setHistoryOpen(true) + setHistoryLoading(true) + setHistoryError(null) + try { + const result = await fetchCatalogSnapshots(selected.connection_id, 20, 0) + setHistorySnapshots(result.items) + const head = result.items.find((item) => item.is_head) || result.items[0] || null + setHistoryActive(head) + if (head) + setHistoryPage(await fetchCatalogSnapshotNodes(selected.connection_id, head.snapshot_id, head.root_node_id)) + else setHistoryPage(null) + } catch (cause) { + setHistoryError(cause instanceof Error ? cause.message : '加载快照历史失败') + } finally { + setHistoryLoading(false) + } + } + const openHistorySnapshot = async (snapshot: CatalogSnapshot) => { + if (!selected || historyLoading) return + setHistoryLoading(true) + setHistoryError(null) + try { + setHistoryActive(snapshot) + setHistoryPage( + await fetchCatalogSnapshotNodes(selected.connection_id, snapshot.snapshot_id, snapshot.root_node_id) + ) + } catch (cause) { + setHistoryError(cause instanceof Error ? cause.message : '加载历史快照目录失败') + } finally { + setHistoryLoading(false) + } + } + const openHistoryFolder = async (snapshot: CatalogSnapshot, nodeID: string) => { + if (!selected || historyLoading) return + setHistoryLoading(true) + setHistoryError(null) + try { + setHistoryPage(await fetchCatalogSnapshotNodes(selected.connection_id, snapshot.snapshot_id, nodeID)) + } catch (cause) { + setHistoryError(cause instanceof Error ? cause.message : '加载历史快照目录失败') + } finally { + setHistoryLoading(false) + } + } + const closeHistory = () => { + setHistoryOpen(false) + setHistoryActive(null) + setHistoryPage(null) + setHistoryError(null) + } - useEffect(()=>{const controller=new AbortController();setLoading(true);void fetchCatalogSources(controller.signal).then(result=>{if(controller.signal.aborted)return;setSources(result);setSelected(current=>current&&result.find(source=>source.connection_id===current.connection_id)||result[0]||null);setParentID(current=>current||result[0]?.root_node_id||'');setError(null)}).catch(cause=>{if(!controller.signal.aborted)setError(cause instanceof Error?cause.message:'加载来源目录失败')}).finally(()=>{if(!controller.signal.aborted)setLoading(false)});return()=>controller.abort()},[revision]) - useEffect(()=>{if(!selected||!parentID||selected.snapshot_status==='scanning')return;const controller=new AbortController();setLoading(true);void fetchCatalogNodes(selected.connection_id,parentID,50,offset,controller.signal).then(result=>{if(!controller.signal.aborted){setPage(result);setError(null)}}).catch(cause=>{if(!controller.signal.aborted)setError(cause instanceof Error?cause.message:'加载目录失败')}).finally(()=>{if(!controller.signal.aborted)setLoading(false)});return()=>controller.abort()},[selected,parentID,offset,revision]) + useEffect(() => { + const controller = new AbortController() + setLoading(true) + void fetchCatalogSources(controller.signal) + .then((result) => { + if (controller.signal.aborted) return + setSources(result) + setSelected( + (current) => + (current && result.find((source) => source.connection_id === current.connection_id)) || result[0] || null + ) + setParentID((current) => current || result[0]?.root_node_id || '') + setError(null) + }) + .catch((cause) => { + if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载来源目录失败') + }) + .finally(() => { + if (!controller.signal.aborted) setLoading(false) + }) + return () => controller.abort() + }, [revision]) + useEffect(() => { + if (!selected || !parentID || selected.snapshot_status === 'scanning') return + const controller = new AbortController() + setLoading(true) + void fetchCatalogNodes(selected.connection_id, parentID, 50, offset, controller.signal) + .then((result) => { + if (!controller.signal.aborted) { + setPage(result) + setError(null) + } + }) + .catch((cause) => { + if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载目录失败') + }) + .finally(() => { + if (!controller.signal.aborted) setLoading(false) + }) + return () => controller.abort() + }, [selected, parentID, offset, revision]) - // 有来源正在首次扫描时自动刷新列表:百分比会自己往前走,扫完那一行自动变成正式来源。 - useEffect(()=>{if(!sources.some(source=>source.snapshot_status==='scanning'))return;const timer=window.setTimeout(()=>setRevision(value=>value+1),3000);return()=>window.clearTimeout(timer)},[sources]) - useEffect(()=>{const controller=new AbortController();void fetchCatalogRoutingCapabilities(controller.signal).then(setRoutingCapabilities).catch(()=>setRoutingCapabilities({internal_enabled:false,external_enabled:false}));return()=>controller.abort()},[revision]) - useEffect(()=>{if(!selected)return;const controller=new AbortController();void fetchJobs(controller.signal).then(items=>{if(controller.signal.aborted)return;const match=items.find(job=>job.type==='source.catalog.refresh'&&job.payload&&typeof job.payload==='object'&&(job.payload as Record).connection_id===selected.connection_id);setRefreshJob(match||null)}).catch(()=>undefined);return()=>controller.abort()},[selected]) - useEffect(()=>{if(!refreshJob||!['pending','running','retry'].includes(refreshJob.state))return;const timer=window.setTimeout(()=>void fetchJobs().then(items=>{const current=items.find(job=>job.id===refreshJob.id);if(!current)return;setRefreshJob(previous=>{if(previous?.state!=='completed'&¤t.state==='completed')setRevision(value=>value+1);return current})}).catch(()=>undefined),750);return()=>window.clearTimeout(timer)},[refreshJob]) - useEffect(()=>{if(!selected||!page){setContextTabs([]);return}setContextTabs(page.breadcrumbs.map(item=>({key:item.node_id,label:item.name,onActivate:()=>{setParentID(item.node_id);setOffset(0)}})));return()=>setContextTabs([])},[selected,page,setContextTabs]) - const selectSource=(source:CatalogSource)=>{if(selected?.connection_id===source.connection_id&&parentID===source.root_node_id&&offset===0)return;setSelected(source);setParentID(source.root_node_id);setOffset(0);setPage(null);setRefreshJob(null);closeHistory()} - const back=()=>{if(!page||page.breadcrumbs.length<2)return;setParentID(page.breadcrumbs[page.breadcrumbs.length-2].node_id);setOffset(0)} - const route=async(nodeIDs:string[],policy:CatalogPolicy):Promise=>{if(!selected||routingLoading)return false;setRoutingLoading(true);setRoutingMessage('');try{const result=await routeCatalogFiles({connection_id:selected.connection_id,node_ids:nodeIDs,policy,reason:`目录页策略:${scope(policy)}`});setRoutingMessage(`策略已保存 ${result.selected_files} 份;已记入意图 ${result.intents_recorded} 份;排队从源头取件 ${result.fetch_queued} 份;列入待入库 ${result.planned_publications} 份;标记禁止 ${result.blocked_items} 份;目录外无文件可标注 ${result.unbound_files} 份。到“解析监控 → 待入库”点开始处理即可。`);setRevision(value=>value+1);return true}catch(cause){setRoutingMessage(cause instanceof Error?cause.message:'文件处理失败');return false}finally{setRoutingLoading(false)}} - const refresh=async()=>{if(!selected||refreshJob&&['pending','running','retry'].includes(refreshJob.state))return;setError(null);try{setRefreshJob(await triggerCatalogRefresh(selected.connection_id))}catch(cause){setError(cause instanceof Error?cause.message:'启动实时刷新失败')}} - return {setRoutingMessage('');selectSource(source)}} onOpenFolder={node=>{setRoutingMessage('');setParentID(node.node_id);setOffset(0)}} onNavigateTo={nodeID=>{setRoutingMessage('');setParentID(nodeID);setOffset(0)}} onBack={back} onPageChange={setOffset} onRefresh={()=>void refresh()} onRoute={(nodeIDs,visibility)=>route(nodeIDs,visibility)} history={{open:historyOpen,snapshots:historySnapshots,active:historyActive,page:historyPage,loading:historyLoading,error:historyError,onOpen:()=>void openHistory(),onClose:closeHistory,onOpenSnapshot:snapshot=>void openHistorySnapshot(snapshot),onOpenFolder:(snapshot,nodeID)=>void openHistoryFolder(snapshot,nodeID)}} refreshHidden={refreshHidden} onToggleRefreshHidden={()=>setRefreshHidden(value=>!value)} onFiltersChanged={()=>setRevision(value=>value+1)} /> + // 从解析监控“在来源与目录定位”进入:这是一次性导航请求。应用后由父消费; + // 同时用 ref 防同一请求在 sources 刷新/revision 重载时重放,手工换目录不会被拽回。 + const appliedFocus = useRef(null) + useEffect(() => { + if (!focus || !sources.length || appliedFocus.current === focus) return + const target = sources.find((source) => source.connection_id === focus.connectionID) + if (!target) return + appliedFocus.current = focus + setSelected(target) + setParentID(focus.nodeID || target.root_node_id) + setOffset(0) + setPage(null) + closeHistory() + onFocusApplied?.() + }, [focus, sources]) + // 有来源正在首次扫描时自动刷新列表:百分比会自己往前走,扫完那一行自动变成正式来源。 + useEffect(() => { + if (!sources.some((source) => source.snapshot_status === 'scanning')) return + const timer = window.setTimeout(() => setRevision((value) => value + 1), 3000) + return () => window.clearTimeout(timer) + }, [sources]) + useEffect(() => { + const controller = new AbortController() + void fetchCatalogRoutingCapabilities(controller.signal) + .then(setRoutingCapabilities) + .catch(() => setRoutingCapabilities({ internal_enabled: false, external_enabled: false })) + return () => controller.abort() + }, [revision]) + useEffect(() => { + if (!selected) return + const controller = new AbortController() + void fetchJobs(controller.signal) + .then((items) => { + if (controller.signal.aborted) return + const match = items.find( + (job) => + job.type === 'source.catalog.refresh' && + job.payload && + typeof job.payload === 'object' && + (job.payload as Record).connection_id === selected.connection_id + ) + setRefreshJob(match || null) + }) + .catch(() => undefined) + return () => controller.abort() + }, [selected]) + useEffect(() => { + if (!refreshJob || !['pending', 'running', 'retry'].includes(refreshJob.state)) return + const timer = window.setTimeout( + () => + void fetchJobs() + .then((items) => { + const current = items.find((job) => job.id === refreshJob.id) + if (!current) return + setRefreshJob((previous) => { + if (previous?.state !== 'completed' && current.state === 'completed') setRevision((value) => value + 1) + return current + }) + }) + .catch(() => undefined), + 750 + ) + return () => window.clearTimeout(timer) + }, [refreshJob]) + useEffect(() => { + if (!selected || !page) { + setContextTabs([]) + return + } + setContextTabs( + page.breadcrumbs.map((item) => ({ + key: item.node_id, + label: item.name, + onActivate: () => { + setParentID(item.node_id) + setOffset(0) + }, + })) + ) + return () => setContextTabs([]) + }, [selected, page, setContextTabs]) + const selectSource = (source: CatalogSource) => { + if (selected?.connection_id === source.connection_id && parentID === source.root_node_id && offset === 0) return + setSelected(source) + setParentID(source.root_node_id) + setOffset(0) + setPage(null) + setRefreshJob(null) + closeHistory() + } + const back = () => { + if (!page || page.breadcrumbs.length < 2) return + setParentID(page.breadcrumbs[page.breadcrumbs.length - 2].node_id) + setOffset(0) + } + const route = async (nodeIDs: string[], policy: CatalogPolicy): Promise => { + if (!selected || routingLoading) return false + setRoutingLoading(true) + setRoutingMessage('') + try { + const result = await routeCatalogFiles({ + connection_id: selected.connection_id, + node_ids: nodeIDs, + policy, + reason: `目录页策略:${scope(policy)}`, + }) + setRoutingMessage( + `策略已保存 ${result.selected_files} 份;已记入意图 ${result.intents_recorded} 份;排队从源头取件 ${result.fetch_queued} 份;列入处理 ${result.planned_publications} 份;标记禁止 ${result.blocked_items} 份;目录外无文件可标注 ${result.unbound_files} 份。取件校验完成后会自动上传解析,可在“解析监控”跟踪进度。` + ) + setRevision((value) => value + 1) + return true + } catch (cause) { + setRoutingMessage(cause instanceof Error ? cause.message : '文件处理失败') + return false + } finally { + setRoutingLoading(false) + } + } + const refresh = async () => { + if (!selected || (refreshJob && ['pending', 'running', 'retry'].includes(refreshJob.state))) return + setError(null) + try { + setRefreshJob(await triggerCatalogRefresh(selected.connection_id)) + } catch (cause) { + setError(cause instanceof Error ? cause.message : '启动实时刷新失败') + } + } + return ( + { + setRoutingMessage('') + selectSource(source) + }} + onOpenFolder={(node) => { + setRoutingMessage('') + setParentID(node.node_id) + setOffset(0) + }} + onNavigateTo={(nodeID) => { + setRoutingMessage('') + setParentID(nodeID) + setOffset(0) + }} + onBack={back} + onPageChange={setOffset} + onRefresh={() => void refresh()} + onRoute={(nodeIDs, visibility) => route(nodeIDs, visibility)} + history={{ + open: historyOpen, + snapshots: historySnapshots, + active: historyActive, + page: historyPage, + loading: historyLoading, + error: historyError, + onOpen: () => void openHistory(), + onClose: closeHistory, + onOpenSnapshot: (snapshot) => void openHistorySnapshot(snapshot), + onOpenFolder: (snapshot, nodeID) => void openHistoryFolder(snapshot, nodeID), + }} + refreshHidden={refreshHidden} + onToggleRefreshHidden={() => setRefreshHidden((value) => !value)} + onFiltersChanged={() => setRevision((value) => value + 1)} + onViewProcessing={onViewProcessing && selected ? (node) => onViewProcessing(selected, node) : undefined} + /> + ) } diff --git a/web/src/SourceLinkManager.test.tsx b/web/src/SourceLinkManager.test.tsx index d52f411..0ae0143 100644 --- a/web/src/SourceLinkManager.test.tsx +++ b/web/src/SourceLinkManager.test.tsx @@ -1,26 +1,114 @@ import { renderToStaticMarkup } from 'react-dom/server' -import { describe,expect,it,vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { SourceLinkManagerView } from './SourceLinkManager' import type { CatalogSource } from './sourceCatalog' -const sources:CatalogSource[]=[ - {connection_id:'ding',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'r1',folder_count:8,file_count:3468,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0}, - {connection_id:'pp',source_type:'pp',name:'PP资料下载中心',root_node_id:'r2',folder_count:64,file_count:613,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0}, - {connection_id:'alist',source_type:'alist',name:'国内工业',root_node_id:'r3',folder_count:1688,file_count:4880,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0}, +const sources: CatalogSource[] = [ + { + connection_id: 'ding', + source_type: 'dingtalk', + name: '公司级技术支持知识库', + root_node_id: 'r1', + folder_count: 8, + file_count: 3468, + observed_at: '2026-09-08T00:00:00Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 0, + }, + { + connection_id: 'pp', + source_type: 'pp', + name: 'PP资料下载中心', + root_node_id: 'r2', + folder_count: 64, + file_count: 613, + observed_at: '2026-09-08T00:00:00Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 0, + }, + { + connection_id: 'alist', + source_type: 'alist', + name: '国内工业', + root_node_id: 'r3', + folder_count: 1688, + file_count: 4880, + observed_at: '2026-09-08T00:00:00Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 0, + }, ] -describe('SourceLinkManagerView',()=>{ - it('shows understandable URL credential and login fields without accepting real secrets locally',()=>{ - const html=renderToStaticMarkup() - for(const text of ['来源链接','本地模拟配置','公司级技术支持知识库','PP资料下载中心','国内工业','知识库链接','认证方式','专用浏览器扫码登录','Key或Token','本地模拟阶段不接收真实Key','模拟登录并验证目录','不保存真实Key'])expect(html).toContain(text) - expect(html).not.toContain('secret_ref') - expect(html).not.toContain('base_url') - }) - it('separates an AList site address from its starting directory and labels simulated status honestly',()=>{ - const html=renderToStaticMarkup() - for(const text of ['AList站点地址','起始目录','/国内工业','模拟验证待执行','不下载文件内容,只读取目录和元数据'])expect(html).toContain(text) - expect(html).not.toContain('实时连接待验证') - }) - it('does not show a successful zero-source state after errors',()=>{ - const html=renderToStaticMarkup() - expect(html).toContain('加载失败');expect(html).not.toContain('尚无来源链接') - }) +describe('SourceLinkManagerView', () => { + it('shows understandable URL credential and login fields without accepting real secrets locally', () => { + const html = renderToStaticMarkup( + + ) + for (const text of [ + '来源链接', + '本地模拟配置', + '公司级技术支持知识库', + 'PP资料下载中心', + '国内工业', + '知识库链接', + '认证方式', + '专用浏览器扫码登录', + 'Key或Token', + '本地模拟阶段不接收真实Key', + '模拟登录并验证目录', + '不保存真实Key', + ]) + expect(html).toContain(text) + expect(html).not.toContain('secret_ref') + expect(html).not.toContain('base_url') + }) + it('separates an AList site address from its starting directory and labels simulated status honestly', () => { + const html = renderToStaticMarkup( + + ) + for (const text of [ + 'AList站点地址', + '起始目录', + '/国内工业', + '模拟验证待执行', + '不下载文件内容,只读取目录和元数据', + ]) + expect(html).toContain(text) + expect(html).not.toContain('实时连接待验证') + }) + it('does not show a successful zero-source state after errors', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('加载失败') + expect(html).not.toContain('尚无来源链接') + }) }) diff --git a/web/src/SourceLinkManager.tsx b/web/src/SourceLinkManager.tsx index 50b8493..16d91d9 100644 --- a/web/src/SourceLinkManager.tsx +++ b/web/src/SourceLinkManager.tsx @@ -1,35 +1,209 @@ -import { useContext,useEffect,useState } from 'react' +import { useContext, useEffect, useState } from 'react' import { fetchCatalogSources } from './sourceCatalog' import type { CatalogSource } from './sourceCatalog' import { WorkspaceContextTabsSetter } from './workspaceContext' import './sourceLinkManager.css' -const typeLabel={dingtalk:'钉钉知识库',pp:'PP资料下载中心',alist:'AList文件源'} -const authLabel={dingtalk:'专用浏览器扫码登录',pp:'公开访问,无需Key',alist:'只读Token'} -const actionLabel={dingtalk:'模拟登录并验证目录',pp:'模拟验证公开目录',alist:'模拟验证只读Token'} -const placeholder={dingtalk:'粘贴钉钉知识库网页链接(模拟)',pp:'粘贴PP资料下载中心链接(模拟)',alist:'例如:https://alist.example.com(模拟)'} -const linkLabel={dingtalk:'知识库链接',pp:'资料中心地址',alist:'AList站点地址'} -interface Props{sources:CatalogSource[];selected:CatalogSource|null;validated:boolean;loading:boolean;error:string|null;onSelect:(source:CatalogSource)=>void;onValidate:()=>void;onRefresh:()=>void} -export function SourceLinkManagerView({sources,selected,validated,loading,error,onSelect,onValidate,onRefresh}:Props){ - const [link,setLink]=useState('') - return
    -

    连接配置

    来源链接

    配置钉钉、PP和AList的入口、认证方式及目录验证。

    - {error?
    {error}
    :null} -
    本地模拟配置使用真实来源名称和快照数量,但不连接登录服务、不保存真实Key。
    -
    - -
    {selected?<>

    {selected.name}

    {typeLabel[selected.source_type]} · 本地只读快照
    模拟验证待执行
    -
    -
    当前快照文件 {selected.file_count}目录 {selected.folder_count}不下载文件内容,只读取目录和元数据不执行上传、移动、重命名或删除
    - - {validated?
    网络连接模拟通过
    登录或Token模拟通过
    根目录模拟通过
    读取第一层目录模拟通过
    只读边界模拟通过
    以上只是本地交互模拟;迁移到测试服务器后才执行真实验证。
    :null} -

    真实模式下,新凭据先验证,成功后才替换旧凭据;网页永远不能读取已保存Key。

    - :loading?
    正在加载来源…
    :null}
    -
    -
    +const typeLabel = { dingtalk: '钉钉知识库', pp: 'PP资料下载中心', alist: 'AList文件源' } +const authLabel = { dingtalk: '专用浏览器扫码登录', pp: '公开访问,无需Key', alist: '只读Token' } +const actionLabel = { dingtalk: '模拟登录并验证目录', pp: '模拟验证公开目录', alist: '模拟验证只读Token' } +const placeholder = { + dingtalk: '粘贴钉钉知识库网页链接(模拟)', + pp: '粘贴PP资料下载中心链接(模拟)', + alist: '例如:https://alist.example.com(模拟)', } -export function SourceLinkManager(){ - const [sources,setSources]=useState([]);const [selected,setSelected]=useState(null);const [validated,setValidated]=useState(false);const [loading,setLoading]=useState(true);const [error,setError]=useState(null);const [revision,setRevision]=useState(0);const setContextTabs=useContext(WorkspaceContextTabsSetter) - useEffect(()=>{const controller=new AbortController();setLoading(true);void fetchCatalogSources(controller.signal).then(result=>{if(!controller.signal.aborted){setSources(result);setSelected(current=>current&&result.find(item=>item.connection_id===current.connection_id)||result[0]||null);setError(null)}}).catch(cause=>{if(!controller.signal.aborted)setError(cause instanceof Error?cause.message:'加载来源链接失败')}).finally(()=>{if(!controller.signal.aborted)setLoading(false)});return()=>controller.abort()},[revision]) - useEffect(()=>{setContextTabs(selected?[{key:selected.connection_id,label:selected.name,onActivate:()=>undefined}]:[]);return()=>setContextTabs([])},[selected,setContextTabs]) - return {setSelected(source);setValidated(false)}} onValidate={()=>setValidated(true)} onRefresh={()=>{setValidated(false);setRevision(value=>value+1)}} /> +const linkLabel = { dingtalk: '知识库链接', pp: '资料中心地址', alist: 'AList站点地址' } +interface Props { + sources: CatalogSource[] + selected: CatalogSource | null + validated: boolean + loading: boolean + error: string | null + onSelect: (source: CatalogSource) => void + onValidate: () => void + onRefresh: () => void +} +export function SourceLinkManagerView({ + sources, + selected, + validated, + loading, + error, + onSelect, + onValidate, + onRefresh, +}: Props) { + const [link, setLink] = useState('') + return ( +
    +
    +
    +

    连接配置

    +

    来源链接

    +

    配置钉钉、PP和AList的入口、认证方式及目录验证。

    +
    + +
    + {error ? ( +
    + {error} +
    + ) : null} +
    + 本地模拟配置 + 使用真实来源名称和快照数量,但不连接登录服务、不保存真实Key。 +
    +
    + +
    + {selected ? ( + <> +
    +
    +

    {selected.name}

    + {typeLabel[selected.source_type]} · 本地只读快照 +
    + 模拟验证待执行 +
    +
    + + + + +
    +
    + 当前快照 + 文件 {selected.file_count} + 目录 {selected.folder_count} + 不下载文件内容,只读取目录和元数据 + 不执行上传、移动、重命名或删除 +
    + + {validated ? ( +
    +
    + 网络连接 + 模拟通过 +
    +
    + 登录或Token + 模拟通过 +
    +
    + 根目录 + 模拟通过 +
    +
    + 读取第一层目录 + 模拟通过 +
    +
    + 只读边界 + 模拟通过 +
    + 以上只是本地交互模拟;迁移到测试服务器后才执行真实验证。 +
    + ) : null} +

    + 真实模式下,新凭据先验证,成功后才替换旧凭据;网页永远不能读取已保存Key。 +

    + + ) : loading ? ( +
    正在加载来源…
    + ) : null} +
    +
    +
    + ) +} +export function SourceLinkManager() { + const [sources, setSources] = useState([]) + const [selected, setSelected] = useState(null) + const [validated, setValidated] = useState(false) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + const [revision, setRevision] = useState(0) + const setContextTabs = useContext(WorkspaceContextTabsSetter) + useEffect(() => { + const controller = new AbortController() + setLoading(true) + void fetchCatalogSources(controller.signal) + .then((result) => { + if (!controller.signal.aborted) { + setSources(result) + setSelected( + (current) => + (current && result.find((item) => item.connection_id === current.connection_id)) || result[0] || null + ) + setError(null) + } + }) + .catch((cause) => { + if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载来源链接失败') + }) + .finally(() => { + if (!controller.signal.aborted) setLoading(false) + }) + return () => controller.abort() + }, [revision]) + useEffect(() => { + setContextTabs(selected ? [{ key: selected.connection_id, label: selected.name, onActivate: () => undefined }] : []) + return () => setContextTabs([]) + }, [selected, setContextTabs]) + return ( + { + setSelected(source) + setValidated(false) + }} + onValidate={() => setValidated(true)} + onRefresh={() => { + setValidated(false) + setRevision((value) => value + 1) + }} + /> + ) } diff --git a/web/src/SourceManagement.css b/web/src/SourceManagement.css index 6bde915..30e8a6e 100644 --- a/web/src/SourceManagement.css +++ b/web/src/SourceManagement.css @@ -20,12 +20,39 @@ border-bottom: 0; } .source-account { - margin: 0 0 14px; + border: 1px solid var(--border, #dce3eb); + border-radius: 10px; + padding: 16px; + margin: 12px 0; + background: var(--surface, #fff); font-size: 12px; } -.source-account > button { - padding: 5px 0; - color: var(--ink-mute); +.dws-account-heading { + display: flex; + align-items: flex-start; + justify-content: space-between; + flex-wrap: wrap; + gap: 12px; + margin-bottom: 8px; +} +.dws-account-heading strong { + display: block; + margin-bottom: 6px; + font-size: 14px; +} +.dws-login-card { + width: min(480px, calc(100vw - 40px)); +} +.dws-authorize-link { + display: inline-block; + margin: 8px 0; +} +.dws-user-code { + font-size: 18px; + letter-spacing: 2px; +} +.dws-login-card .row-actions { + margin-top: 20px; } .source-account-detail { padding: 12px 16px; diff --git a/web/src/SourceManagement.tsx b/web/src/SourceManagement.tsx index e644025..17c9a51 100644 --- a/web/src/SourceManagement.tsx +++ b/web/src/SourceManagement.tsx @@ -21,42 +21,7 @@ const choices = [ ] const errorText = (error: unknown) => (error instanceof Error ? error.message : '操作失败,请重试') -export function DingtalkAccountStatus() { - const [status, setStatus] = useState('读取中…') - const [expires, setExpires] = useState('') - useEffect(() => { - const controller = new AbortController() - void fetch('/api/v1/dingtalk-spaces/credential-status', { - headers: { Accept: 'application/json' }, - signal: controller.signal, - }) - .then(async (response) => { - if (!response.ok) throw new Error('读取失败') - const value = await response.json() - const data = value.data - if (!data || typeof data.authenticated !== 'boolean' || typeof data.refresh_token_valid !== 'boolean') - throw new Error('状态格式错误') - if (controller.signal.aborted) return - setStatus(!data.authenticated ? '未登录' : data.refresh_token_valid ? '已登录' : '凭证需更新') - setExpires(data.authenticated && typeof data.refresh_expires_at === 'string' ? data.refresh_expires_at : '') - }) - .catch(() => { - if (!controller.signal.aborted) setStatus('状态读取失败') - }) - return () => controller.abort() - }, []) - return ( -
    - DWS 凭证 · {status} - {expires ? ( - · 续期凭证有效期至 {new Date(expires).toLocaleString('zh-CN', { hour12: false })} - ) : null} -
    - 仅显示本地凭证状态,不检测目录权限或业务接口。 -
    -
    - ) -} +export { DWSAccount as DingtalkAccountStatus } from './DWSAccount' export function SourceSettingsCard({ connection, @@ -118,6 +83,14 @@ export function SourceSettingsCard({ ? '自动刷新中' : '仅手动刷新'} + {/* 刷新方式之外还要能判断“最近有没有真的跑过、下一次什么时候跑”。 */} + + {`上次更新 ${connection.updated_at ? new Date(connection.updated_at).toLocaleString('zh-CN', { hour12: false }) : '未知'}`} + {manual + ? ' · 手工导入无自动计划' + : ` · 下次计划 ${connection.next_refresh_at ? new Date(connection.next_refresh_at).toLocaleString('zh-CN', { hour12: false }) : '无(仅手动)'}`} + {` · ${connection.item_count} 条`} + {!manual || isAdmin ? ( - - {open ? ( + {open && (
      {steps.map((label, index) => ( @@ -150,8 +297,7 @@ export function SourceWizard({ ))}
    - - {step === 0 ? ( + {step === 0 && (
    {kinds.map((item) => ( ))}
    - ) : null} - - {step === 1 ? ( -
    - {kind === 'pp' ? ( - <> -
    - 授权方式 - 公开只读 -
    -
    - 凭据 - 由服务端持有,无需填写 -
    -

    资料下载中心的登录凭据由运维放在服务端,向导里不录入任何密码。

    - - ) : ( - <> -
    - 授权方式 - 当前钉钉账号扫码会话 -
    -
    - 读取权限 - 只读;不写回、不删除源文件 -
    -

    - 用的是平台已登录的 dws 凭据,不需要每个来源单独扫码;会话失效时会在保存时弹二维码。 -

    - - )} -
    - ) : null} - - {step === 2 ? ( + )} + {step === 1 && ( +
    {kind === 'pp' ? : authPanel}
    + )} + {step === 2 && (
    {kind === 'pp' ? (

    {ppConnected - ? '已接入 PP 资料下载中心(一个门户一条来源),无需重复添加;刷新与归档在下方清单里做。' - : 'PP 需要服务端放置只读凭据后才能接入;凭据到位后联系我开通,向导本身不录密码。'} + ? 'PP 资料下载中心已接入,一个门户保留一条来源。' + : 'PP 来源尚未接入;认证配置与来源登记分别管理。'}

    ) : loading ? ( -

    正在列举当前账号可见的来源…

    +

    正在列举当前 DWS 账号可见的来源…

    ) : loadError ? ( -

    {loadError}

    - ) : visible.length === 0 ? ( -

    - 当前账号没有可添加的{kind === 'wiki' ? '知识库' : '钉盘空间'};已加入的不会重复列出。 -

    + <> +

    {loadError}

    + + ) : ( <> -
    - {visible.map((item) => ( - - ))} -
    -

    - 已选 {selected.length} 项。勾选空间即可,目录细节加入后再在「来源与目录」里标注。 -

    + {scopeNotice &&

    {scopeNotice}

    } + {visible.length ? ( +
    + {visible.map((item) => ( + + ))} +
    + ) : ( +

    当前账号没有可添加的{kind === 'wiki' ? '知识库' : '钉盘空间'}。

    + )} +

    已选 {selected.length} 项;目录规则在加入后的“来源与目录”设置。

    )}
    - ) : null} - - {step === 3 ? ( + )} + {step === 3 && (
    -
      - {(kind === 'pp' ? [] : selected).map((item: DiscoveryCandidate) => ( -
    • - {item.name} - 仍可见 -
    • - ))} - {kind === 'pp' ? ( -
    • - Partner Portal 公开目录 - 公开只读可达 -
    • - ) : null} -
    -

    添加时会按当前账号再读一次;如果已看不到,会拒绝并提示刷新。

    + {busy ? ( +

    正在校验所选来源…

    + ) : verified ? ( + <> +
      + {selected.map((item) => ( +
    • + {item.name} + 校验通过 +
    • + ))} +
    + 检查于 {new Date(verified).toLocaleString('zh-CN', { hour12: false })} + + ) : ( + + )}
    - ) : null} - - {step === 4 ? ( + )} + {step === 4 && (
    - {message ?

    {message}

    : null} - {failure ?

    {failure}

    : null} - {!message && !failure ? ( -

    - 将加入{' '} - {(kind === 'pp' ? ['Partner Portal'] : selected.map((item) => item.name)).join('、') || '(未选择)'} - 。 -

    - ) : null} - {loginRequired ? ( - { - setLoginRequired(false) - void submit(true) - }} - /> - ) : null} + {message &&

    {message}

    } + {pending.current.length > 0 && !authNeeded && !busy && ( + + )}
    - ) : null} - + )} + {failure &&

    {failure}

    } + {authNeeded && step !== 1 && authPanel}
    - - {kind === 'pp' ? ( + {kind === 'pp' && step === 1 ? ( - ) : step < 3 ? ( - + ) : step === 2 ? ( + ) : step === 3 ? ( ) : ( - )}
    - ) : null} + )}
  • ) } diff --git a/web/src/SystemSettings.test.tsx b/web/src/SystemSettings.test.tsx index d49a9ee..5c295c4 100644 --- a/web/src/SystemSettings.test.tsx +++ b/web/src/SystemSettings.test.tsx @@ -1,6 +1,12 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it, vi } from 'vitest' -import { SystemSettingsView, ppSourceConnections, visibleSaveMessage } from './SystemSettings' +import { + SystemSettingsView, + ppSourceConnections, + refreshSettingsInput, + serviceSettingsInput, + visibleSaveMessage, +} from './SystemSettings' import { AuthContext } from './auth' import type { MonitorOverview } from './monitor' import type { CatalogSource } from './sourceCatalog' @@ -113,57 +119,40 @@ const authValue = (role: 'admin' | 'engineer') => ({ signedOut: 0, notifySignedOut: () => {}, }) -describe('SystemSettingsView service configuration', () => { - it('lets an administrator edit exactly the four service fields in the web console', () => { - const configured: UISettings = { - ...settings, - test_weknora_base_url: 'https://weknora.test.example', - production_weknora_base_url: 'https://weknora.prod.example', - production_tenant_id: '10000', - production_knowledge_base_id: 'kb-abc123', - } - const view = (role: 'admin' | 'engineer') => - renderToStaticMarkup( - - - - ) +describe('SystemSettingsView AI 模型连接', () => { + const view = (role: 'admin' | 'engineer') => + renderToStaticMarkup( + + + + ) + it('keeps the model connection alone in AI 模型连接 and points WeKnora to 知识库映射', () => { const adminHtml = view('admin') - for (const text of [ - '测试地址', - '生产地址', - '生产 ID', - '知识库 ID', - '保存并启用服务配置', - 'https://weknora.test.example', - 'https://weknora.prod.example', - '10000', - 'kb-abc123', - '四项留空即表示未配置', - ]) + for (const text of ['AI 模型连接', '问答评估模型', 'WeKnora 的知识库连接已移到「知识库映射」']) { expect(adminHtml).toContain(text) - expect(adminHtml).not.toContain('仅管理员可修改') - // 界面只剩这四项:依赖探活矩阵与对内/对外绑定下拉不再出现在服务配置页。 - for (const removed of ['MinerU', 'Embedding', 'Redis / MQ', 'PostgreSQL', '测试知识库映射']) + } + // 地址类配置已迁走:这里不再出现 WeKnora 连接表单,也不出现旧的“服务配置”分区名。 + for (const removed of ['保存并校验连接', '保存并启用服务配置', '生产租户 ID', '服务配置']) expect(adminHtml).not.toContain(removed) const engineerHtml = view('engineer') - expect(engineerHtml).toContain('仅管理员可修改') - expect(engineerHtml).not.toContain('保存并启用服务配置') + expect(engineerHtml).toContain('仅管理员可修改模型连接') + // 工程师看不到模型编辑表单(QAModelSettings 只在管理员下挂载)。 + expect(engineerHtml).not.toContain('问答评估模型') }) }) describe('SystemSettingsView', () => { @@ -185,7 +174,8 @@ describe('SystemSettingsView', () => { onRefresh={vi.fn()} /> ) - for (const text of ['系统设置', '数据源配置', '服务配置', '存储与备份', '刷新策略']) expect(html).toContain(text) + for (const text of ['系统设置', '数据源配置', 'AI 模型连接', '知识库映射', '存储与备份', '刷新策略']) + expect(html).toContain(text) // 主人 2026-10-26 要求去掉的噪声:页头副标题、刷新状态、权限条、活动版本横幅。 for (const removed of [ '查看内容源、服务与备份状态', @@ -207,26 +197,41 @@ describe('SystemSettingsView', () => { expect(html).not.toContain(removed) // 需求(2026-10-10):新增入口只剩「可加入的来源」勾选,粘贴链接的按钮已下线。 for (const removed of ['+ 新增钉钉知识库', '新增钉钉知识库']) expect(html).not.toContain(removed) - const servicesHtml = renderToStaticMarkup( - + // WeKnora 连接已迁到「知识库映射」:地址与核验参数跟入库/封存/生产目标同屏。 + const mapHtml = renderToStaticMarkup( + + + ) - for (const text of ['测试 WeKnora', '生产 WeKnora', '测试地址', '生产地址', '生产 ID', '知识库 ID']) - expect(servicesHtml).toContain(text) + for (const text of [ + 'WeKnora 连接', + '测试 WeKnora', + '生产 WeKnora', + '测试地址', + '生产地址', + '生产租户 ID', + '知识库 ID', + '保存并校验连接', + '生产核验参数', + ]) + expect(mapHtml).toContain(text) + // 凭据是服务器文件引用:连接卡只报状态,页面不提供 API Key 录入。 + expect(mapHtml).not.toContain('API Key') const storageHtml = renderToStaticMarkup( { 'finalizing 2小时', '文档状态刷新间隔', '15秒', - '解析停滞判定', + '解析停滞阈值', '30分钟', - '保存并应用刷新与告警参数', + '保存刷新与告警参数', ]) expect(refreshHtml).toContain(text) expect(visibleSaveMessage('已保存', true)).toBeNull() @@ -285,9 +290,9 @@ describe('SystemSettingsView', () => { for (const forbidden of ['DATABASE_URL', 'RELEASE_CONFIG_FILE', 'API Key明文', 'secret_ref']) expect(html).not.toContain(forbidden) // 两个环境卡仍由真实探测驱动(依赖矩阵搬到总览页,本页不再渲染)。 - expect(servicesHtml).toContain('解析队列 对内 已配置 · 对外 已配置') - expect(servicesHtml).not.toContain('PostgreSQL') - expect(servicesHtml).toContain('端点探测:暂无真实探测结果') + expect(mapHtml).toContain('解析队列 对内 已配置 · 对外 已配置') + expect(mapHtml).not.toContain('PostgreSQL') + expect(mapHtml).toContain('端点探测:暂无真实探测结果') // V1: left-nav section controls, per-source schedule editing, danger modal & history affordances. expect(html).toContain('settings-nav') for (const kept of ['更多', '自动刷新中']) expect(html).toContain(kept) @@ -322,8 +327,8 @@ describe('SystemSettingsView', () => { /> ) - expect(view('sources')).toContain('测试知识库绑定') - expect(view('sources')).toContain('生产知识库绑定') + // 测试绑定与生产目标已合并为「知识库映射」:入库目标、封存源、生产目标同屏。 + expect(view('sources')).toContain('知识库映射') const bound = view('bindings') expect(bound).toContain('id="settings-routing-bindings"') expect(bound).toContain('分发到对应的测试 WeKnora 知识库') @@ -332,7 +337,8 @@ describe('SystemSettingsView', () => { // 发布目标(源库 → 目标库)是独立分区,与测试端收件库分开。 const target = view('production-bindings') expect(target).toContain('id="settings-production-bindings"') - expect(target).toContain('新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库') + expect(target).toContain('整库发布目标') + expect(target).toContain('文档级绑定') }) it('does not show healthy simulation when the settings data failed to load', () => { const html = renderToStaticMarkup( @@ -417,16 +423,16 @@ describe('SystemSettingsView', () => { onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} - initialSection="services" + initialSection="knowledge-map" /> ) const on = view(true, true) expect(on).toContain('测试 WeKnora') - expect(on).toContain('可达 · 可接单') + expect(on).toContain('接口可达 · 执行器未验证') expect(on).toContain('延迟 86ms') expect(on).toContain('已启用 · 可提交生产请求') expect(on).toContain('生产写入:开启') - expect(on).toContain('发布目标与凭据:管理员受限配置') + expect(on).toContain('凭据:服务器文件引用,页面不回读') const off = view(false, false) expect(off).toContain('未启用') expect(off).toContain('生产写入:关闭') @@ -450,7 +456,7 @@ describe('SystemSettingsView', () => { onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} - initialSection="services" + initialSection="knowledge-map" /> ) expect(blocked).toContain('已启用 · 被阻断') @@ -488,7 +494,7 @@ describe('SystemSettingsView', () => { onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} - initialSection="services" + initialSection="knowledge-map" /> ) expect(unconfigured).toContain('端点探测:未配置') @@ -567,7 +573,9 @@ describe('SystemSettingsView 数据源配置的默认清单', () => { expect(html).toContain('aria-expanded="false"') expect(html).toContain('仅手动刷新') expect(html).toContain('数据源设置审计') - expect((html.match(/DWS 凭证 ·/g) ?? []).length).toBe(1) + expect((html.match(/aria-label="钉钉账号(DWS)"/g) ?? []).length).toBe(1) + expect(html).toContain('登录授权') + expect(html).toContain('检查连接') for (const removed of ['+ 新增钉钉知识库', '文件格式筛选']) expect(html).not.toContain(removed) // 文档工程师看不到添加向导与「去掉来源」:两者都是管理员动作。 const engineer = view('engineer') @@ -640,3 +648,43 @@ describe('ppSourceConnections(数据源配置的清单规则)', () => { expect(ppSourceConnections([])).toEqual([]) }) }) + +// F03 回归:分区保存不能夹带另一分区未保存的草稿。 +describe('保存边界(F03)', () => { + const server = { + document_refresh_seconds: 15, + resource_refresh_seconds: 30, + stalled_after_seconds: 1800, + finalizing_after_seconds: 7200, + ingestion_concurrency: 2, + test_weknora_base_url: 'https://server.test', + production_weknora_base_url: 'https://server.prod', + production_tenant_id: '10000', + production_knowledge_base_id: 'kb-server', + } as unknown as UISettings + + it('保存刷新策略时忽略服务分区里未保存的地址', () => { + const input = refreshSettingsInput(server, { + documentRefresh: 60, + resourceRefresh: 60, + stalled: 3600, + finalizing: 14400, + concurrency: 4, + }) + expect(input.test_weknora_base_url).toBe('https://server.test') + expect(input.production_weknora_base_url).toBe('https://server.prod') + expect(input.document_refresh_seconds).toBe(60) + }) + + it('保存服务配置时忽略刷新分区里未保存的参数', () => { + const input = serviceSettingsInput(server, { + testEndpoint: 'https://draft.test', + endpoint: 'https://draft.prod', + productionTenantID: '20000', + productionKnowledgeBaseID: 'kb-draft', + }) + expect(input.document_refresh_seconds).toBe(15) + expect(input.ingestion_concurrency).toBe(2) + expect(input.test_weknora_base_url).toBe('https://draft.test') + }) +}) diff --git a/web/src/SystemSettings.tsx b/web/src/SystemSettings.tsx index 713cc6e..81b6587 100644 --- a/web/src/SystemSettings.tsx +++ b/web/src/SystemSettings.tsx @@ -8,25 +8,28 @@ import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } fr import { RoutingBindingsSection } from './RoutingBindingsSection' import { ProductionBindingsSection } from './ProductionBindingsSection' import { SourceWizard } from './SourceWizard' +import { PPConnection } from './PPConnection' import { useOptionalAuth } from './auth' import { fetchMonitorOverview } from './monitor' import type { MonitorOverview } from './monitor' import { fetchReleaseCapabilities } from './reviewRelease' +import { fetchWorkerCapabilities } from './systemCapabilities' +import type { WorkerCapabilities } from './systemCapabilities' import { fetchCatalogRoutingCapabilities, fetchCatalogSources } from './sourceCatalog' import type { CatalogRoutingCapabilities, CatalogSource } from './sourceCatalog' import { archiveSourceConnection, fetchSourceConnectionList } from './sourceConnections' import type { SourceConnectionListItem } from './sourceConnections' -import { - activateUISettings, - createUISettingsCandidate, - fetchActiveUISettings, - validKnowledgeBaseID, - validProductionTenantID, - validServiceEndpoint, -} from './uiSettings' +import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings } from './uiSettings' import type { UISettings, UISettingsCandidateInput } from './uiSettings' +import { refreshSettingsInput } from './settingsInputs' +import { WeKnoraConnections } from './WeKnoraConnections' import './systemSettings.css' +// 连接配置已从「服务配置」迁到「知识库映射」。这两个纯函数仍从本模块导出, +// 既有调用与回归测试的导入路径不变。 +export { refreshSettingsInput, serviceSettingsInput } from './settingsInputs' +export type { RefreshDrafts, ServiceDrafts } from './settingsInputs' + interface Props { sources: CatalogSource[] connections: SourceConnectionListItem[] @@ -35,6 +38,7 @@ interface Props { productionEnabled: boolean productionBackupRestoreVerified?: boolean routingCapabilities: CatalogRoutingCapabilities + workerCapabilities?: WorkerCapabilities | null loading: boolean saving: boolean error: string | null @@ -42,16 +46,16 @@ interface Props { onSave: (input: UISettingsCandidateInput) => void onSourcesChanged: () => void onRefresh: () => void - initialSection?: SectionKey + // 兼容旧入口:'bindings'/'production-bindings' 已合并为“知识库映射”。 + initialSection?: SectionKey | 'bindings' | 'production-bindings' } -type SectionKey = 'sources' | 'services' | 'bindings' | 'production-bindings' | 'storage' | 'refresh' | 'members' +type SectionKey = 'sources' | 'services' | 'knowledge-map' | 'storage' | 'refresh' | 'members' const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [ { key: 'sources', label: '数据源配置' }, - { key: 'services', label: '服务配置' }, - { key: 'bindings', label: '测试知识库绑定' }, - { key: 'production-bindings', label: '生产知识库绑定' }, + { key: 'services', label: 'AI 模型连接' }, + { key: 'knowledge-map', label: '知识库映射' }, { key: 'storage', label: '存储与备份' }, { key: 'refresh', label: '刷新策略' }, { key: 'members', label: '成员与角色', adminOnly: true }, @@ -75,50 +79,6 @@ const secondsLabel = (value: number) => value < 60 ? `${value}秒` : value < 3600 ? `${value / 60}分钟` : `${value / 3600}小时` export const visibleSaveMessage = (message: string | null, dirty: boolean) => (dirty ? null : message) -type ServiceHealthView = MonitorOverview['health'][number] -type ServiceView = MonitorOverview['services'][number] - -// 服务配置只保留四项可写值(测试地址、生产地址、生产 ID、知识库 ID), -// 依赖与解析队列的状态仍按真实探测呈现,不写死。 -const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined => - (monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name)) -export const healthStateLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { - if (!health) { - if (!service) return '待配置' - return service.state === 'healthy' ? '正常' : service.state === 'unknown' ? '未接入' : '需关注' - } - if (health.readiness === 'ready') return '可达 · 可接单' - if (health.readiness === 'not_configured') return '状态未知 · 未配置' - if (health.readiness === 'not_applicable') return '未部署' - return health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单' -} -export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { - if (!health) return service?.detail || '真实 Provider 未接入' - const success = health.last_success_at - ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}` - : '' - if (health.readiness === 'ready') return [`延迟 ${health.latency_ms}ms`, success].filter(Boolean).join(';') - const failures = health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : '' - return [health.reason, success, failures].filter(Boolean).join(';') -} - -// 生产 WeKnora 卡片:端点可达性来自真实探测,写入门禁来自生产开关,两者分开呈现。 -// 生产侧只做探活(/health),不做一次真实读写,所以接单能力永远是「未做接单验证」, -// 不跟着别处的「可达 · 可接单」一起含糊过去。 -export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string => { - const health = findHealth(monitor, '生产 WeKnora') - if (!health) return '端点探测:暂无真实探测结果' - if (!health.configured) return '端点探测:未配置' - const label = - health.liveness === 'up' - ? health.readiness === 'ready' - ? '端点可达 · 未做接单验证' - : '端点可达 · 不可接单' - : '端点不可达' - const detail = healthStateDetail(health, undefined) - return `端点探测:${label}${detail ? `(${detail})` : ''}` -} - export function SystemSettingsView({ sources, connections, @@ -127,6 +87,7 @@ export function SystemSettingsView({ productionEnabled, productionBackupRestoreVerified = false, routingCapabilities, + workerCapabilities = null, loading, saving, error, @@ -137,18 +98,16 @@ export function SystemSettingsView({ }: Props) { const auth = useOptionalAuth() const identity = auth?.identity ?? null - const [section, setSection] = useState(initialSection) + const [section, setSection] = useState( + initialSection === 'bindings' || initialSection === 'production-bindings' + ? 'knowledge-map' + : (initialSection as SectionKey) + ) const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15) const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30) const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800) const [finalizing, setFinalizing] = useState<7200 | 14400>(settings?.finalizing_after_seconds ?? 7200) const [concurrency, setConcurrency] = useState(settings?.ingestion_concurrency ?? 2) - const [endpoint, setEndpoint] = useState(settings?.production_weknora_base_url ?? '') - const [testEndpoint, setTestEndpoint] = useState(settings?.test_weknora_base_url ?? '') - const [productionTenantID, setProductionTenantID] = useState(settings?.production_tenant_id ?? '') - const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState( - settings?.production_knowledge_base_id ?? '' - ) const [dirty, setDirty] = useState(false) // 统一入口后,清单里列全部来源(钉钉知识库 / 钉盘 / PP),不再只显示 PP。 @@ -161,49 +120,30 @@ export function SystemSettingsView({ setStalled(settings.stalled_after_seconds) setFinalizing(settings.finalizing_after_seconds) setConcurrency(settings.ingestion_concurrency) - setEndpoint(settings.production_weknora_base_url) - setTestEndpoint(settings.test_weknora_base_url) - setProductionTenantID(settings.production_tenant_id) - setProductionKnowledgeBaseID(settings.production_knowledge_base_id) setDirty(false) }, [settings]) const canSave = Boolean(settings && !saving) const isAdmin = identity?.role === 'admin' - const endpointValid = validServiceEndpoint(endpoint) - const testEndpointValid = validServiceEndpoint(testEndpoint) - const productionTenantIDValid = validProductionTenantID(productionTenantID) - const productionKnowledgeBaseIDValid = validKnowledgeBaseID(productionKnowledgeBaseID) - const serviceSettingsValid = - endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid - const serviceSettingsDirty = Boolean( + const refreshSettingsDirty = Boolean( settings && - (testEndpoint.trim() !== settings.test_weknora_base_url || - endpoint.trim() !== settings.production_weknora_base_url || - productionTenantID.trim() !== settings.production_tenant_id || - productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id) + (documentRefresh !== settings.document_refresh_seconds || + resourceRefresh !== settings.resource_refresh_seconds || + stalled !== settings.stalled_after_seconds || + finalizing !== settings.finalizing_after_seconds || + concurrency !== settings.ingestion_concurrency) ) - const candidateInput = (overrides: Partial = {}): UISettingsCandidateInput => ({ - document_refresh_seconds: documentRefresh, - resource_refresh_seconds: resourceRefresh, - stalled_after_seconds: stalled, - finalizing_after_seconds: finalizing, - ingestion_concurrency: concurrency, - test_weknora_base_url: testEndpoint.trim(), - production_weknora_base_url: endpoint.trim(), - production_tenant_id: productionTenantID.trim(), - production_knowledge_base_id: productionKnowledgeBaseID.trim(), - ...overrides, - }) - const saveEndpoint = () => { - setDirty(false) - onSave(candidateInput()) - } + // 保存边界:刷新分区只带刷新草稿;WeKnora 连接草稿在 WeKnoraConnections 内独立保存, + // 互不夹带(未保存的地址不会因为保存刷新策略被写进去)。 + const refreshInput = (): UISettingsCandidateInput => + settings + ? refreshSettingsInput(settings, { documentRefresh, resourceRefresh, stalled, finalizing, concurrency }) + : ({} as UISettingsCandidateInput) return (
    -
    +
    -

    系统设置

    +

    系统设置

    {error ? ( @@ -211,7 +151,7 @@ export function SystemSettingsView({ {error} ) : null} - {monitor && settings ? ( + {settings || monitor ? (
    ) } -function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void }) { +function TaskDetail({ + item, + onClose, + onLocateSource, +}: { + item: MonitorTask + onClose: () => void + onLocateSource?: (sourceID: string, parentNodeID: string) => void +}) { const ref = useRef(null) useEffect(() => { ref.current?.showModal() @@ -483,6 +539,7 @@ function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void
    {[ ['来源', item.source_name], + ['来源连接', item.source_id], ['目录', item.path], ['目标知识库', item.target_kb], ['处理动作', actionLabels[item.action]], @@ -499,6 +556,17 @@ function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void ))}
    + {onLocateSource ? ( + + ) : null} {item.history?.length ? (

    版本与重试记录

    @@ -522,7 +590,15 @@ function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void ) } -export function WeKnoraMonitor() { +export function WeKnoraMonitor({ + focus, + onLocateSource, + onFocusApplied, +}: { + focus?: { source: string; q: string } | null + onLocateSource?: (sourceID: string, parentNodeID: string) => void + onFocusApplied?: () => void +} = {}) { const auth = useOptionalAuth() const canOperate = auth?.identity?.role === 'admin' || auth?.identity?.role === 'engineer' const [overview, setOverview] = useState(null), @@ -544,6 +620,15 @@ export function WeKnoraMonitor() { setTabs([]) return () => setTabs([]) }, [setTabs]) + // 从来源目录“查看处理”进入:定位是一次性请求,必须清掉未结束/动作/阶段/时间等 + // 会遮蔽已完成文件的筛选;应用后由父消费掉,避免重挂载时旧请求再次覆盖手工筛选。 + useEffect(() => { + if (!focus) return + setFilters({ ...defaultMonitorFilters, q: focus.q, source: focus.source, status: '' }) + setOffset(0) + setSelected([]) + onFocusApplied?.() + }, [focus]) useEffect(() => { const c = new AbortController() void fetchActiveUISettings(c.signal) @@ -742,8 +827,9 @@ export function WeKnoraMonitor() { .catch((e) => setMessage(e instanceof Error ? e.message : '读取详情失败')) }} onRefresh={refresh} + onLocateSource={onLocateSource} /> - {detail ? setDetail(null)} /> : null} + {detail ? setDetail(null)} onLocateSource={onLocateSource} /> : null} ) } diff --git a/web/src/assets.test.ts b/web/src/assets.test.ts index e807e0c..a317053 100644 --- a/web/src/assets.test.ts +++ b/web/src/assets.test.ts @@ -7,12 +7,22 @@ afterEach(() => vi.unstubAllGlobals()) describe('parseSourceAssetsResponse', () => { it('parses the read-only source inventory envelope', () => { const result = parseSourceAssetsResponse({ - data: [{ - id: 'si-safe', source_type: 'pp', connection_name: 'PP历史公开知识', size_bytes: 52428801, - visibility: 'external', source_change: 'unchanged', content_state: 'over_limit', - legacy_status: 'over_limit', has_publication: false, processing_state: '', retrieval_state: '', - updated_at: '2026-09-04T00:00:00Z', - }], + data: [ + { + id: 'si-safe', + source_type: 'pp', + connection_name: 'PP历史公开知识', + size_bytes: 52428801, + visibility: 'external', + source_change: 'unchanged', + content_state: 'over_limit', + legacy_status: 'over_limit', + has_publication: false, + processing_state: '', + retrieval_state: '', + updated_at: '2026-09-04T00:00:00Z', + }, + ], summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 }, limit: 50, offset: 0, @@ -27,7 +37,12 @@ describe('fetchSourceAssets', () => { it('requests the selected state and server-side page', async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: true, - json: async () => ({ data: [], summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 }, limit: 50, offset: 50 }), + json: async () => ({ + data: [], + summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 }, + limit: 50, + offset: 50, + }), }) vi.stubGlobal('fetch', fetchMock) @@ -35,7 +50,7 @@ describe('fetchSourceAssets', () => { expect(fetchMock).toHaveBeenCalledWith( '/api/v1/source-items?state=over_limit&limit=50&offset=50', - expect.objectContaining({ headers: { Accept: 'application/json' } }), + expect.objectContaining({ headers: { Accept: 'application/json' } }) ) }) }) diff --git a/web/src/assets.ts b/web/src/assets.ts index 89431ab..0231cc7 100644 --- a/web/src/assets.ts +++ b/web/src/assets.ts @@ -46,11 +46,17 @@ export interface SourceAssetQuery { export function parseSourceAssetsResponse(value: unknown): SourceAssetPage { if ( - typeof value !== 'object' || value === null || - !('data' in value) || !Array.isArray(value.data) || - !('summary' in value) || typeof value.summary !== 'object' || value.summary === null || - !('limit' in value) || typeof value.limit !== 'number' || - !('offset' in value) || typeof value.offset !== 'number' + typeof value !== 'object' || + value === null || + !('data' in value) || + !Array.isArray(value.data) || + !('summary' in value) || + typeof value.summary !== 'object' || + value.summary === null || + !('limit' in value) || + typeof value.limit !== 'number' || + !('offset' in value) || + typeof value.offset !== 'number' ) { throw new Error('invalid source assets response') } diff --git a/web/src/auth.tsx b/web/src/auth.tsx index 85dddc2..091d6a1 100644 --- a/web/src/auth.tsx +++ b/web/src/auth.tsx @@ -102,7 +102,9 @@ export function AuthProvider({ children }: { children: ReactNode }) { const login = useCallback(async (username: string, password: string) => { const response = await fetch('/api/v1/auth/login', { - method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) if (!response.ok) return readError(response, '登录失败') @@ -116,19 +118,25 @@ export function AuthProvider({ children }: { children: ReactNode }) { setIdentity(null) }, []) - const changePassword = useCallback(async (currentPassword: string, newPassword: string) => { - const response = await fetch('/api/v1/auth/change-password', { - method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }), - }) - if (!response.ok) return readError(response, '修改密码失败') - await probe() - return null - }, [probe]) + const changePassword = useCallback( + async (currentPassword: string, newPassword: string) => { + const response = await fetch('/api/v1/auth/change-password', { + method: 'POST', + credentials: 'same-origin', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }), + }) + if (!response.ok) return readError(response, '修改密码失败') + await probe() + return null + }, + [probe] + ) const value = useMemo( () => ({ identity, ready, login, logout, changePassword, signedOut, notifySignedOut: bumpSignedOut }), - [identity, ready, login, logout, changePassword, signedOut, bumpSignedOut]) + [identity, ready, login, logout, changePassword, signedOut, bumpSignedOut] + ) return {children} } @@ -153,10 +161,31 @@ export function LoginScreen() {

    知识治理平台

    登录后所有操作将记录到你名下

    - - - {error ?

    {error}

    : null} - + + + {error ? ( +

    + {error} +

    + ) : null} +
    ) @@ -172,13 +201,23 @@ export function MustChangePasswordScreen() { const submit = async (event: React.FormEvent) => { event.preventDefault() - if (next.length < 8) { setError('新密码至少 8 位'); return } - if (next !== confirm) { setError('两次输入的新密码不一致'); return } + if (next.length < 8) { + setError('新密码至少 8 位') + return + } + if (next !== confirm) { + setError('两次输入的新密码不一致') + return + } setBusy(true) const failure = await changePassword(current, next) setBusy(false) setError(failure ?? '') - if (!failure) { setCurrent(''); setNext(''); setConfirm('') } + if (!failure) { + setCurrent('') + setNext('') + setConfirm('') + } } return ( @@ -186,12 +225,38 @@ export function MustChangePasswordScreen() {

    首次登录需要设置新密码

    账号 {identity?.username} 的初始密码只能完成这一次登录

    - - - - {error ?

    {error}

    : null} - - + + + + {error ? ( +

    + {error} +

    + ) : null} + +
    ) @@ -205,14 +270,31 @@ export function TopBarUser() { const name = identity.display_name || identity.username return (
    - {menuOpen ? (
    setMenuOpen(false)}> - +
    ) : null}
    diff --git a/web/src/authMembers.test.ts b/web/src/authMembers.test.ts index 8790984..275b708 100644 --- a/web/src/authMembers.test.ts +++ b/web/src/authMembers.test.ts @@ -10,7 +10,18 @@ describe('role labels', () => { describe('members API', () => { it('parses the managed user roster', async () => { - const payload = { data: [{ id: 'usr-1', username: 'boss', display_name: '老板', role: 'admin', state: 'active', must_change_password: false }] } + const payload = { + data: [ + { + id: 'usr-1', + username: 'boss', + display_name: '老板', + role: 'admin', + state: 'active', + must_change_password: false, + }, + ], + } const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(payload), { status: 200 })) vi.stubGlobal('fetch', fetchMock) const users = await fetchManagedUsers() @@ -20,17 +31,33 @@ describe('members API', () => { vi.unstubAllGlobals() }) it('rejects a role the server does not know', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'u', username: 'x', role: 'superuser', state: 'active' }] })))) + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify({ data: [{ id: 'u', username: 'x', role: 'superuser', state: 'active' }] })) + ) + ) await expect(fetchManagedUsers()).rejects.toThrow('成员响应无效') vi.unstubAllGlobals() }) it('surfaces server errors for state changes', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'cannot disable the last active admin' }), { status: 409 }))) + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify({ error: 'cannot disable the last active admin' }), { status: 409 }) + ) + ) await expect(setManagedUserState('usr-1', 'disabled')).rejects.toThrow('cannot disable the last active admin') vi.unstubAllGlobals() }) it('resets passwords without sending any actor field', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { reset: true } }), { status: 200 })) + const fetchMock = vi + .fn() + .mockResolvedValue(new Response(JSON.stringify({ data: { reset: true } }), { status: 200 })) vi.stubGlobal('fetch', fetchMock) await resetManagedUserPassword('usr-2', 'temp-pass-1') const body = JSON.parse(String(fetchMock.mock.calls[0][1].body)) diff --git a/web/src/backupSchedule.test.ts b/web/src/backupSchedule.test.ts index f129dc4..a6f1e4f 100644 --- a/web/src/backupSchedule.test.ts +++ b/web/src/backupSchedule.test.ts @@ -3,24 +3,53 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { fetchBackupSchedule, fetchBackupScheduleHost, runBackupNow, saveBackupSchedule } from './backupSchedule' const payload = { - enabled: true, schedule_time: '03:30', retention_days: 7, retention_months: 3, - updated_by: 'yaozhanghao', updated_at: '2026-10-09T12:00:00Z', last_applied_at: '', last_applied_summary: '', - host_configured: true, host_target: 'weknora-test', host_reachable: true, host_error: '', - host_schedule_enabled: true, host_schedule_time: '03:30', host_keep_days: 7, host_keep_months: 3, - host_cron_lines: ['30 03 * * * root …'], host_cron_service: 'active', host_script_present: true, - last_run_stamp: '20261009T052909Z', last_run_created_at: '2026-10-09T05:29:09Z', - last_run_duration_seconds: 33, last_run_total_bytes: 778502144, - last_run_databases: ['weknora_test'], last_run_failed_databases: [], last_run_error: '', - in_sync: true, applied: true, apply_error: '', running: false, running_started_at: '', run_last_error: '', + enabled: true, + schedule_time: '03:30', + retention_days: 7, + retention_months: 3, + updated_by: 'yaozhanghao', + updated_at: '2026-10-09T12:00:00Z', + last_applied_at: '', + last_applied_summary: '', + host_configured: true, + host_target: 'weknora-test', + host_reachable: true, + host_error: '', + host_schedule_enabled: true, + host_schedule_time: '03:30', + host_keep_days: 7, + host_keep_months: 3, + host_cron_lines: ['30 03 * * * root …'], + host_cron_service: 'active', + host_script_present: true, + last_run_stamp: '20261009T052909Z', + last_run_created_at: '2026-10-09T05:29:09Z', + last_run_duration_seconds: 33, + last_run_total_bytes: 778502144, + last_run_databases: ['weknora_test'], + last_run_failed_databases: [], + last_run_error: '', + in_sync: true, + applied: true, + apply_error: '', + running: false, + running_started_at: '', + run_last_error: '', } -const jsonResponse = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) +const jsonResponse = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) -afterEach(() => { vi.unstubAllGlobals() }) +afterEach(() => { + vi.unstubAllGlobals() +}) describe('backupSchedule 客户端', () => { it('解析计划三要素与主机回执', async () => { - vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ data: payload }))) + vi.stubGlobal( + 'fetch', + vi.fn(async () => jsonResponse({ data: payload })) + ) const schedule = await fetchBackupSchedule() expect(schedule.schedule_time).toBe('03:30') expect(schedule.retention_days).toBe(7) @@ -31,18 +60,28 @@ describe('backupSchedule 客户端', () => { it('缺计划字段就报错,绝不把默认值伪装成真实设置', async () => { const broken = { ...payload } as Record delete broken.retention_days - vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ data: broken }))) + vi.stubGlobal( + 'fetch', + vi.fn(async () => jsonResponse({ data: broken })) + ) await expect(fetchBackupScheduleHost()).rejects.toThrow('存储与备份响应缺少计划字段') }) it('保存失败时把后端的中文原因透出来', async () => { - vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: '储存天数需在 1~365 之间,收到 0' }, 400))) - await expect(saveBackupSchedule({ enabled: true, schedule_time: '03:30', retention_days: 0, retention_months: 3 })) - .rejects.toThrow('储存天数需在 1~365 之间,收到 0') + vi.stubGlobal( + 'fetch', + vi.fn(async () => jsonResponse({ error: '储存天数需在 1~365 之间,收到 0' }, 400)) + ) + await expect( + saveBackupSchedule({ enabled: true, schedule_time: '03:30', retention_days: 0, retention_months: 3 }) + ).rejects.toThrow('储存天数需在 1~365 之间,收到 0') }) it('立即备份返回 202 时识别为已启动', async () => { - vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ data: { started: true, running: true } }, 202))) + vi.stubGlobal( + 'fetch', + vi.fn(async () => jsonResponse({ data: { started: true, running: true } }, 202)) + ) await expect(runBackupNow()).resolves.toEqual({ started: true, running: true }) }) }) diff --git a/web/src/backupSchedule.ts b/web/src/backupSchedule.ts index 3ed9f2a..24d38e4 100644 --- a/web/src/backupSchedule.ts +++ b/web/src/backupSchedule.ts @@ -12,10 +12,15 @@ export interface BackupSchedule { last_applied_summary: string host_configured: boolean host_target: string + // host_endpoint 是这条别名真实拨号的 host:port(来自挂载的 ssh 配置)。 + host_endpoint: string host_reachable: boolean host_error: string host_schedule_enabled: boolean host_schedule_time: string + // 主机若没有返回真实 next-run,保持空串;页面不得用历史下发时间推算。 + host_next_run?: string + host_checked_at?: string host_keep_days: number host_keep_months: number host_cron_lines: string[] @@ -52,7 +57,11 @@ const asStringList = (value: unknown): string[] => // 严格解析:计划三要素(时间/天数/月数)必须是正确类型,缺一个就整块报错, // 而不是让界面显示成"默认 03:30 / 7 天"这种假状态。 function scheduleProjection(item: Record): BackupSchedule { - if (typeof item.schedule_time !== 'string' || typeof item.retention_days !== 'number' || typeof item.retention_months !== 'number') { + if ( + typeof item.schedule_time !== 'string' || + typeof item.retention_days !== 'number' || + typeof item.retention_months !== 'number' + ) { throw new Error('存储与备份响应缺少计划字段(schedule_time / retention_days / retention_months)') } return { @@ -66,10 +75,13 @@ function scheduleProjection(item: Record): BackupSchedule { last_applied_summary: asString(item.last_applied_summary), host_configured: item.host_configured === true, host_target: asString(item.host_target), + host_endpoint: asString(item.host_endpoint), host_reachable: item.host_reachable === true, host_error: asString(item.host_error), host_schedule_enabled: item.host_schedule_enabled === true, host_schedule_time: asString(item.host_schedule_time), + host_next_run: asString(item.host_next_run), + host_checked_at: asString(item.host_checked_at), host_keep_days: asNumber(item.host_keep_days), host_keep_months: asNumber(item.host_keep_months), host_cron_lines: asStringList(item.host_cron_lines), @@ -94,7 +106,7 @@ function scheduleProjection(item: Record): BackupSchedule { async function readSchedule(path: string, failure: string, signal?: AbortSignal): Promise { const response = await fetch(path, { signal, headers: { Accept: 'application/json' } }) if (!response.ok) throw new Error(`${failure}(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效') return scheduleProjection(value.data) } @@ -108,21 +120,30 @@ export function fetchBackupScheduleHost(signal?: AbortSignal): Promise { +async function writeSchedule( + path: string, + method: string, + body: unknown, + failure: string, + signal?: AbortSignal +): Promise { const response = await fetch(path, { - method, signal, + method, + signal, headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() }, body: body === undefined ? undefined : JSON.stringify(body), }) if (!response.ok) { let reason = `${failure}(HTTP ${response.status})` try { - const payload = await response.json() as unknown + const payload = (await response.json()) as unknown if (record(payload) && typeof payload.error === 'string') reason = payload.error - } catch { /* keep the status text */ } + } catch { + /* keep the status text */ + } throw new Error(reason) } - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效') return scheduleProjection(value.data) } @@ -146,18 +167,21 @@ export function applyBackupSchedule(signal?: AbortSignal): Promise { const response = await fetch('/api/v1/backup-schedule/run', { - method: 'POST', signal, + method: 'POST', + signal, headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() }, }) if (!response.ok) { let reason = `触发备份失败(HTTP ${response.status})` try { - const payload = await response.json() as unknown + const payload = (await response.json()) as unknown if (record(payload) && typeof payload.error === 'string') reason = payload.error - } catch { /* keep the status text */ } + } catch { + /* keep the status text */ + } throw new Error(reason) } - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !record(value.data)) throw new Error('触发备份响应无效') return { started: value.data.started === true, running: value.data.running === true } -} \ No newline at end of file +} diff --git a/web/src/dingtalkSession.ts b/web/src/dingtalkSession.ts index d113818..19831fe 100644 --- a/web/src/dingtalkSession.ts +++ b/web/src/dingtalkSession.ts @@ -65,6 +65,7 @@ export async function cancelDingtalkSession(id: string): Promise { export interface RegisteredDingtalkSpace { connection_id: string name: string + first_scan_queued?: boolean } export class DingtalkRequestError extends Error { @@ -81,14 +82,19 @@ export class DingtalkRequestError extends Error { // Register a DingTalk knowledge-base space (URL or bare space id) as a new // source connection. Errors carry the sidecar's machine codes so the UI can // explain them: login_required, space_not_found, name_conflict. -export async function registerDingtalkSpace(url: string): Promise { +export async function registerDingtalkSpace( + url: string, + operationID = newOperationID(), + identity?: string +): Promise { const response = await fetch('/api/v1/dingtalk-spaces', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'dingtalk-space', - 'Idempotency-Key': newOperationID(), + 'Idempotency-Key': operationID, + ...(identity ? { 'X-DWS-Identity': identity } : {}), }, body: JSON.stringify({ url }), }) @@ -106,7 +112,11 @@ export async function registerDingtalkSpace(url: string): Promise = { - login_required: '钉钉扫码会话无效或已过期,请先在钉钉来源卡片上「扫码刷新会话」', + login_required: 'DWS 授权已失效,请重新授权', + dws_login_required: 'DWS 授权已失效,请重新授权', + dws_unavailable: 'DWS 目录暂时不可用,请重试', + dws_permission_denied: '当前 DWS 账号缺少目录权限', + dws_identity_changed: 'DWS 账号或组织已变化,请重新确认来源', space_not_found: '未找到该知识库空间:请确认空间链接正确且当前账号有阅读权限', name_conflict: '该空间与已登记的来源同名', // 登记冲突分两种:同名来源还在用 vs 同一个登记键指向了别的空间。原因要说清, @@ -127,7 +137,11 @@ export async function registerDingtalkSpace(url: string): Promise { describe('fetchAvailableDingtalkSources', () => { it('parses knowledge bases and drive spaces', async () => { - vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(payload), { status: 200 }))) + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify(payload), { status: 200 })) + ) const list = await fetchAvailableDingtalkSources() expect(list.knowledge_bases).toHaveLength(3) expect(list.knowledge_bases[1].url).toBe('https://alidocs.dingtalk.com/i/spaces/9JOGO9EEOMLMWX4Q/overview') @@ -36,16 +58,36 @@ describe('fetchAvailableDingtalkSources', () => { }) it('explains environment problems instead of pretending the list is empty', async () => { - vi.stubGlobal('fetch', vi.fn(async () => new Response('{"error":"dingtalk_discovery_unavailable"}', { status: 503 }))) + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('{"error":"dingtalk_discovery_unavailable"}', { status: 503 })) + ) await expect(fetchAvailableDingtalkSources()).rejects.toThrow(/暂时列不出来/) - vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 501 }))) + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('{}', { status: 501 })) + ) await expect(fetchAvailableDingtalkSources()).rejects.toThrow(/后端未接线/) - vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 403 }))) + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('{}', { status: 403 })) + ) await expect(fetchAvailableDingtalkSources()).rejects.toThrow(/需要管理员身份/) }) it('carries the drive notice so the page can explain a missing 钉盘 list', async () => { - vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: { knowledge_bases: [], drive_spaces: [], drive_notice: 'list orgSpace: permission denied' } }), { status: 200 }))) + vi.stubGlobal( + 'fetch', + vi.fn( + async () => + new Response( + JSON.stringify({ + data: { knowledge_bases: [], drive_spaces: [], drive_notice: 'list orgSpace: permission denied' }, + }), + { status: 200 } + ) + ) + ) const list = await fetchAvailableDingtalkSources() expect(list.drive_notice).toContain('permission denied') }) @@ -55,7 +97,11 @@ describe('discoveryCandidates', () => { it('flattens both groups and marks the ones already registered as sources', () => { const candidates = discoveryCandidates(payload.data as never, ['ATOM知识库', ' (空名字) ']) expect(candidates.map((item) => item.key)).toEqual([ - 'kb:9JOGOQneRgkneX4Q', 'kb:9JOGO9EEOMLMWX4Q', 'kb:9JOGOxeo90ybnz4Q', 'drive:28122692916', 'drive:102571304', + 'kb:9JOGOQneRgkneX4Q', + 'kb:9JOGO9EEOMLMWX4Q', + 'kb:9JOGOxeo90ybnz4Q', + 'drive:28122692916', + 'drive:102571304', ]) expect(candidates[0].alreadyRegistered).toBe(true) expect(candidates[1].alreadyRegistered).toBe(false) @@ -69,4 +115,4 @@ describe('discoveryCandidates', () => { it('returns nothing for an empty list', () => { expect(discoveryCandidates(null, ['X'])).toEqual([]) }) -}) \ No newline at end of file +}) diff --git a/web/src/dingtalkSources.ts b/web/src/dingtalkSources.ts index 255bd1b..c5b9a36 100644 --- a/web/src/dingtalkSources.ts +++ b/web/src/dingtalkSources.ts @@ -1,7 +1,10 @@ // 「系统设置 → 数据源配置」的数据源发现客户端:列出当前 dws 账号能看到的钉钉知识库与钉盘空间。 // 只读;勾选后的登记仍走既有的 /api/v1/dingtalk-spaces(由扫码会话解析空间根目录)。 +import { DingtalkRequestError } from './dingtalkSession' + export interface AvailableKnowledgeBase { + registered?: boolean name: string space_id: string space_type?: string @@ -10,6 +13,7 @@ export interface AvailableKnowledgeBase { } export interface AvailableDriveSpace { + registered?: boolean name: string space_id: string space_type: string @@ -38,13 +42,19 @@ function isRecord(value: unknown): value is Record { export async function fetchAvailableDingtalkSources(signal?: AbortSignal): Promise { const response = await fetch('/api/v1/dingtalk-spaces/available', { headers: { Accept: 'application/json' }, signal }) if (!response.ok) { - // 503 是环境问题(dws 未登录/权限不足),501 是后端没接线:都要说清楚"不是没有来源"。 - if (response.status === 503) throw new Error('暂时列不出来:dws 未登录或缺少租户目录读权限。先刷新钉钉会话,或让管理员检查 dws 凭据。') - if (response.status === 501) throw new Error('后端未接线:数据源发现接口不可用。') - if (response.status === 401 || response.status === 403) throw new Error('需要管理员身份才能列举数据源。') - throw new Error(`列举数据源失败(HTTP ${response.status})`) + const body: unknown = await response.json().catch(() => null) + const code = isRecord(body) && typeof body.error === 'string' ? body.error : 'request_failed' + const hint = + isRecord(body) && typeof body.hint === 'string' + ? body.hint + : response.status === 501 + ? '后端未接线:DWS 来源服务不可用。' + : response.status === 401 || response.status === 403 + ? '需要管理员身份才能列举数据源。' + : `目录暂时列不出来(HTTP ${response.status})` + throw new DingtalkRequestError(hint, code, response.status) } - const payload = await response.json() as unknown + const payload = (await response.json()) as unknown const data = isRecord(payload) && isRecord(payload.data) ? payload.data : {} const knowledgeBases = Array.isArray(data.knowledge_bases) ? data.knowledge_bases : [] const driveSpaces = Array.isArray(data.drive_spaces) ? data.drive_spaces : [] @@ -55,14 +65,35 @@ export async function fetchAvailableDingtalkSources(signal?: AbortSignal): Promi const spaceID = typeof item.space_id === 'string' ? item.space_id : '' const url = typeof item.url === 'string' && item.url ? item.url : driveSpaceURL(spaceID) const spaceType = typeof item.space_type === 'string' ? item.space_type : '' - return name && spaceID ? [{ name, space_id: spaceID, space_type: spaceType, url, description: typeof item.description === 'string' ? item.description : '' }] : [] + return name && spaceID + ? [ + { + name, + registered: item.registered === true, + space_id: spaceID, + space_type: spaceType, + url, + description: typeof item.description === 'string' ? item.description : '', + }, + ] + : [] }), drive_spaces: driveSpaces.flatMap((item) => { if (!isRecord(item)) return [] const name = typeof item.name === 'string' ? item.name : '' const spaceID = typeof item.space_id === 'string' ? item.space_id : '' const spaceType = typeof item.space_type === 'string' ? item.space_type : '' - return name && spaceID ? [{ name, space_id: spaceID, space_type: spaceType, root_folder_id: typeof item.root_folder_id === 'string' ? item.root_folder_id : '' }] : [] + return name && spaceID + ? [ + { + name, + registered: item.registered === true, + space_id: spaceID, + space_type: spaceType, + root_folder_id: typeof item.root_folder_id === 'string' ? item.root_folder_id : '', + }, + ] + : [] }), knowledge_notice: typeof data.knowledge_notice === 'string' ? data.knowledge_notice : '', drive_notice: typeof data.drive_notice === 'string' ? data.drive_notice : '', @@ -81,8 +112,10 @@ export interface DiscoveryCandidate { // 把发现结果拍平成可勾选列表:已登记(按空间名比对来源连接名)的条目打标,页面据此禁用勾选, // 避免重复登记。 -export function discoveryCandidates(list: AvailableDingtalkSources | null, registeredNames: string[]): DiscoveryCandidate[] { - const registered = new Set(registeredNames.map((name) => name.trim()).filter(Boolean)) +export function discoveryCandidates( + list: AvailableDingtalkSources | null, + _registeredNames: string[] +): DiscoveryCandidate[] { const knowledgeBases = (list?.knowledge_bases ?? []).map((item): DiscoveryCandidate => ({ key: `kb:${item.space_id}`, kind: 'knowledge_base', @@ -90,7 +123,7 @@ export function discoveryCandidates(list: AvailableDingtalkSources | null, regis spaceID: item.space_id, url: item.url || driveSpaceURL(item.space_id), detail: item.space_type === 'myWikiSpace' ? '钉钉知识库 · 我的知识库' : '钉钉知识库 · 组织知识库', - alreadyRegistered: registered.has(item.name.trim()), + alreadyRegistered: item.registered === true, })) const driveSpaces = (list?.drive_spaces ?? []).map((item): DiscoveryCandidate => ({ key: `drive:${item.space_id}`, @@ -99,7 +132,36 @@ export function discoveryCandidates(list: AvailableDingtalkSources | null, regis spaceID: item.space_id, url: driveSpaceURL(item.space_id), detail: item.space_type === 'mySpace' ? '钉盘 · 我的文件' : '钉盘 · 组织空间', - alreadyRegistered: registered.has(item.name.trim()), + alreadyRegistered: item.registered === true, })) return [...knowledgeBases, ...driveSpaces] } + +export async function validateDingtalkSources(urls: string[], identity?: string): Promise<{ checked_at: string }> { + const response = await fetch('/api/v1/dingtalk-spaces/validate', { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'X-Governance-Action': 'dingtalk-space', + ...(identity ? { 'X-DWS-Identity': identity } : {}), + }, + body: JSON.stringify({ urls }), + }) + const body: unknown = await response.json().catch(() => null) + if (!response.ok) { + const code = isRecord(body) && typeof body.error === 'string' ? body.error : 'validation_failed' + const hint = isRecord(body) && typeof body.hint === 'string' ? body.hint : '来源校验失败,请重新读取范围' + throw new DingtalkRequestError(hint, code, response.status) + } + if ( + !isRecord(body) || + !isRecord(body.data) || + body.data.valid !== true || + body.data.count !== urls.length || + typeof body.data.checked_at !== 'string' || + !Number.isFinite(Date.parse(body.data.checked_at)) + ) + throw new Error('未取得有效的来源校验结果') + return { checked_at: body.data.checked_at } +} diff --git a/web/src/documentFixture.ts b/web/src/documentFixture.ts index a807af4..8ac0563 100644 --- a/web/src/documentFixture.ts +++ b/web/src/documentFixture.ts @@ -1,6 +1,23 @@ import type { SourceAsset } from './assets' export const document: SourceAsset = { - id: 'a', connection_id: 'pp-1', connection_name: 'PP', source_type: 'pp', title: '手册.pdf', directory_path: '使用指南', visibility_origin: 'pp_public_tag', visibility: 'external', size_bytes: 1024, - content_state: 'verified', source_change: 'unchanged', legacy_status: 'completed', has_publication: true, ingest_state: 'uploaded', processing_state: 'completed', retrieval_state: 'unpublished', last_error: '', publication_id: 'p-a', updated_at: '2026-09-06T01:00:00Z', + id: 'a', + connection_id: 'pp-1', + connection_name: 'PP', + source_type: 'pp', + title: '手册.pdf', + directory_path: '使用指南', + visibility_origin: 'pp_public_tag', + visibility: 'external', + size_bytes: 1024, + content_state: 'verified', + source_change: 'unchanged', + legacy_status: 'completed', + has_publication: true, + ingest_state: 'uploaded', + processing_state: 'completed', + retrieval_state: 'unpublished', + last_error: '', + publication_id: 'p-a', + updated_at: '2026-09-06T01:00:00Z', } diff --git a/web/src/documentWorkbench.css b/web/src/documentWorkbench.css index 7d05c26..6979d71 100644 --- a/web/src/documentWorkbench.css +++ b/web/src/documentWorkbench.css @@ -1,96 +1,488 @@ -.document-workbench { max-width: 1800px; } -.document-layout { display: grid; grid-template-columns: 250px minmax(0, 1fr); gap: 18px; align-items: start; } -.directory-panel, .document-content { min-width: 0; background: white; border: 1px solid var(--border-base); border-radius: 14px; } -.directory-panel { padding: 10px; max-height: calc(100vh - 220px); overflow-y: auto; } -.directory-panel .folder { display: flex; width: 100%; align-items: center; justify-content: space-between; gap: 10px; border: 0; border-radius: 8px; padding: 11px 10px; background: transparent; color: var(--ink-base); text-align: left; box-shadow: none; } -.directory-panel .folder:hover { background: var(--c-run-bg); } -.directory-panel .folder.active { background: var(--c-run-bg); color: var(--c-run); } -.directory-panel .folder span { overflow-wrap: anywhere; } -.directory-panel .folder.child { padding-left: 23px; font-size: 12px; font-weight: 500; } -.directory-panel .folder b { flex: 0 0 auto; font-size: 12px; } -.directory-note { display: block; padding: 8px 12px; color: var(--ink-mute); font-size: 12px; line-height: 1.6; } -.source-unconnected { margin: 8px 0; padding: 12px; border-top: 1px solid var(--bg-soft); color: var(--ink-mute); } -.source-unconnected small { display: block; margin-top: 6px; } -.test-document-toggle { display: flex; align-items: center; gap: 8px; margin: 12px 8px 4px; padding-top: 12px; border-top: 1px solid var(--border-base); color: var(--ink-mute); font-size: 12px; } -.source-progress { margin-bottom: 16px; padding: 16px 18px; border: 1px solid var(--border-base); border-radius: 14px; background: var(--bg-panel); } -.section-title { display: flex; justify-content: space-between; gap: 16px; margin-bottom: 12px; color: var(--ink-base); } -.section-title span { color: var(--ink-mute); font-size: 12px; } -.source-progress-grid { display: grid; grid-template-columns: repeat(auto-fit,minmax(230px,1fr)); gap: 10px; } -.source-progress-card { display: grid; gap: 6px; padding: 13px 15px; border: 1px solid var(--border-base); border-radius: 10px; background: var(--bg-soft); color: var(--ink-base); text-align: left; box-shadow: none; } -.source-progress-card.active { border-color: var(--c-run); background: var(--c-run-bg); } -.source-progress-card span { font-weight: 700; } -.source-progress-card small { color: var(--ink-mute); } +.document-workbench { + max-width: 1800px; +} +.document-layout { + display: grid; + grid-template-columns: 250px minmax(0, 1fr); + gap: 18px; + align-items: start; +} +.directory-panel, +.document-content { + min-width: 0; + background: white; + border: 1px solid var(--border-base); + border-radius: 14px; +} +.directory-panel { + padding: 10px; + max-height: calc(100vh - 220px); + overflow-y: auto; +} +.directory-panel .folder { + display: flex; + width: 100%; + align-items: center; + justify-content: space-between; + gap: 10px; + border: 0; + border-radius: 8px; + padding: 11px 10px; + background: transparent; + color: var(--ink-base); + text-align: left; + box-shadow: none; +} +.directory-panel .folder:hover { + background: var(--c-run-bg); +} +.directory-panel .folder.active { + background: var(--c-run-bg); + color: var(--c-run); +} +.directory-panel .folder span { + overflow-wrap: anywhere; +} +.directory-panel .folder.child { + padding-left: 23px; + font-size: 12px; + font-weight: 500; +} +.directory-panel .folder b { + flex: 0 0 auto; + font-size: 12px; +} +.directory-note { + display: block; + padding: 8px 12px; + color: var(--ink-mute); + font-size: 12px; + line-height: 1.6; +} +.source-unconnected { + margin: 8px 0; + padding: 12px; + border-top: 1px solid var(--bg-soft); + color: var(--ink-mute); +} +.source-unconnected small { + display: block; + margin-top: 6px; +} +.test-document-toggle { + display: flex; + align-items: center; + gap: 8px; + margin: 12px 8px 4px; + padding-top: 12px; + border-top: 1px solid var(--border-base); + color: var(--ink-mute); + font-size: 12px; +} +.source-progress { + margin-bottom: 16px; + padding: 16px 18px; + border: 1px solid var(--border-base); + border-radius: 14px; + background: var(--bg-panel); +} +.section-title { + display: flex; + justify-content: space-between; + gap: 16px; + margin-bottom: 12px; + color: var(--ink-base); +} +.section-title span { + color: var(--ink-mute); + font-size: 12px; +} +.source-progress-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); + gap: 10px; +} +.source-progress-card { + display: grid; + gap: 6px; + padding: 13px 15px; + border: 1px solid var(--border-base); + border-radius: 10px; + background: var(--bg-soft); + color: var(--ink-base); + text-align: left; + box-shadow: none; +} +.source-progress-card.active { + border-color: var(--c-run); + background: var(--c-run-bg); +} +.source-progress-card span { + font-weight: 700; +} +.source-progress-card small { + color: var(--ink-mute); +} -.document-counts { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); padding: 18px; border-bottom: 1px solid var(--border-base); gap: 10px; } -.document-counts span { font-size: 12px; color: var(--ink-mute); } -.document-counts b { display: block; margin-top: 5px; font-size: 24px; color: var(--ink-strong); } -.document-filters { display: flex; flex-wrap: wrap; gap: 12px; padding: 16px 18px; align-items: end; } -.document-filters label { display: grid; gap: 6px; font-size: 12px; color: var(--ink-base); } -.document-filters label:first-child { flex: 1; min-width: 140px; } -.document-filters input, .document-filters select { width: 100%; min-width: 0; border: 1px solid var(--border-strong); border-radius: 8px; padding: 10px; background: white; color: var(--ink-strong); } -.scope-editor { margin: 14px 18px 2px; padding: 13px 14px; border: 1px solid var(--border-strong); border-radius: 10px; background: var(--bg-soft); } -.scope-editor-heading { display: flex; justify-content: space-between; gap: 12px; align-items: center; } -.scope-editor-heading > div { display: grid; gap: 3px; } -.scope-editor-heading span, .scope-rule-meta, .scope-editor small { color: var(--ink-mute); font-size: 11px; } -.inherited-badge { padding: 5px 7px; border-radius: 6px; background: var(--bg-soft); color: var(--ink-mute); font-weight: 650; } -.scope-rule-meta { margin: 7px 0 10px; } -.scope-editor-fields { display: grid; grid-template-columns: 120px 160px minmax(180px,1fr); gap: 9px; } -.scope-editor-fields label { display: grid; gap: 4px; color: var(--ink-base); font-size: 11px; } -.scope-editor-fields input, .scope-editor-fields select { min-width: 0; padding: 8px; border: 1px solid var(--border-strong); border-radius: 7px; background: var(--bg-panel); } -.scope-editor-actions { display: flex; gap: 8px; align-items: center; margin: 10px 0 7px; } -.scope-editor-actions button { padding: 8px 12px; } -.scope-editor-actions .secondary { background: var(--bg-panel); color: var(--ink-base); border-color: var(--ink-faint); box-shadow: none; } -.scope-error, .scope-unavailable { margin: 10px 18px; padding: 10px 12px; border-radius: 8px; background: var(--c-warn-bg); color: var(--c-warn); font-size: 12px; } -.document-location { padding: 0 18px 14px; font-size: 13px; font-weight: 650; color: var(--ink-base); } -.document-location span { float: right; color: var(--ink-mute); font-weight: 400; } -.document-table { table-layout: fixed; width: 100%; } -.document-content .table-wrap { max-height: max(300px, calc(100vh - 470px)); overflow: auto; } -.document-table thead th { position: sticky; top: 0; z-index: 1; background: var(--bg-soft); } -.document-table th:nth-child(1) { width: 37%; } -.document-table th:nth-child(2) { width: 16%; } -.document-table th:nth-child(3) { width: 19%; } -.document-table th:nth-child(4) { width: 10%; } -.document-table th:nth-child(5) { width: 18%; } -.document-table th, .document-table td { padding: 13px 12px; white-space: normal; overflow-wrap: anywhere; font-size: 12px; } -.document-table small { display: block; margin-top: 7px; color: var(--ink-mute); font-size: 11px; } -.document-workbench .file-link { padding: 0; border: 0; background: transparent; color: var(--c-run); text-align: left; font-size: 13px; box-shadow: none; white-space: normal; overflow-wrap: anywhere; line-height: 1.55; } -.document-workbench .file-link:hover { text-decoration: underline; } -.scope-badge, .document-stage { display: inline-block; border-radius: 6px; padding: 5px 7px; font-size: 12px; font-weight: 650; background: var(--border-soft); color: var(--ink-base); } -.scope-badge.external { color: var(--c-done); background: var(--c-done-bg); } -.scope-badge.internal { color: var(--ink-base); background: var(--c-run-bg); } -.document-stage.completed, .document-stage.reused { color: var(--c-done); background: var(--c-done-bg); } -.document-stage.blocked, .document-stage.failed { color: var(--c-warn); background: var(--c-warn-bg); } -.document-stage.parsing, .document-stage.indexing, .document-stage.uploading, .document-stage.downloading { color: var(--c-run); background: var(--c-run-bg); } -.document-inspector { position: fixed; top: 80px; right: 20px; bottom: 20px; z-index: 50; width: min(480px, calc(100vw - 40px)); overflow-y: auto; background: white; border: 2px solid var(--c-run-border); box-shadow: 0 12px 48px #12345240; margin: 0; } -.document-inspector h2 { overflow-wrap: anywhere; font-size: 17px; } -.inspector-body { padding: 0 22px 20px; font-size: 13px; line-height: 1.7; color: var(--ink-base); } -.inspector-body dl { display: grid; grid-template-columns: 100px minmax(0,1fr); gap: 8px; } -.inspector-body dd { margin: 0; overflow-wrap: anywhere; } -.file-facts { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 8px; margin: 14px 0; } -.file-facts span { display: grid; padding: 9px; border-radius: 8px; background: var(--bg-soft); color: var(--ink-mute); font-size: 11px; } -.file-facts b { margin-top: 3px; color: var(--ink-base); font-size: 12px; } -.document-pipeline { display: grid; grid-template-columns: repeat(4,minmax(0,1fr)); gap: 5px; margin: 14px 0; } -.pipeline-step { display: grid; grid-template-columns: 9px minmax(0,1fr); gap: 6px; align-items: start; padding: 8px 5px; border-radius: 7px; background: var(--bg-soft); } -.pipeline-step > span { width: 8px; height: 8px; margin-top: 5px; border-radius: 50%; background: var(--ink-faint); } -.pipeline-step div { display: grid; min-width: 0; } -.pipeline-step strong { font-size: 10px; color: var(--ink-base); } -.pipeline-step small { color: var(--ink-mute); font-size: 9px; overflow-wrap: anywhere; } -.pipeline-step.done > span { background: var(--c-done); } -.pipeline-step.active > span { background: var(--c-run); } -.pipeline-step.problem > span { background: var(--c-warn); } -.document-inspector .scope-editor { margin: 16px 0; } -.document-workbench button:disabled { cursor: not-allowed; color: var(--ink-faint); background: var(--bg-soft); border-color: var(--border-base); } +.document-counts { + display: grid; + grid-template-columns: repeat(6, minmax(0, 1fr)); + padding: 18px; + border-bottom: 1px solid var(--border-base); + gap: 10px; +} +.document-counts span { + font-size: 12px; + color: var(--ink-mute); +} +.document-counts b { + display: block; + margin-top: 5px; + font-size: 24px; + color: var(--ink-strong); +} +.document-filters { + display: flex; + flex-wrap: wrap; + gap: 12px; + padding: 16px 18px; + align-items: end; +} +.document-filters label { + display: grid; + gap: 6px; + font-size: 12px; + color: var(--ink-base); +} +.document-filters label:first-child { + flex: 1; + min-width: 140px; +} +.document-filters input, +.document-filters select { + width: 100%; + min-width: 0; + border: 1px solid var(--border-strong); + border-radius: 8px; + padding: 10px; + background: white; + color: var(--ink-strong); +} +.scope-editor { + margin: 14px 18px 2px; + padding: 13px 14px; + border: 1px solid var(--border-strong); + border-radius: 10px; + background: var(--bg-soft); +} +.scope-editor-heading { + display: flex; + justify-content: space-between; + gap: 12px; + align-items: center; +} +.scope-editor-heading > div { + display: grid; + gap: 3px; +} +.scope-editor-heading span, +.scope-rule-meta, +.scope-editor small { + color: var(--ink-mute); + font-size: 11px; +} +.inherited-badge { + padding: 5px 7px; + border-radius: 6px; + background: var(--bg-soft); + color: var(--ink-mute); + font-weight: 650; +} +.scope-rule-meta { + margin: 7px 0 10px; +} +.scope-editor-fields { + display: grid; + grid-template-columns: 120px 160px minmax(180px, 1fr); + gap: 9px; +} +.scope-editor-fields label { + display: grid; + gap: 4px; + color: var(--ink-base); + font-size: 11px; +} +.scope-editor-fields input, +.scope-editor-fields select { + min-width: 0; + padding: 8px; + border: 1px solid var(--border-strong); + border-radius: 7px; + background: var(--bg-panel); +} +.scope-editor-actions { + display: flex; + gap: 8px; + align-items: center; + margin: 10px 0 7px; +} +.scope-editor-actions button { + padding: 8px 12px; +} +.scope-editor-actions .secondary { + background: var(--bg-panel); + color: var(--ink-base); + border-color: var(--ink-faint); + box-shadow: none; +} +.scope-error, +.scope-unavailable { + margin: 10px 18px; + padding: 10px 12px; + border-radius: 8px; + background: var(--c-warn-bg); + color: var(--c-warn); + font-size: 12px; +} +.document-location { + padding: 0 18px 14px; + font-size: 13px; + font-weight: 650; + color: var(--ink-base); +} +.document-location span { + float: right; + color: var(--ink-mute); + font-weight: 400; +} +.document-table { + table-layout: fixed; + width: 100%; +} +.document-content .table-wrap { + max-height: max(300px, calc(100vh - 470px)); + overflow: auto; +} +.document-table thead th { + position: sticky; + top: 0; + z-index: 1; + background: var(--bg-soft); +} +.document-table th:nth-child(1) { + width: 37%; +} +.document-table th:nth-child(2) { + width: 16%; +} +.document-table th:nth-child(3) { + width: 19%; +} +.document-table th:nth-child(4) { + width: 10%; +} +.document-table th:nth-child(5) { + width: 18%; +} +.document-table th, +.document-table td { + padding: 13px 12px; + white-space: normal; + overflow-wrap: anywhere; + font-size: 12px; +} +.document-table small { + display: block; + margin-top: 7px; + color: var(--ink-mute); + font-size: 11px; +} +.document-workbench .file-link { + padding: 0; + border: 0; + background: transparent; + color: var(--c-run); + text-align: left; + font-size: 13px; + box-shadow: none; + white-space: normal; + overflow-wrap: anywhere; + line-height: 1.55; +} +.document-workbench .file-link:hover { + text-decoration: underline; +} +.scope-badge, +.document-stage { + display: inline-block; + border-radius: 6px; + padding: 5px 7px; + font-size: 12px; + font-weight: 650; + background: var(--border-soft); + color: var(--ink-base); +} +.scope-badge.external { + color: var(--c-done); + background: var(--c-done-bg); +} +.scope-badge.internal { + color: var(--ink-base); + background: var(--c-run-bg); +} +.document-stage.completed, +.document-stage.reused { + color: var(--c-done); + background: var(--c-done-bg); +} +.document-stage.blocked, +.document-stage.failed { + color: var(--c-warn); + background: var(--c-warn-bg); +} +.document-stage.parsing, +.document-stage.indexing, +.document-stage.uploading, +.document-stage.downloading { + color: var(--c-run); + background: var(--c-run-bg); +} +.document-inspector { + position: fixed; + top: 80px; + right: 20px; + bottom: 20px; + z-index: 50; + width: min(480px, calc(100vw - 40px)); + overflow-y: auto; + background: white; + border: 2px solid var(--c-run-border); + box-shadow: 0 12px 48px #12345240; + margin: 0; +} +.document-inspector h2 { + overflow-wrap: anywhere; + font-size: 17px; +} +.inspector-body { + padding: 0 22px 20px; + font-size: 13px; + line-height: 1.7; + color: var(--ink-base); +} +.inspector-body dl { + display: grid; + grid-template-columns: 100px minmax(0, 1fr); + gap: 8px; +} +.inspector-body dd { + margin: 0; + overflow-wrap: anywhere; +} +.file-facts { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; + margin: 14px 0; +} +.file-facts span { + display: grid; + padding: 9px; + border-radius: 8px; + background: var(--bg-soft); + color: var(--ink-mute); + font-size: 11px; +} +.file-facts b { + margin-top: 3px; + color: var(--ink-base); + font-size: 12px; +} +.document-pipeline { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 5px; + margin: 14px 0; +} +.pipeline-step { + display: grid; + grid-template-columns: 9px minmax(0, 1fr); + gap: 6px; + align-items: start; + padding: 8px 5px; + border-radius: 7px; + background: var(--bg-soft); +} +.pipeline-step > span { + width: 8px; + height: 8px; + margin-top: 5px; + border-radius: 50%; + background: var(--ink-faint); +} +.pipeline-step div { + display: grid; + min-width: 0; +} +.pipeline-step strong { + font-size: 10px; + color: var(--ink-base); +} +.pipeline-step small { + color: var(--ink-mute); + font-size: 9px; + overflow-wrap: anywhere; +} +.pipeline-step.done > span { + background: var(--c-done); +} +.pipeline-step.active > span { + background: var(--c-run); +} +.pipeline-step.problem > span { + background: var(--c-warn); +} +.document-inspector .scope-editor { + margin: 16px 0; +} +.document-workbench button:disabled { + cursor: not-allowed; + color: var(--ink-faint); + background: var(--bg-soft); + border-color: var(--border-base); +} @media (max-width: 1150px) { - .document-layout { grid-template-columns: 205px minmax(0,1fr); } - .document-counts { grid-template-columns: repeat(3,minmax(0,1fr)); } - .document-table th, .document-table td { padding: 10px 7px; } - .scope-editor-fields { grid-template-columns: 1fr 1fr; } - .scope-reason { grid-column: 1/-1; } + .document-layout { + grid-template-columns: 205px minmax(0, 1fr); + } + .document-counts { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .document-table th, + .document-table td { + padding: 10px 7px; + } + .scope-editor-fields { + grid-template-columns: 1fr 1fr; + } + .scope-reason { + grid-column: 1/-1; + } } @media (max-width: 860px) { - .document-layout { grid-template-columns: 1fr; } - .directory-panel { max-height: 260px; } - .document-table { min-width: 650px; } - .document-counts { grid-template-columns: repeat(3,minmax(0,1fr)); } - .section-title { display: grid; } + .document-layout { + grid-template-columns: 1fr; + } + .directory-panel { + max-height: 260px; + } + .document-table { + min-width: 650px; + } + .document-counts { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .section-title { + display: grid; + } } diff --git a/web/src/documentWorkbench.test.ts b/web/src/documentWorkbench.test.ts index e1cc1fa..0a9cf8d 100644 --- a/web/src/documentWorkbench.test.ts +++ b/web/src/documentWorkbench.test.ts @@ -1,65 +1,105 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { documentPipeline, documentStage, directoryGroups, filterDocuments, fetchDocumentCatalog, operationalDocuments, sourceProgress, visibilityOrigin } from './documentWorkbench' +import { + documentPipeline, + documentStage, + directoryGroups, + filterDocuments, + fetchDocumentCatalog, + operationalDocuments, + sourceProgress, + visibilityOrigin, +} from './documentWorkbench' import { document } from './documentFixture' afterEach(() => vi.unstubAllGlobals()) describe('document workbench', () => { - it('groups by actual connection and directory, never merges independent sources', () => { - const groups = directoryGroups([document, {...document, id:'b',connection_id:'pp-2'}]) - expect(groups).toHaveLength(2) - expect(groups[0].count).toBe(1) - expect(groups[0].path).toBe('使用指南') - }) - it('maps observed stages and never treats missing publication as failure or published', () => { - expect(documentStage(document)).toBe('completed') - expect(documentStage({...document, has_publication:false, legacy_status:''})).toBe('waiting') - expect(documentStage({...document, content_state:'over_limit',has_publication:false})).toBe('blocked') - expect(documentStage({...document, legacy_status:'content_alias',has_publication:false})).toBe('reused') - expect(documentStage({...document, processing_state:'stalled'})).toBe('failed') - expect(documentStage({...document, processing_state:'finalizing'})).toBe('indexing') - }) - it('builds a factual pipeline without inventing page progress or production status',()=>{ - expect(documentPipeline(document)).toEqual([ - {label:'取得文件',state:'done',detail:'文件已校验'}, - {label:'上传测试库',state:'done',detail:'上传完成'}, - {label:'解析与索引',state:'done',detail:'解析完成'}, - {label:'测试检索',state:'waiting',detail:'未证明已启用'}, - ]) - expect(documentPipeline({...document,content_state:'over_limit',has_publication:false})[0]).toEqual({label:'取得文件',state:'problem',detail:'文件超限'}) - }) - it('shows whether scope comes from a file override, directory inheritance or source metadata',()=>{ - expect(visibilityOrigin({...document,visibility_origin:'file_override'})).toBe('文件单独设置') - expect(visibilityOrigin({...document,visibility_origin:'directory_rule',scope_rule_path:'产品'})).toBe('继承目录设置:产品') - expect(visibilityOrigin({...document,visibility_origin:'configured_scope'})).toBe('来源范围设置') - }) - it('filters source directory, scope, stage and filename together', () => { - expect(filterDocuments([document, {...document,id:'b',visibility:'internal'}], {connection:'pp-1',directory:'使用指南',query:'手册',visibility:'external',stage:'completed'}).map(x=>x.id)).toEqual(['a']) - }) - it('hides isolated acceptance fixtures unless the engineer asks to see them',()=>{ - const manual={...document,id:'manual',source_type:'manual' as const,connection_id:'manual-1'} - expect(operationalDocuments([document,manual],false).map(x=>x.id)).toEqual(['a']) - expect(operationalDocuments([document,manual],true)).toHaveLength(2) - }) - it('aggregates truthful source-level processing stages without fabricated percentages',()=>{ - const progress=sourceProgress([ - document, - {...document,id:'active',processing_state:'processing'}, - {...document,id:'blocked',content_state:'over_limit',has_publication:false}, - {...document,id:'waiting',has_publication:false,legacy_status:''}, - {...document,id:'reused',legacy_status:'content_alias',has_publication:false}, - ]) - expect(progress).toEqual([{connection:'pp-1',total:5,completed:1,active:1,attention:1,waiting:1,reused:1}]) - }) - it('collects every page before claiming a complete directory tree', async () => { - const fetch = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({data:[document],summary:{total:2},limit:1,offset:0}))).mockResolvedValueOnce(new Response(JSON.stringify({data:[{...document,id:'b'}],summary:{total:2},limit:1,offset:1}))) - vi.stubGlobal('fetch',fetch) - expect(await fetchDocumentCatalog()).toHaveLength(2) - expect(fetch).toHaveBeenCalledTimes(2) - }) - it('rejects incomplete or duplicate pages rather than reporting wrong totals', async () => { - vi.stubGlobal('fetch',vi.fn() - .mockResolvedValueOnce(new Response(JSON.stringify({data:[document],summary:{total:2},limit:1,offset:0}))) - .mockResolvedValueOnce(new Response(JSON.stringify({data:[document],summary:{total:2},limit:1,offset:1})))) - await expect(fetchDocumentCatalog()).rejects.toThrow('文档分页发生变化') - }) + it('groups by actual connection and directory, never merges independent sources', () => { + const groups = directoryGroups([document, { ...document, id: 'b', connection_id: 'pp-2' }]) + expect(groups).toHaveLength(2) + expect(groups[0].count).toBe(1) + expect(groups[0].path).toBe('使用指南') + }) + it('maps observed stages and never treats missing publication as failure or published', () => { + expect(documentStage(document)).toBe('completed') + expect(documentStage({ ...document, has_publication: false, legacy_status: '' })).toBe('waiting') + expect(documentStage({ ...document, content_state: 'over_limit', has_publication: false })).toBe('blocked') + expect(documentStage({ ...document, legacy_status: 'content_alias', has_publication: false })).toBe('reused') + expect(documentStage({ ...document, processing_state: 'stalled' })).toBe('failed') + expect(documentStage({ ...document, processing_state: 'finalizing' })).toBe('indexing') + }) + it('builds a factual pipeline without inventing page progress or production status', () => { + expect(documentPipeline(document)).toEqual([ + { label: '取得文件', state: 'done', detail: '文件已校验' }, + { label: '上传测试库', state: 'done', detail: '上传完成' }, + { label: '解析与索引', state: 'done', detail: '解析完成' }, + { label: '测试检索', state: 'waiting', detail: '未证明已启用' }, + ]) + expect(documentPipeline({ ...document, content_state: 'over_limit', has_publication: false })[0]).toEqual({ + label: '取得文件', + state: 'problem', + detail: '文件超限', + }) + }) + it('shows whether scope comes from a file override, directory inheritance or source metadata', () => { + expect(visibilityOrigin({ ...document, visibility_origin: 'file_override' })).toBe('文件单独设置') + expect(visibilityOrigin({ ...document, visibility_origin: 'directory_rule', scope_rule_path: '产品' })).toBe( + '继承目录设置:产品' + ) + expect(visibilityOrigin({ ...document, visibility_origin: 'configured_scope' })).toBe('来源范围设置') + }) + it('filters source directory, scope, stage and filename together', () => { + expect( + filterDocuments([document, { ...document, id: 'b', visibility: 'internal' }], { + connection: 'pp-1', + directory: '使用指南', + query: '手册', + visibility: 'external', + stage: 'completed', + }).map((x) => x.id) + ).toEqual(['a']) + }) + it('hides isolated acceptance fixtures unless the engineer asks to see them', () => { + const manual = { ...document, id: 'manual', source_type: 'manual' as const, connection_id: 'manual-1' } + expect(operationalDocuments([document, manual], false).map((x) => x.id)).toEqual(['a']) + expect(operationalDocuments([document, manual], true)).toHaveLength(2) + }) + it('aggregates truthful source-level processing stages without fabricated percentages', () => { + const progress = sourceProgress([ + document, + { ...document, id: 'active', processing_state: 'processing' }, + { ...document, id: 'blocked', content_state: 'over_limit', has_publication: false }, + { ...document, id: 'waiting', has_publication: false, legacy_status: '' }, + { ...document, id: 'reused', legacy_status: 'content_alias', has_publication: false }, + ]) + expect(progress).toEqual([ + { connection: 'pp-1', total: 5, completed: 1, active: 1, attention: 1, waiting: 1, reused: 1 }, + ]) + }) + it('collects every page before claiming a complete directory tree', async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce( + new Response(JSON.stringify({ data: [document], summary: { total: 2 }, limit: 1, offset: 0 })) + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ data: [{ ...document, id: 'b' }], summary: { total: 2 }, limit: 1, offset: 1 })) + ) + vi.stubGlobal('fetch', fetch) + expect(await fetchDocumentCatalog()).toHaveLength(2) + expect(fetch).toHaveBeenCalledTimes(2) + }) + it('rejects incomplete or duplicate pages rather than reporting wrong totals', async () => { + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValueOnce( + new Response(JSON.stringify({ data: [document], summary: { total: 2 }, limit: 1, offset: 0 })) + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ data: [document], summary: { total: 2 }, limit: 1, offset: 1 })) + ) + ) + await expect(fetchDocumentCatalog()).rejects.toThrow('文档分页发生变化') + }) }) diff --git a/web/src/documentWorkbench.ts b/web/src/documentWorkbench.ts index 485baec..8dacbec 100644 --- a/web/src/documentWorkbench.ts +++ b/web/src/documentWorkbench.ts @@ -1,128 +1,203 @@ import { fetchSourceAssets } from './assets' import type { SourceAsset } from './assets' -export type DocumentStage = 'waiting' | 'downloading' | 'uploading' | 'parsing' | 'indexing' | 'completed' | 'reused' | 'blocked' | 'failed' +export type DocumentStage = + 'waiting' | 'downloading' | 'uploading' | 'parsing' | 'indexing' | 'completed' | 'reused' | 'blocked' | 'failed' export const stageLabels: Record = { - waiting: '等待处理', downloading: '下载中', uploading: '上传中', parsing: '解析中', indexing: '建立索引', completed: '解析完成', reused: '内容重复,复用已有文档', blocked: '文件超限', failed: '需要处理', + waiting: '等待处理', + downloading: '下载中', + uploading: '上传中', + parsing: '解析中', + indexing: '建立索引', + completed: '解析完成', + reused: '内容重复,复用已有文档', + blocked: '文件超限', + failed: '需要处理', } -export type PipelineState='waiting'|'active'|'done'|'problem' -export interface PipelineStep {label:string;state:PipelineState;detail:string} -export function documentPipeline(item:SourceAsset):PipelineStep[]{ - let source:PipelineStep={label:'取得文件',state:'waiting',detail:'等待取得文件'} - if(item.content_state==='verified')source={label:'取得文件',state:'done',detail:'文件已校验'} - else if(item.content_state==='downloading')source={label:'取得文件',state:'active',detail:'下载中'} - else if(item.content_state==='over_limit')source={label:'取得文件',state:'problem',detail:'文件超限'} - else if(['invalid','failed'].includes(item.content_state))source={label:'取得文件',state:'problem',detail:'文件校验失败'} - let upload:PipelineStep={label:'上传测试库',state:'waiting',detail:'等待上传'} - if(item.legacy_status==='content_alias')upload={label:'上传测试库',state:'done',detail:'复用已有内容'} - else if(item.ingest_state==='uploaded')upload={label:'上传测试库',state:'done',detail:'上传完成'} - else if(item.ingest_state==='uploading')upload={label:'上传测试库',state:'active',detail:'上传中'} - else if(item.ingest_state==='failed')upload={label:'上传测试库',state:'problem',detail:'上传失败'} - let processing:PipelineStep={label:'解析与索引',state:'waiting',detail:'等待解析'} - if(item.legacy_status==='content_alias')processing={label:'解析与索引',state:'done',detail:'复用已有解析结果'} - else if(item.processing_state==='completed')processing={label:'解析与索引',state:'done',detail:'解析完成'} - else if(item.processing_state==='processing')processing={label:'解析与索引',state:'active',detail:'解析中'} - else if(item.processing_state==='finalizing')processing={label:'解析与索引',state:'active',detail:'建立索引中'} - else if(['failed','stalled'].includes(item.processing_state))processing={label:'解析与索引',state:'problem',detail:item.processing_state==='stalled'?'处理停滞':'解析失败'} - let retrieval:PipelineStep={label:'测试检索',state:'waiting',detail:'未证明已启用'} - if(item.retrieval_state==='enabled')retrieval={label:'测试检索',state:'done',detail:'测试环境已启用'} - else if(['enabling','disabling'].includes(item.retrieval_state))retrieval={label:'测试检索',state:'active',detail:'状态变更中'} - else if(item.retrieval_state==='failed')retrieval={label:'测试检索',state:'problem',detail:'检索状态失败'} - return [source,upload,processing,retrieval] +export type PipelineState = 'waiting' | 'active' | 'done' | 'problem' +export interface PipelineStep { + label: string + state: PipelineState + detail: string +} +export function documentPipeline(item: SourceAsset): PipelineStep[] { + let source: PipelineStep = { label: '取得文件', state: 'waiting', detail: '等待取得文件' } + if (item.content_state === 'verified') source = { label: '取得文件', state: 'done', detail: '文件已校验' } + else if (item.content_state === 'downloading') source = { label: '取得文件', state: 'active', detail: '下载中' } + else if (item.content_state === 'over_limit') source = { label: '取得文件', state: 'problem', detail: '文件超限' } + else if (['invalid', 'failed'].includes(item.content_state)) + source = { label: '取得文件', state: 'problem', detail: '文件校验失败' } + let upload: PipelineStep = { label: '上传测试库', state: 'waiting', detail: '等待上传' } + if (item.legacy_status === 'content_alias') upload = { label: '上传测试库', state: 'done', detail: '复用已有内容' } + else if (item.ingest_state === 'uploaded') upload = { label: '上传测试库', state: 'done', detail: '上传完成' } + else if (item.ingest_state === 'uploading') upload = { label: '上传测试库', state: 'active', detail: '上传中' } + else if (item.ingest_state === 'failed') upload = { label: '上传测试库', state: 'problem', detail: '上传失败' } + let processing: PipelineStep = { label: '解析与索引', state: 'waiting', detail: '等待解析' } + if (item.legacy_status === 'content_alias') + processing = { label: '解析与索引', state: 'done', detail: '复用已有解析结果' } + else if (item.processing_state === 'completed') + processing = { label: '解析与索引', state: 'done', detail: '解析完成' } + else if (item.processing_state === 'processing') + processing = { label: '解析与索引', state: 'active', detail: '解析中' } + else if (item.processing_state === 'finalizing') + processing = { label: '解析与索引', state: 'active', detail: '建立索引中' } + else if (['failed', 'stalled'].includes(item.processing_state)) + processing = { + label: '解析与索引', + state: 'problem', + detail: item.processing_state === 'stalled' ? '处理停滞' : '解析失败', + } + let retrieval: PipelineStep = { label: '测试检索', state: 'waiting', detail: '未证明已启用' } + if (item.retrieval_state === 'enabled') retrieval = { label: '测试检索', state: 'done', detail: '测试环境已启用' } + else if (['enabling', 'disabling'].includes(item.retrieval_state)) + retrieval = { label: '测试检索', state: 'active', detail: '状态变更中' } + else if (item.retrieval_state === 'failed') + retrieval = { label: '测试检索', state: 'problem', detail: '检索状态失败' } + return [source, upload, processing, retrieval] } export function documentStage(item: SourceAsset): DocumentStage { - if (item.source_change === 'unavailable' || item.source_change === 'deleted') return 'failed' - if (item.content_state === 'over_limit') return 'blocked' - if (['invalid','failed'].includes(item.content_state) || item.ingest_state === 'failed' || ['failed','stalled'].includes(item.processing_state)) return 'failed' - if (item.content_state === 'downloading') return 'downloading' - if (item.legacy_status === 'content_alias' && !item.has_publication) return 'reused' - if (!item.has_publication) return 'waiting' - if (item.ingest_state === 'uploading') return 'uploading' - switch (item.processing_state) { - case 'completed': return 'completed' - case 'processing': return 'parsing' - case 'finalizing': return 'indexing' - default: return 'waiting' - } + if (item.source_change === 'unavailable' || item.source_change === 'deleted') return 'failed' + if (item.content_state === 'over_limit') return 'blocked' + if ( + ['invalid', 'failed'].includes(item.content_state) || + item.ingest_state === 'failed' || + ['failed', 'stalled'].includes(item.processing_state) + ) + return 'failed' + if (item.content_state === 'downloading') return 'downloading' + if (item.legacy_status === 'content_alias' && !item.has_publication) return 'reused' + if (!item.has_publication) return 'waiting' + if (item.ingest_state === 'uploading') return 'uploading' + switch (item.processing_state) { + case 'completed': + return 'completed' + case 'processing': + return 'parsing' + case 'finalizing': + return 'indexing' + default: + return 'waiting' + } } export function documentProblem(item: SourceAsset): string { - if (item.source_change === 'unavailable' || item.source_change === 'deleted') return '来源文件缺失或暂不可访问,请核对来源权限和文件位置。' - if (documentStage(item) === 'blocked') return '超过当前导入大小上限,尚未上传;请拆分文件或由管理员调整限制。' - if (item.processing_state === 'stalled') return '长时间未收到处理进展,请检查解析服务。' - if (documentStage(item) === 'failed') return '处理未完成,请查看错误详情;符合重试条件时可重新处理。' - if (documentStage(item) === 'reused') return '文件内容完全相同,未重复上传。' - return '' + if (item.source_change === 'unavailable' || item.source_change === 'deleted') + return '来源文件缺失或暂不可访问,请核对来源权限和文件位置。' + if (documentStage(item) === 'blocked') return '超过当前导入大小上限,尚未上传;请拆分文件或由管理员调整限制。' + if (item.processing_state === 'stalled') return '长时间未收到处理进展,请检查解析服务。' + if (documentStage(item) === 'failed') return '处理未完成,请查看错误详情;符合重试条件时可重新处理。' + if (documentStage(item) === 'reused') return '文件内容完全相同,未重复上传。' + return '' } export function visibilityOrigin(item: SourceAsset): string { - switch (item.visibility_origin) { - case 'pp_public_tag': return '来自PP公开标记' - case 'manual': return '人工指定' - case 'configured_scope': return '来源范围设置' - case 'file_override': return '文件单独设置' - case 'directory_rule': return item.scope_rule_path ? `继承目录设置:${item.scope_rule_path}` : '继承来源范围设置' - default: return '设置来源待核对' - } + switch (item.visibility_origin) { + case 'pp_public_tag': + return '来自PP公开标记' + case 'manual': + return '人工指定' + case 'configured_scope': + return '来源范围设置' + case 'file_override': + return '文件单独设置' + case 'directory_rule': + return item.scope_rule_path ? `继承目录设置:${item.scope_rule_path}` : '继承来源范围设置' + default: + return '设置来源待核对' + } } export function connectionKey(item: SourceAsset): string { - return item.connection_id || `${item.source_type}:${item.connection_name}` + return item.connection_id || `${item.source_type}:${item.connection_name}` } export function directoryGroups(items: SourceAsset[]) { - const groups = new Map() - for (const item of items) { - const connection = connectionKey(item) - const path = item.directory_path || '' - // JSON tuple avoids cross-source collisions, even when labels contain separators. - const key = JSON.stringify([connection, path]) - const group = groups.get(key) || {key, connection, path, count:0} - group.count++ - groups.set(key, group) - } - return [...groups.values()].sort((a,b) => a.path.localeCompare(b.path,'zh-CN') || a.connection.localeCompare(b.connection)) + const groups = new Map() + for (const item of items) { + const connection = connectionKey(item) + const path = item.directory_path || '' + // JSON tuple avoids cross-source collisions, even when labels contain separators. + const key = JSON.stringify([connection, path]) + const group = groups.get(key) || { key, connection, path, count: 0 } + group.count++ + groups.set(key, group) + } + return [...groups.values()].sort( + (a, b) => a.path.localeCompare(b.path, 'zh-CN') || a.connection.localeCompare(b.connection) + ) } -export function operationalDocuments(items:SourceAsset[],includeTestDocuments:boolean) { - return includeTestDocuments ? items : items.filter(item=>item.source_type!=='manual') +export function operationalDocuments(items: SourceAsset[], includeTestDocuments: boolean) { + return includeTestDocuments ? items : items.filter((item) => item.source_type !== 'manual') } -export interface SourceProgress {connection:string;total:number;completed:number;active:number;attention:number;waiting:number;reused:number} -export function sourceProgress(items:SourceAsset[]):SourceProgress[] { - const result=new Map() - for(const item of items){ - const connection=connectionKey(item) - const progress=result.get(connection)||{connection,total:0,completed:0,active:0,attention:0,waiting:0,reused:0} - const stage=documentStage(item) - progress.total++ - if(stage==='completed') progress.completed++ - if(['downloading','uploading','parsing','indexing'].includes(stage)) progress.active++ - if(['blocked','failed'].includes(stage)) progress.attention++ - if(stage==='waiting') progress.waiting++ - if(stage==='reused') progress.reused++ - result.set(connection,progress) - } - return [...result.values()].sort((a,b)=>a.connection.localeCompare(b.connection)) +export interface SourceProgress { + connection: string + total: number + completed: number + active: number + attention: number + waiting: number + reused: number +} +export function sourceProgress(items: SourceAsset[]): SourceProgress[] { + const result = new Map() + for (const item of items) { + const connection = connectionKey(item) + const progress = result.get(connection) || { + connection, + total: 0, + completed: 0, + active: 0, + attention: 0, + waiting: 0, + reused: 0, + } + const stage = documentStage(item) + progress.total++ + if (stage === 'completed') progress.completed++ + if (['downloading', 'uploading', 'parsing', 'indexing'].includes(stage)) progress.active++ + if (['blocked', 'failed'].includes(stage)) progress.attention++ + if (stage === 'waiting') progress.waiting++ + if (stage === 'reused') progress.reused++ + result.set(connection, progress) + } + return [...result.values()].sort((a, b) => a.connection.localeCompare(b.connection)) +} +export interface DocumentFilter { + connection: string + directory: string | null + query: string + visibility: string + stage: string } -export interface DocumentFilter { connection:string; directory:string|null; query:string; visibility:string; stage:string } export function filterDocuments(items: SourceAsset[], filter: DocumentFilter) { - const query = filter.query.trim().toLocaleLowerCase() - return items.filter(item => (!filter.connection || connectionKey(item) === filter.connection) - && (filter.directory === null || (item.directory_path || '') === filter.directory) - && (!filter.visibility || item.visibility === filter.visibility) - && (!filter.stage || documentStage(item) === filter.stage) - && (!query || `${item.title || ''} ${item.directory_path || ''}`.toLocaleLowerCase().includes(query))) + const query = filter.query.trim().toLocaleLowerCase() + return items.filter( + (item) => + (!filter.connection || connectionKey(item) === filter.connection) && + (filter.directory === null || (item.directory_path || '') === filter.directory) && + (!filter.visibility || item.visibility === filter.visibility) && + (!filter.stage || documentStage(item) === filter.stage) && + (!query || `${item.title || ''} ${item.directory_path || ''}`.toLocaleLowerCase().includes(query)) + ) } export async function fetchDocumentCatalog(signal?: AbortSignal): Promise { - const items: SourceAsset[] = [] - const ids = new Set() - let expected: number | undefined - do { - const page = await fetchSourceAssets({state:'',limit:100,offset:items.length},signal) - if (expected === undefined) expected = page.summary.total - if (!Number.isInteger(expected) || expected < 0 || expected > 10000 || page.summary.total !== expected || page.offset !== items.length) throw new Error('文档清单已变化或过大,请刷新后重试。') - for (const item of page.items) { - if (!item.id || ids.has(item.id)) throw new Error('文档分页发生变化,请刷新后重试。') - ids.add(item.id) - items.push(item) - } - if (!page.items.length && items.length !== expected) throw new Error('文档清单未加载完整,请重试。') - } while (items.length < expected) - if (items.length !== expected) throw new Error('文档数量核验失败,请重试。') - return items + const items: SourceAsset[] = [] + const ids = new Set() + let expected: number | undefined + do { + const page = await fetchSourceAssets({ state: '', limit: 100, offset: items.length }, signal) + if (expected === undefined) expected = page.summary.total + if ( + !Number.isInteger(expected) || + expected < 0 || + expected > 10000 || + page.summary.total !== expected || + page.offset !== items.length + ) + throw new Error('文档清单已变化或过大,请刷新后重试。') + for (const item of page.items) { + if (!item.id || ids.has(item.id)) throw new Error('文档分页发生变化,请刷新后重试。') + ids.add(item.id) + items.push(item) + } + if (!page.items.length && items.length !== expected) throw new Error('文档清单未加载完整,请重试。') + } while (items.length < expected) + if (items.length !== expected) throw new Error('文档数量核验失败,请重试。') + return items } diff --git a/web/src/dwsLogin.test.ts b/web/src/dwsLogin.test.ts new file mode 100644 index 0000000..8c0e641 --- /dev/null +++ b/web/src/dwsLogin.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { checkDWSConnection, fetchDWSCredentials, startDWSLogin, validDWSAuthorizationURL } from './dwsLogin' +afterEach(() => vi.unstubAllGlobals()) +describe('DWS transport boundaries', () => { + it('explains missing directory authorization with the new login entry', async () => { + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue(new Response(JSON.stringify({ error: 'dingtalk_discovery_unavailable' }), { status: 503 })) + ) + await expect(checkDWSConnection()).rejects.toThrow('请先登录授权') + }) + it('accepts only the official device verification URL', () => { + expect(validDWSAuthorizationURL('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST')).toBe(true) + for (const value of [ + 'javascript:alert(1)', + 'http://login.dingtalk.com/oauth2/device/verify.htm', + 'https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm', + 'https://login.dingtalk.com/other', + ]) + expect(validDWSAuthorizationURL(value)).toBe(false) + }) + it('keeps backend errors from a real single-use response', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'DWS 登录服务未接通' }), { status: 503 })) + ) + await expect(startDWSLogin()).rejects.toThrow('DWS 登录服务未接通') + }) + it('rejects missing or hostile session data', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + id: 'a'.repeat(32), + state: 'waiting', + expires_at: '2099-01-01T00:00:00Z', + verification_url: 'https://evil.invalid/', + }, + }) + ) + ) + ) + await expect(startDWSLogin()).rejects.toThrow('不是钉钉官方地址') + }) + it('does not treat an invalid directory envelope as a successful empty result', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: {} })))) + await expect(checkDWSConnection()).rejects.toThrow('未取得有效目录检查结果') + }) + it('returns only safe credential metadata', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + authenticated: true, + refresh_token_valid: true, + corp_name: '测试组织', + user_name: '测试账号', + access_token: 'do-not-return', + }, + }) + ) + ) + ) + const result = await fetchDWSCredentials() + expect(result.corp_name).toBe('测试组织') + expect(JSON.stringify(result)).not.toContain('do-not-return') + }) +}) diff --git a/web/src/dwsLogin.ts b/web/src/dwsLogin.ts new file mode 100644 index 0000000..c9a0db3 --- /dev/null +++ b/web/src/dwsLogin.ts @@ -0,0 +1,105 @@ +export interface DWSCredentials { + identity?: string + authenticated: boolean + refresh_token_valid: boolean + status_known: boolean + corp_name: string + user_name: string + refresh_expires_at: string +} +export type DWSLoginState = 'starting' | 'waiting' | 'verifying' | 'succeeded' | 'failed' | 'expired' | 'cancelled' +export interface DWSLogin { + id: string + state: DWSLoginState + verification_url: string + user_code: string + expires_at: string + error: string +} +const states = new Set(['starting', 'waiting', 'verifying', 'succeeded', 'failed', 'expired', 'cancelled']) +export const dwsLoginActive = (state: DWSLoginState) => ['starting', 'waiting', 'verifying'].includes(state) +const record = (value: unknown): value is Record => typeof value === 'object' && value !== null +const text = (value: unknown) => (typeof value === 'string' ? value : '') +export function validDWSAuthorizationURL(value: string) { + try { + const url = new URL(value) + return ( + url.protocol === 'https:' && + url.host === 'login.dingtalk.com' && + !url.username && + !url.password && + !url.hash && + url.pathname === '/oauth2/device/verify.htm' + ) + } catch { + return false + } +} +async function request(path: string, signal?: AbortSignal, method = 'GET') { + const response = await fetch(path, { + method, + signal, + headers: { Accept: 'application/json', ...(method !== 'GET' ? { 'X-Governance-Action': 'dws-login' } : {}) }, + }) + const payload: unknown = await response.json().catch(() => null) + if (!response.ok) { + const reason = record(payload) && typeof payload.error === 'string' ? payload.error : '' + if (reason === 'dingtalk_discovery_unavailable') + throw new Error('DWS 未登录、授权已过期或缺少目录权限;请先登录授权,再检查连接。') + throw new Error((record(payload) ? text(payload.hint) : '') || reason || `DWS 请求失败(HTTP ${response.status})`) + } + if (!record(payload) || !record(payload.data)) throw new Error('DWS 返回的数据格式不正确,请重试') + return payload.data +} +export async function fetchDWSCredentials(signal?: AbortSignal): Promise { + const data = await request('/api/v1/dingtalk-spaces/credential-status', signal) + if (typeof data.authenticated !== 'boolean' || typeof data.refresh_token_valid !== 'boolean') + throw new Error('无法判断 DWS 登录状态') + return { + identity: text(data.identity), + authenticated: data.authenticated, + refresh_token_valid: data.refresh_token_valid, + status_known: data.status_known !== false, + corp_name: text(data.corp_name), + user_name: text(data.user_name), + refresh_expires_at: text(data.refresh_expires_at), + } +} +function parseLogin(data: Record): DWSLogin { + if ( + typeof data.id !== 'string' || + !/^[a-f0-9]{32}$/.test(data.id) || + typeof data.state !== 'string' || + !states.has(data.state) || + !Number.isFinite(Date.parse(text(data.expires_at))) + ) + throw new Error('授权会话格式不正确,请重新发起') + const url = text(data.verification_url) + if (url && !validDWSAuthorizationURL(url)) throw new Error('授权链接不是钉钉官方地址,请重新发起') + return { + id: data.id, + state: data.state as DWSLoginState, + verification_url: url, + user_code: text(data.user_code), + expires_at: text(data.expires_at), + error: text(data.error), + } +} +export async function startDWSLogin(signal?: AbortSignal) { + return parseLogin(await request('/api/v1/dws-login', signal, 'POST')) +} +export async function fetchDWSLogin(id: string, signal?: AbortSignal) { + return parseLogin(await request(`/api/v1/dws-login/${encodeURIComponent(id)}`, signal)) +} +export async function cancelDWSLogin(id: string) { + return parseLogin(await request(`/api/v1/dws-login/${encodeURIComponent(id)}`, undefined, 'DELETE')) +} +export async function checkDWSConnection(signal?: AbortSignal) { + const data = await request('/api/v1/dingtalk-spaces/available', signal) + if (!('knowledge_bases' in data) || !('drive_spaces' in data) || !text(data.fetched_at)) + throw new Error('未取得有效目录检查结果,请重试') + const knowledge = Array.isArray(data.knowledge_bases) ? data.knowledge_bases.length : 0 + const drive = Array.isArray(data.drive_spaces) ? data.drive_spaces.length : 0 + const notices = [text(data.knowledge_notice), text(data.drive_notice)].filter(Boolean) + return { message: `已读取 ${knowledge} 个知识库、${drive} 个钉盘空间`, notices, checkedAt: text(data.fetched_at) } +} diff --git a/web/src/filenameFilters.ts b/web/src/filenameFilters.ts index f152016..75e5f7f 100644 --- a/web/src/filenameFilters.ts +++ b/web/src/filenameFilters.ts @@ -15,30 +15,44 @@ export async function fetchFilenameFilters(connectionID: string, signal?: AbortS const query = new URLSearchParams({ connection_id: connectionID }) const response = await fetch(`/api/v1/filename-filters?${query}`, { headers: { Accept: 'application/json' }, signal }) if (!response.ok) throw new Error(`加载文件名筛选失败(HTTP ${response.status})`) - const envelope = await response.json() as unknown + const envelope = (await response.json()) as unknown if (!record(envelope) || !Array.isArray(envelope.data)) throw new Error('文件名筛选响应无效') return envelope.data.map((value) => { - if (!record(value) || typeof value.connection_id !== 'string' || typeof value.directory_path !== 'string' || - !Array.isArray(value.excluded_extensions) || !value.excluded_extensions.every((item) => typeof item === 'string') || - typeof value.updated_by !== 'string' || typeof value.updated_at !== 'string') throw new Error('文件名筛选条目无效') + if ( + !record(value) || + typeof value.connection_id !== 'string' || + typeof value.directory_path !== 'string' || + !Array.isArray(value.excluded_extensions) || + !value.excluded_extensions.every((item) => typeof item === 'string') || + typeof value.updated_by !== 'string' || + typeof value.updated_at !== 'string' + ) + throw new Error('文件名筛选条目无效') return value as unknown as FilenameFilterRule }) } -export async function saveFilenameFilter(connectionID: string, directoryPath: string, mode: 'allow' | 'exclude', extensions: string[]): Promise { +export async function saveFilenameFilter( + connectionID: string, + directoryPath: string, + mode: 'allow' | 'exclude', + extensions: string[] +): Promise { const response = await fetch('/api/v1/filename-filters', { - method: 'PUT', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, + method: 'PUT', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, body: JSON.stringify({ connection_id: connectionID, directory_path: directoryPath, mode, extensions }), }) if (!response.ok) throw new Error(`保存文件名筛选失败(HTTP ${response.status})`) - const envelope = await response.json() as { data?: FilenameFilterRule } + const envelope = (await response.json()) as { data?: FilenameFilterRule } if (!envelope.data) throw new Error('文件名筛选响应无效') return envelope.data } export async function clearFilenameFilter(connectionID: string, directoryPath: string): Promise { const response = await fetch('/api/v1/filename-filters', { - method: 'DELETE', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, + method: 'DELETE', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, body: JSON.stringify({ connection_id: connectionID, directory_path: directoryPath }), }) if (!response.ok) throw new Error(`清除文件名筛选失败(HTTP ${response.status})`) @@ -48,24 +62,115 @@ export async function clearFilenameFilter(connectionID: string, directoryPath: s // binaries have no RAG value for the support knowledge bases. Kept for the // legacy "exclude" mode editor prefill. export const DEFAULT_EXCLUDED_EXTENSIONS = [ - "zip", "rar", "7z", "gz", "tgz", "tar", "xz", "iso", "crdownload", - "mp4", "avi", "mkv", "mov", "wmv", "m4v", "mp3", "wav", "flac", - "exe", "dll", "so", "msi", "apk", "bin", "pyc", "pyd", "pyi", "whl", "dtb", "u-boot", "imx", - "stp", "step", "stl", "x_t", "x_b", "jt", "sldprt", "sldasm", "slddrw", "dwg", "dxf", "igs", "cat", "obj", "p2m", "p2s", "sol", "dwf", - "psd", "ai", "otf", "ttf", - "dlink", "atomproject", "amind", "appt", "rdk", "vcmx", "swf", "dav", + 'zip', + 'rar', + '7z', + 'gz', + 'tgz', + 'tar', + 'xz', + 'iso', + 'crdownload', + 'mp4', + 'avi', + 'mkv', + 'mov', + 'wmv', + 'm4v', + 'mp3', + 'wav', + 'flac', + 'exe', + 'dll', + 'so', + 'msi', + 'apk', + 'bin', + 'pyc', + 'pyd', + 'pyi', + 'whl', + 'dtb', + 'u-boot', + 'imx', + 'stp', + 'step', + 'stl', + 'x_t', + 'x_b', + 'jt', + 'sldprt', + 'sldasm', + 'slddrw', + 'dwg', + 'dxf', + 'igs', + 'cat', + 'obj', + 'p2m', + 'p2s', + 'sol', + 'dwf', + 'psd', + 'ai', + 'otf', + 'ttf', + 'dlink', + 'atomproject', + 'amind', + 'appt', + 'rdk', + 'vcmx', + 'swf', + 'dav', ].sort() // Whitelist defaults for the "keep selected" mode: documents, text/scripts // and images that a RAG knowledge base can actually parse and cite. export const DEFAULT_ALLOWED_EXTENSIONS = [ - "adoc", "able", "axls", - "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "csv", - "txt", "md", "json", "xml", "html", "yaml", "conf", "config", "ini", "log", - "lua", "py", "sh", "bat", "qml", - "png", "jpg", "jpeg", "gif", "bmp", "webp", "heic", "tif", + 'adoc', + 'able', + 'axls', + 'pdf', + 'doc', + 'docx', + 'xls', + 'xlsx', + 'ppt', + 'pptx', + 'csv', + 'txt', + 'md', + 'json', + 'xml', + 'html', + 'yaml', + 'conf', + 'config', + 'ini', + 'log', + 'lua', + 'py', + 'sh', + 'bat', + 'qml', + 'png', + 'jpg', + 'jpeg', + 'gif', + 'bmp', + 'webp', + 'heic', + 'tif', ].sort() export function parseExtensionDraft(value: string): string[] { - return [...new Set(value.split(/[,,\s]+/).map((item) => item.trim().toLowerCase().replace(/^\./, '')).filter(Boolean))].sort() + return [ + ...new Set( + value + .split(/[,,\s]+/) + .map((item) => item.trim().toLowerCase().replace(/^\./, '')) + .filter(Boolean) + ), + ].sort() } diff --git a/web/src/libraryOverviewFetch.test.ts b/web/src/libraryOverviewFetch.test.ts new file mode 100644 index 0000000..3136e9f --- /dev/null +++ b/web/src/libraryOverviewFetch.test.ts @@ -0,0 +1,53 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { fetchLibraryOverview } from './librarySnapshots' + +// F16:overview 的非 2xx 响应曾被当成正常状态,页面随后在 `overview.gate.sync_allowed` +// 上抛 TypeError(白屏)。这里把三种真实失败形状固定下来:401/503 与畸形 JSON。 +const originalFetch = globalThis.fetch + +afterEach(() => { + globalThis.fetch = originalFetch + vi.restoreAllMocks() +}) + +describe('fetchLibraryOverview(HTTP 状态与结构)', () => { + it('401 的 {error} 不许被当成发布状态', async () => { + globalThis.fetch = vi.fn( + async () => new Response(JSON.stringify({ error: 'unauthenticated' }), { status: 401 }) + ) as unknown as typeof fetch + await expect(fetchLibraryOverview('internal')).rejects.toThrow(/HTTP 401/) + }) + + it('503 的闸口拒绝同样必须报错', async () => { + globalThis.fetch = vi.fn( + async () => new Response(JSON.stringify({ available: false, reason: '存储不可用' }), { status: 503 }) + ) as unknown as typeof fetch + await expect(fetchLibraryOverview('internal')).rejects.toThrow(/HTTP 503/) + }) + + it('200 但缺 gate/jobs 的结构不符也要报错', async () => { + globalThis.fetch = vi.fn( + async () => new Response(JSON.stringify({ scope: 'internal' }), { status: 200 }) + ) as unknown as typeof fetch + await expect(fetchLibraryOverview('internal')).rejects.toThrow(/结构不符合预期/) + }) + + it('结构正确的 200 正常返回(避免把正常请求也拦掉)', async () => { + const payload = { + scope: 'internal', + production: { state: 'unknown' }, + prebackup: { state: 'unknown' }, + diff: { state: 'unknown', added: [], updated: [], removed: [] }, + jobs: [], + gate: { sync_allowed: false, reasons: [] }, + authorization: { state: 'none' }, + capture_available: false, + now: new Date().toISOString(), + } + globalThis.fetch = vi.fn( + async () => new Response(JSON.stringify(payload), { status: 200 }) + ) as unknown as typeof fetch + const value = await fetchLibraryOverview('internal') + expect(value?.gate.sync_allowed).toBe(false) + }) +}) diff --git a/web/src/librarySnapshots.ts b/web/src/librarySnapshots.ts index 1ca91d2..b0d4646 100644 --- a/web/src/librarySnapshots.ts +++ b/web/src/librarySnapshots.ts @@ -22,6 +22,8 @@ export interface LibraryCompatibility { } export interface LibrarySnapshot { + source_id?: string + source_identity?: { project: string; app: string; scope: string; tenant_id: number; knowledge_base_id: string } snapshot_id: string scope: string knowledge_base_id: string @@ -104,6 +106,16 @@ function parseSnapshot(raw: unknown): LibrarySnapshot | null { } return { snapshot_id: snapshotID, + source_id: text(raw.source_id) || undefined, + source_identity: record(raw.source_identity) + ? { + project: text(raw.source_identity.project), + app: text(raw.source_identity.app), + scope: text(raw.source_identity.scope), + tenant_id: num(raw.source_identity.tenant_id), + knowledge_base_id: text(raw.source_identity.knowledge_base_id), + } + : undefined, scope: text(raw.scope), knowledge_base_id: text(raw.knowledge_base_id), tenant_id: num(raw.tenant_id), @@ -288,11 +300,15 @@ export interface LibrarySyncAccepted { } // 启动同步:闸口未齐时接口返回 503 与逐条缺项,页面照实显示,不假装已启动。 -export async function enqueueLibrarySync(scope: string, targetSnapshotID: string): Promise { +export async function enqueueLibrarySync( + scope: string, + targetSnapshotID: string, + sourceID: string +): Promise { const response = await fetch('/api/v1/library/syncs', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, - body: JSON.stringify({ scope, target_snapshot_id: targetSnapshotID }), + body: JSON.stringify({ scope, target_snapshot_id: targetSnapshotID, source_id: sourceID }), }) const value = (await response.json().catch(() => null)) as unknown if (!response.ok) { @@ -369,6 +385,37 @@ export async function fetchLibraryCaptures(signal?: AbortSignal): Promise { + const response = await fetch(`/api/v1/library/jobs/${encodeURIComponent(id)}/reconcile-capture`, { + method: 'POST', + headers: { Accept: 'application/json' }, + }) + const value = (await response.json().catch(() => null)) as unknown + const body = record(value) ? value : {} + if (!response.ok) { + throw new Error(text(body.reason) || text(body.error) || `核对封存结果失败(HTTP ${response.status})`) + } + return { + repaired: body.repaired === true, + already_succeeded: body.already_succeeded === true, + job_id: text(body.job_id), + snapshot_id: text(body.snapshot_id), + queue_job_id: text(body.queue_job_id), + audit_operation_id: text(body.audit_operation_id), + reason: text(body.reason), + } +} export function formatBytes(bytes: number): string { if (!Number.isFinite(bytes) || bytes <= 0) return '0 B' const units = ['B', 'KB', 'MB', 'GB', 'TB'] @@ -400,9 +447,21 @@ export interface LibraryVersionRecord { } export interface LibraryKnown { - state: 'known' | 'unknown' + /** + * 后端 /api/v1/library/overview 的真实状态: + * - known:有权威生效版本; + * - unknown + empty_baseline:目标可读、确实为空,是首次发布的合法起点; + * - unknown(无 empty_baseline):目标非空却没有权威版本; + * - unreachable:读不到目标,既不能判定空也不能判定非空。 + */ + state: 'known' | 'unknown' | 'unreachable' version?: LibraryVersionRecord reason?: string + /** 目标可读且内容为空:首次发布。只证明生产范围内容表计数为 0, + * ES/对象身份与残留仍由执行侧预备份/准入核验;页面不得据此宣称"三存储已验证"。 */ + empty_baseline?: boolean + /** 只在预备份上有意义:这份备份的内容是否就是当前拟发布目标。 */ + bound_to_target?: boolean } export interface LibraryDiff { @@ -486,6 +545,9 @@ export interface LibraryMaintenanceCapability { project?: string writers?: string[] ingress_service?: string + // gate(默认)或 none:没有闸门的测试栈必须显示"无闸门(测试模式)"。 + ingress_mode?: string + ingress_state?: string note?: string } @@ -503,6 +565,56 @@ export async function fetchLibraryMaintenance( return value as unknown as LibraryMaintenanceView } +/** + * 持有维护窗口的作业 id:实例级记录优先(它才是真正的互斥来源),库级记录兜底。 + * 页面只能按这个 id 去读作业详情 —— 同 scope 的最新作业可能是一次无关的封存。 + */ +export function maintenanceOwnerJobID(view: LibraryMaintenanceView | null | undefined): string { + const record = view?.instance_maintenance ?? view?.maintenance ?? null + return record?.owner_job_id ?? '' +} + +/** + * 持有作业详情的读取结果。失败必须分类,不能都缩成"不存在": + * - missing:接口明确 404 ⇒ 维护记录引用了一个未登记的作业; + * - error:网络/非 2xx/结构不符 ⇒ 只是"没读到",页面只能照实说未知; + * - unread:还没发出读取(例如刚切 scope)。 + * 把 error 当 missing 会让"读不到"看起来像一条库内结论。 + */ +export type LibraryJobLookup = + | { state: 'loaded'; job: LibraryJobRecord } + | { state: 'missing' } + | { state: 'error'; reason: string } + | { state: 'unread' } + +export async function fetchLibraryJobDetail(id: string, signal?: AbortSignal): Promise { + if (!id) return { state: 'unread' } + const response = await fetch(`/api/v1/library/jobs/${encodeURIComponent(id)}`, { + headers: { Accept: 'application/json' }, + signal, + }).catch((error: unknown) => { + if ((error as Error)?.name === 'AbortError') throw error + return null + }) + if (!response) return { state: 'error', reason: '请求失败' } + if (response.status === 404) return { state: 'missing' } + if (!response.ok) return { state: 'error', reason: `HTTP ${response.status}` } + const value = (await response.json().catch(() => null)) as unknown + const job = record(value) ? value.job : null + if ( + !record(job) || + typeof job.id !== 'string' || + job.id === '' || + typeof job.state !== 'string' || + typeof job.scope !== 'string' + ) { + return { state: 'error', reason: '响应结构不符合预期(缺少 job 的 id/state/scope)' } + } + // 身份不符说明拿到的不是这次请求的作业(晚回包/串包):宁可报读取失败,也不能拿去展示。 + if (job.id !== id) return { state: 'error', reason: `返回的作业 ${job.id} 与请求的 ${id} 不一致` } + return { state: 'loaded', job: job as unknown as LibraryJobRecord } +} + export interface LibraryRecoveryAccepted { accepted?: boolean recovery_job?: string @@ -539,7 +651,7 @@ export interface LibraryStageRow { export interface LibraryJobRecord { id: string scope: string - kind: 'seal' | 'sync' | 'restore' + kind: 'seal' | 'sync' | 'restore' | 'baseline' | 'verify' state: 'pending' | 'running' | 'succeeded' | 'failed' | 'cancelled' stage: string request_digest: string @@ -555,6 +667,21 @@ export interface LibraryJobRecord { stages: LibraryStageRow[] } +/** + * 已登记版本的轻量清单(不含 evidence)。 + * 归档里不止"测试封存":目标基线与每次生产预备份也在同一个归档根下, + * 页面必须按登记过的 kind 给每份快照写类型,不能一律写"测试封存"。 + */ +export interface LibraryVersionRef { + id: string + kind: 'test_sealed' | 'production_effective' | 'production_prebackup' | string + snapshot_id: string + version_label: string + source_job_id: string + created_at: string + superseded_at?: string | null +} + export interface LibraryAuthorizationView { state: 'active' | 'none' authorized_by?: string @@ -585,6 +712,8 @@ export interface LibraryOverview { test_sealed_reason?: string production: LibraryKnown prebackup: LibraryKnown + /** 已登记版本(轻量):页面据此给归档里的每份快照标类型。 */ + versions?: LibraryVersionRef[] diff: LibraryDiff job?: LibraryJobRecord jobs: LibraryJobRecord[] @@ -594,6 +723,9 @@ export interface LibraryOverview { capture_reason?: string // 执行器是 worker 的真实观测:指向哪个实例、何时观测、是否降级/在跑。 executor?: LibraryExecutorView + target_instance?: string + target_project?: string + target_knowledge_base_id?: string now: string } @@ -602,8 +734,20 @@ export async function fetchLibraryOverview(scope: string, signal?: AbortSignal): headers: { Accept: 'application/json' }, signal, }) + // 非 2xx 的响应体会是 {error: ...},把它 cast 成 LibraryOverview 会让页面在 + // `overview.gate.sync_allowed` 上抛 TypeError(F16)。这里必须先核状态码与结构, + // 结构不符就**报错**,让页面显示"读取失败"而不是崩溃或当成正常状态。 + if (!response.ok) { + throw new Error(`发布状态读取失败(HTTP ${response.status})`) + } const value = (await response.json().catch(() => null)) as unknown - if (!record(value)) return null + if ( + !record(value) || + !record((value as { gate?: unknown }).gate) || + !Array.isArray((value as { jobs?: unknown }).jobs) + ) { + throw new Error('发布状态响应结构不符合预期(缺 gate/jobs)') + } return value as unknown as LibraryOverview } diff --git a/web/src/librarySyncAuth.test.ts b/web/src/librarySyncAuth.test.ts index 83c7346..d5cb824 100644 --- a/web/src/librarySyncAuth.test.ts +++ b/web/src/librarySyncAuth.test.ts @@ -33,11 +33,15 @@ describe('发布页的同步授权与执行接线', () => { .fn() .mockResolvedValue(jsonResponse(202, { job: { id: 'libsync-internal-1', scope: 'internal' }, reused: false })) vi.stubGlobal('fetch', fetchMock) - const accepted = await enqueueLibrarySync('internal', 'snap-1') + const accepted = await enqueueLibrarySync('internal', 'snap-1', 'source-bound') expect(accepted.job_id).toBe('libsync-internal-1') const [url, init] = fetchMock.mock.calls[0] expect(url).toBe('/api/v1/library/syncs') - expect(JSON.parse(init.body)).toEqual({ scope: 'internal', target_snapshot_id: 'snap-1' }) + expect(JSON.parse(init.body)).toEqual({ + scope: 'internal', + target_snapshot_id: 'snap-1', + source_id: 'source-bound', + }) }) it('闸口未齐时把接口给的缺项原样抛出,而不是假装已启动', async () => { @@ -50,7 +54,7 @@ describe('发布页的同步授权与执行接线', () => { }) ) ) - await expect(enqueueLibrarySync('internal', 'snap-1')).rejects.toThrow( + await expect(enqueueLibrarySync('internal', 'snap-1', 'source-bound')).rejects.toThrow( /目标非空且没有生效版本记录;没有与目标快照匹配的有效发布授权/ ) }) diff --git a/web/src/main.tsx b/web/src/main.tsx index 7ee5c6a..1972d2e 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -13,7 +13,11 @@ if (!root) { function Gate() { const { identity, ready } = useAuth() if (!ready) { - return

    正在检查登录状态…

    + return ( +
    +

    正在检查登录状态…

    +
    + ) } if (!identity) return if (identity.must_change_password) return @@ -25,5 +29,5 @@ createRoot(root).render( - , + ) diff --git a/web/src/members.ts b/web/src/members.ts index e8a51c3..7f31a8c 100644 --- a/web/src/members.ts +++ b/web/src/members.ts @@ -12,17 +12,26 @@ export interface ManagedUser { export const managedUserRoles = ['viewer', 'engineer', 'admin'] as const -const record = (value: unknown): value is Record => Boolean(value) && typeof value === 'object' && !Array.isArray(value) +const record = (value: unknown): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value) function parseUser(raw: unknown): ManagedUser { - if (!record(raw) || typeof raw.id !== 'string' || typeof raw.username !== 'string' || typeof raw.role !== 'string' || - !managedUserRoles.includes(raw.role as ManagedUser['role']) || typeof raw.state !== 'string') { + if ( + !record(raw) || + typeof raw.id !== 'string' || + typeof raw.username !== 'string' || + typeof raw.role !== 'string' || + !managedUserRoles.includes(raw.role as ManagedUser['role']) || + typeof raw.state !== 'string' + ) { throw new Error('成员响应无效') } return { - id: raw.id, username: raw.username, + id: raw.id, + username: raw.username, display_name: typeof raw.display_name === 'string' ? raw.display_name : '', - role: raw.role as ManagedUser['role'], state: raw.state === 'disabled' ? 'disabled' : 'active', + role: raw.role as ManagedUser['role'], + state: raw.state === 'disabled' ? 'disabled' : 'active', must_change_password: raw.must_change_password === true, last_login_at: typeof raw.last_login_at === 'string' ? raw.last_login_at : null, } @@ -32,7 +41,12 @@ async function call(url: string, init: RequestInit, message: string): Promise null)) as { error?: string } | null @@ -47,24 +61,41 @@ export async function fetchManagedUsers(signal?: AbortSignal): Promise { +export async function createManagedUser(input: { + username: string + display_name: string + role: ManagedUser['role'] + password: string +}): Promise { const value = await call('/api/v1/users', { method: 'POST', body: JSON.stringify(input) }, '创建成员失败') if (!record(value) || !record(value.data)) throw new Error('创建成员响应无效') return parseUser(value.data) } export async function setManagedUserRole(userID: string, role: ManagedUser['role']): Promise { - const value = await call(`/api/v1/users/${encodeURIComponent(userID)}/role`, { method: 'POST', body: JSON.stringify({ role }) }, '调整角色失败') + const value = await call( + `/api/v1/users/${encodeURIComponent(userID)}/role`, + { method: 'POST', body: JSON.stringify({ role }) }, + '调整角色失败' + ) if (!record(value) || !record(value.data)) throw new Error('角色更新响应无效') return parseUser(value.data) } export async function setManagedUserState(userID: string, state: ManagedUser['state']): Promise { - const value = await call(`/api/v1/users/${encodeURIComponent(userID)}/state`, { method: 'POST', body: JSON.stringify({ state }) }, '更新账号状态失败') + const value = await call( + `/api/v1/users/${encodeURIComponent(userID)}/state`, + { method: 'POST', body: JSON.stringify({ state }) }, + '更新账号状态失败' + ) if (!record(value) || !record(value.data)) throw new Error('账号状态响应无效') return parseUser(value.data) } export async function resetManagedUserPassword(userID: string, temporaryPassword: string): Promise { - await call(`/api/v1/users/${encodeURIComponent(userID)}/reset-password`, { method: 'POST', body: JSON.stringify({ temporary_password: temporaryPassword }) }, '重置密码失败') + await call( + `/api/v1/users/${encodeURIComponent(userID)}/reset-password`, + { method: 'POST', body: JSON.stringify({ temporary_password: temporaryPassword }) }, + '重置密码失败' + ) } diff --git a/web/src/monitor.test.ts b/web/src/monitor.test.ts index d774192..89724df 100644 --- a/web/src/monitor.test.ts +++ b/web/src/monitor.test.ts @@ -1,34 +1,130 @@ -import { afterEach,describe,expect,it,vi } from 'vitest' -import { fetchMonitorFiles,fetchMonitorOverview,fetchRunMetrics } from './monitor' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { fetchMonitorFiles, fetchMonitorOverview, fetchRunMetrics } from './monitor' -afterEach(()=>vi.unstubAllGlobals()) -const overview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:19971597926,memory_total_bytes:34359738368,simulated:true},services:[{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟',latency_ms:24,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[{id:'kb-sim',name:'公司级技术支持知识库',visibility:'mixed',imported:5750,completed:4530,pending:450,processing:50,finalizing:714,failed:6,cancelled:0,internal_imported:4200,internal_completed:3300,external_imported:1550,external_completed:1230}]} -describe('monitor API',()=>{ - it('requires the backend to label simulation mode explicitly',async()=>{ - vi.stubGlobal('fetch',vi.fn().mockResolvedValue(new Response(JSON.stringify(overview)))) - expect((await fetchMonitorOverview()).simulated).toBe(true) - }) - it('filters files by real WeKnora status contract',async()=>{ - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({items:[{name:'[模拟] 文件.pdf',directory:'02 产品资料',visibility:'internal',status:'finalizing',stage_detail:'Wiki生成中',elapsed_seconds:120,error_code:''}],total:1,limit:20,offset:0,sample_only:true}))) - vi.stubGlobal('fetch',fetchMock) - const page=await fetchMonitorFiles('kb-sim','finalizing',20,0) - expect(page.sample_only).toBe(true) - expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/monitor/knowledge-bases/kb-sim/files?status=finalizing&limit=20&offset=0') - }) - it('keeps insufficient metric samples null and requires a source label',async()=>{ - const payload={data:{observed_at:'2026-09-12T08:00:00Z',active_workers:2,worker_source:'pg_lease', - queue:{pending:1,running:4,retry:1,failed:4,oldest_pending_age_seconds:10800}, - short_window:{window_seconds:3600,jobs_started:9,jobs_completed:6,jobs_failed:2,success_rate:75,failure_rate:25,duration_avg_seconds:411.4,duration_p50_seconds:30,duration_p95_seconds:1800}, - long_window:{window_seconds:86400,jobs_started:10,jobs_completed:0,jobs_failed:0,success_rate:null,failure_rate:null,duration_avg_seconds:null,duration_p50_seconds:null,duration_p95_seconds:null}}} - vi.stubGlobal('fetch',vi.fn().mockResolvedValue(new Response(JSON.stringify(payload)))) - const metrics=await fetchRunMetrics() - expect(metrics.worker_source).toBe('pg_lease') - expect(metrics.long_window.success_rate).toBeNull() - expect(metrics.long_window.duration_p95_seconds).toBeNull() - expect(metrics.short_window.success_rate).toBe(75) - }) - it('rejects metrics without a worker source or with a fake zero rate',async()=>{ - vi.stubGlobal('fetch',vi.fn().mockResolvedValue(new Response(JSON.stringify({data:{observed_at:'',queue:{pending:0},short_window:{window_seconds:3600},long_window:{window_seconds:86400}}})))) - await expect(fetchRunMetrics()).rejects.toThrow() - }) +afterEach(() => vi.unstubAllGlobals()) +const overview = { + mode: 'simulation', + simulated: true, + observed_at: '2026-09-08T12:00:00Z', + host: { cpu_percent: 42, memory_used_bytes: 19971597926, memory_total_bytes: 34359738368, simulated: true }, + services: [ + { + key: 'mineru', + name: 'MinerU', + state: 'healthy', + detail: '模拟', + latency_ms: 24, + observed_at: '2026-09-08T12:00:00Z', + simulated: true, + }, + ], + knowledge_bases: [ + { + id: 'kb-sim', + name: '公司级技术支持知识库', + visibility: 'mixed', + imported: 5750, + completed: 4530, + pending: 450, + processing: 50, + finalizing: 714, + failed: 6, + cancelled: 0, + internal_imported: 4200, + internal_completed: 3300, + external_imported: 1550, + external_completed: 1230, + }, + ], +} +describe('monitor API', () => { + it('requires the backend to label simulation mode explicitly', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify(overview)))) + expect((await fetchMonitorOverview()).simulated).toBe(true) + }) + it('filters files by real WeKnora status contract', async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + items: [ + { + name: '[模拟] 文件.pdf', + directory: '02 产品资料', + visibility: 'internal', + status: 'finalizing', + stage_detail: 'Wiki生成中', + elapsed_seconds: 120, + error_code: '', + }, + ], + total: 1, + limit: 20, + offset: 0, + sample_only: true, + }) + ) + ) + vi.stubGlobal('fetch', fetchMock) + const page = await fetchMonitorFiles('kb-sim', 'finalizing', 20, 0) + expect(page.sample_only).toBe(true) + expect(fetchMock.mock.calls[0][0]).toBe( + '/api/v1/monitor/knowledge-bases/kb-sim/files?status=finalizing&limit=20&offset=0' + ) + }) + it('keeps insufficient metric samples null and requires a source label', async () => { + const payload = { + data: { + observed_at: '2026-09-12T08:00:00Z', + active_workers: 2, + worker_source: 'pg_lease', + queue: { pending: 1, running: 4, retry: 1, failed: 4, oldest_pending_age_seconds: 10800 }, + short_window: { + window_seconds: 3600, + jobs_started: 9, + jobs_completed: 6, + jobs_failed: 2, + success_rate: 75, + failure_rate: 25, + duration_avg_seconds: 411.4, + duration_p50_seconds: 30, + duration_p95_seconds: 1800, + }, + long_window: { + window_seconds: 86400, + jobs_started: 10, + jobs_completed: 0, + jobs_failed: 0, + success_rate: null, + failure_rate: null, + duration_avg_seconds: null, + duration_p50_seconds: null, + duration_p95_seconds: null, + }, + }, + } + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify(payload)))) + const metrics = await fetchRunMetrics() + expect(metrics.worker_source).toBe('pg_lease') + expect(metrics.long_window.success_rate).toBeNull() + expect(metrics.long_window.duration_p95_seconds).toBeNull() + expect(metrics.short_window.success_rate).toBe(75) + }) + it('rejects metrics without a worker source or with a fake zero rate', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + observed_at: '', + queue: { pending: 0 }, + short_window: { window_seconds: 3600 }, + long_window: { window_seconds: 86400 }, + }, + }) + ) + ) + ) + await expect(fetchRunMetrics()).rejects.toThrow() + }) }) diff --git a/web/src/monitor.ts b/web/src/monitor.ts index ccc86eb..664fa44 100644 --- a/web/src/monitor.ts +++ b/web/src/monitor.ts @@ -1,39 +1,190 @@ -export type MonitorStatus='completed'|'pending'|'processing'|'finalizing'|'failed'|'cancelled' -export interface MonitorHost{cpu_percent:number;memory_used_bytes:number;memory_total_bytes:number;disk_used_bytes:number;disk_total_bytes:number;gpu_state:string;gpu_detail:string;simulated:boolean} -export interface MonitorService{key:string;name:string;state:string;detail:string;latency_ms:number;observed_at:string;simulated:boolean} -export interface KnowledgeProgress{id:string;name:string;visibility:string;imported:number;completed:number;pending:number;processing:number;finalizing:number;failed:number;cancelled:number;planned:number;needs_removal:number;stale_planned:number;internal_imported:number;internal_completed:number;external_imported:number;external_completed:number} -export interface ServiceHealth{key:string;name:string;liveness:string;readiness:string;reason:string;latency_ms:number;observed_at:string;last_success_at:string|null;consecutive_failures:number;configured:boolean;applicable:boolean} -export interface IngestionPipeline{fetch_pending:number;fetch_failed:number;fetch_missing:number;concurrency:number} -export interface MonitorOverview{mode:string;simulated:boolean;observed_at:string;host:MonitorHost;services:MonitorService[];knowledge_bases:KnowledgeProgress[];pipeline?:IngestionPipeline;health:ServiceHealth[]} -export interface MonitorFile{name:string;directory:string;visibility:string;status:MonitorStatus;stage_detail:string;elapsed_seconds:number;error_code:string} -export interface MonitorFilePage{items:MonitorFile[];total:number;limit:number;offset:number;sample_only:boolean} -const record=(value:unknown):value is Record=>typeof value==='object'&&value!==null -export async function fetchMonitorOverview(signal?:AbortSignal):Promise{ - const response=await fetch('/api/v1/monitor/overview',{headers:{Accept:'application/json'},signal});if(!response.ok)throw new Error(`加载解析监控失败(HTTP ${response.status})`) - const value=await response.json() as unknown;if(!record(value)||typeof value.mode!=='string'||typeof value.simulated!=='boolean'||!record(value.host)||!Array.isArray(value.services)||!Array.isArray(value.knowledge_bases))throw new Error('解析监控响应无效') - const health=Array.isArray(value.health)?(value.health as unknown[]).filter(record):[] - return {...value,health} as unknown as MonitorOverview +export type MonitorStatus = 'completed' | 'pending' | 'processing' | 'finalizing' | 'failed' | 'cancelled' +export interface MonitorHost { + cpu_percent: number + memory_used_bytes: number + memory_total_bytes: number + disk_used_bytes: number + disk_total_bytes: number + gpu_state: string + gpu_detail: string + simulated: boolean } -export async function fetchMonitorFiles(knowledgeBaseID:string,status:MonitorStatus|'',limit=20,offset=0,signal?:AbortSignal):Promise{ - const query=new URLSearchParams();if(status)query.set('status',status);query.set('limit',String(limit));query.set('offset',String(offset)) - const response=await fetch(`/api/v1/monitor/knowledge-bases/${encodeURIComponent(knowledgeBaseID)}/files?${query}`,{headers:{Accept:'application/json'},signal});if(!response.ok)throw new Error(`加载文档阶段失败(HTTP ${response.status})`) - const value=await response.json() as unknown;if(!record(value)||!Array.isArray(value.items)||typeof value.total!=='number'||typeof value.sample_only!=='boolean')throw new Error('文档阶段响应无效') - return value as unknown as MonitorFilePage +export interface MonitorService { + key: string + name: string + state: string + detail: string + latency_ms: number + observed_at: string + simulated: boolean +} +export interface KnowledgeProgress { + id: string + name: string + visibility: string + imported: number + completed: number + pending: number + processing: number + finalizing: number + failed: number + cancelled: number + planned: number + needs_removal: number + stale_planned: number + internal_imported: number + internal_completed: number + external_imported: number + external_completed: number +} +export interface ServiceHealth { + key: string + name: string + liveness: string + readiness: string + reason: string + latency_ms: number + observed_at: string + last_success_at: string | null + consecutive_failures: number + probe_target?: string + configured: boolean + applicable: boolean +} +export interface IngestionPipeline { + fetch_pending: number + fetch_failed: number + fetch_missing: number + concurrency: number +} +export interface MonitorOverview { + mode: string + simulated: boolean + observed_at: string + host: MonitorHost + services: MonitorService[] + knowledge_bases: KnowledgeProgress[] + pipeline?: IngestionPipeline + health: ServiceHealth[] +} +export interface MonitorFile { + name: string + directory: string + visibility: string + status: MonitorStatus + stage_detail: string + elapsed_seconds: number + error_code: string +} +export interface MonitorFilePage { + items: MonitorFile[] + total: number + limit: number + offset: number + sample_only: boolean +} +const record = (value: unknown): value is Record => typeof value === 'object' && value !== null +export async function fetchMonitorOverview(signal?: AbortSignal): Promise { + const response = await fetch('/api/v1/monitor/overview', { headers: { Accept: 'application/json' }, signal }) + if (!response.ok) throw new Error(`加载解析监控失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if ( + !record(value) || + typeof value.mode !== 'string' || + typeof value.simulated !== 'boolean' || + !record(value.host) || + !Array.isArray(value.services) || + !Array.isArray(value.knowledge_bases) + ) + throw new Error('解析监控响应无效') + const health = Array.isArray(value.health) ? (value.health as unknown[]).filter(record) : [] + return { ...value, health } as unknown as MonitorOverview +} +export async function fetchMonitorFiles( + knowledgeBaseID: string, + status: MonitorStatus | '', + limit = 20, + offset = 0, + signal?: AbortSignal +): Promise { + const query = new URLSearchParams() + if (status) query.set('status', status) + query.set('limit', String(limit)) + query.set('offset', String(offset)) + const response = await fetch( + `/api/v1/monitor/knowledge-bases/${encodeURIComponent(knowledgeBaseID)}/files?${query}`, + { headers: { Accept: 'application/json' }, signal } + ) + if (!response.ok) throw new Error(`加载文档阶段失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if ( + !record(value) || + !Array.isArray(value.items) || + typeof value.total !== 'number' || + typeof value.sample_only !== 'boolean' + ) + throw new Error('文档阶段响应无效') + return value as unknown as MonitorFilePage } -export interface JobWindowMetrics{window_seconds:number;jobs_started:number;jobs_completed:number;jobs_failed:number;success_rate:number|null;failure_rate:number|null;duration_avg_seconds:number|null;duration_p50_seconds:number|null;duration_p95_seconds:number|null} -export interface RunMetrics{observed_at:string;active_workers:number;worker_source:'pg_lease'|'simulation';queue:{pending:number;running:number;retry:number;failed:number;oldest_pending_age_seconds:number|null};short_window:JobWindowMetrics;long_window:JobWindowMetrics} -const finiteOrNull=(value:unknown)=>typeof value==='number'&&Number.isFinite(value)?value:null -const numberOr=(value:unknown,fallback=0)=>typeof value==='number'&&Number.isFinite(value)?value:fallback -const windowMetrics=(value:unknown):JobWindowMetrics=>{if(!record(value))throw new Error('运行指标窗口响应无效') - return{window_seconds:numberOr(value.window_seconds),jobs_started:numberOr(value.jobs_started),jobs_completed:numberOr(value.jobs_completed),jobs_failed:numberOr(value.jobs_failed),success_rate:finiteOrNull(value.success_rate),failure_rate:finiteOrNull(value.failure_rate),duration_avg_seconds:finiteOrNull(value.duration_avg_seconds),duration_p50_seconds:finiteOrNull(value.duration_p50_seconds),duration_p95_seconds:finiteOrNull(value.duration_p95_seconds)}} -export async function fetchRunMetrics(signal?:AbortSignal):Promise{ - const response=await fetch('/api/v1/monitor/metrics',{headers:{Accept:'application/json'},signal});if(!response.ok)throw new Error(`加载运行指标失败(HTTP ${response.status})`) - const value=await response.json() as unknown;if(!record(value)||!record(value.data))throw new Error('运行指标响应无效') - const data=value.data as Record - if(data.worker_source!=='pg_lease'&&data.worker_source!=='simulation')throw new Error('运行指标缺少数据来源标记') - if(!record(data.queue)||!record(data.short_window)||!record(data.long_window))throw new Error('运行指标字段不完整') - return{observed_at:typeof data.observed_at==='string'?data.observed_at:'',active_workers:numberOr(data.active_workers),worker_source:data.worker_source as RunMetrics['worker_source'], - queue:{pending:numberOr(data.queue.pending),running:numberOr(data.queue.running),retry:numberOr(data.queue.retry),failed:numberOr(data.queue.failed),oldest_pending_age_seconds:finiteOrNull(data.queue.oldest_pending_age_seconds)}, - short_window:windowMetrics(data.short_window),long_window:windowMetrics(data.long_window)} +export interface JobWindowMetrics { + window_seconds: number + jobs_started: number + jobs_completed: number + jobs_failed: number + success_rate: number | null + failure_rate: number | null + duration_avg_seconds: number | null + duration_p50_seconds: number | null + duration_p95_seconds: number | null +} +export interface RunMetrics { + observed_at: string + active_workers: number + worker_source: 'pg_lease' | 'simulation' + queue: { pending: number; running: number; retry: number; failed: number; oldest_pending_age_seconds: number | null } + short_window: JobWindowMetrics + long_window: JobWindowMetrics +} +const finiteOrNull = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) ? value : null) +const numberOr = (value: unknown, fallback = 0) => + typeof value === 'number' && Number.isFinite(value) ? value : fallback +const windowMetrics = (value: unknown): JobWindowMetrics => { + if (!record(value)) throw new Error('运行指标窗口响应无效') + return { + window_seconds: numberOr(value.window_seconds), + jobs_started: numberOr(value.jobs_started), + jobs_completed: numberOr(value.jobs_completed), + jobs_failed: numberOr(value.jobs_failed), + success_rate: finiteOrNull(value.success_rate), + failure_rate: finiteOrNull(value.failure_rate), + duration_avg_seconds: finiteOrNull(value.duration_avg_seconds), + duration_p50_seconds: finiteOrNull(value.duration_p50_seconds), + duration_p95_seconds: finiteOrNull(value.duration_p95_seconds), + } +} +export async function fetchRunMetrics(signal?: AbortSignal): Promise { + const response = await fetch('/api/v1/monitor/metrics', { headers: { Accept: 'application/json' }, signal }) + if (!response.ok) throw new Error(`加载运行指标失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if (!record(value) || !record(value.data)) throw new Error('运行指标响应无效') + const data = value.data as Record + if (data.worker_source !== 'pg_lease' && data.worker_source !== 'simulation') + throw new Error('运行指标缺少数据来源标记') + if (!record(data.queue) || !record(data.short_window) || !record(data.long_window)) + throw new Error('运行指标字段不完整') + return { + observed_at: typeof data.observed_at === 'string' ? data.observed_at : '', + active_workers: numberOr(data.active_workers), + worker_source: data.worker_source as RunMetrics['worker_source'], + queue: { + pending: numberOr(data.queue.pending), + running: numberOr(data.queue.running), + retry: numberOr(data.queue.retry), + failed: numberOr(data.queue.failed), + oldest_pending_age_seconds: finiteOrNull(data.queue.oldest_pending_age_seconds), + }, + short_window: windowMetrics(data.short_window), + long_window: windowMetrics(data.long_window), + } } diff --git a/web/src/monitorTasks.test.ts b/web/src/monitorTasks.test.ts index 599dfad..02bf09a 100644 --- a/web/src/monitorTasks.test.ts +++ b/web/src/monitorTasks.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { fetchMonitorTasks } from './monitorTasks' +import { fetchMonitorTasks, isCurrentTarget, targetLabel } from './monitorTasks' import { healthLabel } from './WeKnoraMonitor' import type { ServiceHealth } from './monitor' afterEach(() => vi.unstubAllGlobals()) @@ -44,3 +44,19 @@ describe('monitor table contract', () => { expect(healthLabel({ ...s, readiness: 'blocked' })).toBe('阻断') }) }) + +describe('target identity labels (F15)', () => { + const bindings = { internal: '0c84a098-d3ed-4b82-a165-e6de9691d6a8', external: 'ext-11112222-3333' } + it('distinguishes same-named knowledge bases by short id and binding state', () => { + const current = targetLabel('对内知识库', bindings.internal, 'internal', bindings) + const historical = targetLabel('对内知识库', 'sc-ed1f812c4e5fabe817fc6351104938c4', 'internal', bindings) + expect(current).toContain('0c84a098') + expect(current).toContain('当前绑定') + expect(historical).toContain('sc-ed1f8') + expect(historical).toContain('历史') + expect(current).not.toBe(historical) + }) + it('never treats an env/unknown target as the current binding', () => { + expect(isCurrentTarget('1b52c140-2e18-4676-afc5-4c7d8d190a8c', 'internal', bindings)).toBe(false) + }) +}) diff --git a/web/src/monitorTasks.ts b/web/src/monitorTasks.ts index 3fe2641..dcd3e8e 100644 --- a/web/src/monitorTasks.ts +++ b/web/src/monitorTasks.ts @@ -3,6 +3,8 @@ export interface MonitorTask { id: string title: string path: string + node_id: string + parent_node_id: string source_id: string source_name: string target_scope: string @@ -23,9 +25,22 @@ export interface MonitorTaskPage { limit: number offset: number sources: { id: string; name: string }[] - targets: { id: string; name: string }[] + targets: { id: string; name: string; scope?: string }[] + bindings: MonitorBindings retryable: number } +export interface MonitorBindings { + internal: string + external: string +} +export const shortID = (id: string) => (id.length > 8 ? id.slice(0, 8) : id) +export const isCurrentTarget = (id: string, scope: string, bindings: MonitorBindings) => + Boolean(id) && + (scope === 'external' ? bindings.external === id : scope === 'internal' ? bindings.internal === id : false) +// 同名目标(例如两个“对内知识库”)只靠名称无法区分:名称 + 短 ID, +// 并明确当前绑定/历史;完整 ID 留在详情里。 +export const targetLabel = (name: string, id: string, scope: string, bindings: MonitorBindings) => + `${name || '目标知识库'} · ${shortID(id)}${isCurrentTarget(id, scope, bindings) ? ' · 当前绑定' : ' · 历史'}` export interface MonitorFilters { q: string source: string @@ -102,6 +117,8 @@ export async function fetchMonitorTasks( 'id', 'title', 'path', + 'node_id', + 'parent_node_id', 'source_id', 'source_name', 'target_scope', @@ -125,5 +142,12 @@ export async function fetchMonitorTasks( for (const option of [...d.sources, ...d.targets]) if (!record(option) || typeof option.id !== 'string' || typeof option.name !== 'string') throw new Error('文件处理筛选项无效') - return d as unknown as MonitorTaskPage + const bindings = record(d.bindings) ? d.bindings : {} + return { + ...d, + bindings: { + internal: typeof bindings.internal === 'string' ? bindings.internal : '', + external: typeof bindings.external === 'string' ? bindings.external : '', + }, + } as unknown as MonitorTaskPage } diff --git a/web/src/monitorWorkbench.css b/web/src/monitorWorkbench.css index 43f8d4b..2178ddd 100644 --- a/web/src/monitorWorkbench.css +++ b/web/src/monitorWorkbench.css @@ -6,19 +6,8 @@ box-shadow: none; } .monitor-heading { - display: flex; - align-items: center; - gap: 14px; - margin-bottom: 20px; -} -.monitor-heading h1 { - font-size: 24px; - margin: 0 0 5px; -} -.monitor-heading p { - margin: 0; - color: var(--ink-mute); - font-size: 12px; + flex-wrap: nowrap; + justify-content: flex-start; } .monitor-heading > span { margin-left: auto; @@ -28,15 +17,16 @@ .monitor-metric-grid { display: grid; grid-template-columns: 1fr 1fr 1.3fr 1.1fr; - gap: 14px; - margin-bottom: 15px; + gap: 16px; + margin-bottom: 16px; } .monitor-metric-grid article { min-width: 0; - padding: 18px; + padding: 18px 20px; border: 1px solid var(--border-base); - border-radius: 9px; + border-radius: var(--r-lg); background: var(--bg-panel); + box-shadow: var(--shadow-card); } .monitor-metric-grid h2 { display: flex; @@ -49,8 +39,15 @@ margin: 0; } .monitor-metric-grid h2 small { + /* 口径标签做成徽标:顶部数字是全局口径,下表是筛选口径,二者不能被读成同一个范围 */ + padding: 1px 6px; + border: 1px solid var(--border-base); + border-radius: 999px; + background: var(--bg-soft); font-size: 10px; - color: var(--ink-faint); + font-weight: 500; + color: var(--ink-mute); + white-space: nowrap; } .monitor-numbers { display: flex; @@ -65,10 +62,11 @@ min-width: 0; } .monitor-numbers strong { - font-size: 27px; - line-height: 1.3; - font-weight: 700; - letter-spacing: -0.6px; + font-size: 28px; + line-height: 1.25; + font-weight: 600; + letter-spacing: -0.03em; + color: var(--ink-strong); white-space: nowrap; font-variant-numeric: tabular-nums; } @@ -77,7 +75,7 @@ color: var(--ink-mute); } .monitor-numbers .monitor-memory { - font-size: 23px; + font-size: 24px; } .monitor-good { color: var(--c-done) !important; @@ -88,13 +86,18 @@ .monitor-service-panel, .monitor-files { border: 1px solid var(--border-base); - border-radius: 9px; + border-radius: var(--r-lg); background: var(--bg-panel); + box-shadow: var(--shadow-card); overflow: hidden; } .monitor-service-panel { - padding: 15px 18px; - margin-bottom: 22px; + padding: 18px 20px; + margin-bottom: 16px; +} +.monitor-files { + /* 时间范围浮层要能溢出卡片;圆角由表头/分页各自裁切 */ + overflow: visible; } .monitor-section-heading { display: flex; @@ -102,11 +105,22 @@ justify-content: space-between; gap: 12px; } +.monitor-heading-group { + display: flex; + align-items: baseline; + gap: 10px; +} .monitor-section-heading h2 { - font-size: 16px; + font-size: 15px; margin: 0; font-weight: 650; } +.monitor-scope-note { + font-size: 12px; + font-weight: 500; + color: var(--ink-mute); + font-variant-numeric: tabular-nums; +} .monitor-section-heading > span { font-size: 11px; color: var(--ink-mute); @@ -119,10 +133,18 @@ align-items: start; } .monitor-service { - border: 1px solid var(--border-base); - border-radius: 6px; + border: 1px solid var(--border-soft); + border-radius: var(--r-md); background: var(--bg-soft); - padding: 10px 11px; + padding: 10px 12px; + transition: + border-color 120ms ease, + background 120ms ease; +} +.monitor-service:hover, +.monitor-service[open] { + border-color: var(--border-base); + background: var(--bg-panel); font-size: 12px; min-width: 0; } @@ -138,6 +160,8 @@ } .monitor-service summary > span { overflow-wrap: anywhere; + color: var(--ink-base); + font-weight: 500; } .monitor-service b { font-size: 11px; @@ -152,56 +176,119 @@ line-height: 1.6; } .monitor-files > .monitor-section-heading { - padding: 18px 19px 10px; + padding: 18px 20px 14px; } .monitor-filters { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; - padding: 10px 19px 16px; + padding: 0 20px 14px; + border-bottom: 1px solid var(--border-base); } .monitor-filters input, .monitor-filters select { border: 1px solid var(--border-strong); - border-radius: 6px; - padding: 8px 10px; + border-radius: var(--r-md); + padding: 5px 8px; background: var(--bg-panel); color: var(--ink-base); font: inherit; font-size: 12px; - max-width: 230px; - min-height: 35px; + min-height: 32px; +} +.monitor-filters select { + flex: 0 1 150px; + min-width: 112px; } .monitor-filters > input { - width: 210px; + flex: 1 1 220px; + max-width: 280px; } -.monitor-time-filter { - font-size: 12px; +.monitor-filters input:focus, +.monitor-filters select:focus { + border-color: var(--c-run); + outline: none; + box-shadow: var(--c-focus-ring); +} +.monitor-workbench .monitor-chip { + min-height: 32px; + padding: 5px 10px; + border: 1px dashed var(--border-strong); color: var(--ink-mute); } +.monitor-workbench .monitor-chip[aria-pressed='true'] { + border-style: solid; + border-color: var(--c-run-border); + background: var(--c-run-bg); + color: var(--c-run); +} +.monitor-workbench .monitor-clear { + margin-left: auto; +} +.monitor-time-filter { + position: relative; + font-size: 12px; + color: var(--ink-base); +} .monitor-time-filter summary { + display: flex; + align-items: center; + min-height: 32px; + padding: 0 10px; + border: 1px solid var(--border-strong); + border-radius: var(--r-md); + background: var(--bg-panel); cursor: pointer; + white-space: nowrap; +} +.monitor-time-filter[open] > summary { + border-color: var(--c-run); +} +/* 展开后浮在筛选条之上,不再把整排筛选挤成两行 */ +.monitor-time-panel { + position: absolute; + z-index: 5; + top: calc(100% + 4px); + left: 0; + display: grid; + gap: 8px; + padding: 12px; + border: 1px solid var(--border-base); + border-radius: var(--r-lg); + background: var(--bg-panel); + box-shadow: var(--shadow-float); } .monitor-time-filter label { display: flex; gap: 8px; align-items: center; - margin-top: 8px; + color: var(--ink-mute); + white-space: nowrap; } .monitor-batch { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; - padding: 11px 19px; - background: var(--c-run-bg); - border-top: 1px solid var(--c-run-border); - border-bottom: 1px solid var(--c-run-border); + padding: 8px 20px; + min-height: 48px; + background: var(--bg-panel); + border-bottom: 1px solid var(--border-base); font-size: 12px; } .monitor-batch b { + color: var(--ink-mute); + font-weight: 500; +} +/* 只有真的选中了才变成强调色:否则「已选 0 项」常亮蓝条会让人以为有待处理的批量动作 */ +.monitor-batch.has-selection { + background: var(--c-run-bg); + border-bottom-color: var(--c-run-border); +} +.monitor-batch.has-selection b { color: var(--c-run); + font-weight: 650; } .monitor-batch > span { color: var(--ink-mute); @@ -210,14 +297,21 @@ margin-left: auto; } .monitor-workbench .primary { - background: var(--c-run); - border-color: var(--c-run); + background: var(--c-primary); + border-color: var(--c-primary); color: #fff; } .monitor-workbench button:disabled { cursor: not-allowed; opacity: 0.5; } +.monitor-workbench .primary:disabled { + /* 禁用的主按钮用中性灰:浅蓝半透明看起来像「可点但加载慢」 */ + opacity: 1; + background: var(--bg-softer); + border-color: var(--border-base); + color: var(--ink-faint); +} .monitor-workbench .monitor-link { padding: 4px 6px; background: transparent; @@ -238,16 +332,18 @@ text-align: left; } .monitor-unified-table th { - padding: 12px 9px; + padding: 10px 12px; background: var(--bg-soft); - font-size: 11px; + font-size: 11.5px; font-weight: 500; + letter-spacing: 0.02em; color: var(--ink-mute); border-bottom: 1px solid var(--border-base); white-space: normal; } .monitor-unified-table td { - padding: 14px 9px; + padding: 12px 12px; + color: var(--ink-base); font-size: 12px; line-height: 1.6; border-bottom: 1px solid var(--border-base); @@ -267,31 +363,65 @@ text-overflow: ellipsis; margin-top: 3px; } +.monitor-unified-table th { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +/* 来源名可能是长哈希(legacy 来源),限两行,完整值放 title,避免一格撑高整行 */ +.monitor-clamp { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; + overflow-wrap: anywhere; +} .monitor-file-name { display: block; font-size: 13px; line-height: 1.6; - font-weight: 550; + font-weight: 500; + color: var(--ink-strong); } .monitor-unified-table input { accent-color: var(--c-run); width: 14px; height: 14px; } -.monitor-unified-table tr:hover, -.monitor-selected { +.monitor-unified-table tbody tr:hover { + background: var(--bg-hover); +} +.monitor-unified-table tbody tr.monitor-selected { background: var(--c-run-bg); + box-shadow: inset 2px 0 var(--c-run); +} +.monitor-unified-table tbody tr { + transition: background 100ms ease; } .monitor-state, .monitor-scope { - display: inline-block; + display: inline-flex; + align-items: center; + gap: 5px; font-size: 11px; - padding: 2px 7px; - border-radius: 4px; + padding: 1px 7px; + border-radius: 999px; white-space: nowrap; background: var(--c-run-bg); color: var(--c-run); } +.monitor-state::before { + content: ''; + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; +} +.monitor-scope { + border-radius: var(--r-sm); + background: var(--bg-softer); + color: var(--ink-mute); +} .monitor-state.attention { background: var(--c-fail-bg); color: var(--c-fail); @@ -314,9 +444,9 @@ align-items: center; justify-content: space-between; gap: 12px; - padding: 13px 19px; + padding: 12px 20px; border-top: 1px solid var(--border-base); - font-size: 11px; + font-size: 12px; color: var(--ink-mute); } .monitor-pagination > div { diff --git a/web/src/operationKey.test.ts b/web/src/operationKey.test.ts index 02e8df1..5c20e53 100644 --- a/web/src/operationKey.test.ts +++ b/web/src/operationKey.test.ts @@ -1,31 +1,46 @@ -import { afterEach,describe,expect,it } from 'vitest' +import { afterEach, describe, expect, it } from 'vitest' import { newOperationID } from './operationKey' -const uuidPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ -const originalCrypto=globalThis.crypto +const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ +const originalCrypto = globalThis.crypto -afterEach(()=>{ - Object.defineProperty(globalThis,'crypto',{value:originalCrypto,configurable:true,writable:true}) +afterEach(() => { + Object.defineProperty(globalThis, 'crypto', { value: originalCrypto, configurable: true, writable: true }) }) -describe('newOperationID',()=>{ - it('uses crypto.randomUUID when available (secure context)',()=>{ - expect(newOperationID()).toMatch(uuidPattern) - }) - it('falls back to getRandomValues over plain-HTTP LAN (insecure context)',()=>{ - const randomUUID=globalThis.crypto?.randomUUID - Object.defineProperty(globalThis,'crypto',{configurable:true,value:{randomUUID:undefined,getRandomValues:(buffer:Uint8Array)=>{const source=new Uint8Array([0x6f,0x1a,0x2b,0x3c,0x4d,0x5e,0x6f,0x70,0x81,0x92,0xa3,0xb4,0xc5,0xd6,0xe7,0xf8]);buffer.set(source);return buffer}}}) - try{ - const id=newOperationID() - // version nibble forced to 4 and variant bits to 10x: 0x6f->0x4f, 0x81->0x81 - expect(id).toBe('6f1a2b3c-4d5e-4f70-8192-a3b4c5d6e7f8') - expect(id).toMatch(uuidPattern) - }finally{ - void randomUUID - } - }) - it('refuses to fabricate an identifier when no CSPRNG exists',()=>{ - Object.defineProperty(globalThis,'crypto',{configurable:true,value:{randomUUID:undefined,getRandomValues:undefined}}) - expect(()=>newOperationID()).toThrow('当前环境无法安全生成操作标识') - }) +describe('newOperationID', () => { + it('uses crypto.randomUUID when available (secure context)', () => { + expect(newOperationID()).toMatch(uuidPattern) + }) + it('falls back to getRandomValues over plain-HTTP LAN (insecure context)', () => { + const randomUUID = globalThis.crypto?.randomUUID + Object.defineProperty(globalThis, 'crypto', { + configurable: true, + value: { + randomUUID: undefined, + getRandomValues: (buffer: Uint8Array) => { + const source = new Uint8Array([ + 0x6f, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e, 0x6f, 0x70, 0x81, 0x92, 0xa3, 0xb4, 0xc5, 0xd6, 0xe7, 0xf8, + ]) + buffer.set(source) + return buffer + }, + }, + }) + try { + const id = newOperationID() + // version nibble forced to 4 and variant bits to 10x: 0x6f->0x4f, 0x81->0x81 + expect(id).toBe('6f1a2b3c-4d5e-4f70-8192-a3b4c5d6e7f8') + expect(id).toMatch(uuidPattern) + } finally { + void randomUUID + } + }) + it('refuses to fabricate an identifier when no CSPRNG exists', () => { + Object.defineProperty(globalThis, 'crypto', { + configurable: true, + value: { randomUUID: undefined, getRandomValues: undefined }, + }) + expect(() => newOperationID()).toThrow('当前环境无法安全生成操作标识') + }) }) diff --git a/web/src/operationKey.ts b/web/src/operationKey.ts index 021c259..cc871a9 100644 --- a/web/src/operationKey.ts +++ b/web/src/operationKey.ts @@ -1,13 +1,13 @@ -export function newOperationID():string{ - const cryptoApi=globalThis.crypto - if(typeof cryptoApi?.randomUUID==='function')return cryptoApi.randomUUID() - if(typeof cryptoApi?.getRandomValues==='function'){ - const bytes=new Uint8Array(16) - cryptoApi.getRandomValues(bytes) - bytes[6]=(bytes[6]&0x0f)|0x40 - bytes[8]=(bytes[8]&0x3f)|0x80 - const hex=Array.from(bytes,value=>value.toString(16).padStart(2,'0')).join('') - return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}` - } - throw new Error('当前环境无法安全生成操作标识') +export function newOperationID(): string { + const cryptoApi = globalThis.crypto + if (typeof cryptoApi?.randomUUID === 'function') return cryptoApi.randomUUID() + if (typeof cryptoApi?.getRandomValues === 'function') { + const bytes = new Uint8Array(16) + cryptoApi.getRandomValues(bytes) + bytes[6] = (bytes[6] & 0x0f) | 0x40 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('') + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` + } + throw new Error('当前环境无法安全生成操作标识') } diff --git a/web/src/ppConnection.test.ts b/web/src/ppConnection.test.ts new file mode 100644 index 0000000..2bfe901 --- /dev/null +++ b/web/src/ppConnection.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi, afterEach } from 'vitest' +import { readPPConnection, testPPConnection, savePPConnection } from './ppConnection' +afterEach(() => vi.unstubAllGlobals()) +describe('PP connection transport', () => { + it('uses current draft on POST without saving or sending a placeholder password', async () => { + const fetcher = vi.fn( + async () => + new Response( + JSON.stringify({ data: { state: 'valid', message: '目录可读', checked_at: '2026-11-17T10:00:00Z' } }) + ) + ) + vi.stubGlobal('fetch', fetcher) + const result = await testPPConnection({ base_url: 'https://api.example.invalid', username: 'example', revision: 3 }) + expect(result.state).toBe('valid') + const [path, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit] + expect(path).toBe('/api/v1/pp-connection/test') + expect(init.method).toBe('POST') + expect(JSON.parse(String(init.body))).toEqual({ + base_url: 'https://api.example.invalid', + username: 'example', + revision: 3, + }) + }) + it('preserves real response errors and reads metadata only', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ error: '原配置保留' }), { status: 422 })) + ) + await expect( + savePPConnection({ base_url: 'https://api.example.invalid', username: 'example', revision: 1 }) + ).rejects.toThrow('原配置保留') + vi.stubGlobal( + 'fetch', + vi.fn( + async () => + new Response( + JSON.stringify({ + data: { revision: 1, active: null, pending: null, observation: null, pending_observation: null }, + }) + ) + ) + ) + expect((await readPPConnection()).revision).toBe(1) + }) +}) diff --git a/web/src/ppConnection.ts b/web/src/ppConnection.ts new file mode 100644 index 0000000..7dfe163 --- /dev/null +++ b/web/src/ppConnection.ts @@ -0,0 +1,86 @@ +export type PPObservation = { state: string; message: string; checked_at: string; previous?: PPObservation | null } +export type PPMetadata = { id: string; base_url: string; username: string; password_configured: boolean } +export type PPView = { + revision: number + active: PPMetadata | null + pending: PPMetadata | null + observation: PPObservation | null + pending_observation: PPObservation | null +} +export type PPDraft = { base_url: string; username: string; password?: string; revision: number; pending_id?: string } +const record = (v: unknown): v is Record => typeof v === 'object' && v !== null +const states = new Set(['valid', 'auth_failed', 'permission_denied', 'incomplete', 'unavailable', 'invalid_response']) +async function request(path: string, method: string, draft?: PPDraft, signal?: AbortSignal) { + const response = await fetch(path, { + method, + signal, + cache: 'no-store', + headers: { + Accept: 'application/json', + ...(draft ? { 'Content-Type': 'application/json', 'X-Governance-Action': 'pp-connection' } : {}), + }, + ...(draft ? { body: JSON.stringify(draft) } : {}), + }) + const payload: unknown = await response.json().catch(() => null) + if (!response.ok) + throw new Error( + record(payload) && typeof payload.error === 'string' ? payload.error : `PP 请求失败(HTTP ${response.status})` + ) + if (!record(payload) || !record(payload.data)) throw new Error('PP 返回的数据格式不正确') + return payload.data +} +function parseObservation(data: unknown): PPObservation | null { + if (data === null || data === undefined) return null + if ( + !record(data) || + !states.has(String(data.state)) || + typeof data.message !== 'string' || + typeof data.checked_at !== 'string' || + !Number.isFinite(Date.parse(data.checked_at)) + ) + throw new Error('PP 检查状态无法识别') + return { + state: String(data.state), + message: data.message, + checked_at: data.checked_at, + ...(record(data.previous) ? { previous: parseObservation({ ...data.previous, previous: null }) } : {}), + } +} +function parseMetadata(data: unknown): PPMetadata | null { + if (data === null) return null + if ( + !record(data) || + typeof data.id !== 'string' || + typeof data.base_url !== 'string' || + typeof data.username !== 'string' || + typeof data.password_configured !== 'boolean' + ) + throw new Error('PP 配置元数据不正确') + return { + id: data.id, + base_url: data.base_url, + username: data.username, + password_configured: data.password_configured, + } +} +function parseView(data: Record): PPView { + if (!Number.isSafeInteger(data.revision) || Number(data.revision) < 0) throw new Error('PP 配置版本不正确') + return { + revision: Number(data.revision), + active: parseMetadata(data.active), + pending: parseMetadata(data.pending), + observation: parseObservation(data.observation), + pending_observation: parseObservation(data.pending_observation), + } +} +export async function readPPConnection(signal?: AbortSignal): Promise { + return parseView(await request('/api/v1/pp-connection', 'GET', undefined, signal)) +} +export async function testPPConnection(draft: PPDraft, signal?: AbortSignal): Promise { + const result = parseObservation(await request('/api/v1/pp-connection/test', 'POST', draft, signal)) + if (!result) throw new Error('未取得 PP 检查结果') + return result +} +export async function savePPConnection(draft: PPDraft, signal?: AbortSignal): Promise { + return parseView(await request('/api/v1/pp-connection', 'PUT', draft, signal)) +} diff --git a/web/src/productionBindings.test.ts b/web/src/productionBindings.test.ts index 4c1ffb2..7b70951 100644 --- a/web/src/productionBindings.test.ts +++ b/web/src/productionBindings.test.ts @@ -3,14 +3,24 @@ import { describe, expect, it, vi } from 'vitest' import { fetchProductionBindingOptions, fetchProductionBindings, saveProductionBindings } from './productionBindings' const binding = { - internal_kb_id: '0b217e8a-2a65-40a3-ab8f-34ac5c7a6f05', external_kb_id: '', - internal_kb_name: '对内知识库-wiki', external_kb_name: '', updated_by: 'admin', - production_base_url: 'https://weknora-test.dobot.cn/', production_connected: true, production_message: '', + internal_kb_id: '0b217e8a-2a65-40a3-ab8f-34ac5c7a6f05', + external_kb_id: '', + internal_kb_name: '对内知识库-wiki', + external_kb_name: '', + updated_by: 'admin', + production_base_url: 'https://weknora-test.dobot.cn/', + production_connected: true, + production_message: '', } describe('production bindings API', () => { it('reads the 源库 → 目标库 projection without leaking extra fields', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...binding, api_key: 'drop' } }), { status: 200 }))) + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue(new Response(JSON.stringify({ data: { ...binding, api_key: 'drop' } }), { status: 200 })) + ) const result = await fetchProductionBindings() expect(result.internal_kb_name).toBe('对内知识库-wiki') expect(result.production_connected).toBe(true) @@ -18,16 +28,36 @@ describe('production bindings API', () => { vi.unstubAllGlobals() }) it('lists production knowledge base options for the picker', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'kb-1', name: '对内知识库-wiki', knowledge_count: 2069 }, { id: '', name: '坏行' }] }), { status: 200 }))) - expect(await fetchProductionBindingOptions()).toEqual([{ id: 'kb-1', name: '对内知识库-wiki', knowledge_count: 2069 }]) + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: [ + { id: 'kb-1', name: '对内知识库-wiki', knowledge_count: 2069 }, + { id: '', name: '坏行' }, + ], + }), + { status: 200 } + ) + ) + ) + expect(await fetchProductionBindingOptions()).toEqual([ + { id: 'kb-1', name: '对内知识库-wiki', knowledge_count: 2069 }, + ]) vi.unstubAllGlobals() }) it('saves with an idempotency key and surfaces a rejected base', async () => { - const fetchMock = vi.fn() + const fetchMock = vi + .fn() .mockResolvedValueOnce(new Response(JSON.stringify({ data: binding }), { status: 200 })) - .mockResolvedValueOnce(new Response(JSON.stringify({ error: '对内绑定的生产知识库在该 WeKnora 实例中不存在' }), { status: 400 })) + .mockResolvedValueOnce( + new Response(JSON.stringify({ error: '对内绑定的生产知识库在该 WeKnora 实例中不存在' }), { status: 400 }) + ) vi.stubGlobal('fetch', fetchMock) - await expect(saveProductionBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })).resolves.toMatchObject({ internal_kb_name: '对内知识库-wiki' }) + await expect(saveProductionBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })).resolves.toMatchObject({ + internal_kb_name: '对内知识库-wiki', + }) const [, init] = fetchMock.mock.calls[0] expect(init.method).toBe('PUT') expect(init.headers['Idempotency-Key']).toBeTruthy() @@ -35,10 +65,24 @@ describe('production bindings API', () => { vi.unstubAllGlobals() }) it('reports an unverified save honestly instead of pretending it was checked', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...binding, production_connected: false, production_message: '生产 WeKnora 不可用:dial tcp: timeout' } }), { status: 200 }))) + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + ...binding, + production_connected: false, + production_message: '生产 WeKnora 不可用:dial tcp: timeout', + }, + }), + { status: 200 } + ) + ) + ) const result = await saveProductionBindings({ internal_kb_id: 'kb-1', external_kb_id: '' }) expect(result.production_connected).toBe(false) expect(result.production_message).toContain('不可用') vi.unstubAllGlobals() }) -}) \ No newline at end of file +}) diff --git a/web/src/productionBindings.ts b/web/src/productionBindings.ts index 5702fa6..944e71c 100644 --- a/web/src/productionBindings.ts +++ b/web/src/productionBindings.ts @@ -11,9 +11,26 @@ export interface ProductionBindings { production_base_url: string production_connected: boolean production_message: string + // legacy_scope 标明这条记录属于旧文档级发布路径;整库发布不看它。 + legacy_scope: string + // whole_target 是整库发布真正写入的目标(来自部署配置),只读。 + whole_target: LibraryPublishTarget } -const record = (value: unknown): value is Record => Boolean(value) && typeof value === 'object' && !Array.isArray(value) +export interface LibraryPublishTarget { + configured: boolean + source: string + tenant_id: number + internal_kb_id: string + external_kb_id: string + database: string + elastic_index: string + object_bucket: string + missing_reason: string +} + +const record = (value: unknown): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value) function projection(item: Record): ProductionBindings { return { @@ -25,41 +42,74 @@ function projection(item: Record): ProductionBindings { production_base_url: typeof item.production_base_url === 'string' ? item.production_base_url : '', production_connected: item.production_connected === true, production_message: typeof item.production_message === 'string' ? item.production_message : '', + legacy_scope: typeof item.legacy_scope === 'string' ? item.legacy_scope : '', + whole_target: wholeTarget(item.whole_target), + } +} + +// wholeTarget 只读投影:缺字段就说未配置,不拿可编辑的文档级绑定冒充整库目标。 +function wholeTarget(value: unknown): LibraryPublishTarget { + const item = record(value) ? value : {} + return { + configured: item.configured === true, + source: typeof item.source === 'string' ? item.source : '', + tenant_id: typeof item.tenant_id === 'number' ? item.tenant_id : 0, + internal_kb_id: typeof item.internal_kb_id === 'string' ? item.internal_kb_id : '', + external_kb_id: typeof item.external_kb_id === 'string' ? item.external_kb_id : '', + database: typeof item.database === 'string' ? item.database : '', + elastic_index: typeof item.elastic_index === 'string' ? item.elastic_index : '', + object_bucket: typeof item.object_bucket === 'string' ? item.object_bucket : '', + missing_reason: typeof item.missing_reason === 'string' ? item.missing_reason : '', } } export async function fetchProductionBindings(signal?: AbortSignal): Promise { const response = await fetch('/api/v1/production-kb-bindings', { signal, headers: { Accept: 'application/json' } }) if (!response.ok) throw new Error(`读取生产知识库绑定失败(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !record(value.data)) throw new Error('生产知识库绑定响应无效') return projection(value.data) } export async function fetchProductionBindingOptions(signal?: AbortSignal): Promise { - const response = await fetch('/api/v1/production-kb-bindings/options', { signal, headers: { Accept: 'application/json' } }) + const response = await fetch('/api/v1/production-kb-bindings/options', { + signal, + headers: { Accept: 'application/json' }, + }) if (!response.ok) throw new Error(`读取生产知识库列表失败(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !Array.isArray(value.data)) throw new Error('生产知识库列表响应无效') - return value.data.filter(record).map((item) => ({ - id: typeof item.id === 'string' ? item.id : '', - name: typeof item.name === 'string' ? item.name : '', - knowledge_count: typeof item.knowledge_count === 'number' ? item.knowledge_count : 0, - })).filter((item) => item.id) + return value.data + .filter(record) + .map((item) => ({ + id: typeof item.id === 'string' ? item.id : '', + name: typeof item.name === 'string' ? item.name : '', + knowledge_count: typeof item.knowledge_count === 'number' ? item.knowledge_count : 0, + })) + .filter((item) => item.id) } -export async function saveProductionBindings(input: { internal_kb_id: string; external_kb_id: string }, signal?: AbortSignal): Promise { +export async function saveProductionBindings( + input: { internal_kb_id: string; external_kb_id: string }, + signal?: AbortSignal +): Promise { const response = await fetch('/api/v1/production-kb-bindings', { - method: 'PUT', signal, + method: 'PUT', + signal, headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(input), }) if (!response.ok) { let reason = `保存生产知识库绑定失败(HTTP ${response.status})` - try { const body = await response.json() as unknown; if (record(body) && typeof body.error === 'string') reason = body.error } catch { /* keep status text */ } + try { + const body = (await response.json()) as unknown + if (record(body) && typeof body.error === 'string') reason = body.error + } catch { + /* keep status text */ + } throw new Error(reason) } - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !record(value.data)) throw new Error('生产知识库绑定响应无效') return projection(value.data) -} \ No newline at end of file +} diff --git a/web/src/qaMirror.css b/web/src/qaMirror.css index 442da4e..7109486 100644 --- a/web/src/qaMirror.css +++ b/web/src/qaMirror.css @@ -1,6 +1,6 @@ .qa-mirror-sync { padding: 12px 0; - border-bottom: 1px solid var(--border, #dce4ef); + border-bottom: 1px solid var(--border-base); margin-bottom: 12px; } .qa-mirror-sync-line { diff --git a/web/src/qaOps.css b/web/src/qaOps.css index c295575..3f6d781 100644 --- a/web/src/qaOps.css +++ b/web/src/qaOps.css @@ -2,8 +2,6 @@ display: flex; flex-direction: column; min-width: 0; - gap: 14px; - padding: 20px; height: calc(100dvh - 44px); overflow: hidden; } @@ -130,16 +128,6 @@ grid-template-columns: minmax(0, 1fr); } } -.qa-ops-header h2 { - margin: 0 0 5px; - font-size: 21px; - font-weight: 650; -} -.qa-ops-header h2 span { - font-size: 15px; - color: var(--ink-mute); - font-weight: 400; -} .qa-ops-header p, .qa-ops-slice-note { margin: 0; @@ -152,9 +140,11 @@ flex-wrap: wrap; align-items: end; gap: 12px; - padding: 14px; + padding: 16px; border: 1px solid var(--border-base); + border-radius: var(--r-lg); background: var(--bg-panel); + box-shadow: var(--shadow-card); } .qa-ops-query label { display: flex; @@ -170,7 +160,7 @@ padding: 7px 10px; color: var(--ink-strong); border: 1px solid var(--border-strong); - border-radius: var(--r-sm); + border-radius: var(--r-md); background: var(--bg-panel); } .qa-week-picker { @@ -199,23 +189,40 @@ min-height: 36px; min-width: 72px; color: #fff; - background: var(--c-run); - border: 1px solid var(--c-run); + background: var(--c-primary); + border: 1px solid var(--c-primary); +} +.qa-ops-query button:hover:not(:disabled) { + color: #fff; + background: var(--c-primary-hover); + border-color: var(--c-primary-hover); +} +/* 立即同步会触发后台写入,不能与只读的「查询」同为主按钮:用描边次按钮区分 */ +.qa-ops-query .qa-sync-action, +.qa-ops-query .qa-sync-action:hover:not(:disabled) { + color: var(--c-run); + background: var(--bg-panel); + border-color: var(--c-run-border); +} +.qa-ops-query .qa-sync-action:hover:not(:disabled) { + background: var(--c-run-bg); } .qa-ops-query .qa-week-current { color: var(--ink-strong); background: var(--bg-panel); border-color: var(--border-strong); } -.qa-ops-query .qa-week-current:hover { +.qa-ops-query .qa-week-current:hover:not(:disabled) { + color: var(--ink-strong); background: var(--bg-soft); + border-color: var(--border-strong); } .qa-ops button:focus-visible, .qa-ops input:focus-visible, .qa-ops select:focus-visible, .qa-ops-table-scroll:focus-visible { - outline: 2px solid var(--c-run); - outline-offset: 2px; + outline: none; + box-shadow: var(--c-focus-ring); } .qa-ops-organization { margin: 8px 14px; @@ -230,7 +237,10 @@ min-width: 0; min-height: 0; border: 1px solid var(--border-base); + border-radius: var(--r-lg); background: var(--bg-panel); + box-shadow: var(--shadow-card); + overflow: hidden; } .qa-ops-result-bar, .qa-ops-page-bar { @@ -496,7 +506,8 @@ /* Keep the wide ledger at the top; category colors do not tint entire rows. */ .qa-ops { gap: 8px; - padding: 12px 16px; + /* 纵向保持紧凑(台账要尽量靠上),横向与其他模块统一 24px,切换页面时左边缘不跳 */ + padding: 16px 24px 12px; } .qa-ops-query { flex-wrap: wrap; @@ -561,7 +572,7 @@ cursor: default; } .qa-ops-table tbody tr[data-qa-row]:hover { - background: var(--bg-subtle, #f8fafc); + background: var(--bg-soft); } @media (max-width: 1100px) { .qa-ops-query { @@ -579,13 +590,13 @@ .qa-ai-model-settings { padding: 14px 0; - border-block: 1px solid var(--border, #e2e8f0); + border-block: 1px solid var(--border-base); } .qa-ai-model-settings h3 { margin: 0 0 6px; } .qa-ai-workbench { - border: 1px solid var(--border, #e2e8f0); + border: 1px solid var(--border-base); border-radius: 5px; padding: 6px 10px; } @@ -613,9 +624,9 @@ flex-wrap: wrap; gap: 8px; padding: 10px; - border: 1px solid #93c5fd; - background: #eff6ff; - color: #1e3a8a; + border: 1px solid var(--c-run-border); + background: var(--c-run-bg); + color: var(--c-run); border-radius: 4px; } .qa-ai-confirm strong, @@ -642,16 +653,16 @@ gap: 5px; margin-top: 8px; padding: 8px; - border-top: 1px solid var(--border, #e2e8f0); + border-top: 1px solid var(--border-base); } .qa-ai-task { display: block; line-height: 18px; - color: #475569; + color: var(--ink-mute); } .qa-ai-task-running, .qa-ai-task-queued { - color: #1d4ed8; + color: var(--c-run); } .qa-ai-task-succeeded { color: #166534; @@ -667,14 +678,14 @@ margin-top: 12px; } .qa-ai-evidence > details { - border-top: 1px solid var(--border, #e2e8f0); + border-top: 1px solid var(--border-base); padding: 8px 0; } .qa-ai-field-evidence { margin: 8px 0; padding: 8px; - border-left: 2px solid #93c5fd; - background: #f8fafc; + border-left: 2px solid var(--c-run-border); + background: var(--bg-soft); } .qa-ai-field-evidence p { margin: 5px 0; @@ -684,7 +695,7 @@ .qa-ai-field-evidence blockquote { margin: 8px 0; padding-left: 10px; - border-left: 2px solid #cbd5e1; + border-left: 2px solid var(--border-strong); } .qa-ai-hash { overflow-wrap: anywhere; @@ -740,6 +751,6 @@ margin-top: 6px; } .qa-ledger-export [role='alert'] { - color: var(--danger-ink); + color: var(--c-fail); font-size: 12px; } diff --git a/web/src/qaWeeklyMail.css b/web/src/qaWeeklyMail.css index 31ae2b9..d070f7c 100644 --- a/web/src/qaWeeklyMail.css +++ b/web/src/qaWeeklyMail.css @@ -50,6 +50,22 @@ .qa-weekly-mail-sends li[data-status='sent'] { color: #2d704d; } +/* 正式补发是不可撤回的投递:与普通提示区分开,避免误点。 */ +.qa-weekly-mail-confirm { + display: flex; + flex-direction: column; + gap: 8px; + padding: 10px 12px; + border: 1px solid #f0c36d; + border-radius: 8px; + background: #fffaeb; + font-size: 13px; + color: #5b3d00; +} +.qa-weekly-mail-confirm p { + margin: 0; + line-height: 1.6; +} .qa-weekly-mail-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); diff --git a/web/src/qaWeeklyMail.test.tsx b/web/src/qaWeeklyMail.test.tsx index 9a875de..c4d6493 100644 --- a/web/src/qaWeeklyMail.test.tsx +++ b/web/src/qaWeeklyMail.test.tsx @@ -1,6 +1,12 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it } from 'vitest' -import { parseWeeklyMailConfirmation, parseWeeklyMailSends, parseWeeklyMailSettings } from './qaWeeklyMail' +import { + parseWeeklyMailConfirmation, + parseWeeklyMailFormalResult, + parseWeeklyMailSendPreview, + parseWeeklyMailSends, + parseWeeklyMailSettings, +} from './qaWeeklyMail' import { QAWeeklyMail } from './QAWeeklyMail' const settings = { @@ -72,5 +78,72 @@ it('shows the confirmation gate before any automatic send controls', () => { expect(html).toContain('未确认') expect(html).toContain('确认本周周报') expect(html).not.toContain('立即发送') + expect(html).not.toContain('正式补发') expect(html).not.toContain('发送设置') }) + +describe('weekly mail formal resend contract', () => { + it('shows the real distribution and revision in the pre-send preview', () => { + const preview = parseWeeklyMailSendPreview( + { + week: '2026-W45', + draft_revision: 16, + body_sha256: 'a'.repeat(64), + recipients: 119, + cc_recipients: 8, + status: 'ready', + }, + '2026-W45' + ) + expect(preview).toMatchObject({ recipients: 119, cc_recipients: 8, draft_revision: 16, status: 'ready' }) + expect(() => parseWeeklyMailSendPreview({ ...preview, status: 'queued' }, '2026-W45')).toThrow() + expect(() => parseWeeklyMailSendPreview({ ...preview, week: '2026-W44' }, '2026-W45')).toThrow() + }) + it('never reports success without a real message id', () => { + const sent = parseWeeklyMailFormalResult( + { + week: '2026-W45', + draft_revision: 16, + status: 'sent', + message_id: '', + recipients: 119, + cc_recipients: 8, + }, + '2026-W45' + ) + expect(sent.message_id).toBe('') + expect(() => + parseWeeklyMailFormalResult( + { week: '2026-W45', draft_revision: 16, status: 'sent', message_id: '', recipients: 119, cc_recipients: 8 }, + '2026-W45' + ) + ).toThrow() + expect(() => + parseWeeklyMailFormalResult( + { + week: '2026-W45', + draft_revision: 16, + status: 'failed', + message_id: '', + recipients: 1, + cc_recipients: 0, + }, + '2026-W45' + ) + ).toThrow() + }) + it('keeps the read-back message id on the send history', () => { + const [send] = parseWeeklyMailSends([ + { + week: '2026-W45', + draft_revision: 16, + status: 'sent', + attempts: 1, + last_error: '', + message_id: '', + updated_at: '2026-11-09T00:32:00+08:00', + }, + ]) + expect(send.message_id).toBe('') + }) +}) diff --git a/web/src/qaWeeklyMail.ts b/web/src/qaWeeklyMail.ts index 73d2247..6e8c9ce 100644 --- a/web/src/qaWeeklyMail.ts +++ b/web/src/qaWeeklyMail.ts @@ -33,9 +33,30 @@ export interface WeeklyMailSend { status: 'sending' | 'sent' | 'failed' attempts: number last_error: string + message_id: string updated_at: string } +// 正式补发前的核对结果:确认框显示真实收件人数,而不是测试邮箱。 +export interface WeeklyMailSendPreview { + week: string + draft_revision: number + body_sha256: string + recipients: number + cc_recipients: number + status: 'ready' | 'already_sent' | 'in_flight' + message_id: string +} + +export interface WeeklyMailFormalResult { + week: string + draft_revision: number + status: 'sent' | 'already_sent' + message_id: string + recipients: number + cc_recipients: number +} + const bad = (): never => { throw new Error('周报邮件响应无效,未显示或未标记为已保存') } @@ -99,11 +120,44 @@ export function parseWeeklyMailSends(value: unknown): WeeklyMailSend[] { status: v.status as WeeklyMailSend['status'], attempts: num(v.attempts), last_error: str(v.last_error), + message_id: typeof v.message_id === 'string' ? v.message_id : '', updated_at: str(v.updated_at), } }) } +export function parseWeeklyMailSendPreview(value: unknown, week: string): WeeklyMailSendPreview { + const v = obj(value) + if (v.week !== week) return bad() + if (!['ready', 'already_sent', 'in_flight'].includes(str(v.status))) return bad() + return { + week, + draft_revision: num(v.draft_revision), + body_sha256: str(v.body_sha256), + recipients: num(v.recipients), + cc_recipients: num(v.cc_recipients), + status: v.status as WeeklyMailSendPreview['status'], + message_id: typeof v.message_id === 'string' ? v.message_id : '', + } +} + +export function parseWeeklyMailFormalResult(value: unknown, week: string): WeeklyMailFormalResult { + const v = obj(value) + if (v.week !== week) return bad() + if (!['sent', 'already_sent'].includes(str(v.status))) return bad() + // 没有 message_id 的“成功”是假成功:必须当作无效响应。 + const messageID = str(v.message_id) + if (!messageID) return bad() + return { + week, + draft_revision: num(v.draft_revision), + status: v.status as WeeklyMailFormalResult['status'], + message_id: messageID, + recipients: num(v.recipients), + cc_recipients: num(v.cc_recipients), + } +} + const endpoint = (path: string, week?: string) => `/api/v1/qa-ops/master/weekly-mail/${path}${week ? '/' + encodeURIComponent(week) : ''}` const headers = { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-weekly-mail' } @@ -173,6 +227,29 @@ export async function sendWeeklyMailTest(week: string): Promise { return payload.message_id } +export async function previewWeeklyMailSend( + week: string, + revision: number, + bodySHA256: string +): Promise { + const query = new URLSearchParams({ revision: String(revision), body_sha256: bodySHA256 }).toString() + return parseWeeklyMailSendPreview(await getPayload(endpoint('send', week) + '?' + query), week) +} + +// 正式补发:用当前已确认的版本+hash 精确投递,成功后由服务端写入正式发送记录。 +export async function sendWeeklyMailFormal( + week: string, + revision: number, + bodySHA256: string +): Promise { + const payload = await getPayload(endpoint('send', week), undefined, { + method: 'POST', + headers, + body: JSON.stringify({ revision, body_sha256: bodySHA256 }), + }) + return parseWeeklyMailFormalResult(payload, week) +} + export async function uploadWeeklyMailImage(week: string, png: Blob): Promise { const buffer = await png.arrayBuffer() let binary = '' diff --git a/web/src/releasePlanner.css b/web/src/releasePlanner.css index a65bfee..4c12685 100644 --- a/web/src/releasePlanner.css +++ b/web/src/releasePlanner.css @@ -1,2 +1,262 @@ -.release-planner{max-width:1700px}.production-off{border:1px solid var(--c-fail-border);border-radius:8px;padding:7px 10px;background:var(--c-fail-bg);color:var(--c-fail);font-size:12px;font-weight:700}.release-four-steps{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin:0 0 16px;padding:0;list-style:none}.release-four-steps li{border-top:3px solid var(--border-base);padding:9px;background:var(--bg-panel);color:var(--ink-mute);font-size:11px;text-align:center}.release-four-steps li.active{border-color:var(--c-run);background:var(--c-run-bg);color:var(--c-run);font-weight:700}.release-four-steps li.danger{border-color:var(--c-fail-border);background:var(--c-fail-bg);color:var(--c-fail)}.release-plan-layout{display:grid;grid-template-columns:minmax(0,1fr) 350px;gap:18px;align-items:start}.release-candidates,.release-plan-summary{border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.release-plan-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--border-base);padding:14px 16px}.release-plan-heading>div{display:grid;gap:3px}.release-plan-heading h2,.release-plan-summary h2{margin:0;color:var(--ink-base);font-size:15px}.release-plan-heading span{color:var(--ink-mute);font-size:10px}.release-plan-heading button{padding:7px 10px}.release-candidate-list{display:grid}.release-candidate{display:grid;grid-template-columns:20px minmax(190px,1fr) minmax(330px,1.4fr) auto;gap:12px;align-items:center;border-bottom:1px solid var(--border-soft);padding:14px 16px;color:var(--ink-base)}.release-candidate.blocked{background:var(--c-fail-bg);color:var(--c-fail)}.candidate-title{display:grid;gap:5px}.candidate-title strong{overflow-wrap:anywhere;color:var(--ink-base);font-size:12px}.candidate-title small{color:var(--ink-mute);font-size:10px}.closure-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:5px}.closure-grid span{border-radius:6px;padding:6px 5px;background:var(--bg-soft);color:var(--ink-mute);font-size:9px;text-align:center;white-space:nowrap}.closure-grid .ready{background:var(--c-done-bg);color:var(--c-done)}.closure-grid .shared{background:var(--c-warn-bg);color:var(--c-warn)}.closure-grid .missing{background:var(--c-fail-bg);color:var(--c-fail)}.blocked-reason{color:var(--c-fail);font-size:10px}.release-plan-summary{display:grid;gap:13px;padding:17px;position:sticky;top:80px} -.closure-result{border-radius:6px;padding:6px 8px;font-size:9px;white-space:nowrap}.closure-result.ready{background:var(--c-done-bg);color:var(--c-done)}.closure-result.shared{background:var(--c-warn-bg);color:var(--c-warn)}.closure-result.missing{background:var(--c-fail-bg);color:var(--c-fail)}.release-decision-key{display:grid;gap:6px;border:1px solid var(--border-base);border-radius:8px;padding:9px;background:var(--bg-soft);color:var(--ink-mute);font-size:9px}.release-decision-key b{color:var(--ink-base)}.release-mode{display:grid;gap:5px;border-radius:10px;padding:13px;background:#f3f7fa}.release-mode span,.release-mode small{color:var(--ink-mute);font-size:10px;line-height:1.5}.release-mode strong{color:var(--ink-base)}.release-mode.document{background:var(--c-done-bg)}.release-mode.knowledge_base{background:var(--c-warn-bg)}.release-mode.blocked{background:var(--c-fail-bg)}.release-plan-summary dl{display:grid;grid-template-columns:1fr auto;gap:8px;margin:0;color:var(--ink-mute);font-size:11px}.release-plan-summary dd{margin:0;color:#1c4765;font-weight:700}.kb-warning{margin:0;border-radius:8px;padding:10px;background:var(--c-warn-bg);color:var(--c-warn);font-size:10px;line-height:1.6}.release-gates{display:grid;gap:6px;border-top:1px solid var(--border-base);padding-top:12px}.release-gates span{border-radius:6px;padding:7px;background:var(--c-fail-bg);color:var(--c-fail);font-size:10px}.release-plan-summary>small{color:var(--ink-mute);font-size:9px;line-height:1.5}@media(max-width:1100px){.release-plan-layout{grid-template-columns:1fr}.release-plan-summary{position:static}.release-candidate{grid-template-columns:20px minmax(180px,1fr)}.closure-grid{grid-column:2/-1}.blocked-reason{grid-column:2}}@media(max-width:700px){.release-four-steps{grid-template-columns:1fr 1fr}.closure-grid{grid-template-columns:repeat(2,minmax(0,1fr))}} \ No newline at end of file +.release-planner { + max-width: 1700px; +} +.production-off { + border: 1px solid var(--c-fail-border); + border-radius: 8px; + padding: 7px 10px; + background: var(--c-fail-bg); + color: var(--c-fail); + font-size: 12px; + font-weight: 700; +} +.release-four-steps { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + margin: 0 0 16px; + padding: 0; + list-style: none; +} +.release-four-steps li { + border-top: 3px solid var(--border-base); + padding: 9px; + background: var(--bg-panel); + color: var(--ink-mute); + font-size: 11px; + text-align: center; +} +.release-four-steps li.active { + border-color: var(--c-run); + background: var(--c-run-bg); + color: var(--c-run); + font-weight: 700; +} +.release-four-steps li.danger { + border-color: var(--c-fail-border); + background: var(--c-fail-bg); + color: var(--c-fail); +} +.release-plan-layout { + display: grid; + grid-template-columns: minmax(0, 1fr) 350px; + gap: 18px; + align-items: start; +} +.release-candidates, +.release-plan-summary { + border: 1px solid var(--border-base); + border-radius: 14px; + background: var(--bg-panel); +} +.release-plan-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + border-bottom: 1px solid var(--border-base); + padding: 14px 16px; +} +.release-plan-heading > div { + display: grid; + gap: 3px; +} +.release-plan-heading h2, +.release-plan-summary h2 { + margin: 0; + color: var(--ink-base); + font-size: 15px; +} +.release-plan-heading span { + color: var(--ink-mute); + font-size: 10px; +} +.release-plan-heading button { + padding: 7px 10px; +} +.release-candidate-list { + display: grid; +} +.release-candidate { + display: grid; + grid-template-columns: 20px minmax(190px, 1fr) minmax(330px, 1.4fr) auto; + gap: 12px; + align-items: center; + border-bottom: 1px solid var(--border-soft); + padding: 14px 16px; + color: var(--ink-base); +} +.release-candidate.blocked { + background: var(--c-fail-bg); + color: var(--c-fail); +} +.candidate-title { + display: grid; + gap: 5px; +} +.candidate-title strong { + overflow-wrap: anywhere; + color: var(--ink-base); + font-size: 12px; +} +.candidate-title small { + color: var(--ink-mute); + font-size: 10px; +} +.closure-grid { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 5px; +} +.closure-grid span { + border-radius: 6px; + padding: 6px 5px; + background: var(--bg-soft); + color: var(--ink-mute); + font-size: 9px; + text-align: center; + white-space: nowrap; +} +.closure-grid .ready { + background: var(--c-done-bg); + color: var(--c-done); +} +.closure-grid .shared { + background: var(--c-warn-bg); + color: var(--c-warn); +} +.closure-grid .missing { + background: var(--c-fail-bg); + color: var(--c-fail); +} +.blocked-reason { + color: var(--c-fail); + font-size: 10px; +} +.release-plan-summary { + display: grid; + gap: 13px; + padding: 17px; + position: sticky; + top: 80px; +} +.closure-result { + border-radius: 6px; + padding: 6px 8px; + font-size: 9px; + white-space: nowrap; +} +.closure-result.ready { + background: var(--c-done-bg); + color: var(--c-done); +} +.closure-result.shared { + background: var(--c-warn-bg); + color: var(--c-warn); +} +.closure-result.missing { + background: var(--c-fail-bg); + color: var(--c-fail); +} +.release-decision-key { + display: grid; + gap: 6px; + border: 1px solid var(--border-base); + border-radius: 8px; + padding: 9px; + background: var(--bg-soft); + color: var(--ink-mute); + font-size: 9px; +} +.release-decision-key b { + color: var(--ink-base); +} +.release-mode { + display: grid; + gap: 5px; + border-radius: 10px; + padding: 13px; + background: #f3f7fa; +} +.release-mode span, +.release-mode small { + color: var(--ink-mute); + font-size: 10px; + line-height: 1.5; +} +.release-mode strong { + color: var(--ink-base); +} +.release-mode.document { + background: var(--c-done-bg); +} +.release-mode.knowledge_base { + background: var(--c-warn-bg); +} +.release-mode.blocked { + background: var(--c-fail-bg); +} +.release-plan-summary dl { + display: grid; + grid-template-columns: 1fr auto; + gap: 8px; + margin: 0; + color: var(--ink-mute); + font-size: 11px; +} +.release-plan-summary dd { + margin: 0; + color: #1c4765; + font-weight: 700; +} +.kb-warning { + margin: 0; + border-radius: 8px; + padding: 10px; + background: var(--c-warn-bg); + color: var(--c-warn); + font-size: 10px; + line-height: 1.6; +} +.release-gates { + display: grid; + gap: 6px; + border-top: 1px solid var(--border-base); + padding-top: 12px; +} +.release-gates span { + border-radius: 6px; + padding: 7px; + background: var(--c-fail-bg); + color: var(--c-fail); + font-size: 10px; +} +.release-plan-summary > small { + color: var(--ink-mute); + font-size: 9px; + line-height: 1.5; +} +@media (max-width: 1100px) { + .release-plan-layout { + grid-template-columns: 1fr; + } + .release-plan-summary { + position: static; + } + .release-candidate { + grid-template-columns: 20px minmax(180px, 1fr); + } + .closure-grid { + grid-column: 2/-1; + } + .blocked-reason { + grid-column: 2; + } +} +@media (max-width: 700px) { + .release-four-steps { + grid-template-columns: 1fr 1fr; + } + .closure-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} diff --git a/web/src/releasePlanner.test.ts b/web/src/releasePlanner.test.ts index 6fe6f86..b0a6533 100644 --- a/web/src/releasePlanner.test.ts +++ b/web/src/releasePlanner.test.ts @@ -1,18 +1,39 @@ -import { describe,expect,it } from 'vitest' +import { describe, expect, it } from 'vitest' import { evaluateReleaseSelection } from './releasePlanner' import type { ReleaseCandidate } from './releasePlanner' -const ready:ReleaseCandidate={id:'a',title:'A.pdf',knowledge_base_id:'kb-1',knowledge_base_name:'公司级技术支持知识库',visibility:'internal',parse_status:'completed',chunks:100,vectors:100,assets:2,wiki:'ready',graph:'ready'} -describe('release planner',()=>{ - it('uses document release only when every selected closure is independently complete',()=>{ - expect(evaluateReleaseSelection([ready])).toMatchObject({mode:'document',blocked:false}) - }) - it('escalates shared wiki or graph data to one whole knowledge-base release',()=>{ - expect(evaluateReleaseSelection([{...ready,id:'b',graph:'shared'}])).toMatchObject({mode:'knowledge_base',blocked:false,knowledge_base_id:'kb-1'}) - }) - it('blocks failed parsing, missing core data, or cross-KB fallback',()=>{ - expect(evaluateReleaseSelection([{...ready,parse_status:'failed'}]).blocked).toBe(true) - expect(evaluateReleaseSelection([{...ready,vectors:0}]).blocked).toBe(true) - expect(evaluateReleaseSelection([{...ready,graph:'shared'},{...ready,id:'c',knowledge_base_id:'kb-2'}]).blocked).toBe(true) - }) +const ready: ReleaseCandidate = { + id: 'a', + title: 'A.pdf', + knowledge_base_id: 'kb-1', + knowledge_base_name: '公司级技术支持知识库', + visibility: 'internal', + parse_status: 'completed', + chunks: 100, + vectors: 100, + assets: 2, + wiki: 'ready', + graph: 'ready', +} +describe('release planner', () => { + it('uses document release only when every selected closure is independently complete', () => { + expect(evaluateReleaseSelection([ready])).toMatchObject({ mode: 'document', blocked: false }) + }) + it('escalates shared wiki or graph data to one whole knowledge-base release', () => { + expect(evaluateReleaseSelection([{ ...ready, id: 'b', graph: 'shared' }])).toMatchObject({ + mode: 'knowledge_base', + blocked: false, + knowledge_base_id: 'kb-1', + }) + }) + it('blocks failed parsing, missing core data, or cross-KB fallback', () => { + expect(evaluateReleaseSelection([{ ...ready, parse_status: 'failed' }]).blocked).toBe(true) + expect(evaluateReleaseSelection([{ ...ready, vectors: 0 }]).blocked).toBe(true) + expect( + evaluateReleaseSelection([ + { ...ready, graph: 'shared' }, + { ...ready, id: 'c', knowledge_base_id: 'kb-2' }, + ]).blocked + ).toBe(true) + }) }) diff --git a/web/src/releasePlanner.ts b/web/src/releasePlanner.ts index e59e75a..5553797 100644 --- a/web/src/releasePlanner.ts +++ b/web/src/releasePlanner.ts @@ -1,16 +1,89 @@ -export type ClosureState='ready'|'shared'|'missing'|'not_required' -export interface ReleaseCandidate{id:string;title:string;knowledge_base_id:string;knowledge_base_name:string;visibility:'internal'|'external';parse_status:string;chunks:number;vectors:number;assets:number;wiki:ClosureState;graph:ClosureState} -export interface ReleasePlan{mode:'none'|'document'|'knowledge_base'|'blocked';blocked:boolean;reason:string;knowledge_base_id?:string} -export function evaluateReleaseSelection(items:ReleaseCandidate[]):ReleasePlan{ - if(!items.length)return{mode:'none',blocked:true,reason:'请先选择测试文档'} - if(items.some(item=>item.parse_status!=='completed'))return{mode:'blocked',blocked:true,reason:'存在尚未完成解析的文档'} - if(items.some(item=>item.chunks<1||item.vectors!==item.chunks||item.assets<1||item.wiki==='missing'||item.graph==='missing'))return{mode:'blocked',blocked:true,reason:'切片、向量、文件、Wiki或图谱闭包不完整'} - const needsKB=items.some(item=>item.wiki==='shared'||item.graph==='shared') - if(needsKB){const ids=new Set(items.map(item=>item.knowledge_base_id));if(ids.size!==1)return{mode:'blocked',blocked:true,reason:'整知识库发布不能跨知识库合并'};return{mode:'knowledge_base',blocked:false,reason:'Wiki或图谱包含共享数据,必须按整个知识库同步',knowledge_base_id:items[0].knowledge_base_id}} - return{mode:'document',blocked:false,reason:'所选文档的切片、向量、文件、Wiki和图谱闭包可以独立验证'} +export type ClosureState = 'ready' | 'shared' | 'missing' | 'not_required' +export interface ReleaseCandidate { + id: string + title: string + knowledge_base_id: string + knowledge_base_name: string + visibility: 'internal' | 'external' + parse_status: string + chunks: number + vectors: number + assets: number + wiki: ClosureState + graph: ClosureState } -export const simulatedReleaseCandidates:ReleaseCandidate[]=[ - {id:'sim-cr5',title:'[模拟] CR5用户手册.pdf',knowledge_base_id:'simulation-company-support',knowledge_base_name:'公司级技术支持知识库',visibility:'internal',parse_status:'completed',chunks:186,vectors:186,assets:8,wiki:'ready',graph:'ready'}, - {id:'sim-params',title:'[模拟] 产品参数总表.xlsx',knowledge_base_id:'simulation-company-support',knowledge_base_name:'公司级技术支持知识库',visibility:'external',parse_status:'completed',chunks:94,vectors:94,assets:2,wiki:'ready',graph:'shared'}, - {id:'sim-failed',title:'[模拟] CRA-IP68产品介绍.pdf',knowledge_base_id:'simulation-company-support',knowledge_base_name:'公司级技术支持知识库',visibility:'external',parse_status:'failed',chunks:0,vectors:0,assets:1,wiki:'missing',graph:'missing'}, +export interface ReleasePlan { + mode: 'none' | 'document' | 'knowledge_base' | 'blocked' + blocked: boolean + reason: string + knowledge_base_id?: string +} +export function evaluateReleaseSelection(items: ReleaseCandidate[]): ReleasePlan { + if (!items.length) return { mode: 'none', blocked: true, reason: '请先选择测试文档' } + if (items.some((item) => item.parse_status !== 'completed')) + return { mode: 'blocked', blocked: true, reason: '存在尚未完成解析的文档' } + if ( + items.some( + (item) => + item.chunks < 1 || + item.vectors !== item.chunks || + item.assets < 1 || + item.wiki === 'missing' || + item.graph === 'missing' + ) + ) + return { mode: 'blocked', blocked: true, reason: '切片、向量、文件、Wiki或图谱闭包不完整' } + const needsKB = items.some((item) => item.wiki === 'shared' || item.graph === 'shared') + if (needsKB) { + const ids = new Set(items.map((item) => item.knowledge_base_id)) + if (ids.size !== 1) return { mode: 'blocked', blocked: true, reason: '整知识库发布不能跨知识库合并' } + return { + mode: 'knowledge_base', + blocked: false, + reason: 'Wiki或图谱包含共享数据,必须按整个知识库同步', + knowledge_base_id: items[0].knowledge_base_id, + } + } + return { mode: 'document', blocked: false, reason: '所选文档的切片、向量、文件、Wiki和图谱闭包可以独立验证' } +} +export const simulatedReleaseCandidates: ReleaseCandidate[] = [ + { + id: 'sim-cr5', + title: '[模拟] CR5用户手册.pdf', + knowledge_base_id: 'simulation-company-support', + knowledge_base_name: '公司级技术支持知识库', + visibility: 'internal', + parse_status: 'completed', + chunks: 186, + vectors: 186, + assets: 8, + wiki: 'ready', + graph: 'ready', + }, + { + id: 'sim-params', + title: '[模拟] 产品参数总表.xlsx', + knowledge_base_id: 'simulation-company-support', + knowledge_base_name: '公司级技术支持知识库', + visibility: 'external', + parse_status: 'completed', + chunks: 94, + vectors: 94, + assets: 2, + wiki: 'ready', + graph: 'shared', + }, + { + id: 'sim-failed', + title: '[模拟] CRA-IP68产品介绍.pdf', + knowledge_base_id: 'simulation-company-support', + knowledge_base_name: '公司级技术支持知识库', + visibility: 'external', + parse_status: 'failed', + chunks: 0, + vectors: 0, + assets: 1, + wiki: 'missing', + graph: 'missing', + }, ] diff --git a/web/src/releaseTargets.css b/web/src/releaseTargets.css index 187e433..9efd50e 100644 --- a/web/src/releaseTargets.css +++ b/web/src/releaseTargets.css @@ -9,14 +9,10 @@ display: flex; flex-direction: column; gap: 16px; - padding: 24px 28px 40px; + padding: 22px 24px 40px; color: var(--rel-ink); min-width: 0; } -.release-targets h1 { - margin: 0 0 4px; - font-size: 28px; -} .release-targets h2 { margin: 0; font-size: 18px; @@ -672,3 +668,123 @@ .rel-wiki-pages li { font-variant-numeric: tabular-nums; } + +/* F04/F07/F08: 目标身份、历史筛选与分页、恢复验证报告。 */ +.rel-target-identity { + margin: 8px 0 0; + font-size: 12px; + color: var(--rel-muted); + word-break: break-all; +} +.rel-history-filters { + display: flex; + gap: 6px; + flex-wrap: wrap; + margin: 4px 0 8px; +} +.rel-history-filters button { + font-size: 12px; + padding: 4px 10px; +} +.rel-history-filters button.active { + color: #168b73; + background: #ebf8f3; + border-color: #a6d7c8; +} +.rel-history-pager { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin: 8px 0; + font-size: 12px; + color: var(--rel-muted); +} +.rel-report pre { + max-height: 260px; + overflow: auto; + white-space: pre-wrap; + word-break: break-word; + font-size: 11px; + background: #f7fafc; + border: 1px solid #e6edf2; + border-radius: 7px; + padding: 8px; +} + +/* 发布管理精简版:一个状态卡 + 一个主按钮,其余收进折叠区。 */ +.rel-status { + display: grid; + gap: 14px; + padding: 18px 20px; +} +.rel-status-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 14px; + margin: 0; +} +.rel-status-grid div { + border: 1px solid var(--border); + border-radius: 10px; + padding: 10px 12px; + background: var(--card); +} +.rel-status-grid dt { + font-size: 12px; + color: var(--muted-foreground); + margin-bottom: 4px; +} +.rel-status-grid dd { + margin: 0; + font-weight: 600; + font-size: 15px; + word-break: break-all; +} +.rel-status-grid small { + display: block; + margin-top: 4px; + color: var(--muted-foreground); + font-size: 12px; +} +.rel-status-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} +.rel-next { + flex: 1 1 320px; + margin: 0; + color: var(--muted-foreground); + font-size: 13px; +} +.rel-next span { + display: inline-block; + margin-right: 8px; + padding: 1px 8px; + border-radius: 999px; + background: var(--accent); + color: var(--foreground); + font-size: 12px; +} +.rel-check, +.rel-advanced { + border: 1px solid var(--border); + border-radius: 12px; + padding: 4px 16px 12px; + background: var(--card); +} +.rel-check summary, +.rel-advanced summary { + cursor: pointer; + padding: 10px 0; + font-weight: 600; +} +.rel-check .rel-gate, +.rel-check .rel-checklist { + margin: 6px 0 10px; +} +.rel-advanced > * + * { + margin-top: 10px; +} diff --git a/web/src/releaseTargetsMaintenance.test.tsx b/web/src/releaseTargetsMaintenance.test.tsx index 92ceafc..6bc608c 100644 --- a/web/src/releaseTargetsMaintenance.test.tsx +++ b/web/src/releaseTargetsMaintenance.test.tsx @@ -1,7 +1,8 @@ import { renderToStaticMarkup } from 'react-dom/server' -import { describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it } from 'vitest' import { MaintenanceCard, maintenanceSummary, wikiContributionLines } from './ReleaseTargets' +import { fetchLibraryJobDetail } from './librarySnapshots' import type { LibraryDiff, LibraryJobRecord, LibraryMaintenanceView } from './librarySnapshots' const job: LibraryJobRecord = { @@ -43,7 +44,7 @@ const heldInstance: LibraryMaintenanceView = { describe('维护级别/进度/恢复错误', () => { it('实例级持有:显示级别、入口状态、进度与恢复错误,并允许按预备份恢复', () => { - const summary = maintenanceSummary(heldInstance, job) + const summary = maintenanceSummary(heldInstance, { state: 'loaded', job }) expect(summary.level).toBe('实例级') expect(summary.held).toBe(true) expect(summary.ingress).toContain('已关闭') @@ -54,9 +55,21 @@ describe('维护级别/进度/恢复错误', () => { expect(summary.canRecover).toBe(true) const html = renderToStaticMarkup( - undefined} /> + undefined} + /> ) - for (const text of ['目标维护', '实例级', '入口 已关闭', '按预备份恢复', '写入生产 chunks 失败']) { + for (const text of [ + '目标维护', + '实例级', + '入口(维护记录,未实时探测)', + '已关闭', + '按预备份恢复', + '写入生产 chunks 失败', + ]) { expect(html).toContain(text) } }) @@ -67,12 +80,56 @@ describe('维护级别/进度/恢复错误', () => { expect(summary.held).toBe(false) expect(summary.canRecover).toBe(false) const html = renderToStaticMarkup( - undefined} /> + undefined} /> ) expect(html).toContain('暂无维护窗口') expect(html).not.toContain('按预备份恢复') }) + it('窗口已释放的失败作业不再说"目标保持维护、入口未开"', () => { + // 真实案例:libsync-internal-1793399248431728863 失败后窗口已 released、入口已开, + // 页面却照样渲染 held 诊断文案(只按 failed 渲染),与维护状态自相矛盾。 + const released: LibraryMaintenanceView = { + held: false, + instance_maintenance: { + ...heldInstance.instance_maintenance!, + released_at: '2026-11-01T03:40:00Z', + state: 'released', + ingress_state: 'open', + }, + } + const summary = maintenanceSummary(released, { state: 'loaded', job }) + expect(summary.held).toBe(false) + expect(summary.recoveryError).toBe('') + expect(summary.releasedFailure).toContain('写入生产 chunks 失败') + + const html = renderToStaticMarkup( + undefined} + /> + ) + expect(html).not.toContain('目标保持维护') + expect(html).not.toContain('收尾没有完成') + expect(html).toContain('窗口已释放') + expect(html).toContain('写入生产 chunks 失败') + }) + + it('仍在持有的失败作业保留 held 诊断文案', () => { + const html = renderToStaticMarkup( + undefined} + /> + ) + expect(html).toContain('目标保持维护') + expect(html).toContain('收尾没有完成') + }) + it('已释放的窗口不再提供恢复入口', () => { const released: LibraryMaintenanceView = { held: false, @@ -82,13 +139,242 @@ describe('维护级别/进度/恢复错误', () => { state: 'recovered', }, } - const summary = maintenanceSummary(released, job) + const summary = maintenanceSummary(released, { state: 'loaded', job }) expect(summary.held).toBe(false) expect(summary.canRecover).toBe(false) expect(summary.releasedAt).not.toBe('') }) }) +// ---- 维护窗口的作业归属(A 窗口 ≠ 该 scope 最新作业 B)---- +// +// 真实事故(2026-11-03 22:48 CST):对内维护窗口 owner_job_id=libverify-…A 仍是 +// needs_restore/ingress closed,但 scope 上最新作业是成功封存 B(libseal-…,completed/export)。 +// 页面把 B 的“导出 · 已完成”当成窗口进度,于是需要处理的窗口看起来已经完成。 +const ownerVerify: LibraryJobRecord = { + id: 'libverify-internal-A', + scope: 'internal', + kind: 'verify', + state: 'failed', + stage: 'verify', + request_digest: 'v', + queue_job_id: 'qv', + snapshot_id: '', + target_snapshot_id: '', + actor: 'admin', + error: '恢复验证失败:canary 校验不一致', + recovery: '预备份保留;按归档人工核验', + created_at: '2026-11-03T09:20:00Z', + updated_at: '2026-11-03T09:24:00Z', + finished_at: '2026-11-03T09:24:00Z', + stages: [], +} + +const latestSeal: LibraryJobRecord = { + ...ownerVerify, + id: 'libseal-lib-internal-B', + kind: 'seal', + state: 'succeeded', + stage: 'export', + error: '', + recovery: '', + finished_at: '2026-11-03T09:23:52Z', +} + +const unrelatedFailure: LibraryJobRecord = { + ...latestSeal, + id: 'libseal-lib-internal-C', + state: 'failed', + stage: 'index', + error: '封存索引导出失败:与维护窗口无关', + finished_at: '2026-11-03T09:25:00Z', +} + +const needsRestore: LibraryMaintenanceView = { + held: true, + instance: 'kgmaint-weknora', + instance_maintenance: { + instance: 'kgmaint-weknora', + owner_scope: 'internal', + scope: 'internal', + owner_job_id: 'libverify-internal-A', + level: 'instance', + services: ['app'], + ingress_state: 'closed', + state: 'needs_restore', + acquired_at: '2026-11-03T09:20:00Z', + updated_at: '2026-11-03T09:24:00Z', + released_at: null, + }, +} + +describe('维护窗口作业归属', () => { + it('持有作业 A 失败时显示 A 的进度/错误,不显示较新封存 B 的“导出 · 已完成”', () => { + const summary = maintenanceSummary(needsRestore, { state: 'loaded', job: ownerVerify }, 'internal') + expect(summary.progress).toContain('校验') + expect(summary.progress).toContain('失败') + expect(summary.progress).not.toContain('导出') + expect(summary.recoveryError).toContain('canary 校验不一致') + expect(summary.canRecover).toBe(true) + + const html = renderToStaticMarkup( + undefined} + /> + ) + expect(html).not.toContain('导出 · 已完成') + expect(html).toContain('canary 校验不一致') + expect(html).toContain('按预备份恢复') + // 入口只是维护记录里的字段,页面不得声称实时探测过服务。 + expect(html).toContain('维护记录,未实时探测') + }) + + it('调用方误把较新成功封存 B 传进来时,身份不匹配 ⇒ 明确“持有作业状态未读取”,不冒成功', () => { + const summary = maintenanceSummary(needsRestore, { state: 'loaded', job: latestSeal }, 'internal') + expect(summary.progress).not.toContain('导出') + expect(summary.progress).not.toContain('已完成') + expect(summary.progress).toContain('未读取') + expect(summary.recoveryError).toBe('') + const html = renderToStaticMarkup( + undefined} + /> + ) + expect(html).not.toContain('导出 · 已完成') + // 窗口本身仍是 needs_restore:需要处理的原窗口不能被隐藏。 + expect(html).toContain('needs_restore') + }) + + it('无关的最新失败作业不把错误串进本窗口', () => { + const summary = maintenanceSummary(needsRestore, { state: 'loaded', job: unrelatedFailure }, 'internal') + expect(summary.recoveryError).toBe('') + expect(summary.progress).not.toContain('封存索引导出失败') + }) + + it('持有作业仍在运行 ⇒ 同窗口不允许并发恢复', () => { + const running: LibraryJobRecord = { ...ownerVerify, state: 'running', stage: 'database', finished_at: null } + const summary = maintenanceSummary(needsRestore, { state: 'loaded', job: running }, 'internal') + expect(summary.progress).toContain('执行中') + expect(summary.canRecover).toBe(false) + const html = renderToStaticMarkup( + undefined} + /> + ) + expect(html).not.toContain('按预备份恢复') + }) + + it('窗口已释放的持有作业失败只留历史记录,不提供恢复', () => { + const released: LibraryMaintenanceView = { + held: false, + instance_maintenance: { + ...needsRestore.instance_maintenance!, + state: 'released', + ingress_state: 'open', + released_at: '2026-11-03T10:00:00Z', + }, + } + const summary = maintenanceSummary(released, { state: 'loaded', job: ownerVerify }, 'internal') + expect(summary.held).toBe(false) + expect(summary.canRecover).toBe(false) + expect(summary.releasedFailure).toContain('canary 校验不一致') + expect(summary.releasedAt).not.toBe('') + }) + + it('跨 scope 查看实例级窗口:不给本 scope 投递恢复', () => { + const summary = maintenanceSummary(needsRestore, { state: 'loaded', job: ownerVerify }, 'external') + expect(summary.canRecover).toBe(false) + expect(summary.scopeNote).toContain('internal') + expect(summary.scopeNote).toContain('external') + const html = renderToStaticMarkup( + undefined} + /> + ) + expect(html).not.toContain('按预备份恢复') + }) + + it('持有作业详情读取失败/不存在时明确未知,不退回最新作业也不编造成功', () => { + const failedRead = maintenanceSummary(needsRestore, { state: 'error', reason: 'HTTP 503' }, 'internal') + expect(failedRead.progress).toContain('读取失败') + expect(failedRead.progress).toContain('HTTP 503') + expect(failedRead.recoveryError).toBe('') + + const missing = maintenanceSummary(needsRestore, { state: 'missing' }, 'internal') + expect(missing.progress).toContain('不存在') + expect(missing.recoveryError).toBe('') + + const unread = maintenanceSummary(needsRestore, { state: 'unread' }, 'internal') + expect(unread.progress).toContain('未读取') + // needs_restore 是已确认的维护契约:作业详情读不到也保留恢复入口,由后端按窗口校验。 + expect(unread.canRecover).toBe(true) + }) +}) + +describe('fetchLibraryJobDetail(只读作业详情)', () => { + const originalFetch = globalThis.fetch + afterEach(() => { + globalThis.fetch = originalFetch + }) + + it('按 owner id 读取并校验结构', async () => { + let seen = '' + globalThis.fetch = (async (url: string) => { + seen = String(url) + return new Response(JSON.stringify({ available: true, job: ownerVerify }), { status: 200 }) + }) as unknown as typeof fetch + const value = await fetchLibraryJobDetail('libverify-internal-A') + expect(seen).toBe('/api/v1/library/jobs/libverify-internal-A') + expect(value.state).toBe('loaded') + expect(value.state === 'loaded' && value.job.id).toBe('libverify-internal-A') + }) + + it('id 里的特殊字符必须编码,且返回别的作业按读取失败处理', async () => { + let seen = '' + globalThis.fetch = (async (url: string) => { + seen = String(url) + return new Response(JSON.stringify({ available: true, job: ownerVerify }), { status: 200 }) + }) as unknown as typeof fetch + const value = await fetchLibraryJobDetail('libverify/internal A') + expect(seen).toBe('/api/v1/library/jobs/libverify%2Finternal%20A') + // 串包/晚回包:返回的不是请求的那个作业,不能拿去展示。 + expect(value.state).toBe('error') + }) + + it('404 是“作业不存在”,不是读取失败', async () => { + globalThis.fetch = (async () => + new Response(JSON.stringify({ available: false }), { status: 404 })) as unknown as typeof fetch + expect((await fetchLibraryJobDetail('x')).state).toBe('missing') + }) + + it('5xx 与结构不符是“读取失败”,不能吞成不存在', async () => { + globalThis.fetch = (async () => new Response('{}', { status: 503 })) as unknown as typeof fetch + const error = await fetchLibraryJobDetail('x') + expect(error.state).toBe('error') + expect(error.state === 'error' && error.reason).toContain('503') + + globalThis.fetch = (async () => + new Response(JSON.stringify({ available: true, job: { id: 'x' } }), { status: 200 })) as unknown as typeof fetch + expect((await fetchLibraryJobDetail('x')).state).toBe('error') + }) +}) + describe('Wiki 贡献级差异展示', () => { const diff: LibraryDiff = { state: 'computed', diff --git a/web/src/restoreVerification.test.ts b/web/src/restoreVerification.test.ts new file mode 100644 index 0000000..1995b87 --- /dev/null +++ b/web/src/restoreVerification.test.ts @@ -0,0 +1,119 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + fetchLibraryVerification, + parseVerificationRecord, + parseVerificationView, + verificationStatusText, + verificationTargetLines, +} from './restoreVerification' +import type { LibraryVerificationView } from './restoreVerification' + +const target = { + instance: 'weknora-test', + project: 'weknora', + internal_kb: 'a8e9c8ad-411c-4c53-8421-599d29e9b179', + external_kb: '2e980686-2233-4c4e-b5a6-8b0069477b8e', + index: 'weknora_test_chunks', + s3_bucket: 'dobot-weknora-test', + tenant_id: 10000, + database_configured: true, +} + +const passed = { + id: 'libverify-internal-job1', + scope: 'internal', + status: 'passed', + snapshot_id: '0f9b39a16738', + job_id: 'libverify-internal-1', + started_at: '2026-11-03T01:00:00Z', + finished_at: '2026-11-03T01:02:00Z', +} + +const response = (body: unknown, status = 200) => ({ + ok: status >= 200 && status < 300, + status, + json: async () => body, +}) + +afterEach(() => vi.unstubAllGlobals()) + +describe('fetchLibraryVerification 的失败与身份', () => { + it('HTTP 错误必须抛错,不能把响应当证据', async () => { + vi.stubGlobal('fetch', async () => response({ scope: 'internal', reason: '存储不可用' }, 503)) + await expect(fetchLibraryVerification('internal')).rejects.toThrow('存储不可用') + }) + + it('响应 scope 与请求不一致时拒绝', async () => { + vi.stubGlobal('fetch', async () => response({ scope: 'external', verified: true, target, history: [] })) + await expect(fetchLibraryVerification('internal')).rejects.toThrow('不一致') + }) + + it('不可解析的响应按失败处理', async () => { + vi.stubGlobal('fetch', async () => response({ nope: true })) + await expect(fetchLibraryVerification('internal')).rejects.toThrow('不可解析') + }) +}) + +describe('restoreVerification parsing', () => { + it('只把后端明确 true 当作已验证', () => { + const view = parseVerificationView({ scope: 'internal', target, verified: 'true', reason: '', history: [] }) + expect(view?.verified).toBe(false) + }) + + it('保留失败证据的失败原因', () => { + const record = parseVerificationRecord({ ...passed, status: 'failed', failure: '恢复后内容仍与预备份不一致' }) + expect(record?.status).toBe('failed') + expect(record?.failure).toBe('恢复后内容仍与预备份不一致') + }) + + it('未知状态一律丢弃,不猜成通过', () => { + expect(parseVerificationRecord({ ...passed, status: 'running' })).toBeNull() + }) + + it('没有目标信息的响应视为无效', () => { + expect(parseVerificationView({ scope: 'internal', verified: true })).toBeNull() + }) +}) + +describe('restoreVerification display', () => { + const base: LibraryVerificationView = { + scope: 'internal', + target, + verified: true, + reason: '', + latest: { + id: passed.id, + scope: 'internal', + status: 'passed', + snapshot_id: passed.snapshot_id, + job_id: passed.job_id, + started_at: passed.started_at, + finished_at: passed.finished_at, + }, + history: [], + } + + it('整库目标显示完整 KB ID 与索引/桶,不缩写成"2074 文档库"', () => { + const lines = verificationTargetLines(target, 'internal') + expect(lines.join(' | ')).toContain('a8e9c8ad-411c-4c53-8421-599d29e9b179') + expect(lines.join(' | ')).toContain('weknora_test_chunks') + expect(lines.join(' | ')).toContain('dobot-weknora-test') + }) + + it('对外 scope 显示对外目标', () => { + expect(verificationTargetLines(target, 'external').join(' | ')).toContain('2e980686-2233-4c4e-b5a6-8b0069477b8e') + }) + + it('状态文案区分已验证 / 最近失败 / 无记录', () => { + expect(verificationStatusText(base)).toBe('已验证(当前目标)') + expect( + verificationStatusText({ + ...base, + verified: false, + latest: { ...base.latest!, status: 'failed' }, + }) + ).toBe('最近一次未通过') + expect(verificationStatusText({ ...base, verified: false, latest: null })).toBe('还没有验证记录') + }) +}) diff --git a/web/src/restoreVerification.ts b/web/src/restoreVerification.ts new file mode 100644 index 0000000..3e79e7b --- /dev/null +++ b/web/src/restoreVerification.ts @@ -0,0 +1,212 @@ +// 恢复验证的页面数据层:读证据 + 投递真实演练。 +// +// 关键约定:verified 只由后端证据回答(当前目标 + scope 的最近一次真实演练)。 +// 页面不提供任何"我确认已验证"的开关——那正是旧实现的问题(一个可手填的 env)。 +export type LibraryVerificationStatus = 'passed' | 'failed' + +export interface LibraryVerificationRecord { + id: string + scope: string + status: LibraryVerificationStatus + snapshot_id: string + job_id: string + failure?: string + report?: Record + started_at: string + finished_at: string +} + +export interface LibraryVerificationTarget { + instance: string + project: string + internal_kb: string + external_kb: string + index: string + s3_bucket: string + tenant_id: number + database_configured: boolean +} + +export interface LibraryVerificationView { + scope: string + target: LibraryVerificationTarget + verified: boolean + reason: string + latest?: LibraryVerificationRecord | null + snapshot_latest?: LibraryVerificationRecord | null + history: LibraryVerificationRecord[] + running?: boolean + job_id?: string + state?: string + stage?: string +} + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function text(value: unknown): string { + return typeof value === 'string' ? value : '' +} + +function bool(value: unknown): boolean { + return value === true +} + +export function parseVerificationTarget(value: unknown): LibraryVerificationTarget | null { + if (!record(value)) return null + return { + instance: text(value.instance), + project: text(value.project), + internal_kb: text(value.internal_kb), + external_kb: text(value.external_kb), + index: text(value.index), + s3_bucket: text(value.s3_bucket), + tenant_id: typeof value.tenant_id === 'number' ? value.tenant_id : 0, + database_configured: bool(value.database_configured), + } +} + +export function parseVerificationRecord(value: unknown): LibraryVerificationRecord | null { + if (!record(value)) return null + const status = text(value.status) + if (status !== 'passed' && status !== 'failed') return null + return { + id: text(value.id), + scope: text(value.scope), + status, + snapshot_id: text(value.snapshot_id), + job_id: text(value.job_id), + failure: text(value.failure) || undefined, + report: record(value.report) ? value.report : undefined, + started_at: text(value.started_at), + finished_at: text(value.finished_at), + } +} + +export function parseVerificationView(value: unknown): LibraryVerificationView | null { + if (!record(value)) return null + const target = parseVerificationTarget(value.target) + if (!target) return null + const history = Array.isArray(value.history) + ? value.history.map(parseVerificationRecord).filter((item): item is LibraryVerificationRecord => item !== null) + : [] + const latest = parseVerificationRecord(value.latest) ?? null + const snapshotLatest = parseVerificationRecord(value.snapshot_latest) ?? null + return { + scope: text(value.scope), + target, + // 只有后端明确说 true 才算已验证:任何解析失败都退回"没有证据"。 + verified: bool(value.verified), + reason: text(value.reason), + latest, + snapshot_latest: snapshotLatest, + history, + running: bool(value.running), + job_id: text(value.job_id) || undefined, + state: text(value.state) || undefined, + stage: text(value.stage) || undefined, + } +} + +// fetchLibraryVerification 只返回**这份 scope** 的观测: +// HTTP 非 2xx、响应不可解析、或响应 scope 与请求不一致都抛错。 +// 调用方据此把"读失败"和"没有证据"分开显示,不能拿旧绿色遮住失败(审核 B5)。 + +// F03: exact snapshot report. Never fall back to the scope's latest record. +export async function fetchSnapshotVerification( + scope: string, + snapshotID: string, + signal?: AbortSignal +): Promise { + const query = `scope=${encodeURIComponent(scope)}&snapshot_id=${encodeURIComponent(snapshotID)}` + const response = await fetch(`/api/v1/library/verifications?${query}`, { + headers: { Accept: 'application/json' }, + signal, + }) + const value = (await response.json().catch(() => null)) as unknown + if (!response.ok) throw new Error(`读取该快照的恢复验证记录失败(HTTP ${response.status})`) + const parsed = parseVerificationView(value) + if (!parsed) throw new Error('读取该快照的恢复验证记录失败:响应不可解析') + if (parsed.scope !== scope) throw new Error('读取该快照的恢复验证记录失败:scope 不一致') + return parsed +} + +export async function fetchLibraryVerification(scope: string, signal?: AbortSignal): Promise { + const response = await fetch(`/api/v1/library/verifications?scope=${encodeURIComponent(scope)}`, { + headers: { Accept: 'application/json' }, + signal, + }) + const value = (await response.json().catch(() => null)) as unknown + if (!response.ok) { + if (record(value) && text(value.reason)) throw new Error(`读取验证状态失败:${text(value.reason)}`) + throw new Error(`读取验证状态失败(HTTP ${response.status})`) + } + const parsed = parseVerificationView(value) + if (!parsed) throw new Error('读取验证状态失败:响应不可解析') + if (parsed.scope !== scope) + throw new Error(`读取验证状态失败:响应 scope=${parsed.scope || '空'} 与请求 ${scope} 不一致`) + return parsed +} + +export interface LibraryVerificationAccepted { + job_id: string + scope: string +} + +// 投递一次真实恢复验证。失败时把后端的逐条拒绝原因原样显示, +// 不把它包装成"稍后再试"——否则用户不知道是闸口、维护还是目标不可达。 +export async function enqueueLibraryVerification(scope: string): Promise { + const response = await fetch('/api/v1/library/verifications', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ scope }), + }) + const value = (await response.json().catch(() => null)) as unknown + if (!response.ok) { + if (response.status === 403) throw new Error('恢复验证仅管理员可发起。') + if (record(value) && Array.isArray(value.reasons)) { + const reasons = value.reasons.map(text).filter(Boolean) + if (reasons.length > 0) throw new Error(`恢复验证被拒绝:${reasons.join(';')}`) + } + if (record(value) && text(value.error)) throw new Error(text(value.error)) + throw new Error(`投递恢复验证失败(HTTP ${response.status})`) + } + if (!record(value) || !record(value.job)) throw new Error('恢复验证作业响应无效') + return { job_id: text(value.job.id), scope: text(value.job.scope) } +} + +// 目标展示:整库目标必须显示完整 ID 与端点,避免"看着像 2074 文档库"这类误读。 +export function verificationTargetLines(target: LibraryVerificationTarget, scope: string): string[] { + const kb = scope === 'internal' ? target.internal_kb : target.external_kb + return [ + `实例 ${target.instance || '未配置'} · 项目 ${target.project || '未配置'}`, + `知识库 ${kb || '未配置'}`, + `索引 ${target.index || '未配置'} · 桶 ${target.s3_bucket || '未配置'}`, + `租户 ${target.tenant_id || '未配置'} · 数据库${target.database_configured ? '已配置' : '未配置'}`, + ] +} + +// verificationStatusText 只在**当前 scope 的新鲜观测**上允许说"已验证"。 +// stale 表示这次刷新失败、显示的是上一次结果:它既不是当前结论,也不能是绿灯。 +export function verificationStatusText(view: LibraryVerificationView | null, stale = false): string { + if (!view) return '还没有读到验证状态' + if (stale) return '上次观测已过期(刷新失败)' + if (view.running) return '验证执行中' + if (view.verified) return '已验证(当前目标)' + if (view.latest) return view.latest.status === 'failed' ? '最近一次未通过' : '未通过' + return '还没有验证记录' +} + +// F03: when the API has a passed record, its reason is empty by design. The +// panel must not fall back to "还没有读到验证状态" and contradict the green +// status. This also keeps loading/error/never-verified distinct. +export function verificationReasonText(view: LibraryVerificationView | null, stale = false): string { + if (!view) return '还没有读到验证状态' + if (stale) return '刷新失败:这是上次成功读取的证据,当前目标是否仍可恢复未知' + if (view.running) return view.reason || `验证作业 ${view.job_id || ''} 正在执行(${view.stage || '执行中'})` + if (view.verified) + return `当前目标的最近一次真实恢复验证已通过${view.latest ? `(快照 ${view.latest.snapshot_id.slice(0, 12)})` : ''}` + if (view.latest) return view.reason || view.latest.failure || '最近一次恢复验证未通过' + return view.reason || '还没有验证记录' +} diff --git a/web/src/reviewRelease.test.ts b/web/src/reviewRelease.test.ts index 3ad851b..1114c7d 100644 --- a/web/src/reviewRelease.test.ts +++ b/web/src/reviewRelease.test.ts @@ -30,58 +30,168 @@ import { afterEach(() => vi.unstubAllGlobals()) const candidate = { - publication_id: 'tp-safe', title: 'Synthetic', source_type: 'manual', current_visibility: 'internal', - knowledge_exists: 'passed', chunks_present: 'passed', retrieval_hit: 'manual_required', - gate_status: 'ready', gate_code: 'ready', review_state: 'pending', decided_visibility: '', - decision_code: '', reviewer_ref: '', reviewed_at: null, updated_at: '2026-09-06T10:00:00Z', - acceptance_run_id: 'must-drop', knowledge_id: 'must-drop', + publication_id: 'tp-safe', + title: 'Synthetic', + source_type: 'manual', + current_visibility: 'internal', + knowledge_exists: 'passed', + chunks_present: 'passed', + retrieval_hit: 'manual_required', + gate_status: 'ready', + gate_code: 'ready', + review_state: 'pending', + decided_visibility: '', + decision_code: '', + reviewer_ref: '', + reviewed_at: null, + updated_at: '2026-09-06T10:00:00Z', + acceptance_run_id: 'must-drop', + knowledge_id: 'must-drop', } const batch = { - id: 'rb-safe', name: 'Batch', state: 'draft', policy_version: 'release-gate-v1', - created_by: 'engineer-1', sealed_by: '', item_count: 1, - created_at: '2026-09-06T10:00:00Z', sealed_at: null, acceptance_run_id: 'must-drop', + id: 'rb-safe', + name: 'Batch', + state: 'draft', + policy_version: 'release-gate-v1', + created_by: 'engineer-1', + sealed_by: '', + item_count: 1, + created_at: '2026-09-06T10:00:00Z', + sealed_at: null, + acceptance_run_id: 'must-drop', } describe('review and batch response parsing', () => { it('strictly rebuilds the source-truth release plan', () => { - const plan = parseReleasePlanResponse({ data: { items: [{ publication_id: 'tp-safe', title: 'B.pdf', target_scope: 'external', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '', production_revision: 'must-drop' }], summary: { add: 1, update: 0, delete: 0, blocked: 0, unchanged: 10 } } }) + const plan = parseReleasePlanResponse({ + data: { + items: [ + { + publication_id: 'tp-safe', + title: 'B.pdf', + target_scope: 'external', + action: 'add', + test_state: 'ready', + production_state: 'absent', + can_release: true, + blocker: '', + production_revision: 'must-drop', + }, + ], + summary: { add: 1, update: 0, delete: 0, blocked: 0, unchanged: 10 }, + }, + }) expect(plan.summary).toEqual({ add: 1, update: 0, delete: 0, blocked: 0, unchanged: 10 }) - expect(plan.items[0]).toEqual({ publication_id: 'tp-safe', title: 'B.pdf', target_scope: 'external', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '' }) + expect(plan.items[0]).toEqual({ + publication_id: 'tp-safe', + title: 'B.pdf', + target_scope: 'external', + action: 'add', + test_state: 'ready', + production_state: 'absent', + can_release: true, + blocker: '', + }) expect(plan.items[0]).not.toHaveProperty('production_revision') }) it('strictly rebuilds safe review candidates', () => { const page = parseReviewCandidatesResponse({ data: [candidate], total: 1, limit: 20, offset: 0 }) - expect(page).toEqual({ items: [{ - publication_id: 'tp-safe', title: 'Synthetic', source_type: 'manual', current_visibility: 'internal', - knowledge_exists: 'passed', chunks_present: 'passed', retrieval_hit: 'manual_required', - gate_status: 'ready', gate_code: 'ready', review_state: 'pending', decided_visibility: '', - decision_code: '', reviewer_ref: '', reviewed_at: null, updated_at: '2026-09-06T10:00:00Z', - }], total: 1, limit: 20, offset: 0 }) + expect(page).toEqual({ + items: [ + { + publication_id: 'tp-safe', + title: 'Synthetic', + source_type: 'manual', + current_visibility: 'internal', + knowledge_exists: 'passed', + chunks_present: 'passed', + retrieval_hit: 'manual_required', + gate_status: 'ready', + gate_code: 'ready', + review_state: 'pending', + decided_visibility: '', + decision_code: '', + reviewer_ref: '', + reviewed_at: null, + updated_at: '2026-09-06T10:00:00Z', + }, + ], + total: 1, + limit: 20, + offset: 0, + }) expect(page.items[0]).not.toHaveProperty('acceptance_run_id') expect(page.items[0]).not.toHaveProperty('knowledge_id') }) it('strictly rebuilds safe batch list and detail', () => { expect(parseReleaseBatchesResponse({ data: [batch], total: 1, limit: 20, offset: 0 }).items[0]).toEqual({ - id: 'rb-safe', name: 'Batch', state: 'draft', policy_version: 'release-gate-v1', created_by: 'engineer-1', - sealed_by: '', item_count: 1, created_at: '2026-09-06T10:00:00Z', sealed_at: null, + id: 'rb-safe', + name: 'Batch', + state: 'draft', + policy_version: 'release-gate-v1', + created_by: 'engineer-1', + sealed_by: '', + item_count: 1, + created_at: '2026-09-06T10:00:00Z', + sealed_at: null, }) - expect(parseReleaseBatchDetailResponse({ data: { ...batch, items: [{ publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete', publication_updated_at: 'must-drop' }] } }).items).toEqual([ - { publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete' }, - ]) + expect( + parseReleaseBatchDetailResponse({ + data: { + ...batch, + items: [ + { + publication_id: 'tp-safe', + title: 'Synthetic', + decided_visibility: 'internal', + action: 'delete', + publication_updated_at: 'must-drop', + }, + ], + }, + }).items + ).toEqual([{ publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete' }]) }) }) describe('review and batch requests', () => { it('uses fixed scoped endpoints and explicit JSON fields', async () => { - const fetchMock = vi.fn() - .mockResolvedValueOnce(new Response(JSON.stringify({ data: [candidate], total: 1, limit: 20, offset: 0 }), { status: 200 })) - .mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'rv-safe', publication_id: 'tp-safe', decision: 'approved', decided_visibility: 'internal', reviewer_ref: 'engineer-1', decision_code: 'approved_for_release', created_at: '2026-09-06T10:01:00Z' } }), { status: 201 })) + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + new Response(JSON.stringify({ data: [candidate], total: 1, limit: 20, offset: 0 }), { status: 200 }) + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + data: { + id: 'rv-safe', + publication_id: 'tp-safe', + decision: 'approved', + decided_visibility: 'internal', + reviewer_ref: 'engineer-1', + decision_code: 'approved_for_release', + created_at: '2026-09-06T10:01:00Z', + }, + }), + { status: 201 } + ) + ) .mockResolvedValueOnce(new Response(JSON.stringify({ data: batch }), { status: 201 })) - .mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...batch, state: 'sealed', sealed_by: 'engineer-2', sealed_at: '2026-09-06T10:02:00Z' } }), { status: 200 })) - .mockResolvedValueOnce(new Response(JSON.stringify({ data: [batch], total: 1, limit: 20, offset: 0 }), { status: 200 })) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + data: { ...batch, state: 'sealed', sealed_by: 'engineer-2', sealed_at: '2026-09-06T10:02:00Z' }, + }), + { status: 200 } + ) + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ data: [batch], total: 1, limit: 20, offset: 0 }), { status: 200 }) + ) vi.stubGlobal('fetch', fetchMock) await fetchReviewCandidates('pending') @@ -94,9 +204,19 @@ describe('review and batch requests', () => { expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/review-candidates/tp-safe/decision') // actor fields are server-stamped from the session; bodies must not carry them // P0: the browser must never name the actor again; the server stamps it. - expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ decision: 'approved', decided_visibility: 'internal', decision_code: 'approved_for_release' }) + expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ + decision: 'approved', + decided_visibility: 'internal', + decision_code: 'approved_for_release', + }) expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/release-batches') - expect(JSON.parse((fetchMock.mock.calls[2][1] as RequestInit).body as string)).toEqual({ name: 'Batch', publication_ids: ['tp-safe'], delete_publication_ids: ['tp-delete'], release_change_set_id: '', seal: false }) + expect(JSON.parse((fetchMock.mock.calls[2][1] as RequestInit).body as string)).toEqual({ + name: 'Batch', + publication_ids: ['tp-safe'], + delete_publication_ids: ['tp-delete'], + release_change_set_id: '', + seal: false, + }) expect(fetchMock.mock.calls[3][0]).toBe('/api/v1/release-batches/rb-safe/seal') expect(fetchMock.mock.calls[4][0]).toBe('/api/v1/release-batches?state=draft&limit=20&offset=0') }) @@ -104,11 +224,27 @@ describe('review and batch requests', () => { describe('release execution audit parsing', () => { const execution = { - id: 'rx-safe', release_batch_id: 'rb-safe', operation: 'publish', prior_execution_id: '', state: 'completed', - target_environment: 'production', authorized_by: 'owner', job_id: 'job-safe', item_count: 105, batch_size: 50, current_batch: 2, total_batches: 3, - completed_item_count: 1, failed_item_count: 0, error_code: '', created_at: '2026-09-06T10:00:00Z', - started_at: '2026-09-06T10:01:00Z', completed_at: '2026-09-06T10:02:00Z', - authorization_code: 'must-drop', manifest_sha256: 'must-drop', knowledge_id: 'must-drop', + id: 'rx-safe', + release_batch_id: 'rb-safe', + operation: 'publish', + prior_execution_id: '', + state: 'completed', + target_environment: 'production', + authorized_by: 'owner', + job_id: 'job-safe', + item_count: 105, + batch_size: 50, + current_batch: 2, + total_batches: 3, + completed_item_count: 1, + failed_item_count: 0, + error_code: '', + created_at: '2026-09-06T10:00:00Z', + started_at: '2026-09-06T10:01:00Z', + completed_at: '2026-09-06T10:02:00Z', + authorization_code: 'must-drop', + manifest_sha256: 'must-drop', + knowledge_id: 'must-drop', } it('strictly rebuilds execution and capability responses', () => { @@ -116,22 +252,81 @@ describe('release execution audit parsing', () => { expect(page.items[0]).toMatchObject({ batch_size: 50, current_batch: 2, total_batches: 3 }) expect(page.items[0]).not.toHaveProperty('authorization_code') expect(page.items[0]).not.toHaveProperty('manifest_sha256') - const detail = parseReleaseExecutionDetailResponse({ data: { ...execution, items: [{ publication_id: 'tp-safe', title: 'Synthetic', action: 'delete', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: '2026-09-06T10:00:00Z', completed_at: '2026-09-06T10:02:00Z', target_knowledge_base_id: 'kb-target-1', knowledge_id: 'must-drop' }] } }) - expect(detail.items[0]).toEqual({ publication_id: 'tp-safe', title: 'Synthetic', action: 'delete', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: '2026-09-06T10:00:00Z', completed_at: '2026-09-06T10:02:00Z', target_knowledge_base_id: 'kb-target-1' }) - expect(parseReleaseCapabilitiesResponse({ data: { production_release_requests_enabled: true, production_backup_restore_verified: false, secret: 'drop' } })).toEqual({ production_release_requests_enabled: true, production_backup_restore_verified: false, test_auto_review_policy: '' }) + const detail = parseReleaseExecutionDetailResponse({ + data: { + ...execution, + items: [ + { + publication_id: 'tp-safe', + title: 'Synthetic', + action: 'delete', + state: 'verified', + previous_production_revision: 'prod-v0', + production_revision: 'absent', + error_code: '', + created_at: '2026-09-06T10:00:00Z', + completed_at: '2026-09-06T10:02:00Z', + target_knowledge_base_id: 'kb-target-1', + knowledge_id: 'must-drop', + }, + ], + }, + }) + expect(detail.items[0]).toEqual({ + publication_id: 'tp-safe', + title: 'Synthetic', + action: 'delete', + state: 'verified', + previous_production_revision: 'prod-v0', + production_revision: 'absent', + error_code: '', + created_at: '2026-09-06T10:00:00Z', + completed_at: '2026-09-06T10:02:00Z', + target_knowledge_base_id: 'kb-target-1', + }) + expect( + parseReleaseCapabilitiesResponse({ + data: { production_release_requests_enabled: true, production_backup_restore_verified: false, secret: 'drop' }, + }) + ).toEqual({ + production_release_requests_enabled: true, + production_backup_restore_verified: false, + test_auto_review_policy: '', + }) }) it('rejects a release item execution the API forgot to describe', () => { // 线上 DTO 曾漏 action:一条明细不合法就让整个明细区报 invalid release item execution。 - const missingAction = { publication_id: 'tp-safe', title: 'Synthetic', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: '2026-09-06T10:00:00Z', completed_at: null } - expect(() => parseReleaseExecutionDetailResponse({ data: { ...execution, items: [missingAction] } })).toThrow('invalid release item execution') + const missingAction = { + publication_id: 'tp-safe', + title: 'Synthetic', + state: 'verified', + previous_production_revision: 'prod-v0', + production_revision: 'absent', + error_code: '', + created_at: '2026-09-06T10:00:00Z', + completed_at: null, + } + expect(() => parseReleaseExecutionDetailResponse({ data: { ...execution, items: [missingAction] } })).toThrow( + 'invalid release item execution' + ) }) it('fetches only read-only execution audit endpoints', async () => { - const fetchMock = vi.fn() - .mockResolvedValueOnce(new Response(JSON.stringify({ data: [execution], total: 1, limit: 20, offset: 0 }), { status: 200 })) + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + new Response(JSON.stringify({ data: [execution], total: 1, limit: 20, offset: 0 }), { status: 200 }) + ) .mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...execution, items: [] } }), { status: 200 })) - .mockResolvedValueOnce(new Response(JSON.stringify({ data: { production_release_requests_enabled: false, production_backup_restore_verified: false } }), { status: 200 })) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + data: { production_release_requests_enabled: false, production_backup_restore_verified: false }, + }), + { status: 200 } + ) + ) vi.stubGlobal('fetch', fetchMock) await fetchReleaseExecutions('publish', 'completed') await fetchReleaseExecution('rx-safe') @@ -145,30 +340,80 @@ describe('release execution audit parsing', () => { }) it('fetches the source-truth release plan from its fixed endpoint', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { items: [], summary: { add: 0, update: 0, delete: 0, blocked: 0, unchanged: 0 } } }), { status: 200 })) + const fetchMock = vi + .fn() + .mockResolvedValue( + new Response( + JSON.stringify({ data: { items: [], summary: { add: 0, update: 0, delete: 0, blocked: 0, unchanged: 0 } } }), + { status: 200 } + ) + ) vi.stubGlobal('fetch', fetchMock) await fetchReleasePlan() - expect(fetchMock).toHaveBeenCalledWith('/api/v1/release-plan', expect.objectContaining({ headers: { Accept: 'application/json' } })) + expect(fetchMock).toHaveBeenCalledWith( + '/api/v1/release-plan', + expect.objectContaining({ headers: { Accept: 'application/json' } }) + ) }) }) describe('release change set (R1)', () => { - const changeSetPayload = { id: 'rcs-1', number: 1, name: '9月发布', state: 'planned', source_snapshot_ids: ['snap-a'], source_change_set_ids: [], acceptance_cutoff: '2026-09-11T21:00:00Z', production_baseline_ref: '', item_count: 1, add_count: 1, update_count: 0, delete_count: 0, blocked_count: 0, manifest_sha256: 'a'.repeat(64), created_by: 'engineer-1', created_at: '2026-09-12T07:00:00Z', confirmed_by: '', confirmed_at: null } + const changeSetPayload = { + id: 'rcs-1', + number: 1, + name: '9月发布', + state: 'planned', + source_snapshot_ids: ['snap-a'], + source_change_set_ids: [], + acceptance_cutoff: '2026-09-11T21:00:00Z', + production_baseline_ref: '', + item_count: 1, + add_count: 1, + update_count: 0, + delete_count: 0, + blocked_count: 0, + manifest_sha256: 'a'.repeat(64), + created_by: 'engineer-1', + created_at: '2026-09-12T07:00:00Z', + confirmed_by: '', + confirmed_at: null, + } it('generates with idempotency and rejects a manifest-less envelope', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: changeSetPayload, operation: 'created' }), { status: 201 })) + const fetchMock = vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify({ data: changeSetPayload, operation: 'created' }), { status: 201 }) + ) vi.stubGlobal('fetch', fetchMock) const set = await generateReleaseChangeSet('9月发布') expect(set.id).toBe('rcs-1') expect(set.manifest_sha256).toBe('a'.repeat(64)) const [, init] = fetchMock.mock.calls[0] as [string, RequestInit] expect(init.headers).toMatchObject({ 'Idempotency-Key': expect.any(String) }) - expect((init.body as string)).toContain('"name":"9月发布"') - const bad = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...changeSetPayload, manifest_sha256: '' } }), { status: 201 })) + expect(init.body as string).toContain('"name":"9月发布"') + const bad = vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify({ data: { ...changeSetPayload, manifest_sha256: '' } }), { status: 201 }) + ) vi.stubGlobal('fetch', bad) await expect(generateReleaseChangeSet('x')).rejects.toThrow('发布计划集响应缺少标识或清单摘要') }) it('confirms via scoped endpoint and loads latest detail tolerating 404', async () => { - const confirmMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...changeSetPayload, state: 'confirmed', confirmed_by: 'boss', confirmed_at: '2026-09-12T08:00:00Z' }, operation: 'created' }), { status: 200 })) + const confirmMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + ...changeSetPayload, + state: 'confirmed', + confirmed_by: 'boss', + confirmed_at: '2026-09-12T08:00:00Z', + }, + operation: 'created', + }), + { status: 200 } + ) + ) vi.stubGlobal('fetch', confirmMock) const confirmed = await confirmReleaseChangeSet('rcs-1') expect(confirmed.state).toBe('confirmed') @@ -176,7 +421,40 @@ describe('release change set (R1)', () => { const latest404 = vi.fn().mockResolvedValue(new Response('{}', { status: 404 })) vi.stubGlobal('fetch', latest404) expect(await fetchLatestReleaseChangeSet()).toBeNull() - const detailMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...changeSetPayload, items: [{ seq: 1, publication_id: 'tp-keep', title: '手册', target_scope: 'internal', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '' }, { seq: 2, publication_id: 'x', title: '', target_scope: 'bogus', action: 'nope', test_state: '', production_state: '', can_release: false, blocker: '' }] } }), { status: 200 })) + const detailMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + ...changeSetPayload, + items: [ + { + seq: 1, + publication_id: 'tp-keep', + title: '手册', + target_scope: 'internal', + action: 'add', + test_state: 'ready', + production_state: 'absent', + can_release: true, + blocker: '', + }, + { + seq: 2, + publication_id: 'x', + title: '', + target_scope: 'bogus', + action: 'nope', + test_state: '', + production_state: '', + can_release: false, + blocker: '', + }, + ], + }, + }), + { status: 200 } + ) + ) vi.stubGlobal('fetch', detailMock) const detail = await fetchLatestReleaseChangeSet() expect(detail?.items.length).toBe(1) @@ -185,7 +463,46 @@ describe('release change set (R1)', () => { }) describe('release audit chain (R6)', () => { - const chain = { execution_id:'rx-1', operation:'publish', state:'completed', failure_level:'', release_batch_id:'rb-1', release_batch_name:'9月批次', created_by:'e1', sealed_by:'e2', authorized_by:'own', release_change_set_id:'rcs-1', release_change_set_name:'9月发布', release_change_set_state:'confirmed', release_change_set_created_by:'e1', release_change_set_confirmed_by:'boss', release_change_set_confirmed_at:'2026-09-12T08:00:00Z', manifest_sha256:'a'.repeat(64), snapshots:[{id:'snap-1',source_name:'PP',node_count:66,file_count:621,observed_at:'2026-09-11T00:00:00Z'}], catalog_change_sets:[{id:'cs-1',state:'applied',add_count:2,update_count:1,move_count:0,delete_count:0}], prior_execution_id:'', rollback_execution_id:'', items:[{publication_id:'tp-1',title:'手册.pdf',action:'upsert',item_state:'verified',review_id:'rev-1',acceptance_run_id:'run-1',source_item_id:'si-1',source_item_version_id:'siv-1',production_revision:'v1',error_code:''}] } + const chain = { + execution_id: 'rx-1', + operation: 'publish', + state: 'completed', + failure_level: '', + release_batch_id: 'rb-1', + release_batch_name: '9月批次', + created_by: 'e1', + sealed_by: 'e2', + authorized_by: 'own', + release_change_set_id: 'rcs-1', + release_change_set_name: '9月发布', + release_change_set_state: 'confirmed', + release_change_set_created_by: 'e1', + release_change_set_confirmed_by: 'boss', + release_change_set_confirmed_at: '2026-09-12T08:00:00Z', + manifest_sha256: 'a'.repeat(64), + snapshots: [ + { id: 'snap-1', source_name: 'PP', node_count: 66, file_count: 621, observed_at: '2026-09-11T00:00:00Z' }, + ], + catalog_change_sets: [ + { id: 'cs-1', state: 'applied', add_count: 2, update_count: 1, move_count: 0, delete_count: 0 }, + ], + prior_execution_id: '', + rollback_execution_id: '', + items: [ + { + publication_id: 'tp-1', + title: '手册.pdf', + action: 'upsert', + item_state: 'verified', + review_id: 'rev-1', + acceptance_run_id: 'run-1', + source_item_id: 'si-1', + source_item_version_id: 'siv-1', + production_revision: 'v1', + error_code: '', + }, + ], + } it('loads the chain and returns null on 404', async () => { const ok = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: chain }), { status: 200 })) vi.stubGlobal('fetch', ok) @@ -206,9 +523,23 @@ describe('release audit chain (R6)', () => { // 生产动作:三条路径 + 服务端原因回传(页面通道 = 管理员会话 + 固定确认语句)。 describe('production actions', () => { it('routes each action to its endpoint with the fixed phrase and an idempotency key', async () => { - const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(JSON.stringify({ data: { id: 'rx-1', state: 'pending', operation: 'publish', item_count: 1 } }), { status: 202 }))) + const fetchMock = vi + .fn() + .mockImplementation(() => + Promise.resolve( + new Response( + JSON.stringify({ data: { id: 'rx-1', state: 'pending', operation: 'publish', item_count: 1 } }), + { status: 202 } + ) + ) + ) vi.stubGlobal('fetch', fetchMock) - await expect(runProductionAction('authorize', 'rb-1', 'publish-to-production')).resolves.toEqual({ id: 'rx-1', state: 'pending', operation: 'publish', item_count: 1 }) + await expect(runProductionAction('authorize', 'rb-1', 'publish-to-production')).resolves.toEqual({ + id: 'rx-1', + state: 'pending', + operation: 'publish', + item_count: 1, + }) await runProductionAction('retry', 'rx-1', 'retry-production-release') await runProductionAction('rollback', 'rx-1', 'rollback-production-release') const urls = fetchMock.mock.calls.map((call) => call[0]) @@ -221,9 +552,23 @@ describe('production actions', () => { vi.unstubAllGlobals() }) it('surfaces the server reason and keeps the phrases fixed', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'production release authorization required' }), { status: 401 }))) - await expect(runProductionAction('authorize', 'rb-1', 'publish-to-production')).rejects.toThrow('production release authorization required') - expect(productionConfirmationPhrases).toEqual({ authorize: 'publish-to-production', retry: 'retry-production-release', rollback: 'rollback-production-release', publish_now: 'publish-to-production' }) + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify({ error: 'production release authorization required' }), { status: 401 }) + ) + ) + await expect(runProductionAction('authorize', 'rb-1', 'publish-to-production')).rejects.toThrow( + 'production release authorization required' + ) + expect(productionConfirmationPhrases).toEqual({ + authorize: 'publish-to-production', + retry: 'retry-production-release', + rollback: 'rollback-production-release', + publish_now: 'publish-to-production', + }) vi.unstubAllGlobals() }) }) @@ -236,11 +581,15 @@ describe('建批失败时把服务端原因带出来', () => { json: async () => ({ error: 'release change set must be confirmed and cover every requested publication' }), }) vi.stubGlobal('fetch', fetchMock) - await expect(createReleaseBatch('验收12', ['tp-x'], [], 'rcs-x')).rejects.toThrow('请先点「生成新版本」再「确认冻结(此后不可更改)」') + await expect(createReleaseBatch('验收12', ['tp-x'], [], 'rcs-x')).rejects.toThrow( + '请先点「生成新版本」再「确认冻结(此后不可更改)」' + ) }) it('未知原因原样带出,不再只给状态码', async () => { - const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 500, json: async () => ({ error: 'could not create release batch' }) }) + const fetchMock = vi + .fn() + .mockResolvedValue({ ok: false, status: 500, json: async () => ({ error: 'could not create release batch' }) }) vi.stubGlobal('fetch', fetchMock) await expect(createReleaseBatch('验收12', ['tp-x'], [], '')).rejects.toThrow('could not create release batch') }) @@ -248,31 +597,55 @@ describe('建批失败时把服务端原因带出来', () => { describe('审核策略的只读展示', () => { it('服务端返回策略时解析出来', () => { - const parsed = parseReleaseCapabilitiesResponse({ data: { production_release_requests_enabled: true, production_backup_restore_verified: true, test_auto_review_policy: 'internal' } }) + const parsed = parseReleaseCapabilitiesResponse({ + data: { + production_release_requests_enabled: true, + production_backup_restore_verified: true, + test_auto_review_policy: 'internal', + }, + }) expect(parsed.test_auto_review_policy).toBe('internal') }) it('旧服务端不返回策略时不报错', () => { - const parsed = parseReleaseCapabilitiesResponse({ data: { production_release_requests_enabled: false, production_backup_restore_verified: false } }) + const parsed = parseReleaseCapabilitiesResponse({ + data: { production_release_requests_enabled: false, production_backup_restore_verified: false }, + }) expect(parsed.test_auto_review_policy).toBe('') }) }) describe('批量审核与建批即锁定', () => { it('批量审核发送选中的条目与同一决定', async () => { - const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { selected: 2, decided: 2, skipped: 0, skipped_ids: [], reviews: [] } }) }) + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ data: { selected: 2, decided: 2, skipped: 0, skipped_ids: [], reviews: [] } }), + }) vi.stubGlobal('fetch', fetchMock) const result = await reviewPublicationsBatch(['tp-a', 'tp-b'], 'approved', 'internal', 'approved_for_release') expect(result).toEqual({ selected: 2, decided: 2, skipped: 0, skipped_ids: [] }) const [url, init] = fetchMock.mock.calls[0] expect(url).toBe('/api/v1/review-candidates/batch-decision') - expect(JSON.parse(String(init.body))).toEqual({ publication_ids: ['tp-a', 'tp-b'], decision: 'approved', decided_visibility: 'internal', decision_code: 'approved_for_release' }) + expect(JSON.parse(String(init.body))).toEqual({ + publication_ids: ['tp-a', 'tp-b'], + decision: 'approved', + decided_visibility: 'internal', + decision_code: 'approved_for_release', + }) }) it('如实回报被跳过的条目', async () => { - const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { selected: 3, decided: 2, skipped: 1, skipped_ids: ['tp-c'], reviews: [] } }) }) + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ data: { selected: 3, decided: 2, skipped: 1, skipped_ids: ['tp-c'], reviews: [] } }), + }) vi.stubGlobal('fetch', fetchMock) - const result = await reviewPublicationsBatch(['tp-a', 'tp-b', 'tp-c'], 'approved', 'internal', 'approved_for_release') + const result = await reviewPublicationsBatch( + ['tp-a', 'tp-b', 'tp-c'], + 'approved', + 'internal', + 'approved_for_release' + ) expect(result.skipped).toBe(1) expect(result.skipped_ids).toEqual(['tp-c']) }) @@ -290,18 +663,34 @@ describe('批量审核与建批即锁定', () => { describe('发布到生产(建批+锁定+授权合成一个动作)', () => { it('提交条目与固定确认语句,回传批次与执行', async () => { - const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { batch: { id: 'rb-now', name: '立即发布 · 2026/10/10' }, execution: { id: 'rx-now' } } }) }) + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + data: { batch: { id: 'rb-now', name: '立即发布 · 2026/10/10' }, execution: { id: 'rx-now' } }, + }), + }) vi.stubGlobal('fetch', fetchMock) const result = await runPublishNow(['tp-a', 'tp-b'], [], '立即发布 · 2026/10/10', 'publish-to-production') expect(result).toEqual({ batch_id: 'rb-now', batch_name: '立即发布 · 2026/10/10', execution_id: 'rx-now' }) const [url, init] = fetchMock.mock.calls[0] expect(url).toBe('/api/v1/release-batches/publish-now') - expect(JSON.parse(String(init.body))).toEqual({ publication_ids: ['tp-a', 'tp-b'], delete_publication_ids: [], name: '立即发布 · 2026/10/10', confirmation: 'publish-to-production' }) + expect(JSON.parse(String(init.body))).toEqual({ + publication_ids: ['tp-a', 'tp-b'], + delete_publication_ids: [], + name: '立即发布 · 2026/10/10', + confirmation: 'publish-to-production', + }) }) it('服务端拒绝时把原因带出来', async () => { - const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 412, json: async () => ({ error: 'production backup restore verification is required' }) }) + const fetchMock = vi.fn().mockResolvedValue({ + ok: false, + status: 412, + json: async () => ({ error: 'production backup restore verification is required' }), + }) vi.stubGlobal('fetch', fetchMock) - await expect(runPublishNow(['tp-a'], [], 'x', 'publish-to-production')).rejects.toThrow('production backup restore verification is required') + await expect(runPublishNow(['tp-a'], [], 'x', 'publish-to-production')).rejects.toThrow( + 'production backup restore verification is required' + ) }) }) diff --git a/web/src/reviewRelease.ts b/web/src/reviewRelease.ts index 1ddf298..192806f 100644 --- a/web/src/reviewRelease.ts +++ b/web/src/reviewRelease.ts @@ -5,7 +5,8 @@ export type AcceptanceState = 'pending' | 'passed' | 'failed' | 'manual_required export type ReviewGateStatus = 'ready' | 'blocked' export type ReleaseBatchState = 'draft' | 'sealed' | 'cancelled' export type ReleaseOperation = 'publish' | 'rollback' -export type ReleaseExecutionState = 'pending' | 'running' | 'completed' | 'failed' | 'rolling_back' | 'rolled_back' | 'rollback_failed' +export type ReleaseExecutionState = + 'pending' | 'running' | 'completed' | 'failed' | 'rolling_back' | 'rolled_back' | 'rollback_failed' export interface ReviewCandidate { publication_id: string @@ -150,8 +151,23 @@ const reviewStates = new Set(['pending', 'approved', 'rejected']) const gateStatuses = new Set(['ready', 'blocked']) const batchStates = new Set(['draft', 'sealed', 'cancelled']) const releaseOperations = new Set(['publish', 'rollback']) -const releaseExecutionStates = new Set(['pending', 'running', 'completed', 'failed', 'rolling_back', 'rolled_back', 'rollback_failed']) -const releaseItemStates = new Set(['pending', 'staged', 'activated', 'verified', 'failed', 'rolled_back']) +const releaseExecutionStates = new Set([ + 'pending', + 'running', + 'completed', + 'failed', + 'rolling_back', + 'rolled_back', + 'rollback_failed', +]) +const releaseItemStates = new Set([ + 'pending', + 'staged', + 'activated', + 'verified', + 'failed', + 'rolled_back', +]) const releasePlanActions = new Set(['add', 'update', 'delete', 'blocked']) const releasePlanTestStates = new Set(['ready', 'not_ready', 'not_required']) @@ -181,12 +197,22 @@ export function parseReleaseBatchDetailResponse(value: unknown): ReleaseBatchDet } const batch = parseReleaseBatch(value.data) const items = value.data.items.map((raw): ReleaseBatchItem => { - if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' || - typeof raw.decided_visibility !== 'string' || !visibilities.has(raw.decided_visibility as Visibility) || - (raw.action !== 'upsert' && raw.action !== 'delete')) { + if ( + !isRecord(raw) || + typeof raw.publication_id !== 'string' || + typeof raw.title !== 'string' || + typeof raw.decided_visibility !== 'string' || + !visibilities.has(raw.decided_visibility as Visibility) || + (raw.action !== 'upsert' && raw.action !== 'delete') + ) { throw new Error('invalid release batch item') } - return { publication_id: raw.publication_id, title: raw.title, decided_visibility: raw.decided_visibility as Visibility, action: raw.action } + return { + publication_id: raw.publication_id, + title: raw.title, + decided_visibility: raw.decided_visibility as Visibility, + action: raw.action, + } }) return { ...batch, items } } @@ -211,7 +237,12 @@ export function parseReleaseExecutionDetailResponse(value: unknown): ReleaseExec } export function parseReleaseCapabilitiesResponse(value: unknown): ReleaseCapabilities { - if (!isRecord(value) || !isRecord(value.data) || typeof value.data.production_release_requests_enabled !== 'boolean' || typeof value.data.production_backup_restore_verified !== 'boolean') { + if ( + !isRecord(value) || + !isRecord(value.data) || + typeof value.data.production_release_requests_enabled !== 'boolean' || + typeof value.data.production_backup_restore_verified !== 'boolean' + ) { throw new Error('invalid release capabilities response') } // 审核策略是只读展示项:旧服务端不返回时不报错(空串 = 界面不显示这一行)。 @@ -228,15 +259,30 @@ export function parseReleasePlanResponse(value: unknown): ReleasePlan { throw new Error('invalid release plan response') } const summary = value.data.summary - if (!isCount(summary.add) || !isCount(summary.update) || !isCount(summary.delete) || !isCount(summary.blocked) || !isCount(summary.unchanged)) { + if ( + !isCount(summary.add) || + !isCount(summary.update) || + !isCount(summary.delete) || + !isCount(summary.blocked) || + !isCount(summary.unchanged) + ) { throw new Error('invalid release plan response') } const items = value.data.items.map((raw): ReleasePlanItem => { - if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' || - typeof raw.target_scope !== 'string' || !visibilities.has(raw.target_scope as Visibility) || - typeof raw.action !== 'string' || !releasePlanActions.has(raw.action as ReleasePlanItem['action']) || - typeof raw.test_state !== 'string' || !releasePlanTestStates.has(raw.test_state as ReleasePlanItem['test_state']) || - (raw.production_state !== 'present' && raw.production_state !== 'absent') || typeof raw.can_release !== 'boolean' || typeof raw.blocker !== 'string') { + if ( + !isRecord(raw) || + typeof raw.publication_id !== 'string' || + typeof raw.title !== 'string' || + typeof raw.target_scope !== 'string' || + !visibilities.has(raw.target_scope as Visibility) || + typeof raw.action !== 'string' || + !releasePlanActions.has(raw.action as ReleasePlanItem['action']) || + typeof raw.test_state !== 'string' || + !releasePlanTestStates.has(raw.test_state as ReleasePlanItem['test_state']) || + (raw.production_state !== 'present' && raw.production_state !== 'absent') || + typeof raw.can_release !== 'boolean' || + typeof raw.blocker !== 'string' + ) { throw new Error('invalid release plan item') } return { @@ -250,10 +296,24 @@ export function parseReleasePlanResponse(value: unknown): ReleasePlan { blocker: raw.blocker, } }) - return { items, summary: { add: summary.add, update: summary.update, delete: summary.delete, blocked: summary.blocked, unchanged: summary.unchanged } } + return { + items, + summary: { + add: summary.add, + update: summary.update, + delete: summary.delete, + blocked: summary.blocked, + unchanged: summary.unchanged, + }, + } } -export async function fetchReviewCandidates(reviewState: ReviewState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise { +export async function fetchReviewCandidates( + reviewState: ReviewState | '' = '', + limit = 20, + offset = 0, + signal?: AbortSignal +): Promise { const params = new URLSearchParams({ review_state: reviewState, limit: String(limit), offset: String(offset) }) return parseReviewCandidatesResponse(await getJSON(`/api/v1/review-candidates?${params}`, signal, '加载审核队列失败')) } @@ -269,35 +329,93 @@ export interface ReviewBatchResult { * 一次对多条候选做同一个审核决定。服务端逐条复用单条审核的写入路径, * 并回报"哪几条当时不可审核",界面据此如实说明,而不是含糊地当作全成功。 */ -export async function reviewPublicationsBatch(publicationIDs: string[], decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string): Promise { - const value = await sendJSON('/api/v1/review-candidates/batch-decision', { - publication_ids: publicationIDs, decision, decided_visibility: visibility, decision_code: decisionCode, - }, '批量审核失败') +export async function reviewPublicationsBatch( + publicationIDs: string[], + decision: 'approved' | 'rejected', + visibility: Visibility, + decisionCode: string +): Promise { + const value = await sendJSON( + '/api/v1/review-candidates/batch-decision', + { + publication_ids: publicationIDs, + decision, + decided_visibility: visibility, + decision_code: decisionCode, + }, + '批量审核失败' + ) if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid review batch response') const data = value.data - if (!isCount(data.selected) || !isCount(data.decided) || !isCount(data.skipped)) throw new Error('invalid review batch response') - const skipped = Array.isArray(data.skipped_ids) ? data.skipped_ids.filter((item): item is string => typeof item === 'string') : [] + if (!isCount(data.selected) || !isCount(data.decided) || !isCount(data.skipped)) + throw new Error('invalid review batch response') + const skipped = Array.isArray(data.skipped_ids) + ? data.skipped_ids.filter((item): item is string => typeof item === 'string') + : [] return { selected: data.selected, decided: data.decided, skipped: data.skipped, skipped_ids: skipped } } -export async function reviewPublication(publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string): Promise { - const value = await sendJSON(`/api/v1/review-candidates/${encodeURIComponent(publicationID)}/decision`, { - decision, decided_visibility: visibility, decision_code: decisionCode, - }, '提交审核决定失败') +export async function reviewPublication( + publicationID: string, + decision: 'approved' | 'rejected', + visibility: Visibility, + decisionCode: string +): Promise { + const value = await sendJSON( + `/api/v1/review-candidates/${encodeURIComponent(publicationID)}/decision`, + { + decision, + decided_visibility: visibility, + decision_code: decisionCode, + }, + '提交审核决定失败' + ) if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid publication review response') const raw = value.data - if (typeof raw.id !== 'string' || typeof raw.publication_id !== 'string' || - (raw.decision !== 'approved' && raw.decision !== 'rejected') || typeof raw.decided_visibility !== 'string' || - !visibilities.has(raw.decided_visibility as Visibility) || typeof raw.reviewer_ref !== 'string' || - typeof raw.decision_code !== 'string' || typeof raw.created_at !== 'string') { + if ( + typeof raw.id !== 'string' || + typeof raw.publication_id !== 'string' || + (raw.decision !== 'approved' && raw.decision !== 'rejected') || + typeof raw.decided_visibility !== 'string' || + !visibilities.has(raw.decided_visibility as Visibility) || + typeof raw.reviewer_ref !== 'string' || + typeof raw.decision_code !== 'string' || + typeof raw.created_at !== 'string' + ) { throw new Error('invalid publication review response') } - return { id: raw.id, publication_id: raw.publication_id, decision: raw.decision, decided_visibility: raw.decided_visibility as Visibility, reviewer_ref: raw.reviewer_ref, decision_code: raw.decision_code, created_at: raw.created_at } + return { + id: raw.id, + publication_id: raw.publication_id, + decision: raw.decision, + decided_visibility: raw.decided_visibility as Visibility, + reviewer_ref: raw.reviewer_ref, + decision_code: raw.decision_code, + created_at: raw.created_at, + } } -export async function createReleaseBatch(name: string, publicationIDs: string[], deletePublicationIDs: string[] = [], releaseChangeSetID = '', seal = false): Promise { +export async function createReleaseBatch( + name: string, + publicationIDs: string[], + deletePublicationIDs: string[] = [], + releaseChangeSetID = '', + seal = false +): Promise { // seal=true:建批即锁定(P0-3)。清单在冻结时已不可变,草稿态只是多按一次。 - return parseBatchEnvelope(await sendJSON('/api/v1/release-batches', { name, publication_ids: publicationIDs, delete_publication_ids: deletePublicationIDs, release_change_set_id: releaseChangeSetID, seal }, '创建封批失败')) + return parseBatchEnvelope( + await sendJSON( + '/api/v1/release-batches', + { + name, + publication_ids: publicationIDs, + delete_publication_ids: deletePublicationIDs, + release_change_set_id: releaseChangeSetID, + seal, + }, + '创建封批失败' + ) + ) } export interface ReleaseChangeSetItem { @@ -338,23 +456,39 @@ export interface ReleaseChangeSetDetail extends ReleaseChangeSet { function parseChangeSetEnvelope(value: unknown): ReleaseChangeSet { if (!isRecord(value) || !isRecord(value.data)) throw new Error('发布计划集响应无效') const data = value.data - const text = (key: string) => typeof data[key] === 'string' ? data[key] as string : '' - const number = (key: string) => typeof data[key] === 'number' && Number.isFinite(data[key]) ? data[key] as number : 0 + const text = (key: string) => (typeof data[key] === 'string' ? (data[key] as string) : '') + const number = (key: string) => + typeof data[key] === 'number' && Number.isFinite(data[key]) ? (data[key] as number) : 0 const id = text('id') const manifest = text('manifest_sha256') if (!id || !/^[0-9a-f]{64}$/.test(manifest)) throw new Error('发布计划集响应缺少标识或清单摘要') - const snapshots = Array.isArray(data.source_snapshot_ids) ? data.source_snapshot_ids.filter((item): item is string => typeof item === 'string') : [] - const catalogSets = Array.isArray(data.source_change_set_ids) ? data.source_change_set_ids.filter((item): item is string => typeof item === 'string') : [] + const snapshots = Array.isArray(data.source_snapshot_ids) + ? data.source_snapshot_ids.filter((item): item is string => typeof item === 'string') + : [] + const catalogSets = Array.isArray(data.source_change_set_ids) + ? data.source_change_set_ids.filter((item): item is string => typeof item === 'string') + : [] const confirmedRaw = data.confirmed_at return { - id, number: number('number'), name: text('name'), - state: data.state === 'confirmed' || data.state === 'consumed' || data.state === 'cancelled' ? data.state : 'planned', - source_snapshot_ids: snapshots, source_change_set_ids: catalogSets, - acceptance_cutoff: text('acceptance_cutoff'), production_baseline_ref: text('production_baseline_ref'), - item_count: number('item_count'), add_count: number('add_count'), update_count: number('update_count'), - delete_count: number('delete_count'), blocked_count: number('blocked_count'), - manifest_sha256: manifest, created_by: text('created_by'), created_at: text('created_at'), - confirmed_by: text('confirmed_by'), confirmed_at: typeof confirmedRaw === 'string' && confirmedRaw ? confirmedRaw : null, + id, + number: number('number'), + name: text('name'), + state: + data.state === 'confirmed' || data.state === 'consumed' || data.state === 'cancelled' ? data.state : 'planned', + source_snapshot_ids: snapshots, + source_change_set_ids: catalogSets, + acceptance_cutoff: text('acceptance_cutoff'), + production_baseline_ref: text('production_baseline_ref'), + item_count: number('item_count'), + add_count: number('add_count'), + update_count: number('update_count'), + delete_count: number('delete_count'), + blocked_count: number('blocked_count'), + manifest_sha256: manifest, + created_by: text('created_by'), + created_at: text('created_at'), + confirmed_by: text('confirmed_by'), + confirmed_at: typeof confirmedRaw === 'string' && confirmedRaw ? confirmedRaw : null, } } @@ -364,14 +498,19 @@ export async function generateReleaseChangeSet(name: string): Promise { - return parseChangeSetEnvelope(await sendJSON(`/api/v1/release-change-sets/${encodeURIComponent(changeSetID)}/confirm`, {}, '确认发布计划集失败')) + return parseChangeSetEnvelope( + await sendJSON(`/api/v1/release-change-sets/${encodeURIComponent(changeSetID)}/confirm`, {}, '确认发布计划集失败') + ) } export async function fetchLatestReleaseChangeSet(signal?: AbortSignal): Promise { - const response = await fetch('/api/v1/release-change-sets/latest', { headers: { Accept: 'application/json' }, signal }) + const response = await fetch('/api/v1/release-change-sets/latest', { + headers: { Accept: 'application/json' }, + signal, + }) if (response.status === 404) return null if (!response.ok) throw new Error(`加载发布计划集失败(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown const base = parseChangeSetEnvelope(value) const data = (value as Record).data as Record const rawItems = Array.isArray(data.items) ? data.items : [] @@ -380,36 +519,73 @@ export async function fetchLatestReleaseChangeSet(signal?: AbortSignal): Promise if (!isRecord(raw)) continue const action = raw.action const scope = raw.target_scope - if (typeof raw.publication_id !== 'string' || (action !== 'add' && action !== 'update' && action !== 'delete' && action !== 'blocked' && action !== 'unchanged') || (scope !== 'internal' && scope !== 'external')) continue + if ( + typeof raw.publication_id !== 'string' || + (action !== 'add' && + action !== 'update' && + action !== 'delete' && + action !== 'blocked' && + action !== 'unchanged') || + (scope !== 'internal' && scope !== 'external') + ) + continue items.push({ - seq: typeof raw.seq === 'number' ? raw.seq : 0, publication_id: raw.publication_id, title: typeof raw.title === 'string' ? raw.title : '', - target_scope: scope, action, test_state: typeof raw.test_state === 'string' ? raw.test_state : '', production_state: typeof raw.production_state === 'string' ? raw.production_state : '', - can_release: raw.can_release === true, blocker: typeof raw.blocker === 'string' ? raw.blocker : '', + seq: typeof raw.seq === 'number' ? raw.seq : 0, + publication_id: raw.publication_id, + title: typeof raw.title === 'string' ? raw.title : '', + target_scope: scope, + action, + test_state: typeof raw.test_state === 'string' ? raw.test_state : '', + production_state: typeof raw.production_state === 'string' ? raw.production_state : '', + can_release: raw.can_release === true, + blocker: typeof raw.blocker === 'string' ? raw.blocker : '', }) } return { ...base, items } } export async function sealReleaseBatch(batchID: string): Promise { - return parseBatchEnvelope(await sendJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}/seal`, {}, '封批失败')) + return parseBatchEnvelope( + await sendJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}/seal`, {}, '封批失败') + ) } -export async function fetchReleaseBatches(state: ReleaseBatchState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise { +export async function fetchReleaseBatches( + state: ReleaseBatchState | '' = '', + limit = 20, + offset = 0, + signal?: AbortSignal +): Promise { const params = new URLSearchParams({ state, limit: String(limit), offset: String(offset) }) return parseReleaseBatchesResponse(await getJSON(`/api/v1/release-batches?${params}`, signal, '加载封批列表失败')) } export async function fetchReleaseBatch(batchID: string, signal?: AbortSignal): Promise { - return parseReleaseBatchDetailResponse(await getJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}`, signal, '加载封批详情失败')) + return parseReleaseBatchDetailResponse( + await getJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}`, signal, '加载封批详情失败') + ) } -export async function fetchReleaseExecutions(operation: ReleaseOperation | '' = '', state: ReleaseExecutionState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise { +export async function fetchReleaseExecutions( + operation: ReleaseOperation | '' = '', + state: ReleaseExecutionState | '' = '', + limit = 20, + offset = 0, + signal?: AbortSignal +): Promise { const params = new URLSearchParams({ operation, state, limit: String(limit), offset: String(offset) }) - return parseReleaseExecutionsResponse(await getJSON(`/api/v1/release-executions?${params}`, signal, '加载生产发布审计失败')) + return parseReleaseExecutionsResponse( + await getJSON(`/api/v1/release-executions?${params}`, signal, '加载生产发布审计失败') + ) } -export async function fetchReleaseExecution(executionID: string, signal?: AbortSignal): Promise { - return parseReleaseExecutionDetailResponse(await getJSON(`/api/v1/release-executions/${encodeURIComponent(executionID)}`, signal, '加载生产发布详情失败')) +export async function fetchReleaseExecution( + executionID: string, + signal?: AbortSignal +): Promise { + return parseReleaseExecutionDetailResponse( + await getJSON(`/api/v1/release-executions/${encodeURIComponent(executionID)}`, signal, '加载生产发布详情失败') + ) } export async function fetchReleaseCapabilities(signal?: AbortSignal): Promise { @@ -421,46 +597,97 @@ export async function fetchReleasePlan(signal?: AbortSignal): Promise = { } async function failureMessage(response: Response, message: string): Promise { - const body = await response.json().catch(() => null) as unknown + const body = (await response.json().catch(() => null)) as unknown const reason = isRecord(body) && typeof body.error === 'string' ? body.error : '' if (!reason) return `${message}(HTTP ${response.status})` return `${message}(HTTP ${response.status})${releaseFailureHints[reason] ?? `:${reason}`}` @@ -531,7 +797,11 @@ async function getJSON(url: string, signal: AbortSignal | undefined, message: st } async function sendJSON(url: string, body: unknown, message: string): Promise { - const response = await fetch(url, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(body) }) + const response = await fetch(url, { + method: 'POST', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, + body: JSON.stringify(body), + }) if (!response.ok) throw new Error(await failureMessage(response, message)) return response.json() } @@ -544,38 +814,122 @@ function isCount(value: unknown): value is number { return typeof value === 'number' && Number.isInteger(value) && value >= 0 } -const auditText = (row: Record, key: string): string => typeof row[key] === 'string' ? row[key] as string : '' -const auditNumber = (row: Record, key: string): number => typeof row[key] === 'number' && Number.isFinite(row[key]) ? row[key] as number : 0 -export interface AuditSnapshot { id: string; source_name: string; node_count: number; file_count: number; observed_at: string } -export interface AuditCatalogSet { id: string; state: string; add_count: number; update_count: number; move_count: number; delete_count: number } -export interface AuditChainItem { publication_id: string; title: string; action: string; item_state: string; review_id: string; acceptance_run_id: string; source_item_id: string; source_item_version_id: string; production_revision: string; error_code: string } -export interface ReleaseAuditChain { - execution_id: string; operation: string; state: string; failure_level: string - release_batch_id: string; release_batch_name: string; created_by: string; sealed_by: string; authorized_by: string - release_change_set_id: string; release_change_set_name: string; release_change_set_state: string - release_change_set_created_by: string; release_change_set_confirmed_by: string; release_change_set_confirmed_at: string | null - manifest_sha256: string; snapshots: AuditSnapshot[]; catalog_change_sets: AuditCatalogSet[] - prior_execution_id: string; rollback_execution_id: string; items: AuditChainItem[] +const auditText = (row: Record, key: string): string => + typeof row[key] === 'string' ? (row[key] as string) : '' +const auditNumber = (row: Record, key: string): number => + typeof row[key] === 'number' && Number.isFinite(row[key]) ? (row[key] as number) : 0 +export interface AuditSnapshot { + id: string + source_name: string + node_count: number + file_count: number + observed_at: string } -export async function fetchReleaseAuditChain(executionID: string, signal?: AbortSignal): Promise { - const response = await fetch(`/api/v1/release-executions/${encodeURIComponent(executionID)}/audit-chain`, { headers: { Accept: 'application/json' }, signal }) +export interface AuditCatalogSet { + id: string + state: string + add_count: number + update_count: number + move_count: number + delete_count: number +} +export interface AuditChainItem { + publication_id: string + title: string + action: string + item_state: string + review_id: string + acceptance_run_id: string + source_item_id: string + source_item_version_id: string + production_revision: string + error_code: string +} +export interface ReleaseAuditChain { + execution_id: string + operation: string + state: string + failure_level: string + release_batch_id: string + release_batch_name: string + created_by: string + sealed_by: string + authorized_by: string + release_change_set_id: string + release_change_set_name: string + release_change_set_state: string + release_change_set_created_by: string + release_change_set_confirmed_by: string + release_change_set_confirmed_at: string | null + manifest_sha256: string + snapshots: AuditSnapshot[] + catalog_change_sets: AuditCatalogSet[] + prior_execution_id: string + rollback_execution_id: string + items: AuditChainItem[] +} +export async function fetchReleaseAuditChain( + executionID: string, + signal?: AbortSignal +): Promise { + const response = await fetch(`/api/v1/release-executions/${encodeURIComponent(executionID)}/audit-chain`, { + headers: { Accept: 'application/json' }, + signal, + }) if (response.status === 404) return null if (!response.ok) throw new Error(`加载发布审计链失败(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!isRecord(value) || !isRecord(value.data)) throw new Error('发布审计链响应无效') const data = value.data - const rows = (key: string): Record[] => Array.isArray(data[key]) ? (data[key] as unknown[]).filter(isRecord) : [] + const rows = (key: string): Record[] => + Array.isArray(data[key]) ? (data[key] as unknown[]).filter(isRecord) : [] return { - execution_id: auditText(data, 'execution_id'), operation: auditText(data, 'operation'), state: auditText(data, 'state'), failure_level: auditText(data, 'failure_level'), - release_batch_id: auditText(data, 'release_batch_id'), release_batch_name: auditText(data, 'release_batch_name'), created_by: auditText(data, 'created_by'), sealed_by: auditText(data, 'sealed_by'), authorized_by: auditText(data, 'authorized_by'), - release_change_set_id: auditText(data, 'release_change_set_id'), release_change_set_name: auditText(data, 'release_change_set_name'), release_change_set_state: auditText(data, 'release_change_set_state'), - release_change_set_created_by: auditText(data, 'release_change_set_created_by'), release_change_set_confirmed_by: auditText(data, 'release_change_set_confirmed_by'), - release_change_set_confirmed_at: typeof data.release_change_set_confirmed_at === 'string' ? data.release_change_set_confirmed_at : null, + execution_id: auditText(data, 'execution_id'), + operation: auditText(data, 'operation'), + state: auditText(data, 'state'), + failure_level: auditText(data, 'failure_level'), + release_batch_id: auditText(data, 'release_batch_id'), + release_batch_name: auditText(data, 'release_batch_name'), + created_by: auditText(data, 'created_by'), + sealed_by: auditText(data, 'sealed_by'), + authorized_by: auditText(data, 'authorized_by'), + release_change_set_id: auditText(data, 'release_change_set_id'), + release_change_set_name: auditText(data, 'release_change_set_name'), + release_change_set_state: auditText(data, 'release_change_set_state'), + release_change_set_created_by: auditText(data, 'release_change_set_created_by'), + release_change_set_confirmed_by: auditText(data, 'release_change_set_confirmed_by'), + release_change_set_confirmed_at: + typeof data.release_change_set_confirmed_at === 'string' ? data.release_change_set_confirmed_at : null, manifest_sha256: auditText(data, 'manifest_sha256'), - snapshots: rows('snapshots').map((row) => ({ id: auditText(row, 'id'), source_name: auditText(row, 'source_name'), node_count: auditNumber(row, 'node_count'), file_count: auditNumber(row, 'file_count'), observed_at: auditText(row, 'observed_at') })), - catalog_change_sets: rows('catalog_change_sets').map((row) => ({ id: auditText(row, 'id'), state: auditText(row, 'state'), add_count: auditNumber(row, 'add_count'), update_count: auditNumber(row, 'update_count'), move_count: auditNumber(row, 'move_count'), delete_count: auditNumber(row, 'delete_count') })), - prior_execution_id: auditText(data, 'prior_execution_id'), rollback_execution_id: auditText(data, 'rollback_execution_id'), - items: rows('items').map((row) => ({ publication_id: auditText(row, 'publication_id'), title: auditText(row, 'title'), action: auditText(row, 'action'), item_state: auditText(row, 'item_state'), review_id: auditText(row, 'review_id'), acceptance_run_id: auditText(row, 'acceptance_run_id'), source_item_id: auditText(row, 'source_item_id'), source_item_version_id: auditText(row, 'source_item_version_id'), production_revision: auditText(row, 'production_revision'), error_code: auditText(row, 'error_code') })), + snapshots: rows('snapshots').map((row) => ({ + id: auditText(row, 'id'), + source_name: auditText(row, 'source_name'), + node_count: auditNumber(row, 'node_count'), + file_count: auditNumber(row, 'file_count'), + observed_at: auditText(row, 'observed_at'), + })), + catalog_change_sets: rows('catalog_change_sets').map((row) => ({ + id: auditText(row, 'id'), + state: auditText(row, 'state'), + add_count: auditNumber(row, 'add_count'), + update_count: auditNumber(row, 'update_count'), + move_count: auditNumber(row, 'move_count'), + delete_count: auditNumber(row, 'delete_count'), + })), + prior_execution_id: auditText(data, 'prior_execution_id'), + rollback_execution_id: auditText(data, 'rollback_execution_id'), + items: rows('items').map((row) => ({ + publication_id: auditText(row, 'publication_id'), + title: auditText(row, 'title'), + action: auditText(row, 'action'), + item_state: auditText(row, 'item_state'), + review_id: auditText(row, 'review_id'), + acceptance_run_id: auditText(row, 'acceptance_run_id'), + source_item_id: auditText(row, 'source_item_id'), + source_item_version_id: auditText(row, 'source_item_version_id'), + production_revision: auditText(row, 'production_revision'), + error_code: auditText(row, 'error_code'), + })), } } @@ -616,15 +970,28 @@ export interface PublishNowResult { * 服务端不放松任何约束:请求门禁、备份恢复验证门禁、管理员身份、固定确认语句、 * 发布前快照硬门禁全部照旧;这里只是把操作员的两步点击合成一次带确认的提交。 */ -export async function runPublishNow(publicationIDs: string[], deletePublicationIDs: string[], name: string, confirmation: string): Promise { +export async function runPublishNow( + publicationIDs: string[], + deletePublicationIDs: string[], + name: string, + confirmation: string +): Promise { const response = await fetch('/api/v1/release-batches/publish-now', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, - body: JSON.stringify({ publication_ids: publicationIDs, delete_publication_ids: deletePublicationIDs, name, confirmation }), + body: JSON.stringify({ + publication_ids: publicationIDs, + delete_publication_ids: deletePublicationIDs, + name, + confirmation, + }), }) const payload: unknown = await response.json().catch(() => null) if (!response.ok) { - const reason = isRecord(payload) && typeof payload.error === 'string' ? payload.error : `发布到生产失败(HTTP ${response.status})` + const reason = + isRecord(payload) && typeof payload.error === 'string' + ? payload.error + : `发布到生产失败(HTTP ${response.status})` throw new Error(reason) } if (!isRecord(payload) || !isRecord(payload.data)) throw new Error('发布到生产响应无效') @@ -633,10 +1000,18 @@ export async function runPublishNow(publicationIDs: string[], deletePublicationI if (!isRecord(batch) || !isRecord(execution) || typeof batch.id !== 'string' || typeof execution.id !== 'string') { throw new Error('发布到生产响应无效') } - return { batch_id: batch.id, batch_name: typeof batch.name === 'string' ? batch.name : '', execution_id: execution.id } + return { + batch_id: batch.id, + batch_name: typeof batch.name === 'string' ? batch.name : '', + execution_id: execution.id, + } } -export async function runProductionAction(kind: ConfirmedActionKind, id: string, confirmation: string): Promise { +export async function runProductionAction( + kind: ConfirmedActionKind, + id: string, + confirmation: string +): Promise { const response = await fetch(productionActionPaths[kind](id), { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, @@ -644,7 +1019,8 @@ export async function runProductionAction(kind: ConfirmedActionKind, id: string, }) const payload: unknown = await response.json().catch(() => null) if (!response.ok) { - const reason = isRecord(payload) && typeof payload.error === 'string' ? payload.error : `生产操作失败(HTTP ${response.status})` + const reason = + isRecord(payload) && typeof payload.error === 'string' ? payload.error : `生产操作失败(HTTP ${response.status})` throw new Error(reason) } if (!isRecord(payload) || !isRecord(payload.data)) throw new Error('生产操作响应无效') diff --git a/web/src/routingBindings.test.ts b/web/src/routingBindings.test.ts index b689c29..2366641 100644 --- a/web/src/routingBindings.test.ts +++ b/web/src/routingBindings.test.ts @@ -3,14 +3,24 @@ import { describe, expect, it, vi } from 'vitest' import { fetchRoutingBindingOptions, fetchRoutingBindings, saveRoutingBindings } from './routingBindings' const binding = { - internal_kb_id: '1b52c140-2e18-4676-afc5-4c7d8d190a8c', external_kb_id: 'fd7db6aa-763a-46f1-84d2-ecc7c952a5ea', - internal_env_fallback: true, external_env_fallback: false, internal_bound_by_ui: false, external_bound_by_ui: true, - internal_kb_name: '', external_kb_name: 'governance-external-local', updated_by: 'yao', weknora_connected: true, + internal_kb_id: '1b52c140-2e18-4676-afc5-4c7d8d190a8c', + external_kb_id: 'fd7db6aa-763a-46f1-84d2-ecc7c952a5ea', + internal_env_fallback: true, + external_env_fallback: false, + internal_bound_by_ui: false, + external_bound_by_ui: true, + internal_kb_name: '', + external_kb_name: 'governance-external-local', + updated_by: 'yao', + weknora_connected: true, } describe('routing bindings API', () => { it('reads the active binding projection', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...binding, secret: 'drop' } }), { status: 200 }))) + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...binding, secret: 'drop' } }), { status: 200 })) + ) const result = await fetchRoutingBindings() expect(result.internal_env_fallback).toBe(true) expect(result.external_bound_by_ui).toBe(true) @@ -18,20 +28,38 @@ describe('routing bindings API', () => { vi.unstubAllGlobals() }) it('lists knowledge base options for the picker', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'kb-1', name: '对内', knowledge_count: 4 }, { id: '', name: '坏行' }] }), { status: 200 }))) + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: [ + { id: 'kb-1', name: '对内', knowledge_count: 4 }, + { id: '', name: '坏行' }, + ], + }), + { status: 200 } + ) + ) + ) expect(await fetchRoutingBindingOptions()).toEqual([{ id: 'kb-1', name: '对内', knowledge_count: 4 }]) vi.unstubAllGlobals() }) it('saves bindings with an idempotency key and surfaces the server reason', async () => { - const fetchMock = vi.fn() + const fetchMock = vi + .fn() .mockResolvedValueOnce(new Response(JSON.stringify({ data: binding }), { status: 200 })) .mockResolvedValueOnce(new Response(JSON.stringify({ error: '对内与对外必须绑定不同的知识库' }), { status: 400 })) vi.stubGlobal('fetch', fetchMock) - await expect(saveRoutingBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })).resolves.toMatchObject({ internal_bound_by_ui: false }) + await expect(saveRoutingBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })).resolves.toMatchObject({ + internal_bound_by_ui: false, + }) const [, init] = fetchMock.mock.calls[0] expect(init.method).toBe('PUT') expect(init.headers['Idempotency-Key']).toBeTruthy() - await expect(saveRoutingBindings({ internal_kb_id: 'kb-1', external_kb_id: 'kb-1' })).rejects.toThrow('对内与对外必须绑定不同的知识库') + await expect(saveRoutingBindings({ internal_kb_id: 'kb-1', external_kb_id: 'kb-1' })).rejects.toThrow( + '对内与对外必须绑定不同的知识库' + ) vi.unstubAllGlobals() }) }) diff --git a/web/src/routingBindings.ts b/web/src/routingBindings.ts index 7424f5b..d9b9f97 100644 --- a/web/src/routingBindings.ts +++ b/web/src/routingBindings.ts @@ -14,6 +14,11 @@ export interface RoutingBindings { // 本次保存把多少条「还没上传」的待入库项重新指向了新库(读取时为 0)。 replanned: number retired_duplicates: number + // 整库封存源与“测试入库绑定”是两套配置:这里给出封存源 ID 与一致性判定。 + library_source_internal_kb: string + library_source_external_kb: string + internal_source_state: 'consistent' | 'mismatch' | 'unconfigured' + external_source_state: 'consistent' | 'mismatch' | 'unconfigured' } export interface KnowledgeBaseOption { @@ -22,7 +27,8 @@ export interface KnowledgeBaseOption { knowledge_count: number } -const record = (value: unknown): value is Record => Boolean(value) && typeof value === 'object' && !Array.isArray(value) +const record = (value: unknown): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value) function bindingProjection(item: Record): RoutingBindings { return { @@ -37,6 +43,18 @@ function bindingProjection(item: Record): RoutingBindings { updated_by: typeof item.updated_by === 'string' ? item.updated_by : '', weknora_connected: item.weknora_connected === true, replanned: typeof item.replanned === 'number' ? item.replanned : 0, + library_source_internal_kb: + typeof item.library_source_internal_kb === 'string' ? item.library_source_internal_kb : '', + library_source_external_kb: + typeof item.library_source_external_kb === 'string' ? item.library_source_external_kb : '', + internal_source_state: + item.internal_source_state === 'consistent' || item.internal_source_state === 'mismatch' + ? item.internal_source_state + : 'unconfigured', + external_source_state: + item.external_source_state === 'consistent' || item.external_source_state === 'mismatch' + ? item.external_source_state + : 'unconfigured', retired_duplicates: typeof item.retired_duplicates === 'number' ? item.retired_duplicates : 0, } } @@ -44,7 +62,7 @@ function bindingProjection(item: Record): RoutingBindings { export async function fetchRoutingBindings(signal?: AbortSignal): Promise { const response = await fetch('/api/v1/routing-bindings', { signal, headers: { Accept: 'application/json' } }) if (!response.ok) throw new Error(`读取测试知识库绑定失败(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !record(value.data)) throw new Error('测试知识库绑定响应无效') return bindingProjection(value.data) } @@ -52,27 +70,39 @@ export async function fetchRoutingBindings(signal?: AbortSignal): Promise { const response = await fetch('/api/v1/routing-bindings/options', { signal, headers: { Accept: 'application/json' } }) if (!response.ok) throw new Error(`读取可绑定知识库失败(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !Array.isArray(value.data)) throw new Error('知识库列表响应无效') - return value.data.filter(record).map((item) => ({ - id: typeof item.id === 'string' ? item.id : '', - name: typeof item.name === 'string' ? item.name : '', - knowledge_count: typeof item.knowledge_count === 'number' ? item.knowledge_count : 0, - })).filter((item) => item.id) + return value.data + .filter(record) + .map((item) => ({ + id: typeof item.id === 'string' ? item.id : '', + name: typeof item.name === 'string' ? item.name : '', + knowledge_count: typeof item.knowledge_count === 'number' ? item.knowledge_count : 0, + })) + .filter((item) => item.id) } -export async function saveRoutingBindings(input: { internal_kb_id: string; external_kb_id: string }, signal?: AbortSignal): Promise { +export async function saveRoutingBindings( + input: { internal_kb_id: string; external_kb_id: string }, + signal?: AbortSignal +): Promise { const response = await fetch('/api/v1/routing-bindings', { - method: 'PUT', signal, + method: 'PUT', + signal, headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(input), }) if (!response.ok) { let reason = `保存测试知识库绑定失败(HTTP ${response.status})` - try { const body = await response.json() as unknown; if (record(body) && typeof body.error === 'string') reason = body.error } catch { /* keep status text */ } + try { + const body = (await response.json()) as unknown + if (record(body) && typeof body.error === 'string') reason = body.error + } catch { + /* keep status text */ + } throw new Error(reason) } - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!record(value) || !record(value.data)) throw new Error('测试知识库绑定响应无效') return bindingProjection(value.data) } diff --git a/web/src/scopeRules.test.ts b/web/src/scopeRules.test.ts index 475e71c..61d95ea 100644 --- a/web/src/scopeRules.test.ts +++ b/web/src/scopeRules.test.ts @@ -1,25 +1,81 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { clearScopeRule, fetchScopeRules, setScopeRule } from './scopeRules' -afterEach(()=>vi.unstubAllGlobals()) +afterEach(() => vi.unstubAllGlobals()) -describe('scope rule API',()=>{ - it('lists rules for exactly one configured connection',async()=>{ - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:[{target_type:'directory',connection_id:'conn-1',directory_path:'产品',visibility:'internal',updated_by:'engineer',reason:'内部资料',updated_at:'2026-09-08T00:00:00Z'}],summary:{total:1}}))) - vi.stubGlobal('fetch',fetchMock) - const rules=await fetchScopeRules('conn-1') - expect(rules).toHaveLength(1) - expect(fetchMock).toHaveBeenCalledWith('/api/v1/scope-rules?connection_id=conn-1',expect.objectContaining({headers:{Accept:'application/json'}})) - }) - it('sets and clears rules with explicit audited payloads',async()=>{ - const fetchMock=vi.fn().mockImplementation(()=>Promise.resolve(new Response(JSON.stringify({data:{target_type:'directory',connection_id:'conn-1',directory_path:'产品',visibility:'internal'}})))) - vi.stubGlobal('fetch',fetchMock) - const target={target_type:'directory' as const,connection_id:'conn-1',directory_path:'产品',source_item_id:''} - await setScopeRule({...target,visibility:'internal',reason:'内部资料'}) - await clearScopeRule({...target,reason:'恢复来源设置'}) - expect(fetchMock.mock.calls[0][1]).toMatchObject({method:'PUT',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':expect.any(String)}}) - expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({...target,visibility:'internal',reason:'内部资料'}) - expect(fetchMock.mock.calls[1][1]).toMatchObject({method:'DELETE',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':expect.any(String)}}) - expect(JSON.parse(fetchMock.mock.calls[1][1].body)).not.toHaveProperty('visibility') - }) +describe('scope rule API', () => { + it('lists rules for exactly one configured connection', async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: [ + { + target_type: 'directory', + connection_id: 'conn-1', + directory_path: '产品', + visibility: 'internal', + updated_by: 'engineer', + reason: '内部资料', + updated_at: '2026-09-08T00:00:00Z', + }, + ], + summary: { total: 1 }, + }) + ) + ) + vi.stubGlobal('fetch', fetchMock) + const rules = await fetchScopeRules('conn-1') + expect(rules).toHaveLength(1) + expect(fetchMock).toHaveBeenCalledWith( + '/api/v1/scope-rules?connection_id=conn-1', + expect.objectContaining({ headers: { Accept: 'application/json' } }) + ) + }) + it('sets and clears rules with explicit audited payloads', async () => { + const fetchMock = vi.fn().mockImplementation(() => + Promise.resolve( + new Response( + JSON.stringify({ + data: { + target_type: 'directory', + connection_id: 'conn-1', + directory_path: '产品', + visibility: 'internal', + }, + }) + ) + ) + ) + vi.stubGlobal('fetch', fetchMock) + const target = { + target_type: 'directory' as const, + connection_id: 'conn-1', + directory_path: '产品', + source_item_id: '', + } + await setScopeRule({ ...target, visibility: 'internal', reason: '内部资料' }) + await clearScopeRule({ ...target, reason: '恢复来源设置' }) + expect(fetchMock.mock.calls[0][1]).toMatchObject({ + method: 'PUT', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'Idempotency-Key': expect.any(String), + }, + }) + expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ + ...target, + visibility: 'internal', + reason: '内部资料', + }) + expect(fetchMock.mock.calls[1][1]).toMatchObject({ + method: 'DELETE', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'Idempotency-Key': expect.any(String), + }, + }) + expect(JSON.parse(fetchMock.mock.calls[1][1].body)).not.toHaveProperty('visibility') + }) }) diff --git a/web/src/scopeRules.ts b/web/src/scopeRules.ts index 476e24c..1a357d7 100644 --- a/web/src/scopeRules.ts +++ b/web/src/scopeRules.ts @@ -3,49 +3,61 @@ export type ScopeTargetType = 'directory' | 'item' export type Visibility = 'internal' | 'external' export interface ScopeRule { - target_type: ScopeTargetType - connection_id?: string - directory_path?: string - source_item_id?: string - visibility: Visibility - updated_by: string - reason: string - updated_at: string + target_type: ScopeTargetType + connection_id?: string + directory_path?: string + source_item_id?: string + visibility: Visibility + updated_by: string + reason: string + updated_at: string } export interface ScopeRuleTarget { - target_type: ScopeTargetType - connection_id: string - directory_path: string - source_item_id: string + target_type: ScopeTargetType + connection_id: string + directory_path: string + source_item_id: string } export interface ScopeRuleDecision extends ScopeRuleTarget { - visibility: Visibility - reason: string + visibility: Visibility + reason: string } export interface ClearScopeRuleDecision extends ScopeRuleTarget { - reason: string + reason: string } - - -export async function fetchScopeRules(connectionID:string,signal?:AbortSignal):Promise { - const response=await fetch(`/api/v1/scope-rules?${new URLSearchParams({connection_id:connectionID})}`,{headers:{Accept:'application/json'},signal}) - if(!response.ok) throw new Error(`加载范围规则失败(HTTP ${response.status})`) - const value=await response.json() as {data?:unknown} - if(!Array.isArray(value.data)) throw new Error('范围规则响应无效') - return value.data as ScopeRule[] +export async function fetchScopeRules(connectionID: string, signal?: AbortSignal): Promise { + const response = await fetch(`/api/v1/scope-rules?${new URLSearchParams({ connection_id: connectionID })}`, { + headers: { Accept: 'application/json' }, + signal, + }) + if (!response.ok) throw new Error(`加载范围规则失败(HTTP ${response.status})`) + const value = (await response.json()) as { data?: unknown } + if (!Array.isArray(value.data)) throw new Error('范围规则响应无效') + return value.data as ScopeRule[] } -async function mutateScopeRule(method:'PUT'|'DELETE',body:ScopeRuleDecision|ClearScopeRuleDecision):Promise { - const response=await fetch('/api/v1/scope-rules',{method,headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':newOperationID()},body:JSON.stringify(body)}) - if(!response.ok) throw new Error(`${method==='PUT'?'保存':'清除'}范围规则失败(HTTP ${response.status})`) - const value=await response.json() as {data?:ScopeRule} - if(!value.data || typeof value.data!=='object') throw new Error('范围规则响应无效') - return value.data +async function mutateScopeRule( + method: 'PUT' | 'DELETE', + body: ScopeRuleDecision | ClearScopeRuleDecision +): Promise { + const response = await fetch('/api/v1/scope-rules', { + method, + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, + body: JSON.stringify(body), + }) + if (!response.ok) throw new Error(`${method === 'PUT' ? '保存' : '清除'}范围规则失败(HTTP ${response.status})`) + const value = (await response.json()) as { data?: ScopeRule } + if (!value.data || typeof value.data !== 'object') throw new Error('范围规则响应无效') + return value.data } -export function setScopeRule(decision:ScopeRuleDecision){return mutateScopeRule('PUT',decision)} -export function clearScopeRule(decision:ClearScopeRuleDecision){return mutateScopeRule('DELETE',decision)} +export function setScopeRule(decision: ScopeRuleDecision) { + return mutateScopeRule('PUT', decision) +} +export function clearScopeRule(decision: ClearScopeRuleDecision) { + return mutateScopeRule('DELETE', decision) +} diff --git a/web/src/settingsInputs.ts b/web/src/settingsInputs.ts new file mode 100644 index 0000000..f56da20 --- /dev/null +++ b/web/src/settingsInputs.ts @@ -0,0 +1,39 @@ +import type { UISettings, UISettingsCandidateInput } from './uiSettings' + +// 保存边界是纯函数:连接分区只取连接草稿,刷新分区只取刷新草稿, +// 另一侧一律用服务器当前值。组件与测试共用同一实现。 +export interface ServiceDrafts { + testEndpoint: string + endpoint: string + productionTenantID: string + productionKnowledgeBaseID: string +} +export interface RefreshDrafts { + documentRefresh: 15 | 30 | 60 + resourceRefresh: 30 | 60 + stalled: 1800 | 3600 + finalizing: 7200 | 14400 + concurrency: number +} +export const serviceSettingsInput = (settings: UISettings, drafts: ServiceDrafts): UISettingsCandidateInput => ({ + document_refresh_seconds: settings.document_refresh_seconds, + resource_refresh_seconds: settings.resource_refresh_seconds, + stalled_after_seconds: settings.stalled_after_seconds, + finalizing_after_seconds: settings.finalizing_after_seconds, + ingestion_concurrency: settings.ingestion_concurrency, + test_weknora_base_url: drafts.testEndpoint.trim(), + production_weknora_base_url: drafts.endpoint.trim(), + production_tenant_id: drafts.productionTenantID.trim(), + production_knowledge_base_id: drafts.productionKnowledgeBaseID.trim(), +}) +export const refreshSettingsInput = (settings: UISettings, drafts: RefreshDrafts): UISettingsCandidateInput => ({ + document_refresh_seconds: drafts.documentRefresh, + resource_refresh_seconds: drafts.resourceRefresh, + stalled_after_seconds: drafts.stalled, + finalizing_after_seconds: drafts.finalizing, + ingestion_concurrency: drafts.concurrency, + test_weknora_base_url: settings.test_weknora_base_url, + production_weknora_base_url: settings.production_weknora_base_url, + production_tenant_id: settings.production_tenant_id, + production_knowledge_base_id: settings.production_knowledge_base_id, +}) diff --git a/web/src/sourceCatalog.test.ts b/web/src/sourceCatalog.test.ts index 0e48a78..e1d665d 100644 --- a/web/src/sourceCatalog.test.ts +++ b/web/src/sourceCatalog.test.ts @@ -1,94 +1,346 @@ -import { afterEach,describe,expect,it,vi } from 'vitest' -import { fetchAllCatalogFolders,fetchCatalogNodes,fetchCatalogRoutingCapabilities,fetchCatalogSources,fetchLatestCatalogChangeSet,routeCatalogFiles,triggerCatalogRefresh } from './sourceCatalog' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + fetchAllCatalogFolders, + fetchCatalogNodes, + fetchCatalogRoutingCapabilities, + fetchCatalogSources, + fetchLatestCatalogChangeSet, + routeCatalogFiles, + triggerCatalogRefresh, +} from './sourceCatalog' -afterEach(()=>vi.unstubAllGlobals()) +afterEach(() => vi.unstubAllGlobals()) -describe('source catalog API',()=>{ - it('keeps a source that is still scanning, with its progress',async()=>{ - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:[ - {connection_id:'conn-scan',source_type:'dingtalk',name:'公司级营销资料管理',root_node_id:'',folder_count:1153,file_count:1428,observed_at:'2026-10-10T08:51:44Z',snapshot_only:true,snapshot_status:'scanning',last_refresh_duration_ms:0,scan_progress:36,scan_message:'正在扫描目录:已完成 470 个文件夹,待处理 683 个'}, - {connection_id:'conn-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:8,file_count:3468,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:12000} - ],summary:{total:2}}))) - vi.stubGlobal('fetch',fetchMock) - const sources=await fetchCatalogSources() - expect(sources).toHaveLength(2) - expect(sources[0].snapshot_status).toBe('scanning') - expect(sources[0].scan_progress).toBe(36) - expect(sources[0].scan_message).toContain('470 个文件夹') - expect(sources[1].snapshot_status).toBe('ready') - expect(sources[1].scan_progress).toBeUndefined() - }) +describe('source catalog API', () => { + it('keeps a source that is still scanning, with its progress', async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: [ + { + connection_id: 'conn-scan', + source_type: 'dingtalk', + name: '公司级营销资料管理', + root_node_id: '', + folder_count: 1153, + file_count: 1428, + observed_at: '2026-10-10T08:51:44Z', + snapshot_only: true, + snapshot_status: 'scanning', + last_refresh_duration_ms: 0, + scan_progress: 36, + scan_message: '正在扫描目录:已完成 470 个文件夹,待处理 683 个', + }, + { + connection_id: 'conn-1', + source_type: 'dingtalk', + name: '公司级技术支持知识库', + root_node_id: 'root-1', + folder_count: 8, + file_count: 3468, + observed_at: '2026-09-08T00:00:00Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 12000, + }, + ], + summary: { total: 2 }, + }) + ) + ) + vi.stubGlobal('fetch', fetchMock) + const sources = await fetchCatalogSources() + expect(sources).toHaveLength(2) + expect(sources[0].snapshot_status).toBe('scanning') + expect(sources[0].scan_progress).toBe(36) + expect(sources[0].scan_message).toContain('470 个文件夹') + expect(sources[1].snapshot_status).toBe('ready') + expect(sources[1].scan_progress).toBeUndefined() + }) - it('rejects a scanning source without progress instead of rendering a fake 0%',async()=>{ - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:[{connection_id:'conn-scan',source_type:'dingtalk',name:'X',root_node_id:'',folder_count:0,file_count:0,observed_at:'2026-10-10T08:51:44Z',snapshot_only:true,snapshot_status:'scanning',last_refresh_duration_ms:0}],summary:{total:1}}))) - vi.stubGlobal('fetch',fetchMock) - await expect(fetchCatalogSources()).rejects.toThrow(/来源目录响应无效/) - }) - it('loads safe source roots',async()=>{ - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:[{connection_id:'conn-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:8,file_count:3468,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:12000,secret:'drop'}],summary:{total:1}}))) - vi.stubGlobal('fetch',fetchMock) - const sources=await fetchCatalogSources() - expect(sources[0].name).toBe('公司级技术支持知识库') - expect(sources[0].snapshot_status).toBe('ready') - expect(sources[0].last_refresh_duration_ms).toBe(12000) - expect(sources[0]).not.toHaveProperty('secret') - expect(fetchMock).toHaveBeenCalledWith('/api/v1/source-catalog/sources',expect.objectContaining({headers:{Accept:'application/json'}})) - }) - it('loads every page for a complete deduplicated folder tree level',async()=>{ - const folderA={node_id:'folder-a',parent_node_id:'root',node_type:'folder',name:'A',direct_child_count:1,subtree_file_count:1,subtree_bytes:1,visibility:'unknown',imported_count:0,parsed_count:0,active_count:0,failed_count:0,routable_count:0} - const file={...folderA,node_id:'file-a',node_type:'file',name:'a.pdf'} - const folderB={...folderA,node_id:'folder-b',name:'B'} - const response=(items:unknown[],offset:number)=>new Response(JSON.stringify({current:{...folderA,node_id:'root',name:'Root'},breadcrumbs:[{node_id:'root',name:'Root'}],items,total:3,limit:2,offset})) - const fetchMock=vi.fn().mockResolvedValueOnce(response([folderA,file],0)).mockResolvedValueOnce(response([folderB,folderA],2)) - vi.stubGlobal('fetch',fetchMock) - await expect(fetchAllCatalogFolders('conn-1','root')).resolves.toEqual([folderA,folderB]) - expect(fetchMock.mock.calls.map(call=>call[0])).toEqual(['/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root&limit=100&offset=0','/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root&limit=100&offset=2']) - }) - it('requests only one parent page at a time',async()=>{ - const response={current:{node_id:'root-1',node_type:'folder',name:'公司级技术支持知识库',direct_child_count:1,subtree_file_count:10,subtree_bytes:20,visibility:'unknown',imported_count:0,parsed_count:0,active_count:0,failed_count:0,routable_count:0},breadcrumbs:[{node_id:'root-1',name:'公司级技术支持知识库'}],items:[{node_id:'folder-1',parent_node_id:'root-1',node_type:'folder',name:'01|产品资料',direct_child_count:2,subtree_file_count:10,subtree_bytes:20,visibility:'internal',imported_count:8,parsed_count:7,active_count:1,failed_count:0,routable_count:8}],total:1,limit:50,offset:0} - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify(response))) - vi.stubGlobal('fetch',fetchMock) - const page=await fetchCatalogNodes('conn-1','root-1',50,0) - expect(page.items).toHaveLength(1) - expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root-1&limit=50&offset=0') - expect(JSON.stringify(page)).not.toContain('relative_path') - }) - it('routes selected files without exposing target knowledge-base IDs to the browser',async()=>{ - const fetchMock=vi.fn() - .mockResolvedValueOnce(new Response(JSON.stringify({data:{internal_enabled:true,external_enabled:true}}))) - .mockResolvedValueOnce(new Response(JSON.stringify({data:{selected_files:2,intents_recorded:2,fetch_queued:1,planned_publications:4,blocked_items:0,unbound_files:0}}))) - vi.stubGlobal('fetch',fetchMock) - expect((await fetchCatalogRoutingCapabilities()).internal_enabled).toBe(true) - const result=await routeCatalogFiles({connection_id:'conn-1',node_ids:['a','b'],policy:'both',reason:'批量标注'}) - expect(result.planned_publications).toBe(4) - expect(result.unbound_files).toBe(0) - const payload=JSON.parse(fetchMock.mock.calls[1][1].body) - expect(payload.policy).toBe('both') - expect(payload).not.toHaveProperty('visibility') - expect(payload).not.toHaveProperty('target_knowledge_base_id') - expect(fetchMock.mock.calls[1][1].headers).toMatchObject({Accept:'application/json','Content-Type':'application/json','Idempotency-Key':expect.any(String)}) - expect(fetchMock.mock.calls[1][1].headers['Idempotency-Key']).not.toBe('') - }) - it('reports blocked items without planning anything',async()=>{ - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:{selected_files:2,intents_recorded:2,fetch_queued:0,planned_publications:0,blocked_items:2,unbound_files:0}}))) - vi.stubGlobal('fetch',fetchMock) - const result=await routeCatalogFiles({connection_id:'conn-1',node_ids:['a','b'],policy:'blocked',reason:'禁止导入'}) - expect(result.blocked_items).toBe(2) - expect(result.planned_publications).toBe(0) - }) - it('starts a durable background refresh job with no source credential payload',async()=>{ - const job={id:'job-refresh',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'queued',progress:0,message:'等待后台刷新'},state:'pending',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:0,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'} - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:job})));vi.stubGlobal('fetch',fetchMock) - const result=await triggerCatalogRefresh('conn-1') - expect(result.id).toBe('job-refresh');expect(fetchMock.mock.calls[0][1].method).toBe('POST');expect(fetchMock.mock.calls[0][1].headers).toMatchObject({Accept:'application/json','Idempotency-Key':expect.any(String)});expect(fetchMock.mock.calls[0][1].headers['Idempotency-Key']).not.toBe('');expect(JSON.stringify(result.payload)).not.toContain('token') - }) - it('loads the latest persisted snapshot change set without internal hashes',async()=>{ - const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:{id:'cs-1',connection_id:'conn-1',source_name:'国内工业',state:'planned',add_count:2,update_count:1,move_count:0,move_scope_count:1,delete_count:1,no_change_count:10,created_at:'2026-09-10T00:00:00Z',items:[{action:'delete',title:'旧手册.pdf',old_path:'旧目录/旧手册.pdf',reason_code:'source_missing',seq:7}],total:1,limit:20,offset:0,source_locator_hash:'drop'}}))) - vi.stubGlobal('fetch',fetchMock) - const result=await fetchLatestCatalogChangeSet('conn-1','delete',20,0) - expect(result.add_count).toBe(2) - expect(result.items[0]).toEqual({action:'delete',title:'旧手册.pdf',old_path:'旧目录/旧手册.pdf',new_path:'',reason_code:'source_missing',seq:7}) - expect(result).not.toHaveProperty('source_locator_hash') - expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/source-catalog/change-sets/latest?connection_id=conn-1&action=delete&limit=20&offset=0') - }) + it('rejects a scanning source without progress instead of rendering a fake 0%', async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: [ + { + connection_id: 'conn-scan', + source_type: 'dingtalk', + name: 'X', + root_node_id: '', + folder_count: 0, + file_count: 0, + observed_at: '2026-10-10T08:51:44Z', + snapshot_only: true, + snapshot_status: 'scanning', + last_refresh_duration_ms: 0, + }, + ], + summary: { total: 1 }, + }) + ) + ) + vi.stubGlobal('fetch', fetchMock) + await expect(fetchCatalogSources()).rejects.toThrow(/来源目录响应无效/) + }) + it('loads safe source roots', async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: [ + { + connection_id: 'conn-1', + source_type: 'dingtalk', + name: '公司级技术支持知识库', + root_node_id: 'root-1', + folder_count: 8, + file_count: 3468, + observed_at: '2026-09-08T00:00:00Z', + snapshot_only: true, + snapshot_status: 'ready', + last_refresh_duration_ms: 12000, + secret: 'drop', + }, + ], + summary: { total: 1 }, + }) + ) + ) + vi.stubGlobal('fetch', fetchMock) + const sources = await fetchCatalogSources() + expect(sources[0].name).toBe('公司级技术支持知识库') + expect(sources[0].snapshot_status).toBe('ready') + expect(sources[0].last_refresh_duration_ms).toBe(12000) + expect(sources[0]).not.toHaveProperty('secret') + expect(fetchMock).toHaveBeenCalledWith( + '/api/v1/source-catalog/sources', + expect.objectContaining({ headers: { Accept: 'application/json' } }) + ) + }) + it('loads every page for a complete deduplicated folder tree level', async () => { + const folderA = { + node_id: 'folder-a', + parent_node_id: 'root', + node_type: 'folder', + name: 'A', + direct_child_count: 1, + subtree_file_count: 1, + subtree_bytes: 1, + visibility: 'unknown', + imported_count: 0, + parsed_count: 0, + active_count: 0, + failed_count: 0, + routable_count: 0, + } + const file = { ...folderA, node_id: 'file-a', node_type: 'file', name: 'a.pdf' } + const folderB = { ...folderA, node_id: 'folder-b', name: 'B' } + const response = (items: unknown[], offset: number) => + new Response( + JSON.stringify({ + current: { ...folderA, node_id: 'root', name: 'Root' }, + breadcrumbs: [{ node_id: 'root', name: 'Root' }], + items, + total: 3, + limit: 2, + offset, + }) + ) + const fetchMock = vi + .fn() + .mockResolvedValueOnce(response([folderA, file], 0)) + .mockResolvedValueOnce(response([folderB, folderA], 2)) + vi.stubGlobal('fetch', fetchMock) + await expect(fetchAllCatalogFolders('conn-1', 'root')).resolves.toEqual([folderA, folderB]) + expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([ + '/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root&limit=100&offset=0', + '/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root&limit=100&offset=2', + ]) + }) + it('requests only one parent page at a time', async () => { + const response = { + current: { + node_id: 'root-1', + node_type: 'folder', + name: '公司级技术支持知识库', + direct_child_count: 1, + subtree_file_count: 10, + subtree_bytes: 20, + visibility: 'unknown', + imported_count: 0, + parsed_count: 0, + active_count: 0, + failed_count: 0, + routable_count: 0, + }, + breadcrumbs: [{ node_id: 'root-1', name: '公司级技术支持知识库' }], + items: [ + { + node_id: 'folder-1', + parent_node_id: 'root-1', + node_type: 'folder', + name: '01|产品资料', + direct_child_count: 2, + subtree_file_count: 10, + subtree_bytes: 20, + visibility: 'internal', + imported_count: 8, + parsed_count: 7, + active_count: 1, + failed_count: 0, + routable_count: 8, + }, + ], + total: 1, + limit: 50, + offset: 0, + } + const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(response))) + vi.stubGlobal('fetch', fetchMock) + const page = await fetchCatalogNodes('conn-1', 'root-1', 50, 0) + expect(page.items).toHaveLength(1) + expect(fetchMock.mock.calls[0][0]).toBe( + '/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root-1&limit=50&offset=0' + ) + expect(JSON.stringify(page)).not.toContain('relative_path') + }) + it('routes selected files without exposing target knowledge-base IDs to the browser', async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce(new Response(JSON.stringify({ data: { internal_enabled: true, external_enabled: true } }))) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + data: { + selected_files: 2, + intents_recorded: 2, + fetch_queued: 1, + planned_publications: 4, + blocked_items: 0, + unbound_files: 0, + }, + }) + ) + ) + vi.stubGlobal('fetch', fetchMock) + expect((await fetchCatalogRoutingCapabilities()).internal_enabled).toBe(true) + const result = await routeCatalogFiles({ + connection_id: 'conn-1', + node_ids: ['a', 'b'], + policy: 'both', + reason: '批量标注', + }) + expect(result.planned_publications).toBe(4) + expect(result.unbound_files).toBe(0) + const payload = JSON.parse(fetchMock.mock.calls[1][1].body) + expect(payload.policy).toBe('both') + expect(payload).not.toHaveProperty('visibility') + expect(payload).not.toHaveProperty('target_knowledge_base_id') + expect(fetchMock.mock.calls[1][1].headers).toMatchObject({ + Accept: 'application/json', + 'Content-Type': 'application/json', + 'Idempotency-Key': expect.any(String), + }) + expect(fetchMock.mock.calls[1][1].headers['Idempotency-Key']).not.toBe('') + }) + it('reports blocked items without planning anything', async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + selected_files: 2, + intents_recorded: 2, + fetch_queued: 0, + planned_publications: 0, + blocked_items: 2, + unbound_files: 0, + }, + }) + ) + ) + vi.stubGlobal('fetch', fetchMock) + const result = await routeCatalogFiles({ + connection_id: 'conn-1', + node_ids: ['a', 'b'], + policy: 'blocked', + reason: '禁止导入', + }) + expect(result.blocked_items).toBe(2) + expect(result.planned_publications).toBe(0) + }) + it('starts a durable background refresh job with no source credential payload', async () => { + const job = { + id: 'job-refresh', + type: 'source.catalog.refresh', + payload: { connection_id: 'conn-1', stage: 'queued', progress: 0, message: '等待后台刷新' }, + state: 'pending', + priority: 20, + available_at: '2026-09-09T00:00:00Z', + attempt: 0, + max_attempts: 3, + idempotency_key: 'safe', + created_at: '2026-09-09T00:00:00Z', + updated_at: '2026-09-09T00:00:00Z', + } + const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: job }))) + vi.stubGlobal('fetch', fetchMock) + const result = await triggerCatalogRefresh('conn-1') + expect(result.id).toBe('job-refresh') + expect(fetchMock.mock.calls[0][1].method).toBe('POST') + expect(fetchMock.mock.calls[0][1].headers).toMatchObject({ + Accept: 'application/json', + 'Idempotency-Key': expect.any(String), + }) + expect(fetchMock.mock.calls[0][1].headers['Idempotency-Key']).not.toBe('') + expect(JSON.stringify(result.payload)).not.toContain('token') + }) + it('loads the latest persisted snapshot change set without internal hashes', async () => { + const fetchMock = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + id: 'cs-1', + connection_id: 'conn-1', + source_name: '国内工业', + state: 'planned', + add_count: 2, + update_count: 1, + move_count: 0, + move_scope_count: 1, + delete_count: 1, + no_change_count: 10, + created_at: '2026-09-10T00:00:00Z', + items: [ + { + action: 'delete', + title: '旧手册.pdf', + old_path: '旧目录/旧手册.pdf', + reason_code: 'source_missing', + seq: 7, + }, + ], + total: 1, + limit: 20, + offset: 0, + source_locator_hash: 'drop', + }, + }) + ) + ) + vi.stubGlobal('fetch', fetchMock) + const result = await fetchLatestCatalogChangeSet('conn-1', 'delete', 20, 0) + expect(result.add_count).toBe(2) + expect(result.items[0]).toEqual({ + action: 'delete', + title: '旧手册.pdf', + old_path: '旧目录/旧手册.pdf', + new_path: '', + reason_code: 'source_missing', + seq: 7, + }) + expect(result).not.toHaveProperty('source_locator_hash') + expect(fetchMock.mock.calls[0][0]).toBe( + '/api/v1/source-catalog/change-sets/latest?connection_id=conn-1&action=delete&limit=20&offset=0' + ) + }) }) diff --git a/web/src/sourceCatalog.ts b/web/src/sourceCatalog.ts index 5f3c00a..c648e2f 100644 --- a/web/src/sourceCatalog.ts +++ b/web/src/sourceCatalog.ts @@ -1,115 +1,537 @@ import type { Job } from './jobs' import { newOperationID } from './operationKey' -export type CatalogSourceType='dingtalk'|'pp'|'alist' -export type CatalogPolicy='internal'|'external'|'both'|'blocked' -export interface CatalogSource {connection_id:string;source_type:CatalogSourceType;name:string;root_node_id:string;folder_count:number;file_count:number;observed_at:string;snapshot_only:boolean;snapshot_status:'ready'|'scanning';last_refresh_duration_ms:number;scan_progress?:number;scan_message?:string} -export interface CatalogBreadcrumb {node_id:string;name:string} -export interface CatalogNode {node_id:string;parent_node_id?:string;node_type:'folder'|'file';name:string;direct_child_count:number;subtree_file_count:number;subtree_bytes:number;size_bytes?:number;modified_at?:string;content_sha256?:string;visibility:'internal'|'external'|'both'|'blocked'|'mixed'|'unknown';imported_count:number;parsed_count:number;active_count:number;failed_count:number;routable_count:number} -export interface CatalogSnapshot {snapshot_id:string;connection_id:string;root_node_id:string;source_name:string;node_count:number;folder_count:number;file_count:number;observed_at:string;created_at:string;is_head:boolean} -export interface CatalogSnapshotPage {items:CatalogSnapshot[];total:number;limit:number;offset:number} -export interface CatalogNodePage {current:CatalogNode;breadcrumbs:CatalogBreadcrumb[];items:CatalogNode[];total:number;limit:number;offset:number} -const sourceTypes=new Set(['dingtalk','pp','alist']);const nodeTypes=new Set(['folder','file']);const visibilities=new Set(['internal','external','both','blocked','mixed','unknown']) -const record=(value:unknown):value is Record=>typeof value==='object'&&value!==null -const count=(value:unknown):value is number=>typeof value==='number'&&Number.isInteger(value)&&value>=0 -function parseNode(value:unknown):CatalogNode{ - if(!record(value)||typeof value.node_id!=='string'||typeof value.node_type!=='string'||!nodeTypes.has(value.node_type)||typeof value.name!=='string'||!count(value.direct_child_count)||!count(value.subtree_file_count)||!count(value.subtree_bytes)||typeof value.visibility!=='string'||!visibilities.has(value.visibility)||!count(value.imported_count)||!count(value.parsed_count)||!count(value.active_count)||!count(value.failed_count)||!count(value.routable_count)||value.content_sha256!==undefined&&typeof value.content_sha256!=='string')throw new Error('目录节点响应无效') - return value as unknown as CatalogNode +export type CatalogSourceType = 'dingtalk' | 'pp' | 'alist' +export type CatalogPolicy = 'internal' | 'external' | 'both' | 'blocked' +export interface CatalogSource { + connection_id: string + source_type: CatalogSourceType + name: string + root_node_id: string + folder_count: number + file_count: number + observed_at: string + snapshot_only: boolean + snapshot_status: 'ready' | 'scanning' + last_refresh_duration_ms: number + scan_progress?: number + scan_message?: string } -export async function fetchCatalogSources(signal?:AbortSignal):Promise{ - const response=await fetch('/api/v1/source-catalog/sources',{headers:{Accept:'application/json'},signal}) - if(!response.ok)throw new Error(`加载来源目录失败(HTTP ${response.status})`) - const value=await response.json() as unknown - if(!record(value)||!Array.isArray(value.data))throw new Error('来源目录响应无效') - return value.data.map(raw=>{ - if(!record(raw)||typeof raw.connection_id!=='string'||typeof raw.source_type!=='string'||!sourceTypes.has(raw.source_type)||typeof raw.name!=='string'||typeof raw.root_node_id!=='string'||!count(raw.folder_count)||!count(raw.file_count)||typeof raw.observed_at!=='string'||raw.snapshot_only!==true||(raw.snapshot_status!=='ready'&&raw.snapshot_status!=='scanning')||!count(raw.last_refresh_duration_ms))throw new Error('来源目录响应无效') - // scanning = 已登记但首次扫描还没落地:带进度,正好让新来源立刻出现在列表里。 - const scanning=raw.snapshot_status==='scanning' - if(scanning&&!count(raw.scan_progress))throw new Error('来源目录响应无效') - return {connection_id:raw.connection_id,source_type:raw.source_type as CatalogSourceType,name:raw.name,root_node_id:raw.root_node_id,folder_count:raw.folder_count,file_count:raw.file_count,observed_at:raw.observed_at,snapshot_only:true,snapshot_status:raw.snapshot_status as 'ready'|'scanning',last_refresh_duration_ms:raw.last_refresh_duration_ms,scan_progress:scanning?raw.scan_progress as number:undefined,scan_message:typeof raw.scan_message==='string'?raw.scan_message:undefined} - }) +export interface CatalogBreadcrumb { + node_id: string + name: string } -export async function fetchCatalogSnapshots(connectionID:string,limit=20,offset=0,signal?:AbortSignal):Promise{ - const query=new URLSearchParams({connection_id:connectionID,limit:String(limit),offset:String(offset)}) - const response=await fetch(`/api/v1/source-catalog/snapshots?${query}`,{headers:{Accept:'application/json'},signal}) - if(!response.ok)throw new Error(`加载快照历史失败(HTTP ${response.status})`) - const value=await response.json() as unknown - if(!record(value)||!Array.isArray(value.items)||!count(value.total)||!count(value.limit)||!count(value.offset))throw new Error('快照历史响应无效') - const items=value.items.map(raw=>{if(!record(raw)||typeof raw.snapshot_id!=='string'||typeof raw.connection_id!=='string'||typeof raw.root_node_id!=='string'||typeof raw.source_name!=='string'||!count(raw.node_count)||!count(raw.folder_count)||!count(raw.file_count)||typeof raw.observed_at!=='string'||typeof raw.created_at!=='string'||typeof raw.is_head!=='boolean')throw new Error('快照历史条目无效');return raw as unknown as CatalogSnapshot}) - return {items,total:value.total,limit:value.limit,offset:value.offset} +export interface CatalogNode { + node_id: string + parent_node_id?: string + node_type: 'folder' | 'file' + name: string + direct_child_count: number + subtree_file_count: number + subtree_bytes: number + size_bytes?: number + modified_at?: string + content_sha256?: string + visibility: 'internal' | 'external' | 'both' | 'blocked' | 'mixed' | 'unknown' + imported_count: number + parsed_count: number + active_count: number + failed_count: number + routable_count: number } -export async function fetchCatalogSnapshotNodes(connectionID:string,snapshotID:string,parentID:string,limit=50,offset=0,signal?:AbortSignal):Promise{ - const query=new URLSearchParams({connection_id:connectionID,parent_id:parentID,limit:String(limit),offset:String(offset)}) - const response=await fetch(`/api/v1/source-catalog/snapshots/${encodeURIComponent(snapshotID)}/nodes?${query}`,{headers:{Accept:'application/json'},signal}) - if(!response.ok)throw new Error(`加载历史快照目录失败(HTTP ${response.status})`) - const value=await response.json() as unknown - if(!record(value)||!Array.isArray(value.items)||!count(value.total)||!count(value.limit)||!count(value.offset))throw new Error('历史快照目录响应无效') - return {current:parseNode(value.current),breadcrumbs:Array.isArray(value.breadcrumbs)?value.breadcrumbs.map(raw=>{if(!record(raw)||typeof raw.node_id!=='string'||typeof raw.name!=='string')throw new Error('目录路径响应无效');return raw as unknown as CatalogBreadcrumb}):[],items:value.items.map(parseNode),total:value.total,limit:value.limit,offset:value.offset} +export interface CatalogSnapshot { + snapshot_id: string + connection_id: string + root_node_id: string + source_name: string + node_count: number + folder_count: number + file_count: number + observed_at: string + created_at: string + is_head: boolean } -export interface ConfirmChangeSetResult{change_set_id:string;confirmed_items:number;uploads_created:number;uploads_existing:number;removals_requested:number;skipped_no_artifact:number;skipped_no_target:number;no_change_ignored:number} -export async function confirmCatalogChangeSet(changeSetID:string,itemSeqs:number[],reason:string):Promise<{result:ConfirmChangeSetResult;operation:string}>{ - const response=await fetch(`/api/v1/source-catalog/change-sets/${encodeURIComponent(changeSetID)}/confirm`,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':newOperationID()},body:JSON.stringify({item_seqs:itemSeqs,reason})}) - if(!response.ok)throw new Error(response.status===409?'操作标识与另一请求冲突,请刷新后重试':`确认快照差异失败(HTTP ${response.status})`) - const value=await response.json() as unknown;if(!record(value)||!record(value.data)||!count(value.data.confirmed_items)||!count(value.data.uploads_created)||!count(value.data.uploads_existing)||!count(value.data.removals_requested)||!count(value.data.skipped_no_artifact)||!count(value.data.skipped_no_target)||!count(value.data.no_change_ignored)||typeof value.operation!=='string')throw new Error('确认快照差异响应无效') - return {result:value.data as unknown as ConfirmChangeSetResult,operation:value.operation} +export interface CatalogSnapshotPage { + items: CatalogSnapshot[] + total: number + limit: number + offset: number } -export async function fetchCatalogNodes(connectionID:string,parentID:string,limit=50,offset=0,signal?:AbortSignal):Promise{ - const query=new URLSearchParams({connection_id:connectionID,parent_id:parentID,limit:String(limit),offset:String(offset)}) - const response=await fetch(`/api/v1/source-catalog/nodes?${query}`,{headers:{Accept:'application/json'},signal}) - if(!response.ok)throw new Error(response.status===404?'目录已更新,请返回来源首页':`加载目录失败(HTTP ${response.status})`) - const value=await response.json() as unknown - if(!record(value)||!Array.isArray(value.breadcrumbs)||!Array.isArray(value.items)||!count(value.total)||!count(value.limit)||!count(value.offset))throw new Error('目录列表响应无效') - const breadcrumbs=value.breadcrumbs.map(raw=>{if(!record(raw)||typeof raw.node_id!=='string'||typeof raw.name!=='string')throw new Error('目录路径响应无效');return raw as unknown as CatalogBreadcrumb}) - return {current:parseNode(value.current),breadcrumbs,items:value.items.map(parseNode),total:value.total,limit:value.limit,offset:value.offset} +export interface CatalogNodePage { + current: CatalogNode + breadcrumbs: CatalogBreadcrumb[] + items: CatalogNode[] + total: number + limit: number + offset: number } - -export async function fetchAllCatalogFolders(connectionID:string,parentID:string,signal?:AbortSignal):Promise{ - const folders:CatalogNode[]=[] - const seen=new Set() - let offset=0 - while(true){ - const page=await fetchCatalogNodes(connectionID,parentID,100,offset,signal) - for(const node of page.items){ - if(node.node_type==='folder'&&!seen.has(node.node_id)){seen.add(node.node_id);folders.push(node)} +const sourceTypes = new Set(['dingtalk', 'pp', 'alist']) +const nodeTypes = new Set(['folder', 'file']) +const visibilities = new Set(['internal', 'external', 'both', 'blocked', 'mixed', 'unknown']) +const record = (value: unknown): value is Record => typeof value === 'object' && value !== null +const count = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value >= 0 +function parseNode(value: unknown): CatalogNode { + if ( + !record(value) || + typeof value.node_id !== 'string' || + typeof value.node_type !== 'string' || + !nodeTypes.has(value.node_type) || + typeof value.name !== 'string' || + !count(value.direct_child_count) || + !count(value.subtree_file_count) || + !count(value.subtree_bytes) || + typeof value.visibility !== 'string' || + !visibilities.has(value.visibility) || + !count(value.imported_count) || + !count(value.parsed_count) || + !count(value.active_count) || + !count(value.failed_count) || + !count(value.routable_count) || + (value.content_sha256 !== undefined && typeof value.content_sha256 !== 'string') + ) + throw new Error('目录节点响应无效') + return value as unknown as CatalogNode +} +export async function fetchCatalogSources(signal?: AbortSignal): Promise { + const response = await fetch('/api/v1/source-catalog/sources', { headers: { Accept: 'application/json' }, signal }) + if (!response.ok) throw new Error(`加载来源目录失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if (!record(value) || !Array.isArray(value.data)) throw new Error('来源目录响应无效') + return value.data.map((raw) => { + if ( + !record(raw) || + typeof raw.connection_id !== 'string' || + typeof raw.source_type !== 'string' || + !sourceTypes.has(raw.source_type) || + typeof raw.name !== 'string' || + typeof raw.root_node_id !== 'string' || + !count(raw.folder_count) || + !count(raw.file_count) || + typeof raw.observed_at !== 'string' || + raw.snapshot_only !== true || + (raw.snapshot_status !== 'ready' && raw.snapshot_status !== 'scanning') || + !count(raw.last_refresh_duration_ms) + ) + throw new Error('来源目录响应无效') + // scanning = 已登记但首次扫描还没落地:带进度,正好让新来源立刻出现在列表里。 + const scanning = raw.snapshot_status === 'scanning' + if (scanning && !count(raw.scan_progress)) throw new Error('来源目录响应无效') + return { + connection_id: raw.connection_id, + source_type: raw.source_type as CatalogSourceType, + name: raw.name, + root_node_id: raw.root_node_id, + folder_count: raw.folder_count, + file_count: raw.file_count, + observed_at: raw.observed_at, + snapshot_only: true, + snapshot_status: raw.snapshot_status as 'ready' | 'scanning', + last_refresh_duration_ms: raw.last_refresh_duration_ms, + scan_progress: scanning ? (raw.scan_progress as number) : undefined, + scan_message: typeof raw.scan_message === 'string' ? raw.scan_message : undefined, + } + }) +} +export async function fetchCatalogSnapshots( + connectionID: string, + limit = 20, + offset = 0, + signal?: AbortSignal +): Promise { + const query = new URLSearchParams({ connection_id: connectionID, limit: String(limit), offset: String(offset) }) + const response = await fetch(`/api/v1/source-catalog/snapshots?${query}`, { + headers: { Accept: 'application/json' }, + signal, + }) + if (!response.ok) throw new Error(`加载快照历史失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if ( + !record(value) || + !Array.isArray(value.items) || + !count(value.total) || + !count(value.limit) || + !count(value.offset) + ) + throw new Error('快照历史响应无效') + const items = value.items.map((raw) => { + if ( + !record(raw) || + typeof raw.snapshot_id !== 'string' || + typeof raw.connection_id !== 'string' || + typeof raw.root_node_id !== 'string' || + typeof raw.source_name !== 'string' || + !count(raw.node_count) || + !count(raw.folder_count) || + !count(raw.file_count) || + typeof raw.observed_at !== 'string' || + typeof raw.created_at !== 'string' || + typeof raw.is_head !== 'boolean' + ) + throw new Error('快照历史条目无效') + return raw as unknown as CatalogSnapshot + }) + return { items, total: value.total, limit: value.limit, offset: value.offset } +} +export async function fetchCatalogSnapshotNodes( + connectionID: string, + snapshotID: string, + parentID: string, + limit = 50, + offset = 0, + signal?: AbortSignal +): Promise { + const query = new URLSearchParams({ + connection_id: connectionID, + parent_id: parentID, + limit: String(limit), + offset: String(offset), + }) + const response = await fetch(`/api/v1/source-catalog/snapshots/${encodeURIComponent(snapshotID)}/nodes?${query}`, { + headers: { Accept: 'application/json' }, + signal, + }) + if (!response.ok) throw new Error(`加载历史快照目录失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if ( + !record(value) || + !Array.isArray(value.items) || + !count(value.total) || + !count(value.limit) || + !count(value.offset) + ) + throw new Error('历史快照目录响应无效') + return { + current: parseNode(value.current), + breadcrumbs: Array.isArray(value.breadcrumbs) + ? value.breadcrumbs.map((raw) => { + if (!record(raw) || typeof raw.node_id !== 'string' || typeof raw.name !== 'string') + throw new Error('目录路径响应无效') + return raw as unknown as CatalogBreadcrumb + }) + : [], + items: value.items.map(parseNode), + total: value.total, + limit: value.limit, + offset: value.offset, + } +} +export interface ConfirmChangeSetResult { + change_set_id: string + confirmed_items: number + uploads_created: number + uploads_existing: number + removals_requested: number + skipped_no_artifact: number + skipped_no_target: number + no_change_ignored: number +} +export async function confirmCatalogChangeSet( + changeSetID: string, + itemSeqs: number[], + reason: string +): Promise<{ result: ConfirmChangeSetResult; operation: string }> { + const response = await fetch(`/api/v1/source-catalog/change-sets/${encodeURIComponent(changeSetID)}/confirm`, { + method: 'POST', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, + body: JSON.stringify({ item_seqs: itemSeqs, reason }), + }) + if (!response.ok) + throw new Error( + response.status === 409 ? '操作标识与另一请求冲突,请刷新后重试' : `确认快照差异失败(HTTP ${response.status})` + ) + const value = (await response.json()) as unknown + if ( + !record(value) || + !record(value.data) || + !count(value.data.confirmed_items) || + !count(value.data.uploads_created) || + !count(value.data.uploads_existing) || + !count(value.data.removals_requested) || + !count(value.data.skipped_no_artifact) || + !count(value.data.skipped_no_target) || + !count(value.data.no_change_ignored) || + typeof value.operation !== 'string' + ) + throw new Error('确认快照差异响应无效') + return { result: value.data as unknown as ConfirmChangeSetResult, operation: value.operation } +} +export async function fetchCatalogNodes( + connectionID: string, + parentID: string, + limit = 50, + offset = 0, + signal?: AbortSignal +): Promise { + const query = new URLSearchParams({ + connection_id: connectionID, + parent_id: parentID, + limit: String(limit), + offset: String(offset), + }) + const response = await fetch(`/api/v1/source-catalog/nodes?${query}`, { + headers: { Accept: 'application/json' }, + signal, + }) + if (!response.ok) + throw new Error(response.status === 404 ? '目录已更新,请返回来源首页' : `加载目录失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if ( + !record(value) || + !Array.isArray(value.breadcrumbs) || + !Array.isArray(value.items) || + !count(value.total) || + !count(value.limit) || + !count(value.offset) + ) + throw new Error('目录列表响应无效') + const breadcrumbs = value.breadcrumbs.map((raw) => { + if (!record(raw) || typeof raw.node_id !== 'string' || typeof raw.name !== 'string') + throw new Error('目录路径响应无效') + return raw as unknown as CatalogBreadcrumb + }) + return { + current: parseNode(value.current), + breadcrumbs, + items: value.items.map(parseNode), + total: value.total, + limit: value.limit, + offset: value.offset, } - const next=page.offset+page.limit - if(next>=page.total)return folders - if(page.limit<=0||next<=offset)throw new Error('目录分页游标无效') - offset=next - } } -export interface CatalogRoutingCapabilities{internal_enabled:boolean;external_enabled:boolean} -export interface CatalogRouteInput{connection_id:string;node_ids:string[];policy:CatalogPolicy;reason:string} -export interface CatalogRouteResult{selected_files:number;intents_recorded:number;fetch_queued:number;planned_publications:number;blocked_items:number;unbound_files:number} - -export async function fetchCatalogRoutingCapabilities(signal?:AbortSignal):Promise{ - const response=await fetch('/api/v1/source-catalog/routing-capabilities',{headers:{Accept:'application/json'},signal});if(!response.ok)throw new Error(`加载分流配置失败(HTTP ${response.status})`) - const value=await response.json() as unknown;if(!record(value)||!record(value.data)||typeof value.data.internal_enabled!=='boolean'||typeof value.data.external_enabled!=='boolean')throw new Error('分流配置响应无效') - return value.data as unknown as CatalogRoutingCapabilities -} -export async function routeCatalogFiles(input:CatalogRouteInput):Promise{ - const response=await fetch('/api/v1/source-catalog/route',{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':newOperationID()},body:JSON.stringify(input)});if(!response.ok)throw new Error(response.status===503?'对内/对外知识库尚未配置':`处理策略保存失败(HTTP ${response.status})`) - const value=await response.json() as unknown;if(!record(value)||!record(value.data)||!count(value.data.selected_files)||!count(value.data.intents_recorded)||!count(value.data.fetch_queued)||!count(value.data.planned_publications)||!count(value.data.blocked_items)||!count(value.data.unbound_files))throw new Error('文件处理响应无效') - return value.data as unknown as CatalogRouteResult -} -export async function triggerCatalogRefresh(connectionID:string):Promise{ - const response=await fetch(`/api/v1/source-catalog/sources/${encodeURIComponent(connectionID)}/refresh`,{method:'POST',headers:{Accept:'application/json','Idempotency-Key':newOperationID()}});if(!response.ok)throw new Error(`启动实时刷新失败(HTTP ${response.status})`) - const value=await response.json() as unknown;if(!record(value)||!record(value.data)||typeof value.data.id!=='string'||value.data.type!=='source.catalog.refresh')throw new Error('实时刷新任务响应无效') - return value.data as unknown as Job +export async function fetchAllCatalogFolders( + connectionID: string, + parentID: string, + signal?: AbortSignal +): Promise { + const folders: CatalogNode[] = [] + const seen = new Set() + let offset = 0 + while (true) { + const page = await fetchCatalogNodes(connectionID, parentID, 100, offset, signal) + for (const node of page.items) { + if (node.node_type === 'folder' && !seen.has(node.node_id)) { + seen.add(node.node_id) + folders.push(node) + } + } + const next = page.offset + page.limit + if (next >= page.total) return folders + if (page.limit <= 0 || next <= offset) throw new Error('目录分页游标无效') + offset = next + } } -export type CatalogChangeAction='add'|'update'|'move'|'move_scope'|'delete'|'no_change' -export interface CatalogChangeItem{action:CatalogChangeAction;title:string;old_path:string;new_path:string;old_size_bytes?:number;new_size_bytes?:number;old_modified_at?:string;new_modified_at?:string;old_content_sha256?:string;new_content_sha256?:string;reason_code:string;seq:number;old_scope?:string;new_scope?:string;old_version_id?:string;new_version_id?:string} -export interface CatalogChangeSetDetail{id:string;connection_id:string;source_name:string;state:'planned'|'confirmed'|'applying'|'applied'|'cancelled'|'failed';add_count:number;update_count:number;move_count:number;move_scope_count:number;delete_count:number;no_change_count:number;created_at:string;items:CatalogChangeItem[];total:number;limit:number;offset:number} -const changeActions=new Set(['add','update','move','move_scope','delete','no_change']) -export async function fetchLatestCatalogChangeSet(connectionID:string,action:CatalogChangeAction|'',limit=20,offset=0,signal?:AbortSignal):Promise{ - const query=new URLSearchParams({connection_id:connectionID});if(action)query.set('action',action);query.set('limit',String(limit));query.set('offset',String(offset)) - const response=await fetch(`/api/v1/source-catalog/change-sets/latest?${query}`,{headers:{Accept:'application/json'},signal}) - if(!response.ok)throw new Error(response.status===404?'当前来源尚无快照差异':`加载快照差异失败(HTTP ${response.status})`) - const envelope=await response.json() as unknown;if(!record(envelope)||!record(envelope.data))throw new Error('快照差异响应无效') - const raw=envelope.data - if(typeof raw.id!=='string'||typeof raw.connection_id!=='string'||typeof raw.source_name!=='string'||typeof raw.state!=='string'||!['planned','confirmed','applying','applied','cancelled','failed'].includes(raw.state)||!count(raw.add_count)||!count(raw.update_count)||!count(raw.move_count)||!count(raw.move_scope_count)||!count(raw.delete_count)||!count(raw.no_change_count)||typeof raw.created_at!=='string'||!Array.isArray(raw.items)||!count(raw.total)||!count(raw.limit)||!count(raw.offset))throw new Error('快照差异响应无效') - const items=raw.items.map(item=>{if(!record(item)||typeof item.action!=='string'||!changeActions.has(item.action as CatalogChangeAction)||typeof item.title!=='string'||item.old_path!==undefined&&typeof item.old_path!=='string'||item.new_path!==undefined&&typeof item.new_path!=='string'||item.old_content_sha256!==undefined&&typeof item.old_content_sha256!=='string'||item.new_content_sha256!==undefined&&typeof item.new_content_sha256!=='string'||item.old_scope!==undefined&&typeof item.old_scope!=='string'||item.new_scope!==undefined&&typeof item.new_scope!=='string'||item.old_version_id!==undefined&&typeof item.old_version_id!=='string'||item.new_version_id!==undefined&&typeof item.new_version_id!=='string'||typeof item.reason_code!=='string'||!count(item.seq))throw new Error('快照差异条目无效');return {action:item.action as CatalogChangeAction,title:item.title,old_path:typeof item.old_path==='string'?item.old_path:'',new_path:typeof item.new_path==='string'?item.new_path:'',...(typeof item.old_size_bytes==='number'?{old_size_bytes:item.old_size_bytes}:{}),...(typeof item.new_size_bytes==='number'?{new_size_bytes:item.new_size_bytes}:{}),...(typeof item.old_modified_at==='string'?{old_modified_at:item.old_modified_at}:{}),...(typeof item.new_modified_at==='string'?{new_modified_at:item.new_modified_at}:{}),...(typeof item.old_content_sha256==='string'&&item.old_content_sha256?{old_content_sha256:item.old_content_sha256}:{}),...(typeof item.new_content_sha256==='string'&&item.new_content_sha256?{new_content_sha256:item.new_content_sha256}:{}),...(typeof item.old_scope==='string'&&item.old_scope?{old_scope:item.old_scope}:{}),...(typeof item.new_scope==='string'&&item.new_scope?{new_scope:item.new_scope}:{}),...(typeof item.old_version_id==='string'&&item.old_version_id?{old_version_id:item.old_version_id}:{}),...(typeof item.new_version_id==='string'&&item.new_version_id?{new_version_id:item.new_version_id}:{}),reason_code:item.reason_code,seq:item.seq}}) - return {id:raw.id,connection_id:raw.connection_id,source_name:raw.source_name,state:raw.state as CatalogChangeSetDetail['state'],add_count:raw.add_count,update_count:raw.update_count,move_count:raw.move_count,move_scope_count:raw.move_scope_count,delete_count:raw.delete_count,no_change_count:raw.no_change_count,created_at:raw.created_at,items,total:raw.total,limit:raw.limit,offset:raw.offset} +export interface CatalogRoutingCapabilities { + internal_enabled: boolean + external_enabled: boolean +} +export interface CatalogRouteInput { + connection_id: string + node_ids: string[] + policy: CatalogPolicy + reason: string +} +export interface CatalogRouteResult { + selected_files: number + intents_recorded: number + fetch_queued: number + planned_publications: number + blocked_items: number + unbound_files: number +} + +export async function fetchCatalogRoutingCapabilities(signal?: AbortSignal): Promise { + const response = await fetch('/api/v1/source-catalog/routing-capabilities', { + headers: { Accept: 'application/json' }, + signal, + }) + if (!response.ok) throw new Error(`加载分流配置失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if ( + !record(value) || + !record(value.data) || + typeof value.data.internal_enabled !== 'boolean' || + typeof value.data.external_enabled !== 'boolean' + ) + throw new Error('分流配置响应无效') + return value.data as unknown as CatalogRoutingCapabilities +} +export async function routeCatalogFiles(input: CatalogRouteInput): Promise { + const response = await fetch('/api/v1/source-catalog/route', { + method: 'POST', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, + body: JSON.stringify(input), + }) + if (!response.ok) + throw new Error(response.status === 503 ? '对内/对外知识库尚未配置' : `处理策略保存失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if ( + !record(value) || + !record(value.data) || + !count(value.data.selected_files) || + !count(value.data.intents_recorded) || + !count(value.data.fetch_queued) || + !count(value.data.planned_publications) || + !count(value.data.blocked_items) || + !count(value.data.unbound_files) + ) + throw new Error('文件处理响应无效') + return value.data as unknown as CatalogRouteResult +} +export async function triggerCatalogRefresh(connectionID: string): Promise { + const response = await fetch(`/api/v1/source-catalog/sources/${encodeURIComponent(connectionID)}/refresh`, { + method: 'POST', + headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() }, + }) + if (!response.ok) throw new Error(`启动实时刷新失败(HTTP ${response.status})`) + const value = (await response.json()) as unknown + if ( + !record(value) || + !record(value.data) || + typeof value.data.id !== 'string' || + value.data.type !== 'source.catalog.refresh' + ) + throw new Error('实时刷新任务响应无效') + return value.data as unknown as Job +} + +export type CatalogChangeAction = 'add' | 'update' | 'move' | 'move_scope' | 'delete' | 'no_change' +export interface CatalogChangeItem { + action: CatalogChangeAction + title: string + old_path: string + new_path: string + old_size_bytes?: number + new_size_bytes?: number + old_modified_at?: string + new_modified_at?: string + old_content_sha256?: string + new_content_sha256?: string + reason_code: string + seq: number + old_scope?: string + new_scope?: string + old_version_id?: string + new_version_id?: string +} +export interface CatalogChangeSetDetail { + id: string + connection_id: string + source_name: string + state: 'planned' | 'confirmed' | 'applying' | 'applied' | 'cancelled' | 'failed' + add_count: number + update_count: number + move_count: number + move_scope_count: number + delete_count: number + no_change_count: number + created_at: string + items: CatalogChangeItem[] + total: number + limit: number + offset: number +} +const changeActions = new Set(['add', 'update', 'move', 'move_scope', 'delete', 'no_change']) +export async function fetchLatestCatalogChangeSet( + connectionID: string, + action: CatalogChangeAction | '', + limit = 20, + offset = 0, + signal?: AbortSignal +): Promise { + const query = new URLSearchParams({ connection_id: connectionID }) + if (action) query.set('action', action) + query.set('limit', String(limit)) + query.set('offset', String(offset)) + const response = await fetch(`/api/v1/source-catalog/change-sets/latest?${query}`, { + headers: { Accept: 'application/json' }, + signal, + }) + if (!response.ok) + throw new Error(response.status === 404 ? '当前来源尚无快照差异' : `加载快照差异失败(HTTP ${response.status})`) + const envelope = (await response.json()) as unknown + if (!record(envelope) || !record(envelope.data)) throw new Error('快照差异响应无效') + const raw = envelope.data + if ( + typeof raw.id !== 'string' || + typeof raw.connection_id !== 'string' || + typeof raw.source_name !== 'string' || + typeof raw.state !== 'string' || + !['planned', 'confirmed', 'applying', 'applied', 'cancelled', 'failed'].includes(raw.state) || + !count(raw.add_count) || + !count(raw.update_count) || + !count(raw.move_count) || + !count(raw.move_scope_count) || + !count(raw.delete_count) || + !count(raw.no_change_count) || + typeof raw.created_at !== 'string' || + !Array.isArray(raw.items) || + !count(raw.total) || + !count(raw.limit) || + !count(raw.offset) + ) + throw new Error('快照差异响应无效') + const items = raw.items.map((item) => { + if ( + !record(item) || + typeof item.action !== 'string' || + !changeActions.has(item.action as CatalogChangeAction) || + typeof item.title !== 'string' || + (item.old_path !== undefined && typeof item.old_path !== 'string') || + (item.new_path !== undefined && typeof item.new_path !== 'string') || + (item.old_content_sha256 !== undefined && typeof item.old_content_sha256 !== 'string') || + (item.new_content_sha256 !== undefined && typeof item.new_content_sha256 !== 'string') || + (item.old_scope !== undefined && typeof item.old_scope !== 'string') || + (item.new_scope !== undefined && typeof item.new_scope !== 'string') || + (item.old_version_id !== undefined && typeof item.old_version_id !== 'string') || + (item.new_version_id !== undefined && typeof item.new_version_id !== 'string') || + typeof item.reason_code !== 'string' || + !count(item.seq) + ) + throw new Error('快照差异条目无效') + return { + action: item.action as CatalogChangeAction, + title: item.title, + old_path: typeof item.old_path === 'string' ? item.old_path : '', + new_path: typeof item.new_path === 'string' ? item.new_path : '', + ...(typeof item.old_size_bytes === 'number' ? { old_size_bytes: item.old_size_bytes } : {}), + ...(typeof item.new_size_bytes === 'number' ? { new_size_bytes: item.new_size_bytes } : {}), + ...(typeof item.old_modified_at === 'string' ? { old_modified_at: item.old_modified_at } : {}), + ...(typeof item.new_modified_at === 'string' ? { new_modified_at: item.new_modified_at } : {}), + ...(typeof item.old_content_sha256 === 'string' && item.old_content_sha256 + ? { old_content_sha256: item.old_content_sha256 } + : {}), + ...(typeof item.new_content_sha256 === 'string' && item.new_content_sha256 + ? { new_content_sha256: item.new_content_sha256 } + : {}), + ...(typeof item.old_scope === 'string' && item.old_scope ? { old_scope: item.old_scope } : {}), + ...(typeof item.new_scope === 'string' && item.new_scope ? { new_scope: item.new_scope } : {}), + ...(typeof item.old_version_id === 'string' && item.old_version_id + ? { old_version_id: item.old_version_id } + : {}), + ...(typeof item.new_version_id === 'string' && item.new_version_id + ? { new_version_id: item.new_version_id } + : {}), + reason_code: item.reason_code, + seq: item.seq, + } + }) + return { + id: raw.id, + connection_id: raw.connection_id, + source_name: raw.source_name, + state: raw.state as CatalogChangeSetDetail['state'], + add_count: raw.add_count, + update_count: raw.update_count, + move_count: raw.move_count, + move_scope_count: raw.move_scope_count, + delete_count: raw.delete_count, + no_change_count: raw.no_change_count, + created_at: raw.created_at, + items, + total: raw.total, + limit: raw.limit, + offset: raw.offset, + } } diff --git a/web/src/sourceCatalogBrowser.css b/web/src/sourceCatalogBrowser.css index 25fd460..a350571 100644 --- a/web/src/sourceCatalogBrowser.css +++ b/web/src/sourceCatalogBrowser.css @@ -1,42 +1,848 @@ -.catalog-format-filter{border-bottom:1px solid var(--border-base)}.catalog-format-filter>summary{cursor:pointer;padding:12px 16px;color:var(--ink-mute);font-size:12px}.catalog-format-filter>summary:focus-visible{outline:2px solid var(--c-run);outline-offset:-2px} -.catalog-browser{max-width:1800px}.catalog-layout{display:grid;grid-template-columns:285px minmax(0,1fr);gap:18px;align-items:start}.catalog-sources,.catalog-content{min-width:0;border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.catalog-sources{max-height:calc(100vh - 220px);overflow:auto;padding:12px}.catalog-sources h2{margin:4px 8px 12px;color:var(--ink-base);font-size:13px}.catalog-source{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;margin:4px 0;border:1px solid transparent;border-radius:9px;padding:11px;background:transparent;box-shadow:none;color:var(--ink-base);text-align:left}.catalog-source:hover{background:var(--bg-soft)}.catalog-source.active{border-color:var(--c-run-border);background:var(--c-run-bg);color:var(--c-run)}.catalog-source>span{display:grid;min-width:0;gap:5px}.catalog-source b{overflow-wrap:anywhere;font-size:12px}.catalog-source small{color:var(--ink-mute);font-size:10px}.catalog-source strong{flex:0 0 auto;font-size:12px}.catalog-directory-tree{margin-top:14px;border-top:1px solid var(--border-base);padding-top:12px}.catalog-directory-tree h3{margin:0 8px 8px;color:var(--ink-base);font-size:11px}.catalog-directory-tree ul{display:grid;gap:2px;margin:0;padding:0;list-style:none}.catalog-directory-tree ul[role="group"]{margin-left:16px;border-left:1px solid var(--border-base);padding-left:5px}.catalog-tree-row{display:grid;grid-template-columns:24px minmax(0,1fr);align-items:center;gap:2px}.catalog-tree-toggle,.catalog-tree-name{border:0;background:transparent;box-shadow:none;color:var(--ink-mute)}.catalog-tree-toggle{display:grid;width:24px;height:24px;place-items:center;padding:0;border-radius:5px;font-weight:800}.catalog-tree-toggle:hover{background:#e9f4fb}.catalog-tree-name{overflow:hidden;padding:5px 4px;text-align:left;text-overflow:ellipsis;white-space:nowrap}.catalog-tree-name:hover{color:var(--c-run);text-decoration:underline}.catalog-breadcrumbs{display:flex;min-height:48px;align-items:center;gap:5px;overflow-x:auto;border-bottom:1px solid var(--border-base);padding:8px 16px;white-space:nowrap}.catalog-breadcrumbs span{display:flex;align-items:center;gap:5px}.catalog-breadcrumbs i{color:var(--ink-faint);font-style:normal}.catalog-breadcrumbs button{max-width:320px;overflow:hidden;border:0;padding:6px 8px;background:transparent;box-shadow:none;color:var(--c-run);text-overflow:ellipsis;white-space:nowrap}.catalog-breadcrumbs span:last-child button{border-radius:6px;background:#eaf4fc;color:var(--c-run);font-weight:700}.catalog-summary{display:flex;align-items:center;gap:20px;border-bottom:1px solid var(--border-base);padding:14px 18px;color:var(--ink-mute);font-size:12px}.catalog-summary>div{display:grid;min-width:220px;margin-right:auto;gap:4px}.catalog-summary strong{color:var(--ink-strong);font-size:16px}.catalog-summary small{color:var(--ink-mute);font-size:10px}.catalog-table-wrap{max-height:calc(100vh - 390px);overflow:auto} -.root-file-notice{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--border-base);padding:9px 18px;background:var(--c-warn-bg);color:var(--c-warn);font-size:11px}.root-file-notice button{flex:0 0 auto;border:1px solid var(--c-warn-border);padding:6px 9px;background:var(--bg-panel);box-shadow:none;color:var(--c-warn)}.catalog-table .scope-badge{white-space:nowrap} -.catalog-back-row{border-bottom:1px solid var(--border-base);padding:8px 16px}.catalog-back-row button{border:0;padding:6px 8px;background:transparent;box-shadow:none;color:var(--c-run)}.snapshot-timestamp{padding:10px 16px;color:var(--ink-mute);font-size:10px;text-align:right} -.catalog-routing{display:grid;gap:9px;border-bottom:1px solid var(--border-base);padding:11px 16px;background:var(--bg-soft)}.routing-fields,.routing-actions{display:flex;flex-wrap:wrap;align-items:end;gap:9px}.routing-fields label{display:grid;gap:4px;color:var(--ink-mute);font-size:9px}.routing-fields input{border:1px solid var(--border-strong);border-radius:6px;padding:7px}.routing-check{display:flex!important;align-items:center;gap:5px;padding-bottom:7px}.routing-actions span{margin-right:auto;color:var(--ink-mute);font-size:10px}.routing-actions button{padding:7px 9px}.catalog-routing p{margin:0;border-radius:6px;padding:7px;background:var(--c-done-bg);color:var(--c-done);font-size:10px}.catalog-file-routing{display:grid;gap:6px}.catalog-file-routing .catalog-file{align-items:center}.catalog-file-routing select{width:max-content;max-width:100%;border:1px solid var(--border-strong);border-radius:6px;padding:5px;background:var(--bg-panel);color:var(--ink-base);font-size:9px}.catalog-file-routing small{color:var(--c-warn);font-size:9px} -.catalog-refresh-progress{display:grid;grid-template-columns:minmax(220px,1fr) minmax(180px,2fr) auto;align-items:center;gap:12px;margin-bottom:14px;border:1px solid var(--c-run-border);border-radius:10px;padding:10px 14px;background:var(--c-run-bg)}.catalog-refresh-progress>div{display:grid;gap:3px}.catalog-refresh-progress strong{color:var(--c-run);font-size:11px}.catalog-refresh-progress span,.catalog-refresh-progress small{color:var(--ink-mute);font-size:9px}.catalog-refresh-progress progress{width:100%;height:12px}.catalog-refresh-progress.completed{border-color:var(--c-done-border);background:var(--c-done-bg)}.catalog-refresh-progress.failed{border-color:var(--c-fail-border);background:var(--c-fail-bg)}@media(max-width:700px){.catalog-refresh-progress{grid-template-columns:1fr}.routing-fields{align-items:stretch;flex-direction:column}} -.routing-actions button:disabled,.catalog-file-routing select:disabled{cursor:not-allowed;border-color:var(--border-base);background:var(--bg-soft);color:var(--ink-faint);box-shadow:none}.snapshot-timestamp{color:var(--ink-base);font-size:11px;font-weight:600}.catalog-table tbody tr{scroll-margin-top:42px}.catalog-table{width:100%;table-layout:fixed}.catalog-table thead th{position:sticky;z-index:2;top:0;background:var(--bg-soft)}.catalog-table th,.catalog-table td{padding:12px 10px;white-space:normal;overflow-wrap:anywhere;font-size:11px}.catalog-table th:nth-child(1){width:32%}.catalog-table th:nth-child(2){width:8%}.catalog-table th:nth-child(3){width:15%}.catalog-table th:nth-child(4){width:9%}.catalog-table th:nth-child(5){width:16%}.catalog-table th:nth-child(6){width:20%}.catalog-name{display:flex;align-items:flex-start;gap:7px;border:0;padding:0;background:transparent;box-shadow:none;color:var(--c-run);text-align:left;line-height:1.5}.catalog-name:hover{text-decoration:underline}.catalog-file{display:flex;align-items:flex-start;gap:7px;color:var(--ink-base);line-height:1.5}.catalog-table td>span:not(.scope-badge){display:block}.catalog-table td small{display:block;margin-top:4px;color:var(--ink-mute)}.problem-text{color:var(--c-warn)!important}.scope-badge.mixed{background:var(--c-run-bg);color:var(--c-run)}.scope-badge.unknown{background:var(--bg-soft);color:var(--ink-mute)}@media(max-width:1100px){.catalog-layout{grid-template-columns:220px minmax(0,1fr)}.catalog-summary{flex-wrap:wrap}.catalog-summary>div{width:100%;margin:0}.catalog-table{min-width:800px}}@media(max-width:800px){.catalog-layout{grid-template-columns:1fr}.catalog-sources{max-height:240px}.catalog-table-wrap{max-height:520px}} -.routing-actions label{display:flex;align-items:center;gap:7px;color:var(--ink-mute);font-size:10px;font-weight:700}.routing-actions select,.catalog-folder-routing select{border:1px solid var(--border-strong);border-radius:7px;padding:7px 9px;background:var(--bg-panel);color:var(--ink-base);font:inherit}.blocked-policy-note{color:var(--c-warn);font-size:10px;line-height:1.5}.catalog-folder-routing{display:grid;gap:7px}.catalog-folder-routing select{width:max-content;max-width:100%;font-size:9px}.catalog-folder-routing small{color:var(--ink-mute)!important;font-size:9px}.scope-badge.both{background:var(--c-run-bg);color:var(--c-run)}.scope-badge.blocked{background:var(--c-fail-bg);color:var(--c-fail)} -.catalog-pathbar{display:flex;align-items:center;gap:10px;min-height:48px;border-bottom:1px solid var(--border-base);padding:8px 16px;background:var(--bg-panel)}.catalog-back-button{display:grid;flex:0 0 auto;width:30px;height:30px;place-items:center;border:1px solid var(--border-strong);border-radius:7px;padding:0;background:var(--bg-panel);color:var(--c-run);box-shadow:none;font-size:18px}.catalog-back-button:hover:not(:disabled){background:var(--c-run-bg)}.catalog-pathbar nav{display:flex;min-width:0;align-items:center;gap:4px;overflow-x:auto;white-space:nowrap}.catalog-pathbar nav span{display:flex;min-width:0;align-items:center;gap:4px}.catalog-pathbar nav i{color:var(--ink-faint);font-style:normal}.catalog-pathbar nav button{overflow:hidden;border:0;border-radius:6px;padding:6px 7px;background:transparent;color:var(--c-run);box-shadow:none;text-overflow:ellipsis;white-space:nowrap}.catalog-pathbar nav button:hover:not(:disabled){background:var(--c-run-bg)}.catalog-pathbar nav button.current{color:var(--ink-base);font-weight:700}.catalog-pathbar nav button:disabled{cursor:default;background:transparent;color:var(--ink-base)} -.catalog-policy-cell{display:grid;gap:6px;justify-items:start}.catalog-policy-cell select{max-width:100%;border:1px solid var(--border-strong);border-radius:7px;padding:6px 8px;background:var(--bg-panel);color:var(--ink-base);font-size:10px}.catalog-policy-cell small{min-height:14px;color:var(--ink-mute);font-size:9px}.catalog-table th:nth-child(1){width:32%}.catalog-table th:nth-child(2){width:8%}.catalog-table th:nth-child(3){width:15%}.catalog-table th:nth-child(4){width:9%}.catalog-table th:nth-child(5){width:16%}.catalog-table th:nth-child(6){width:20%} -.routing-actions .blocked-policy-button{border-color:var(--c-fail-border);background:var(--c-fail-bg);color:var(--c-fail)}.routing-actions .blocked-policy-button:hover:not(:disabled){background:var(--c-fail-bg)} -.catalog-node-control{display:flex;align-items:flex-start;gap:7px}.catalog-node-control input{margin-top:4px;flex:0 0 auto} -.routing-actions .internal-policy-button{border-color:var(--c-done);background:var(--c-done);color:var(--bg-panel)}.routing-actions .internal-policy-button:hover:not(:disabled){background:var(--c-done)}.routing-actions .external-policy-button{border-color:var(--c-warn);background:var(--c-warn);color:var(--bg-panel)}.routing-actions .external-policy-button:hover:not(:disabled){background:var(--c-warn)}.routing-actions .blocked-policy-button{border-color:var(--c-fail);background:var(--c-fail);color:var(--bg-panel)}.routing-actions .blocked-policy-button:hover:not(:disabled){background:var(--c-fail)} -.catalog-policy-cell .scope-badge.internal{background:var(--c-done-bg);color:var(--c-done)}.catalog-policy-cell .scope-badge.external{background:var(--c-warn-bg);color:var(--c-warn)}.catalog-policy-cell .scope-badge.blocked{background:var(--c-fail-bg);color:var(--c-fail)} -.catalog-policy-actions{display:flex;align-items:flex-start;gap:8px;margin-left:auto}.blocked-policy-stack{display:grid;gap:4px}.blocked-policy-stack .selected-count{margin:0;color:var(--ink-mute);font-size:10px;line-height:1.2;text-align:center;white-space:nowrap} -.snapshot-history{margin:12px 0;border:1px solid #d8e3f0;border-radius:10px;padding:14px 16px;background:var(--bg-soft)} -.snapshot-history header{display:flex;align-items:center;gap:12px;flex-wrap:wrap} -.snapshot-history header h2{margin:0;font-size:16px} -.snapshot-history header p{margin:0;flex:1;color:var(--ink-mute);font-size:13px} -.snapshot-history-list{list-style:none;margin:10px 0 0;padding:0;display:flex;flex-direction:column;gap:6px} -.snapshot-history-list li{display:flex;align-items:center;gap:12px;padding:8px 10px;border:1px solid var(--border-base);border-radius:8px;background:var(--bg-panel)} -.snapshot-history-list li>div{flex:1;display:flex;align-items:center;gap:8px;flex-wrap:wrap} -.snapshot-history-list small{width:100%;color:var(--ink-mute)} -.snapshot-history-table{margin-top:12px} -.catalog-history-button{margin-left:auto} -.catalog-refresh-detail{display:flex;gap:16px;flex-wrap:wrap;margin-top:6px;color:var(--ink-base);font-size:11px} -.catalog-refresh-pill{display:flex;align-items:center;gap:8px;width:max-content;margin:8px 0;padding:7px 12px;border:1px solid var(--c-run-border);border-radius:999px;background:#eef6fc;color:var(--ink-base);font:inherit;font-size:11px;font-weight:700;box-shadow:none} -.catalog-refresh-pill:hover{background:var(--c-run-bg)} -.pill-dot{width:8px;height:8px;border-radius:50%;background:var(--c-run);display:inline-block} -.pill-dot.retry{background:var(--c-warn)} -.catalog-refresh-hide{margin-left:auto;border:0;background:transparent;color:#4c7d9e;font:inherit;font-size:11px;text-decoration:underline;padding:0 2px} -.catalog-refresh-failed-note{margin:6px 0 0;color:var(--c-fail);font-size:11px} +.catalog-format-filter { + border-bottom: 1px solid var(--border-base); +} +.catalog-format-filter > summary { + cursor: pointer; + padding: 12px 16px; + color: var(--ink-mute); + font-size: 12px; +} +.catalog-format-filter > summary:focus-visible { + outline: 2px solid var(--c-run); + outline-offset: -2px; +} +.catalog-browser { + max-width: 1800px; +} +.catalog-layout { + display: grid; + grid-template-columns: 285px minmax(0, 1fr); + gap: 18px; + align-items: start; +} +.catalog-sources, +.catalog-content { + min-width: 0; + border: 1px solid var(--border-base); + border-radius: 14px; + background: var(--bg-panel); +} +.catalog-sources { + max-height: calc(100vh - 220px); + overflow: auto; + padding: 12px; +} +.catalog-sources h2 { + margin: 4px 8px 12px; + color: var(--ink-base); + font-size: 13px; +} +.catalog-source { + display: flex; + width: 100%; + align-items: center; + justify-content: space-between; + gap: 10px; + margin: 4px 0; + border: 1px solid transparent; + border-radius: 9px; + padding: 11px; + background: transparent; + box-shadow: none; + color: var(--ink-base); + text-align: left; +} +.catalog-source:hover { + background: var(--bg-soft); +} +.catalog-source.active { + border-color: var(--c-run-border); + background: var(--c-run-bg); + color: var(--c-run); +} +.catalog-source > span { + display: grid; + min-width: 0; + gap: 5px; +} +.catalog-source b { + overflow-wrap: anywhere; + font-size: 12px; +} +.catalog-source small { + color: var(--ink-mute); + font-size: 10px; +} +.catalog-source strong { + flex: 0 0 auto; + font-size: 12px; +} +.catalog-directory-tree { + margin-top: 14px; + border-top: 1px solid var(--border-base); + padding-top: 12px; +} +.catalog-directory-tree h3 { + margin: 0 8px 8px; + color: var(--ink-base); + font-size: 11px; +} +.catalog-directory-tree ul { + display: grid; + gap: 2px; + margin: 0; + padding: 0; + list-style: none; +} +.catalog-directory-tree ul[role='group'] { + margin-left: 16px; + border-left: 1px solid var(--border-base); + padding-left: 5px; +} +.catalog-tree-row { + display: grid; + grid-template-columns: 24px minmax(0, 1fr); + align-items: center; + gap: 2px; +} +.catalog-tree-toggle, +.catalog-tree-name { + border: 0; + background: transparent; + box-shadow: none; + color: var(--ink-mute); +} +.catalog-tree-toggle { + display: grid; + width: 24px; + height: 24px; + place-items: center; + padding: 0; + border-radius: 5px; + font-weight: 800; +} +.catalog-tree-toggle:hover { + background: var(--c-run-bg); +} +.catalog-tree-name { + overflow: hidden; + padding: 5px 4px; + text-align: left; + text-overflow: ellipsis; + white-space: nowrap; +} +.catalog-tree-name:hover { + color: var(--c-run); + text-decoration: underline; +} +.catalog-breadcrumbs { + display: flex; + min-height: 48px; + align-items: center; + gap: 5px; + overflow-x: auto; + border-bottom: 1px solid var(--border-base); + padding: 8px 16px; + white-space: nowrap; +} +.catalog-breadcrumbs span { + display: flex; + align-items: center; + gap: 5px; +} +.catalog-breadcrumbs i { + color: var(--ink-faint); + font-style: normal; +} +.catalog-breadcrumbs button { + max-width: 320px; + overflow: hidden; + border: 0; + padding: 6px 8px; + background: transparent; + box-shadow: none; + color: var(--c-run); + text-overflow: ellipsis; + white-space: nowrap; +} +.catalog-breadcrumbs span:last-child button { + border-radius: 6px; + background: var(--c-run-bg); + color: var(--c-run); + font-weight: 700; +} +.catalog-summary { + display: flex; + align-items: center; + gap: 20px; + border-bottom: 1px solid var(--border-base); + padding: 14px 18px; + color: var(--ink-mute); + font-size: 12px; +} +.catalog-summary > div { + display: grid; + min-width: 220px; + margin-right: auto; + gap: 4px; +} +.catalog-summary strong { + color: var(--ink-strong); + font-size: 16px; +} +.catalog-summary small { + color: var(--ink-mute); + font-size: 10px; +} +.catalog-table-wrap { + max-height: calc(100vh - 390px); + overflow: auto; +} +.root-file-notice { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + border-bottom: 1px solid var(--border-base); + padding: 9px 18px; + background: var(--c-warn-bg); + color: var(--c-warn); + font-size: 11px; +} +.root-file-notice button { + flex: 0 0 auto; + border: 1px solid var(--c-warn-border); + padding: 6px 9px; + background: var(--bg-panel); + box-shadow: none; + color: var(--c-warn); +} +.catalog-table .scope-badge { + white-space: nowrap; +} +.catalog-back-row { + border-bottom: 1px solid var(--border-base); + padding: 8px 16px; +} +.catalog-back-row button { + border: 0; + padding: 6px 8px; + background: transparent; + box-shadow: none; + color: var(--c-run); +} +.snapshot-timestamp { + padding: 10px 16px; + color: var(--ink-mute); + font-size: 10px; + text-align: right; +} +.catalog-routing { + display: grid; + gap: 9px; + border-bottom: 1px solid var(--border-base); + padding: 10px 16px; + background: var(--bg-panel); +} +.routing-fields { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: 9px; +} +.routing-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; +} +.routing-fields label { + display: grid; + gap: 4px; + color: var(--ink-mute); + font-size: 9px; +} +.routing-fields input { + border: 1px solid var(--border-strong); + border-radius: 6px; + padding: 7px; +} +.routing-check { + display: flex !important; + align-items: center; + gap: 6px; +} +.routing-actions span { + margin-right: auto; + color: var(--ink-mute); + font-size: 10px; +} +.routing-actions button { + padding: 5px 12px; +} +.catalog-routing p { + margin: 0; + border-radius: 6px; + padding: 7px; + background: var(--c-done-bg); + color: var(--c-done); + font-size: 10px; +} +.catalog-file-routing { + display: grid; + gap: 6px; +} +.catalog-file-routing .catalog-file { + align-items: center; +} +.catalog-file-routing select { + width: max-content; + max-width: 100%; + border: 1px solid var(--border-strong); + border-radius: 6px; + padding: 5px; + background: var(--bg-panel); + color: var(--ink-base); + font-size: 9px; +} +.catalog-file-routing small { + color: var(--c-warn); + font-size: 9px; +} +.catalog-refresh-progress { + display: grid; + grid-template-columns: minmax(220px, 1fr) minmax(180px, 2fr) auto; + align-items: center; + gap: 12px; + margin-bottom: 14px; + border: 1px solid var(--c-run-border); + border-radius: 10px; + padding: 10px 14px; + background: var(--c-run-bg); +} +.catalog-refresh-progress > div { + display: grid; + gap: 3px; +} +.catalog-refresh-progress strong { + color: var(--c-run); + font-size: 11px; +} +.catalog-refresh-progress span, +.catalog-refresh-progress small { + color: var(--ink-mute); + font-size: 9px; +} +.catalog-refresh-progress progress { + width: 100%; + height: 12px; +} +.catalog-refresh-progress.completed { + border-color: var(--c-done-border); + background: var(--c-done-bg); +} +.catalog-refresh-progress.failed { + border-color: var(--c-fail-border); + background: var(--c-fail-bg); +} +@media (max-width: 700px) { + .catalog-refresh-progress { + grid-template-columns: 1fr; + } + .routing-fields { + align-items: stretch; + flex-direction: column; + } +} +.routing-actions button:disabled, +.catalog-file-routing select:disabled { + cursor: not-allowed; + border-color: var(--border-base); + background: var(--bg-soft); + color: var(--ink-faint); + box-shadow: none; +} +.snapshot-timestamp { + color: var(--ink-base); + font-size: 11px; + font-weight: 600; +} +.catalog-table tbody tr { + scroll-margin-top: 42px; +} +.catalog-table { + width: 100%; + table-layout: fixed; +} +.catalog-table thead th { + position: sticky; + z-index: 2; + top: 0; + background: var(--bg-soft); + color: var(--ink-mute); + font-weight: 500; + font-size: 11.5px; + letter-spacing: 0.02em; +} +.catalog-table th, +.catalog-table td { + padding: 11px 12px; + white-space: normal; + overflow-wrap: anywhere; + font-size: 12.5px; +} +.catalog-table tbody tr:hover { + background: var(--bg-hover); +} +.catalog-table th:nth-child(1) { + width: 32%; +} +.catalog-table th:nth-child(2) { + width: 8%; +} +.catalog-table th:nth-child(3) { + width: 15%; +} +.catalog-table th:nth-child(4) { + width: 9%; +} +.catalog-table th:nth-child(5) { + width: 16%; +} +.catalog-table th:nth-child(6) { + width: 20%; +} +.catalog-name { + display: flex; + align-items: flex-start; + gap: 8px; + border: 0; + padding: 0; + background: transparent; + box-shadow: none; + color: var(--ink-strong); + font-weight: 500; + text-align: left; + line-height: 1.5; +} +.catalog-name:hover:not(:disabled) { + border: 0; + background: transparent; + color: var(--c-run); +} +.catalog-file { + display: flex; + align-items: flex-start; + gap: 7px; + color: var(--ink-base); + line-height: 1.5; +} +.catalog-table td > span:not(.scope-badge) { + display: block; +} +.catalog-table td small { + display: block; + margin-top: 4px; + color: var(--ink-mute); +} +.problem-text { + color: var(--c-warn) !important; +} +.scope-badge.mixed { + background: var(--c-run-bg); + color: var(--c-run); +} +.scope-badge.unknown { + background: var(--bg-soft); + color: var(--ink-mute); +} +@media (max-width: 1100px) { + .catalog-layout { + grid-template-columns: 220px minmax(0, 1fr); + } + .catalog-summary { + flex-wrap: wrap; + } + .catalog-summary > div { + width: 100%; + margin: 0; + } + .catalog-table { + min-width: 800px; + } +} +@media (max-width: 800px) { + .catalog-layout { + grid-template-columns: 1fr; + } + .catalog-sources { + max-height: 240px; + } + .catalog-table-wrap { + max-height: 520px; + } +} +.routing-actions label { + display: flex; + align-items: center; + gap: 7px; + color: var(--ink-mute); + font-size: 10px; + font-weight: 700; +} +.routing-actions select, +.catalog-folder-routing select { + border: 1px solid var(--border-strong); + border-radius: 7px; + padding: 7px 9px; + background: var(--bg-panel); + color: var(--ink-base); + font: inherit; +} +.blocked-policy-note { + color: var(--c-warn); + font-size: 10px; + line-height: 1.5; +} +.catalog-folder-routing { + display: grid; + gap: 7px; +} +.catalog-folder-routing select { + width: max-content; + max-width: 100%; + font-size: 9px; +} +.catalog-folder-routing small { + color: var(--ink-mute) !important; + font-size: 9px; +} +.scope-badge.both { + background: var(--c-run-bg); + color: var(--c-run); +} +.scope-badge.blocked { + background: var(--c-fail-bg); + color: var(--c-fail); +} +.catalog-pathbar { + display: flex; + align-items: center; + gap: 10px; + min-height: 48px; + border-bottom: 1px solid var(--border-base); + padding: 8px 16px; + background: var(--bg-panel); +} +.catalog-back-button { + display: grid; + flex: 0 0 auto; + width: 30px; + height: 30px; + place-items: center; + border: 1px solid var(--border-strong); + border-radius: 7px; + padding: 0; + background: var(--bg-panel); + color: var(--c-run); + box-shadow: none; + font-size: 18px; +} +.catalog-back-button:hover:not(:disabled) { + background: var(--c-run-bg); +} +.catalog-pathbar nav { + display: flex; + min-width: 0; + align-items: center; + gap: 4px; + overflow-x: auto; + white-space: nowrap; +} +.catalog-pathbar nav span { + display: flex; + min-width: 0; + align-items: center; + gap: 4px; +} +.catalog-pathbar nav i { + color: var(--ink-faint); + font-style: normal; +} +.catalog-pathbar nav button { + overflow: hidden; + border: 0; + border-radius: 6px; + padding: 6px 7px; + background: transparent; + color: var(--c-run); + box-shadow: none; + text-overflow: ellipsis; + white-space: nowrap; +} +.catalog-pathbar nav button:hover:not(:disabled) { + background: var(--c-run-bg); +} +.catalog-pathbar nav button.current { + color: var(--ink-base); + font-weight: 700; +} +.catalog-pathbar nav button:disabled { + cursor: default; + background: transparent; + color: var(--ink-base); +} +.catalog-policy-cell { + display: grid; + gap: 6px; + justify-items: start; +} +.catalog-policy-cell select { + max-width: 100%; + border: 1px solid var(--border-strong); + border-radius: 7px; + padding: 6px 8px; + background: var(--bg-panel); + color: var(--ink-base); + font-size: 10px; +} +.catalog-policy-cell small { + min-height: 14px; + color: var(--ink-mute); + font-size: 9px; +} +.catalog-node-control { + display: flex; + align-items: flex-start; + gap: 7px; +} +.catalog-node-control input { + margin-top: 4px; + flex: 0 0 auto; +} +/* 策略按钮用浅底语义色:三种实心色块并排太抢眼,且与表格里的策略徽标同色同形,一眼对应 */ +.routing-actions .internal-policy-button { + border-color: var(--c-done-border); + background: var(--c-done-bg); + color: var(--c-done); +} +.routing-actions .external-policy-button { + border-color: var(--c-warn-border); + background: var(--c-warn-bg); + color: var(--c-warn); +} +.routing-actions .blocked-policy-button { + border-color: var(--c-fail-border); + background: var(--c-fail-bg); + color: var(--c-fail); +} +.routing-actions .internal-policy-button:hover:not(:disabled) { + border-color: var(--c-done); + background: var(--c-done-bg); +} +.routing-actions .external-policy-button:hover:not(:disabled) { + border-color: var(--c-warn); + background: var(--c-warn-bg); +} +.routing-actions .blocked-policy-button:hover:not(:disabled) { + border-color: var(--c-fail); + background: var(--c-fail-bg); +} +.catalog-policy-cell .scope-badge.internal { + background: var(--c-done-bg); + color: var(--c-done); +} +.catalog-policy-cell .scope-badge.external { + background: var(--c-warn-bg); + color: var(--c-warn); +} +.catalog-policy-cell .scope-badge.blocked { + background: var(--c-fail-bg); + color: var(--c-fail); +} +.catalog-policy-actions { + display: flex; + align-items: center; + gap: 8px; + margin-left: auto; +} +.routing-actions .selected-count { + color: var(--ink-mute); + font-size: 12px; + white-space: nowrap; + font-variant-numeric: tabular-nums; +} +/* 只有真的选中了才变成强调色,与解析监控的批量条同一规则 */ +.catalog-routing.has-selection { + border-bottom-color: var(--c-run-border); + background: var(--c-run-bg); +} +.catalog-routing.has-selection .selected-count { + color: var(--c-run); + font-weight: 600; +} +.catalog-icon { + width: 16px; + height: 16px; + flex: none; + margin-top: 1px; + background: currentColor; + -webkit-mask: var(--icon) center / contain no-repeat; + mask: var(--icon) center / contain no-repeat; +} +.catalog-icon.folder { + color: var(--c-run); + --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M1.5 4A1.5 1.5 0 0 1 3 2.5h3.1l1.6 1.6H13A1.5 1.5 0 0 1 14.5 5.6V12A1.5 1.5 0 0 1 13 13.5H3A1.5 1.5 0 0 1 1.5 12z'/%3E%3C/svg%3E"); + opacity: 0.85; +} +.catalog-icon.file { + color: var(--ink-faint); + --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M4 1.5h5l3.5 3.5v8A1.5 1.5 0 0 1 11 14.5H4A1.5 1.5 0 0 1 2.5 13V3A1.5 1.5 0 0 1 4 1.5zm4.5 1v3h3' fill='none' stroke='black' stroke-width='1.3' stroke-linejoin='round'/%3E%3C/svg%3E"); +} +.snapshot-history { + margin: 12px 0; + border: 1px solid var(--border-base); + border-radius: 10px; + padding: 14px 16px; + background: var(--bg-soft); +} +.snapshot-history header { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; +} +.snapshot-history header h2 { + margin: 0; + font-size: 16px; +} +.snapshot-history header p { + margin: 0; + flex: 1; + color: var(--ink-mute); + font-size: 13px; +} +.snapshot-history-list { + list-style: none; + margin: 10px 0 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 6px; +} +.snapshot-history-list li { + display: flex; + align-items: center; + gap: 12px; + padding: 8px 10px; + border: 1px solid var(--border-base); + border-radius: 8px; + background: var(--bg-panel); +} +.snapshot-history-list li > div { + flex: 1; + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +.snapshot-history-list small { + width: 100%; + color: var(--ink-mute); +} +.snapshot-history-table { + margin-top: 12px; +} +.catalog-history-button { + margin-left: auto; +} +.catalog-refresh-detail { + display: flex; + gap: 16px; + flex-wrap: wrap; + margin-top: 6px; + color: var(--ink-base); + font-size: 11px; +} +.catalog-refresh-pill { + display: flex; + align-items: center; + gap: 8px; + width: max-content; + margin: 8px 0; + padding: 7px 12px; + border: 1px solid var(--c-run-border); + border-radius: 999px; + background: var(--c-run-bg); + color: var(--ink-base); + font: inherit; + font-size: 11px; + font-weight: 700; + box-shadow: none; +} +.catalog-refresh-pill:hover { + background: var(--c-run-bg); +} +.pill-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--c-run); + display: inline-block; +} +.pill-dot.retry { + background: var(--c-warn); +} +.catalog-refresh-hide { + margin-left: auto; + border: 0; + background: transparent; + color: var(--ink-mute); + font: inherit; + font-size: 11px; + text-decoration: underline; + padding: 0 2px; +} +.catalog-refresh-failed-note { + margin: 6px 0 0; + color: var(--c-fail); + font-size: 11px; +} /* 首次扫描中的来源:还没快照,但立刻出现在列表里并显示进度。 */ -.catalog-source.scanning strong { color: #b45309; } -.catalog-scanning-state { display: flex; flex-direction: column; gap: 10px; padding: 18px; border: 1px solid var(--border, #e3e8ec); border-radius: 10px; background: var(--card, #fff); } -.catalog-scanning-state > div { display: flex; align-items: baseline; gap: 10px; } -.catalog-scanning-state strong { font-size: 15px; } -.catalog-scanning-state span { color: var(--muted-foreground, #5b6773); font-size: 13px; } -.catalog-scanning-state progress { width: 100%; height: 10px; } -.catalog-scanning-state p { margin: 0; font-size: 13px; } -.catalog-scanning-state small { color: var(--muted-foreground, #5b6773); font-size: 12px; } +.catalog-source.scanning strong { + color: #b45309; +} +.catalog-scanning-state { + display: flex; + flex-direction: column; + gap: 10px; + padding: 18px; + border: 1px solid var(--border-base); + border-radius: 10px; + background: var(--bg-panel); +} +.catalog-scanning-state > div { + display: flex; + align-items: baseline; + gap: 10px; +} +.catalog-scanning-state strong { + font-size: 15px; +} +.catalog-scanning-state span { + color: var(--ink-mute); + font-size: 13px; +} +.catalog-scanning-state progress { + width: 100%; + height: 10px; +} +.catalog-scanning-state p { + margin: 0; + font-size: 13px; +} +.catalog-scanning-state small { + color: var(--ink-mute); + font-size: 12px; +} diff --git a/web/src/sourceLinkManager.css b/web/src/sourceLinkManager.css index cf7a074..77102cb 100644 --- a/web/src/sourceLinkManager.css +++ b/web/src/sourceLinkManager.css @@ -1 +1,178 @@ -.source-link-manager{max-width:1500px}.source-link-layout{display:grid;grid-template-columns:300px minmax(0,1fr);gap:18px}.source-link-list,.source-link-editor{min-width:0;border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.source-link-list{max-height:calc(100vh - 260px);overflow:auto;padding:12px}.source-link-list h2{margin:5px 8px 12px;color:var(--ink-base);font-size:13px}.source-link-list button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;border:1px solid transparent;border-radius:9px;padding:11px;background:transparent;box-shadow:none;color:var(--ink-base);text-align:left}.source-link-list button.active{border-color:var(--c-run-border);background:var(--c-run-bg);color:var(--c-run)}.source-link-list button>span{display:grid;gap:4px}.source-link-list small{color:var(--ink-mute);font-size:10px}.source-link-list strong{font-size:10px}.source-link-editor{padding-bottom:18px}.source-link-title{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--border-base);padding:15px 18px}.source-link-title>div{display:grid;gap:4px}.source-link-title h2{margin:0;color:var(--ink-base);font-size:16px}.source-link-title span{color:var(--ink-mute);font-size:10px}.connection-unverified{border-radius:6px;padding:5px 7px;background:var(--c-warn-bg)!important;color:var(--c-warn)!important;font-weight:700}.source-link-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:18px}.source-link-fields label{display:grid;gap:6px;color:var(--ink-base);font-size:11px}.source-link-fields input{min-width:0;border:1px solid var(--border-strong);border-radius:8px;padding:10px;background:var(--bg-panel);color:var(--ink-base)}.source-link-fields input:read-only,.source-link-fields input:disabled{background:var(--bg-soft);color:var(--ink-mute)}.source-link-boundary{display:flex;flex-wrap:wrap;gap:8px;margin:0 18px 14px}.source-link-boundary>*{border-radius:6px;padding:6px 8px;background:var(--border-soft);color:var(--ink-mute);font-size:10px}.validate-source-link{margin:0 18px}.validation-results{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:7px;margin:16px 18px;border:1px solid var(--c-done-border);border-radius:10px;padding:12px;background:var(--c-done-bg)}.validation-results div{display:grid;gap:3px}.validation-results span{color:var(--ink-mute);font-size:9px}.validation-results b{color:var(--c-done);font-size:10px}.validation-results small{grid-column:1/-1;color:var(--c-warn);font-size:9px}.credential-note{margin:15px 18px 0;border-top:1px solid var(--border-base);padding-top:13px;color:var(--ink-mute);font-size:10px;line-height:1.6}@media(max-width:900px){.source-link-layout{grid-template-columns:1fr}.source-link-list{max-height:260px}}@media(max-width:650px){.source-link-fields{grid-template-columns:1fr}.validation-results{grid-template-columns:1fr 1fr}} \ No newline at end of file +.source-link-manager { + max-width: 1500px; +} +.source-link-layout { + display: grid; + grid-template-columns: 300px minmax(0, 1fr); + gap: 18px; +} +.source-link-list, +.source-link-editor { + min-width: 0; + border: 1px solid var(--border-base); + border-radius: 14px; + background: var(--bg-panel); +} +.source-link-list { + max-height: calc(100vh - 260px); + overflow: auto; + padding: 12px; +} +.source-link-list h2 { + margin: 5px 8px 12px; + color: var(--ink-base); + font-size: 13px; +} +.source-link-list button { + display: flex; + width: 100%; + align-items: center; + justify-content: space-between; + gap: 10px; + border: 1px solid transparent; + border-radius: 9px; + padding: 11px; + background: transparent; + box-shadow: none; + color: var(--ink-base); + text-align: left; +} +.source-link-list button.active { + border-color: var(--c-run-border); + background: var(--c-run-bg); + color: var(--c-run); +} +.source-link-list button > span { + display: grid; + gap: 4px; +} +.source-link-list small { + color: var(--ink-mute); + font-size: 10px; +} +.source-link-list strong { + font-size: 10px; +} +.source-link-editor { + padding-bottom: 18px; +} +.source-link-title { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + border-bottom: 1px solid var(--border-base); + padding: 15px 18px; +} +.source-link-title > div { + display: grid; + gap: 4px; +} +.source-link-title h2 { + margin: 0; + color: var(--ink-base); + font-size: 16px; +} +.source-link-title span { + color: var(--ink-mute); + font-size: 10px; +} +.connection-unverified { + border-radius: 6px; + padding: 5px 7px; + background: var(--c-warn-bg) !important; + color: var(--c-warn) !important; + font-weight: 700; +} +.source-link-fields { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + padding: 18px; +} +.source-link-fields label { + display: grid; + gap: 6px; + color: var(--ink-base); + font-size: 11px; +} +.source-link-fields input { + min-width: 0; + border: 1px solid var(--border-strong); + border-radius: 8px; + padding: 10px; + background: var(--bg-panel); + color: var(--ink-base); +} +.source-link-fields input:read-only, +.source-link-fields input:disabled { + background: var(--bg-soft); + color: var(--ink-mute); +} +.source-link-boundary { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin: 0 18px 14px; +} +.source-link-boundary > * { + border-radius: 6px; + padding: 6px 8px; + background: var(--border-soft); + color: var(--ink-mute); + font-size: 10px; +} +.validate-source-link { + margin: 0 18px; +} +.validation-results { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 7px; + margin: 16px 18px; + border: 1px solid var(--c-done-border); + border-radius: 10px; + padding: 12px; + background: var(--c-done-bg); +} +.validation-results div { + display: grid; + gap: 3px; +} +.validation-results span { + color: var(--ink-mute); + font-size: 9px; +} +.validation-results b { + color: var(--c-done); + font-size: 10px; +} +.validation-results small { + grid-column: 1/-1; + color: var(--c-warn); + font-size: 9px; +} +.credential-note { + margin: 15px 18px 0; + border-top: 1px solid var(--border-base); + padding-top: 13px; + color: var(--ink-mute); + font-size: 10px; + line-height: 1.6; +} +@media (max-width: 900px) { + .source-link-layout { + grid-template-columns: 1fr; + } + .source-link-list { + max-height: 260px; + } +} +@media (max-width: 650px) { + .source-link-fields { + grid-template-columns: 1fr; + } + .validation-results { + grid-template-columns: 1fr 1fr; + } +} diff --git a/web/src/sourceSettingsAudit.ts b/web/src/sourceSettingsAudit.ts index 73cf6cf..9b1d434 100644 --- a/web/src/sourceSettingsAudit.ts +++ b/web/src/sourceSettingsAudit.ts @@ -38,6 +38,10 @@ export async function fetchSourceAudit(offset = 0, signal?: AbortSignal): Promis return data } export const sourceAuditActions: Record = { + credential_configured: '更新认证配置', + credential_rejected: '认证配置校验失败', + credential_test: '测试连接', + dws_authorization: '钉钉授权', created: '添加连接', settings_updated: '修改配置', paused: '暂停自动刷新', diff --git a/web/src/styles.css b/web/src/styles.css index 98f4ad9..472e280 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -1,75 +1,85 @@ /* ============================================================ - 知识治理平台 · 方向 A · Data-console - 冷灰白底、1px 细边、零阴影、等宽数字 + 知识治理平台 · 工作台视觉(配色取自越疆官网 dobot.cn) + 纯中性灰底与文字(不带蓝紫偏色,久看不累)、细边 + 极轻投影、等宽数字; + 全站只有一个强调色:越疆品牌钴蓝 #0039C8 彩色仅用于语义(红=失败、橙=停滞、蓝=处理中、绿=完成、灰=死信) ============================================================ */ :root { - /* 基础色板(A 风格) */ - --bg-page: #fafbfc; + --bg-page: #f7f8fc; --bg-panel: #ffffff; - --bg-soft: #f8fafc; - --bg-softer: #f3f6f9; - --bg-hover: #f3f7fa; - --bg-active: #eff4fd; + --bg-soft: #f8f9fb; + --bg-softer: #f2f3f5; + --bg-hover: #f5f6f9; + --bg-active: #edf1fb; - --border-strong: #d3dce3; - --border-base: #e3e8ec; - --border-soft: #eef2f6; + --border-strong: #d9d9d9; + --border-base: #e8e8e8; + --border-soft: #efeff2; - --ink-strong: #0f1720; - --ink-base: #16324f; - --ink-mute: #57687a; - --ink-faint: #8a98a4; + --ink-strong: #1d1d1f; + --ink-base: #333336; + --ink-mute: #6e6e73; + --ink-faint: #a6a6a8; /* 语义色 */ - --c-fail: #b91c1c; - --c-fail-bg: #fdecec; - --c-fail-border: #f2baba; + --c-fail: #c0362c; + --c-fail-bg: #fef3f2; + --c-fail-border: #fecdca; - --c-warn: #d97706; - --c-warn-bg: #fef3e2; - --c-warn-border: #f3d9a8; + --c-warn: #b54708; + --c-warn-bg: #fffaeb; + --c-warn-border: #fedf89; - --c-run: #2563eb; - --c-run-bg: #eff4fd; - --c-run-border: #c7d7f2; + --c-run: #0039c8; + --c-run-bg: #edf1fb; + --c-run-border: #bccbef; - --c-done: #059669; - --c-done-bg: #eefaf4; - --c-done-border: #bfe3d4; + --c-done: #067647; + --c-done-bg: #ecfdf3; + --c-done-border: #abefc6; - --c-dead: #6b7280; - --c-dead-bg: #f3f4f6; + --c-dead: #6e6e73; + --c-dead-bg: #f2f3f5; - --c-cyan: #0891b2; - --c-cyan-bg: #ddf7fb; + --c-cyan: #0e7090; + --c-cyan-bg: #e8f7fb; - /* 深侧栏(A 风格) */ - --side-bg: #0e1c2b; - --side-bg-active: #16324a; - --side-bg-hover: #152a3d; - --side-border: #1a2f44; - --side-accent: #2dd4bf; - --side-ink: #9fb6c6; - --side-ink-strong: #e8f2f8; - --side-ink-faint: #5b7789; + /* 侧栏与内容同一明度,靠细边与浅钴蓝选中态区分,长时间操作不刺眼 */ + --side-bg: #ffffff; + --side-bg-active: #edf1fb; + --side-bg-hover: #f5f6f9; + --side-border: #e8e8e8; + --side-accent: #0039c8; + --side-ink: #474747; + --side-ink-strong: #1d1d1f; + --side-ink-faint: #a6a6a8; + + /* 全站唯一的主操作色;以前主按钮借用深色侧栏底色,各模块又各自改成蓝/黑,出现三种"主按钮" */ + --c-primary: #0039c8; + --c-primary-hover: #002fa5; + --c-focus-ring: 0 0 0 3px rgb(0 57 200 / 15%); + + /* 卡片只用极轻投影托起,层级靠留白而不是色块 */ + --shadow-card: 0 1px 2px rgb(0 0 0 / 4%), 0 1px 3px rgb(0 0 0 / 3%); + --shadow-float: 0 12px 32px rgb(0 0 0 / 10%), 0 2px 6px rgb(0 0 0 / 5%); /* 字体 */ - --font-base: Inter, "Noto Sans SC", "PingFang SC", system-ui, sans-serif; - --font-mono: "IBM Plex Mono", "SF Mono", Menlo, Consolas, monospace; + --font-base: Inter, 'Noto Sans SC', 'PingFang SC', system-ui, sans-serif; + --font-mono: 'IBM Plex Mono', 'SF Mono', Menlo, Consolas, monospace; /* 圆角(A 风格:小圆角) */ - --r-sm: 3px; - --r-md: 4px; - --r-lg: 6px; + --r-sm: 4px; + --r-md: 6px; + --r-lg: 10px; } * { box-sizing: border-box; } -html, body { +html, +body { margin: 0; padding: 0; } @@ -79,7 +89,8 @@ body { background: var(--bg-page); color: var(--ink-strong); font-size: 13px; - line-height: 1.5; + line-height: 1.55; + letter-spacing: 0.005em; -webkit-font-smoothing: antialiased; font-synthesis: none; text-rendering: optimizeLegibility; @@ -93,20 +104,29 @@ body { button { border: 1px solid var(--border-strong); border-radius: var(--r-md); - padding: 5px 11px; - color: var(--ink-strong); + padding: 5px 12px; + color: var(--ink-base); background: var(--bg-panel); font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; - box-shadow: none; - transition: background 120ms ease, border-color 120ms ease, color 120ms ease; + box-shadow: 0 1px 2px rgb(0 0 0 / 4%); + transition: + background 120ms ease, + border-color 120ms ease, + color 120ms ease; } button:hover:not(:disabled) { background: var(--bg-soft); - border-color: #94a3b8; + border-color: var(--border-strong); + color: var(--ink-strong); +} + +button:focus-visible { + outline: none; + box-shadow: var(--c-focus-ring); } button:disabled { @@ -115,18 +135,19 @@ button:disabled { } button.primary, -button[type="submit"], +button[type='submit'], .primary-link { - background: var(--side-bg); - border-color: var(--side-bg); + background: var(--c-primary); + border-color: var(--c-primary); color: #fff; font-weight: 600; } button.primary:hover:not(:disabled), +button[type='submit']:hover:not(:disabled), .primary-link:hover { - background: #1a2f44; - border-color: #1a2f44; + background: var(--c-primary-hover); + border-color: var(--c-primary-hover); } /* ========== 代码与等宽 ========== */ @@ -161,7 +182,7 @@ code { padding: 18px 0; color: var(--side-ink); background: var(--side-bg); - border-right: 1px solid #0a141f; + border-right: 1px solid var(--side-border); box-shadow: none; } @@ -181,7 +202,7 @@ code { flex: none; place-items: center; border-radius: var(--r-md); - color: #04211d; + color: #fff; background: var(--side-accent); font-size: 13px; font-weight: 700; @@ -220,27 +241,32 @@ code { border: 1px solid transparent; border-radius: var(--r-md); padding: 9px 10px; - color: #8aa2b3; + color: var(--side-ink); background: transparent; box-shadow: none; font-weight: 500; font-size: 16px; min-height: 44px; text-align: left; - transition: background 120ms ease, color 120ms ease; + transition: + background 120ms ease, + color 120ms ease; } -.nav-item:hover { - color: #d9e8f1; +/* 必须带 :not(:disabled):全局 button:hover:not(:disabled) 特异性更高, + 少了它悬停会被刷成白底,选中项文字几乎看不见 */ +.nav-item:hover:not(:disabled) { + color: var(--side-ink-strong); background: var(--side-bg-hover); + border-color: transparent; } -.nav-item.active { +.nav-item.active, +.nav-item.active:hover:not(:disabled) { border-color: transparent; - color: #fff; + color: var(--side-accent); + font-weight: 600; background: var(--side-bg-active); - border-left: 2px solid var(--side-accent); - padding-left: 8px; } .nav-icon { @@ -249,10 +275,14 @@ code { height: 24px; flex: none; place-items: center; - color: var(--side-accent); + color: var(--ink-faint); font-size: 20px; } +.nav-item.active .nav-icon { + color: var(--side-accent); +} + .sidebar-footer { display: flex; align-items: center; @@ -260,7 +290,7 @@ code { margin-top: auto; padding: 14px 18px 0; border-top: 1px solid var(--side-border); - color: #46647a; + color: var(--side-ink-faint); font-size: 11px; } @@ -332,8 +362,15 @@ code { font-size: 11px; } -.workspace-context-tabs span { display: flex; align-items: center; gap: 4px; } -.workspace-context-tabs i { color: var(--ink-faint); font-style: normal; } +.workspace-context-tabs span { + display: flex; + align-items: center; + gap: 4px; +} +.workspace-context-tabs i { + color: var(--ink-faint); + font-style: normal; +} .workspace-context-tabs button { max-width: 180px; overflow: hidden; @@ -375,11 +412,46 @@ code { /* ========== 页面外壳 ========== */ .page-shell { - width: min(1240px, calc(100% - 48px)); + /* 模块自己的 max-width(目录/监控 1800、设置 1500)此前被 min() 宽度压成 1240,宽屏上与发布/问答页不齐 */ + width: calc(100% - 48px); + max-width: 1240px; margin: 0 auto; padding: 22px 0 40px; } +/* 六个模块共用的页头:标题、说明与右侧操作的字号和位置只在这里定义一份 */ +.page-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + flex-wrap: wrap; + margin: 0 0 20px; +} +.page-header .page-title { + margin: 0 0 4px; + color: var(--ink-strong); + font-size: 22px; + font-weight: 600; + letter-spacing: -0.02em; + line-height: 1.3; +} +.page-header .page-subtitle { + margin: 0; + color: var(--ink-mute); + font-size: 13px; +} +/* 这三个页面的外层是带 gap 的纵向 flex,页头间距已由 gap 提供 */ +.page-header:where(.rel-head, .version-history-header, .qa-ops-header) { + margin-bottom: 4px; +} +.page-header-actions { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + .hero { display: flex; align-items: flex-start; @@ -397,7 +469,9 @@ code { text-transform: uppercase; } -h1, h2, p { +h1, +h2, +p { margin-top: 0; } @@ -453,11 +527,21 @@ h1 { font-variant-numeric: tabular-nums; } -.tone-blue { border-top: 2px solid var(--c-run); } -.tone-cyan { border-top: 2px solid var(--c-cyan); } -.tone-amber { border-top: 2px solid var(--c-warn); } -.tone-red { border-top: 2px solid var(--c-fail); } -.tone-green { border-top: 2px solid var(--c-done); } +.tone-blue { + border-top: 2px solid var(--c-run); +} +.tone-cyan { + border-top: 2px solid var(--c-cyan); +} +.tone-amber { + border-top: 2px solid var(--c-warn); +} +.tone-red { + border-top: 2px solid var(--c-fail); +} +.tone-green { + border-top: 2px solid var(--c-done); +} /* ========== Panel(A:细边 + 6px 圆角 + 无阴影) ========== */ .panel { @@ -465,7 +549,7 @@ h1 { border: 1px solid var(--border-base); border-radius: var(--r-lg); background: var(--bg-panel); - box-shadow: none; + box-shadow: var(--shadow-card); } .panel-heading { @@ -513,7 +597,8 @@ table { font-size: 12.5px; } -th, td { +th, +td { padding: 10px 14px; border-bottom: 1px solid var(--border-soft); text-align: left; @@ -534,21 +619,39 @@ tbody tr:hover { } /* ========== 来源连接表 ========== */ -.source-connections-table { table-layout: fixed; } +.source-connections-table { + table-layout: fixed; +} .source-connections-table th, .source-connections-table td { padding: 10px 8px; white-space: normal; overflow-wrap: anywhere; } -.source-connections-table th:nth-child(1) { width: 22%; } -.source-connections-table th:nth-child(2) { width: 7%; } -.source-connections-table th:nth-child(3) { width: 8%; } -.source-connections-table th:nth-child(4) { width: 8%; } -.source-connections-table th:nth-child(5) { width: 8%; } -.source-connections-table th:nth-child(6) { width: 7%; } -.source-connections-table th:nth-child(7) { width: 30%; } -.source-connections-table th:nth-child(8) { width: 10%; } +.source-connections-table th:nth-child(1) { + width: 22%; +} +.source-connections-table th:nth-child(2) { + width: 7%; +} +.source-connections-table th:nth-child(3) { + width: 8%; +} +.source-connections-table th:nth-child(4) { + width: 8%; +} +.source-connections-table th:nth-child(5) { + width: 8%; +} +.source-connections-table th:nth-child(6) { + width: 7%; +} +.source-connections-table th:nth-child(7) { + width: 30%; +} +.source-connections-table th:nth-child(8) { + width: 10%; +} .source-connection-name, .source-scan-summary { @@ -579,21 +682,37 @@ tbody tr:hover { padding: 14px 16px 16px; } -.scan-audit-grid > * { min-width: 0; } +.scan-audit-grid > * { + min-width: 0; +} -.source-scan-history-table { table-layout: fixed; } +.source-scan-history-table { + table-layout: fixed; +} .source-scan-history-table th, .source-scan-history-table td { padding: 9px 8px; white-space: normal; overflow-wrap: anywhere; } -.source-scan-history-table th:nth-child(1) { width: 25%; } -.source-scan-history-table th:nth-child(2) { width: 12%; } -.source-scan-history-table th:nth-child(3) { width: 9%; } -.source-scan-history-table th:nth-child(4) { width: 27%; } -.source-scan-history-table th:nth-child(5) { width: 12%; } -.source-scan-history-table th:nth-child(6) { width: 15%; } +.source-scan-history-table th:nth-child(1) { + width: 25%; +} +.source-scan-history-table th:nth-child(2) { + width: 12%; +} +.source-scan-history-table th:nth-child(3) { + width: 9%; +} +.source-scan-history-table th:nth-child(4) { + width: 27%; +} +.source-scan-history-table th:nth-child(5) { + width: 12%; +} +.source-scan-history-table th:nth-child(6) { + width: 15%; +} .source-scan-history-table code, .source-scan-history-table time { @@ -640,7 +759,9 @@ tbody tr:hover { } /* ========== Release page ========== */ -.release-page .panel { margin-top: 14px; } +.release-page .panel { + margin-top: 14px; +} .module-tabs { display: flex; @@ -685,12 +806,23 @@ tbody tr:hover { grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1px; } -.monitor-summary-grid .summary-card { padding: 10px 12px; } -.monitor-summary-grid .summary-card span { margin-bottom: 4px; font-size: 11px; } -.monitor-summary-grid .summary-card strong { font-size: 20px; } +.monitor-summary-grid .summary-card { + padding: 10px 12px; +} +.monitor-summary-grid .summary-card span { + margin-bottom: 4px; + font-size: 11px; +} +.monitor-summary-grid .summary-card strong { + font-size: 20px; +} -.parsing-monitor-panel { margin-top: 0; } -.parsing-monitor-panel .panel-heading { padding: 10px 14px; } +.parsing-monitor-panel { + margin-top: 0; +} +.parsing-monitor-panel .panel-heading { + padding: 10px 14px; +} .release-snapshot-callout { display: flex; @@ -705,14 +837,33 @@ tbody tr:hover { font-size: 12px; } -.release-snapshot-callout > span { font-size: 14px; line-height: 1.25; } -.release-snapshot-callout div { display: grid; gap: 2px; } -.release-snapshot-callout strong { font-size: 12px; color: var(--ink-strong); } -.release-snapshot-callout small { color: var(--ink-mute); font-size: 11px; line-height: 1.4; } +.release-snapshot-callout > span { + font-size: 14px; + line-height: 1.25; +} +.release-snapshot-callout div { + display: grid; + gap: 2px; +} +.release-snapshot-callout strong { + font-size: 12px; + color: var(--ink-strong); +} +.release-snapshot-callout small { + color: var(--ink-mute); + font-size: 11px; + line-height: 1.4; +} -.release-page .hero + .module-tabs { margin-top: -4px; } -.release-page .summary-grid { margin-top: 14px; } -.release-page .summary-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } +.release-page .hero + .module-tabs { + margin-top: -4px; +} +.release-page .summary-grid { + margin-top: 14px; +} +.release-page .summary-grid { + grid-template-columns: repeat(4, minmax(0, 1fr)); +} .release-page button:disabled { border-color: var(--border-base); @@ -729,7 +880,8 @@ tbody tr:hover { #release-plan, #release-execution, #settings-sources, -#settings-services, +#settings-ai-model, +#settings-weknora-connections, #settings-storage, #settings-refresh { scroll-margin-top: 60px; @@ -1003,14 +1155,18 @@ tbody tr:hover { background: var(--c-done-bg); } -.batch-requirements .met::before { content: '✓'; } +.batch-requirements .met::before { + content: '✓'; +} .batch-requirements .unmet { color: var(--c-warn); background: var(--c-warn-bg); } -.batch-requirements .unmet::before { content: '○'; } +.batch-requirements .unmet::before { + content: '○'; +} .acceptance-summary > strong, .acceptance-summary > span { @@ -1045,7 +1201,7 @@ tbody tr:hover { border-radius: var(--r-md); padding: 5px 11px; color: #fff; - background: var(--side-bg); + background: var(--c-primary); box-shadow: none; font-size: 12px; font-weight: 600; @@ -1078,7 +1234,9 @@ tbody tr:hover { font-size: 12px; } -.button-reason strong { margin-right: 4px; } +.button-reason strong { + margin-right: 4px; +} .release-actions, .row-actions { @@ -1122,7 +1280,9 @@ tbody tr:hover { font-size: 12px; } -.review-table { table-layout: fixed; } +.review-table { + table-layout: fixed; +} .review-table th, .review-table td { padding: 8px 8px; @@ -1130,13 +1290,27 @@ tbody tr:hover { overflow-wrap: anywhere; vertical-align: top; } -.review-table th:nth-child(1) { width: 5%; } -.review-table th:nth-child(2) { width: 20%; } -.review-table th:nth-child(3) { width: 19%; } -.review-table th:nth-child(4) { width: 10%; } -.review-table th:nth-child(5) { width: 13%; } -.review-table th:nth-child(6) { width: 13%; } -.review-table th:nth-child(7) { width: 20%; } +.review-table th:nth-child(1) { + width: 5%; +} +.review-table th:nth-child(2) { + width: 20%; +} +.review-table th:nth-child(3) { + width: 19%; +} +.review-table th:nth-child(4) { + width: 10%; +} +.review-table th:nth-child(5) { + width: 13%; +} +.review-table th:nth-child(6) { + width: 13%; +} +.review-table th:nth-child(7) { + width: 20%; +} .review-table td > strong, .review-table td > code, @@ -1166,7 +1340,9 @@ tbody tr:hover { padding: 12px 16px; } -.batch-create-bar label { margin-right: auto; } +.batch-create-bar label { + margin-right: auto; +} .batch-grid { display: grid; @@ -1175,7 +1351,9 @@ tbody tr:hover { padding: 12px 16px 16px; } -.batch-grid > * { min-width: 0; } +.batch-grid > * { + min-width: 0; +} .batch-grid th, .batch-grid td { @@ -1235,13 +1413,41 @@ tbody tr:hover { letter-spacing: 0.02em; } -.status-pending { color: var(--ink-mute); background: var(--bg-softer); border-color: var(--border-base); } -.status-running { color: var(--c-cyan); background: var(--c-cyan-bg); border-color: #b5e5ee; } -.status-retry { color: var(--c-warn); background: var(--c-warn-bg); border-color: var(--c-warn-border); } -.status-completed { color: var(--c-done); background: var(--c-done-bg); border-color: var(--c-done-border); } -.status-failed { color: var(--c-fail); background: var(--c-fail-bg); border-color: var(--c-fail-border); } -.status-over_limit { color: var(--c-warn); background: var(--c-warn-bg); border-color: var(--c-warn-border); } -.status-content_alias { color: var(--c-cyan); background: var(--c-cyan-bg); border-color: #b5e5ee; } +.status-pending { + color: var(--ink-mute); + background: var(--bg-softer); + border-color: var(--border-base); +} +.status-running { + color: var(--c-cyan); + background: var(--c-cyan-bg); + border-color: #b5e5ee; +} +.status-retry { + color: var(--c-warn); + background: var(--c-warn-bg); + border-color: var(--c-warn-border); +} +.status-completed { + color: var(--c-done); + background: var(--c-done-bg); + border-color: var(--c-done-border); +} +.status-failed { + color: var(--c-fail); + background: var(--c-fail-bg); + border-color: var(--c-fail-border); +} +.status-over_limit { + color: var(--c-warn); + background: var(--c-warn-bg); + border-color: var(--c-warn-border); +} +.status-content_alias { + color: var(--c-cyan); + background: var(--c-cyan-bg); + border-color: #b5e5ee; +} /* ========== Error / Empty / Banner ========== */ .error-cell { @@ -1296,7 +1502,9 @@ tbody tr:hover { } /* ========== Release Plan ========== */ -.release-plan-panel { margin-bottom: 14px; } +.release-plan-panel { + margin-bottom: 14px; +} .release-plan-filters { display: flex; @@ -1323,8 +1531,13 @@ tbody tr:hover { background: var(--bg-panel); } -.release-plan-filters .filter-check { cursor: pointer; } -.release-plan-filters .filter-count { margin-left: auto; color: var(--ink-faint); } +.release-plan-filters .filter-check { + cursor: pointer; +} +.release-plan-filters .filter-count { + margin-left: auto; + color: var(--ink-faint); +} .release-plan-pager { display: flex; @@ -1440,9 +1653,13 @@ tbody tr:hover { } /* ========== Dashboard ========== */ -.dashboard-recent { margin-top: 0; } +.dashboard-recent { + margin-top: 0; +} -.recent-list { display: grid; } +.recent-list { + display: grid; +} .recent-row { display: grid; @@ -1453,8 +1670,12 @@ tbody tr:hover { border-bottom: 1px solid var(--border-soft); } -.recent-row:last-child { border-bottom: 0; } -.recent-row div { min-width: 0; } +.recent-row:last-child { + border-bottom: 0; +} +.recent-row div { + min-width: 0; +} .recent-row strong, .recent-row code { @@ -1519,7 +1740,9 @@ tbody tr:hover { } /* ========== Asset ========== */ -.asset-summary { grid-template-columns: repeat(4, minmax(0, 1fr)); } +.asset-summary { + grid-template-columns: repeat(4, minmax(0, 1fr)); +} .asset-toolbar label { display: flex; @@ -1604,7 +1827,9 @@ tbody tr:hover { font-family: var(--font-mono); } -.release-changeset-items { margin: 4px 0; } +.release-changeset-items { + margin: 4px 0; +} .release-changeset-items summary { cursor: pointer; @@ -1759,12 +1984,24 @@ tbody tr:hover { /* ========== Responsive ========== */ @media (max-width: 860px) { - .summary-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } - .asset-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); } - .scan-audit-grid { grid-template-columns: 1fr; } - .batch-grid { grid-template-columns: 1fr; } - .journey-steps { grid-template-columns: repeat(2, minmax(0, 1fr)); } - .review-decision-guide { grid-template-columns: 1fr; } + .summary-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .asset-summary { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .scan-audit-grid { + grid-template-columns: 1fr; + } + .batch-grid { + grid-template-columns: 1fr; + } + .journey-steps { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .review-decision-guide { + grid-template-columns: 1fr; + } } @media (max-width: 760px) { @@ -1773,7 +2010,9 @@ tbody tr:hover { transform: translateX(-105%); transition: transform 180ms ease; } - .sidebar.open { transform: translateX(0); } + .sidebar.open { + transform: translateX(0); + } .sidebar-backdrop { position: fixed; z-index: 35; @@ -1789,8 +2028,12 @@ tbody tr:hover { width: 100%; margin-left: 0; } - .workspace-topbar { align-items: center; } - .workspace-context-tabs { display: none; } + .workspace-topbar { + align-items: center; + } + .workspace-context-tabs { + display: none; + } .mobile-nav-toggle { display: grid; width: 32px; @@ -1816,8 +2059,12 @@ tbody tr:hover { align-items: stretch; flex-direction: column; } - .summary-grid { grid-template-columns: 1fr; } - .asset-summary { grid-template-columns: 1fr; } + .summary-grid { + grid-template-columns: 1fr; + } + .asset-summary { + grid-template-columns: 1fr; + } .asset-toolbar label, .pagination, .batch-create-bar { @@ -1831,13 +2078,28 @@ tbody tr:hover { align-items: flex-start; flex-direction: column; } - .journey-heading { display: flex; } - .journey-heading p { text-align: left; } - .journey-steps { grid-template-columns: 1fr; } - .current-guidance { display: flex; } - .guidance-step { max-width: none; } - .recent-row { grid-template-columns: minmax(0, 1fr) auto; } - .recent-row time { grid-column: 1 / -1; text-align: left; } + .journey-heading { + display: flex; + } + .journey-heading p { + text-align: left; + } + .journey-steps { + grid-template-columns: 1fr; + } + .current-guidance { + display: flex; + } + .guidance-step { + max-width: none; + } + .recent-row { + grid-template-columns: minmax(0, 1fr) auto; + } + .recent-row time { + grid-column: 1 / -1; + text-align: left; + } } /* ── 登录 / 强制改密 / 顶栏身份(A · Data-console) ─────────────── */ @@ -1856,13 +2118,28 @@ tbody tr:hover { border: 1px solid var(--border-base); border-radius: 10px; padding: 28px 26px 24px; - box-shadow: 0 18px 46px rgba(15, 23, 32, 0.10); + box-shadow: 0 18px 46px rgba(15, 23, 32, 0.1); display: grid; gap: 14px; } -.login-card h1 { margin: 0; font-size: 20px; color: var(--ink-strong); letter-spacing: 0.01em; } -.login-subtitle { margin: 0; color: var(--ink-mute); font-size: 13px; } -.login-card label { display: grid; gap: 6px; font-size: 13px; color: var(--ink-base); font-weight: 600; } +.login-card h1 { + margin: 0; + font-size: 20px; + color: var(--ink-strong); + letter-spacing: 0.01em; +} +.login-subtitle { + margin: 0; + color: var(--ink-mute); + font-size: 13px; +} +.login-card label { + display: grid; + gap: 6px; + font-size: 13px; + color: var(--ink-base); + font-weight: 600; +} .login-card input { padding: 10px 12px; border: 1px solid var(--border-strong); @@ -1871,55 +2148,162 @@ tbody tr:hover { background: var(--bg-panel); color: var(--ink-strong); } -.login-card input:focus { outline: 2px solid var(--c-run); outline-offset: 1px; border-color: transparent; } -.login-card button[type="submit"] { width: 100%; margin-top: 4px; } +.login-card input:focus { + outline: 2px solid var(--c-run); + outline-offset: 1px; + border-color: transparent; +} +.login-card button[type='submit'] { + width: 100%; + margin-top: 4px; +} /* Password visibility toggle: button sits inside the field's right edge. */ -.password-field { position: relative; display: block; } -.password-field input { width: 100%; padding-right: 56px; } +.password-field { + position: relative; + display: block; +} +.password-field input { + width: 100%; + padding-right: 56px; +} .password-toggle { position: absolute; top: 50%; right: 6px; transform: translateY(-50%); padding: 2px 8px; - border: 1px solid var(--line-base, #d7dbe0); + border: 1px solid var(--border-strong); border-radius: 6px; background: #fff; - color: var(--ink-base, #333); + color: var(--ink-base); font-size: 12px; font-weight: 600; line-height: 20px; cursor: pointer; } -.password-toggle:hover { border-color: var(--c-run, #2f6feb); color: var(--c-run, #2f6feb); } -.login-error { margin: 0; font-size: 13px; color: var(--c-fail); background: var(--c-fail-bg); border: 1px solid var(--c-fail-border); border-radius: 6px; padding: 8px 10px; } -.login-secondary { background: transparent; border: none; color: var(--ink-mute); font-size: 12.5px; cursor: pointer; text-decoration: underline; } +.password-toggle:hover { + border-color: var(--c-run); + color: var(--c-run); +} +.login-error { + margin: 0; + font-size: 13px; + color: var(--c-fail); + background: var(--c-fail-bg); + border: 1px solid var(--c-fail-border); + border-radius: 6px; + padding: 8px 10px; +} +.login-secondary { + background: transparent; + border: none; + color: var(--ink-mute); + font-size: 12.5px; + cursor: pointer; + text-decoration: underline; +} -.topbar-user { position: relative; margin-left: auto; } +.topbar-user { + position: relative; + margin-left: auto; +} .topbar-user-button { - display: inline-flex; align-items: center; gap: 8px; - background: var(--bg-soft); border: 1px solid var(--border-base); border-radius: 999px; - padding: 4px 12px 4px 4px; cursor: pointer; color: var(--ink-base); font: inherit; + display: inline-flex; + align-items: center; + gap: 8px; + background: var(--bg-soft); + border: 1px solid var(--border-base); + border-radius: 999px; + padding: 4px 12px 4px 4px; + cursor: pointer; + color: var(--ink-base); + font: inherit; +} +.topbar-user-button:hover { + background: var(--bg-hover); } -.topbar-user-button:hover { background: var(--bg-hover); } .topbar-user-avatar { - width: 26px; height: 26px; border-radius: 50%; - background: var(--side-bg); color: var(--side-accent); - display: grid; place-items: center; font-size: 13px; font-weight: 700; + width: 26px; + height: 26px; + border-radius: 50%; + background: var(--c-primary); + color: #fff; + display: grid; + place-items: center; + font-size: 13px; + font-weight: 700; +} +.topbar-user-name { + font-size: 13px; + font-weight: 600; +} +.role-badge { + font-size: 11px; + padding: 1px 8px; + border-radius: 999px; + border: 1px solid var(--border-base); + background: var(--bg-panel); + color: var(--ink-mute); +} +.role-badge.role-admin { + color: var(--c-run); + border-color: var(--c-run-border); + background: var(--c-run-bg); +} +.role-badge.role-engineer { + color: var(--c-done); + border-color: var(--c-done-border); + background: var(--c-done-bg); } -.topbar-user-name { font-size: 13px; font-weight: 600; } -.role-badge { font-size: 11px; padding: 1px 8px; border-radius: 999px; border: 1px solid var(--border-base); background: var(--bg-panel); color: var(--ink-mute); } -.role-badge.role-admin { color: var(--c-run); border-color: var(--c-run-border); background: var(--c-run-bg); } -.role-badge.role-engineer { color: var(--c-done); border-color: var(--c-done-border); background: var(--c-done-bg); } .topbar-user-menu { - position: absolute; right: 0; top: calc(100% + 6px); z-index: 30; - background: var(--bg-panel); border: 1px solid var(--border-base); border-radius: 8px; - box-shadow: 0 12px 30px rgba(15, 23, 32, 0.12); min-width: 140px; padding: 4px; + position: absolute; + right: 0; + top: calc(100% + 6px); + z-index: 30; + background: var(--bg-panel); + border: 1px solid var(--border-base); + border-radius: 8px; + box-shadow: 0 12px 30px rgba(15, 23, 32, 0.12); + min-width: 140px; + padding: 4px; +} +.topbar-user-menu button { + width: 100%; + text-align: left; + background: transparent; + border: none; + padding: 8px 10px; + border-radius: 6px; + cursor: pointer; + font: inherit; + color: var(--ink-base); +} +.topbar-user-menu button:hover { + background: var(--bg-hover); } -.topbar-user-menu button { width: 100%; text-align: left; background: transparent; border: none; padding: 8px 10px; border-radius: 6px; cursor: pointer; font: inherit; color: var(--ink-base); } -.topbar-user-menu button:hover { background: var(--bg-hover); } -.member-create-form { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border-soft); } -.member-create-form label { display: grid; gap: 5px; font-size: 12.5px; color: var(--ink-base); font-weight: 600; } -.member-create-form input, .member-create-form select { padding: 8px 10px; border: 1px solid var(--border-strong); border-radius: 6px; font: inherit; background: var(--bg-panel); } +.member-create-form { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: flex-end; + margin-top: 14px; + padding-top: 14px; + border-top: 1px solid var(--border-soft); +} +.member-create-form label { + display: grid; + gap: 5px; + font-size: 12.5px; + color: var(--ink-base); + font-weight: 600; +} +.member-create-form input, +.member-create-form select { + padding: 8px 10px; + border: 1px solid var(--border-strong); + border-radius: 6px; + font: inherit; + background: var(--bg-panel); +} diff --git a/web/src/systemCapabilities.ts b/web/src/systemCapabilities.ts new file mode 100644 index 0000000..252a88c --- /dev/null +++ b/web/src/systemCapabilities.ts @@ -0,0 +1,56 @@ +// Worker 能力心跳:页面的“执行器能力”只信 worker 自己上报的记录。 +export interface WorkerCapability { + worker_id: string + job_types: string[] + alive: boolean + last_seen_at: string +} + +export interface WorkerCapabilities { + test_upload: { state: 'enabled' | 'disabled' | 'stale' | 'unknown'; consumers: number; detail: string } + workers: WorkerCapability[] +} + +const record = (value: unknown): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value) + +export async function fetchWorkerCapabilities(signal?: AbortSignal): Promise { + const response = await fetch('/api/v1/system/worker-capabilities', { credentials: 'include', signal }) + if (!response.ok) throw new Error(`读取执行器能力失败(${response.status})`) + const body = (await response.json()) as { data?: unknown } + const data = record(body.data) ? body.data : {} + const upload = record(data.test_upload) ? data.test_upload : {} + const state = upload.state + const workers = Array.isArray(data.workers) + ? data.workers.filter(record).map((item) => ({ + worker_id: typeof item.worker_id === 'string' ? item.worker_id : '', + job_types: Array.isArray(item.job_types) + ? item.job_types.filter((t): t is string => typeof t === 'string') + : [], + alive: item.alive === true, + last_seen_at: typeof item.last_seen_at === 'string' ? item.last_seen_at : '', + })) + : [] + return { + test_upload: { + state: state === 'enabled' || state === 'disabled' || state === 'stale' ? state : 'unknown', + consumers: typeof upload.consumers === 'number' ? upload.consumers : 0, + detail: typeof upload.detail === 'string' ? upload.detail : '能力心跳不可用', + }, + workers, + } +} + +export const testUploadLabel = (capabilities: WorkerCapabilities | null): string => { + if (!capabilities) return '执行器:未知' + switch (capabilities.test_upload.state) { + case 'enabled': + return `执行器:已启用(${capabilities.test_upload.consumers} 个 worker)` + case 'disabled': + return '执行器:已停用(不会消费上传/解析)' + case 'stale': + return '执行器:无心跳(worker 未运行)' + default: + return '执行器:未知' + } +} diff --git a/web/src/systemSettings.css b/web/src/systemSettings.css index 221d345..d343869 100644 --- a/web/src/systemSettings.css +++ b/web/src/systemSettings.css @@ -281,7 +281,7 @@ font-size: 9px; } .settings-source-row select { - border: 1px solid #c9d9e4; + border: 1px solid var(--border-strong); border-radius: 7px; padding: 7px; background: var(--bg-panel); @@ -321,7 +321,7 @@ min-width: 64px; } .settings-source-row .source-more:focus-visible { - outline: 2px solid #2978bd; + outline: 2px solid var(--c-run); outline-offset: 3px; } .dependency-grid { @@ -657,8 +657,8 @@ button.link { .dingtalk-qr-loading span { width: 42px; height: 42px; - border: 4px solid #dbe4ee; - border-top-color: var(--brand); + border: 4px solid var(--border-base); + border-top-color: var(--c-run); border-radius: 50%; animation: dingtalk-qr-spin 0.8s linear infinite; } @@ -707,8 +707,8 @@ button.link { .filename-filter-editor code { padding: 2px 7px; border-radius: 999px; - background: #eaf2ff; - color: #2456a6; + background: var(--c-run-bg); + color: var(--c-run); font-family: inherit; font-size: 11px; } @@ -791,9 +791,9 @@ button.link { gap: 10px; padding: 12px; margin-bottom: 14px; - border: 1px solid var(--border, #e3e8ec); + border: 1px solid var(--border-base); border-radius: 10px; - background: var(--card, #fff); + background: var(--bg-panel); } .dingtalk-discovery-heading { display: flex; @@ -807,7 +807,7 @@ button.link { } .dingtalk-discovery-heading small { display: block; - color: var(--muted-foreground, #5b6773); + color: var(--ink-mute); font-size: 12px; } .dingtalk-discovery-groups { @@ -838,7 +838,7 @@ button.link { border-radius: 6px; } .discovery-row:hover { - background: var(--accent, #f2f5f8); + background: var(--bg-soft); } .discovery-row label { display: flex; @@ -848,7 +848,7 @@ button.link { } .discovery-row.registered label { cursor: default; - color: var(--muted-foreground, #5b6773); + color: var(--ink-mute); } .discovery-row strong { font-size: 13px; @@ -857,7 +857,7 @@ button.link { .discovery-row small { display: block; font-size: 11px; - color: var(--muted-foreground, #5b6773); + color: var(--ink-mute); } .dingtalk-discovery-actions { display: flex; @@ -865,7 +865,7 @@ button.link { gap: 10px; } .dingtalk-discovery-actions small { - color: var(--muted-foreground, #5b6773); + color: var(--ink-mute); font-size: 12px; } @@ -878,7 +878,32 @@ button.link { margin: 0 0 0.75rem; } .settings-legacy-toggle small { - color: #5a6572; + color: var(--ink-mute); font-size: 0.8rem; line-height: 1.5; } + +.settings-warn { + margin: 8px 0 0; + color: #b45309; + font-size: 12px; +} + +.member-reset-dialog { + margin-top: 16px; + border: 1px solid var(--border); + border-radius: 12px; + padding: 14px 16px; + background: var(--card); + display: grid; + gap: 8px; +} +.member-reset-dialog h3 { + margin: 0; + font-size: 15px; +} +.member-reset-dialog p { + margin: 0; + color: var(--muted-foreground); + font-size: 12px; +} diff --git a/web/src/testPublications.test.ts b/web/src/testPublications.test.ts index b04688a..7e2dc82 100644 --- a/web/src/testPublications.test.ts +++ b/web/src/testPublications.test.ts @@ -1,19 +1,40 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { fetchAcceptanceResults, fetchTestPublications, parseTestPublicationsResponse, retryPublication, retryPublicationsBatch, startTestPublications, fetchJobFailures, fetchRemovalRequiredPublications, startPublicationRemoval } from './testPublications' +import { + fetchAcceptanceResults, + fetchTestPublications, + parseTestPublicationsResponse, + retryPublication, + retryPublicationsBatch, + startTestPublications, + fetchJobFailures, + fetchRemovalRequiredPublications, + startPublicationRemoval, +} from './testPublications' afterEach(() => vi.unstubAllGlobals()) describe('parseTestPublicationsResponse', () => { it('parses the safe publication projection envelope', () => { const result = parseTestPublicationsResponse({ - data: [{ - id: 'pub-safe', title: 'Safe title', ingest_state: 'failed', - processing_state: 'failed', retrieval_state: 'unpublished', - target_scope: 'external', change_set_id: 'cs-1', change_type: 'updated', can_start: false, - retry_count: 2, last_error: 'remote_parse_failed', can_retry: true, - updated_at: '2026-09-04T05:00:00Z', test_kb_id: 'must-drop', - }], + data: [ + { + id: 'pub-safe', + title: 'Safe title', + ingest_state: 'failed', + processing_state: 'failed', + retrieval_state: 'unpublished', + target_scope: 'external', + change_set_id: 'cs-1', + change_type: 'updated', + can_start: false, + retry_count: 2, + last_error: 'remote_parse_failed', + can_retry: true, + updated_at: '2026-09-04T05:00:00Z', + test_kb_id: 'must-drop', + }, + ], total: 1, limit: 25, offset: 0, @@ -40,7 +61,7 @@ describe('fetchTestPublications', () => { expect(fetchMock).toHaveBeenCalledWith( '/api/v1/test-publications?processing_state=failed&limit=25&offset=0', - expect.objectContaining({ headers: { Accept: 'application/json' } }), + expect.objectContaining({ headers: { Accept: 'application/json' } }) ) }) }) @@ -49,7 +70,9 @@ describe('fetchAcceptanceResults', () => { it('reads the acceptance record list', async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: true, - json: async () => ({ data: [{ check_type: 'chunks_present', state: 'passed', observed_at: '2026-09-04T05:05:00Z' }] }), + json: async () => ({ + data: [{ check_type: 'chunks_present', state: 'passed', observed_at: '2026-09-04T05:05:00Z' }], + }), }) vi.stubGlobal('fetch', fetchMock) @@ -59,7 +82,7 @@ describe('fetchAcceptanceResults', () => { expect(records[0].check_type).toBe('chunks_present') expect(fetchMock).toHaveBeenCalledWith( '/api/v1/test-publications/pub-safe/acceptance', - expect.objectContaining({ headers: { Accept: 'application/json' } }), + expect.objectContaining({ headers: { Accept: 'application/json' } }) ) }) }) @@ -73,7 +96,7 @@ describe('retryPublication', () => { expect(fetchMock).toHaveBeenCalledWith( '/api/v1/test-publications/pub-safe/retry', - expect.objectContaining({ method: 'POST' }), + expect.objectContaining({ method: 'POST' }) ) }) @@ -91,7 +114,9 @@ describe('retryPublication', () => { describe('需下架条目的移除入口', () => { it('只取被禁止但仍存活在测试库的条目', async () => { - const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [], total: 0, limit: 50, offset: 0 }) }) + const fetchMock = vi + .fn() + .mockResolvedValue({ ok: true, json: async () => ({ data: [], total: 0, limit: 50, offset: 0 }) }) vi.stubGlobal('fetch', fetchMock) await fetchRemovalRequiredPublications() @@ -102,7 +127,11 @@ describe('需下架条目的移除入口', () => { }) it('带幂等键触发下架并回传任务号', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ publication_id: 'tp-1', job_id: 'job-remove-1', state: 'disabling' }), { status: 202 })) + const fetchMock = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ publication_id: 'tp-1', job_id: 'job-remove-1', state: 'disabling' }), { + status: 202, + }) + ) vi.stubGlobal('fetch', fetchMock) await expect(startPublicationRemoval('tp-1')).resolves.toEqual({ job_id: 'job-remove-1' }) @@ -113,7 +142,9 @@ describe('需下架条目的移除入口', () => { }) it('把服务端拒绝原因原样抛给界面', async () => { - const fetchMock = vi.fn().mockResolvedValue({ status: 409, json: async () => ({ error: '该知识的检索已经移除,无需重复下架' }) }) + const fetchMock = vi + .fn() + .mockResolvedValue({ status: 409, json: async () => ({ error: '该知识的检索已经移除,无需重复下架' }) }) vi.stubGlobal('fetch', fetchMock) await expect(startPublicationRemoval('tp-1')).rejects.toThrow('该知识的检索已经移除,无需重复下架') @@ -122,30 +153,56 @@ describe('需下架条目的移除入口', () => { describe('startTestPublications', () => { it('starts only the explicitly confirmed processing plans', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { selected: 2, started: 1, already_started: 1, unavailable: 0 } }), { status: 202 })) + const fetchMock = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ data: { selected: 2, started: 1, already_started: 1, unavailable: 0 } }), { + status: 202, + }) + ) vi.stubGlobal('fetch', fetchMock) - await expect(startTestPublications(['pub-a', 'pub-b'], '已核对差异')).resolves.toEqual({ selected: 2, started: 1, already_started: 1, unavailable: 0 }) - expect(fetchMock).toHaveBeenCalledWith('/api/v1/test-publications/start', expect.objectContaining({ - method: 'POST', - headers: expect.objectContaining({ 'Idempotency-Key': expect.any(String) }), - body: JSON.stringify({ publication_ids: ['pub-a', 'pub-b'], reason: '已核对差异' }), - })) + await expect(startTestPublications(['pub-a', 'pub-b'], '已核对差异')).resolves.toEqual({ + selected: 2, + started: 1, + already_started: 1, + unavailable: 0, + }) + expect(fetchMock).toHaveBeenCalledWith( + '/api/v1/test-publications/start', + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ 'Idempotency-Key': expect.any(String) }), + body: JSON.stringify({ publication_ids: ['pub-a', 'pub-b'], reason: '已核对差异' }), + }) + ) }) }) describe('retryPublicationsBatch', () => { it('sends one server-side batch request and parses per-item outcomes', async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: true, - json: async () => ({ data: { batch_key: 'op-1', total: 2, started: 1, already_running: 1, not_retryable: 0, - outcomes: [{ publication_id: 'tp-1', result: 'started' }, { publication_id: 'tp-2', result: 'already_running' }] }, operation: 'created' }), + json: async () => ({ + data: { + batch_key: 'op-1', + total: 2, + started: 1, + already_running: 1, + not_retryable: 0, + outcomes: [ + { publication_id: 'tp-1', result: 'started' }, + { publication_id: 'tp-2', result: 'already_running' }, + ], + }, + operation: 'created', + }), }) vi.stubGlobal('fetch', fetchMock) const result = await retryPublicationsBatch(['tp-1', 'tp-2'], '解析服务恢复') - expect(fetchMock).toHaveBeenCalledWith('/api/v1/test-publications/retry-batch', - expect.objectContaining({ method: 'POST' })) + expect(fetchMock).toHaveBeenCalledWith( + '/api/v1/test-publications/retry-batch', + expect.objectContaining({ method: 'POST' }) + ) const call = fetchMock.mock.calls[0] as [string, RequestInit] expect(JSON.parse(String(call[1].body))).toEqual({ publication_ids: ['tp-1', 'tp-2'], reason: '解析服务恢复' }) expect(result.started).toBe(1) @@ -162,13 +219,34 @@ describe('fetchJobFailures', () => { it('reads the open dead-letter projection', async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: true, - json: async () => ({ data: { items: [{ id: 'jf-1', job_id: 'job-1', job_type: 'test.upload', error_code: 'remote_permanent', attempt: 5, max_attempts_at_failure: 5, state: 'open', created_at: '2026-09-11T20:00:00Z' }], total: 1, limit: 50, offset: 0 } }), + json: async () => ({ + data: { + items: [ + { + id: 'jf-1', + job_id: 'job-1', + job_type: 'test.upload', + error_code: 'remote_permanent', + attempt: 5, + max_attempts_at_failure: 5, + state: 'open', + created_at: '2026-09-11T20:00:00Z', + }, + ], + total: 1, + limit: 50, + offset: 0, + }, + }), }) vi.stubGlobal('fetch', fetchMock) const items = await fetchJobFailures() - expect(fetchMock).toHaveBeenCalledWith('/api/v1/job-failures?state=open&limit=50', expect.objectContaining({ headers: { Accept: 'application/json' } })) + expect(fetchMock).toHaveBeenCalledWith( + '/api/v1/job-failures?state=open&limit=50', + expect.objectContaining({ headers: { Accept: 'application/json' } }) + ) expect(items[0].error_code).toBe('remote_permanent') }) }) diff --git a/web/src/testPublications.ts b/web/src/testPublications.ts index 8ae3f8e..0fae5ce 100644 --- a/web/src/testPublications.ts +++ b/web/src/testPublications.ts @@ -1,6 +1,7 @@ import { newOperationID } from './operationKey' export type IngestState = 'pending' | 'uploading' | 'uploaded' | 'failed' -export type ProcessingState = 'planned' | 'pending' | 'processing' | 'finalizing' | 'completed' | 'failed' | 'stalled' | 'cancelled' +export type ProcessingState = + 'planned' | 'pending' | 'processing' | 'finalizing' | 'completed' | 'failed' | 'stalled' | 'cancelled' export interface TestPublication { id: string @@ -35,7 +36,7 @@ export interface AcceptanceRecord { export interface TestPublicationQuery { /** removal: 'required' 只取「被禁止导入但仍存活在测试库」的条目(解析监控 → 需下架)。 */ - removal?: 'required' + removal?: 'required' // A single state, or several at once (joined into a comma list server-side). processing_state: ProcessingState | '' | ProcessingState[] target_scope?: 'internal' | 'external' | '' @@ -53,16 +54,36 @@ export interface StartTestPublicationsResult { const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null const isCount = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value >= 0 const ingestStates = new Set(['pending', 'uploading', 'uploaded', 'failed']) -const processingStates = new Set(['planned', 'pending', 'processing', 'finalizing', 'completed', 'failed', 'stalled', 'cancelled']) +const processingStates = new Set([ + 'planned', + 'pending', + 'processing', + 'finalizing', + 'completed', + 'failed', + 'stalled', + 'cancelled', +]) function parseTestPublication(value: unknown): TestPublication { - if (!isRecord(value) || typeof value.id !== 'string' || typeof value.title !== 'string' || - typeof value.ingest_state !== 'string' || !ingestStates.has(value.ingest_state as IngestState) || - typeof value.processing_state !== 'string' || !processingStates.has(value.processing_state as ProcessingState) || - typeof value.retrieval_state !== 'string' || (value.target_scope !== 'internal' && value.target_scope !== 'external') || + if ( + !isRecord(value) || + typeof value.id !== 'string' || + typeof value.title !== 'string' || + typeof value.ingest_state !== 'string' || + !ingestStates.has(value.ingest_state as IngestState) || + typeof value.processing_state !== 'string' || + !processingStates.has(value.processing_state as ProcessingState) || + typeof value.retrieval_state !== 'string' || + (value.target_scope !== 'internal' && value.target_scope !== 'external') || typeof value.change_set_id !== 'string' || - (value.change_type !== 'added' && value.change_type !== 'updated') || typeof value.can_start !== 'boolean' || - !isCount(value.retry_count) || typeof value.last_error !== 'string' || typeof value.can_retry !== 'boolean' || typeof value.updated_at !== 'string') { + (value.change_type !== 'added' && value.change_type !== 'updated') || + typeof value.can_start !== 'boolean' || + !isCount(value.retry_count) || + typeof value.last_error !== 'string' || + typeof value.can_retry !== 'boolean' || + typeof value.updated_at !== 'string' + ) { throw new Error('invalid test publication response') } return { @@ -83,7 +104,13 @@ function parseTestPublication(value: unknown): TestPublication { } export function parseTestPublicationsResponse(value: unknown): TestPublicationPage { - if (!isRecord(value) || !Array.isArray(value.data) || !isCount(value.total) || !isCount(value.limit) || !isCount(value.offset)) { + if ( + !isRecord(value) || + !Array.isArray(value.data) || + !isCount(value.total) || + !isCount(value.limit) || + !isCount(value.offset) + ) { throw new Error('invalid test publications response') } return { @@ -94,14 +121,24 @@ export function parseTestPublicationsResponse(value: unknown): TestPublicationPa } } -export async function fetchTestPublications(query: TestPublicationQuery, signal?: AbortSignal): Promise { +export async function fetchTestPublications( + query: TestPublicationQuery, + signal?: AbortSignal +): Promise { const parameters = new URLSearchParams() - if (query.processing_state) parameters.set('processing_state', Array.isArray(query.processing_state) ? query.processing_state.join(',') : query.processing_state) + if (query.processing_state) + parameters.set( + 'processing_state', + Array.isArray(query.processing_state) ? query.processing_state.join(',') : query.processing_state + ) if (query.target_scope) parameters.set('target_scope', query.target_scope) if (query.removal) parameters.set('removal', query.removal) parameters.set('limit', String(query.limit)) parameters.set('offset', String(query.offset)) - const response = await fetch(`/api/v1/test-publications?${parameters.toString()}`, { headers: { Accept: 'application/json' }, signal }) + const response = await fetch(`/api/v1/test-publications?${parameters.toString()}`, { + headers: { Accept: 'application/json' }, + signal, + }) if (!response.ok) throw new Error(`加载测试发布失败(HTTP ${response.status})`) return parseTestPublicationsResponse(await response.json()) } @@ -127,28 +164,37 @@ export async function startPublicationRemoval(publicationId: string): Promise<{ const body = (await response.json().catch(() => null)) as { error?: string } | null throw new Error(body?.error ?? `触发下架失败(HTTP ${response.status})`) } - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!isRecord(value) || typeof value.job_id !== 'string') throw new Error('下架响应无效') return { job_id: value.job_id } } export async function fetchAcceptanceResults(publicationId: string, signal?: AbortSignal): Promise { - const response = await fetch(`/api/v1/test-publications/${encodeURIComponent(publicationId)}/acceptance`, { headers: { Accept: 'application/json' }, signal }) + const response = await fetch(`/api/v1/test-publications/${encodeURIComponent(publicationId)}/acceptance`, { + headers: { Accept: 'application/json' }, + signal, + }) if (!response.ok) throw new Error(`加载验收结果失败(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid acceptance response') return value.data as AcceptanceRecord[] } export async function retryPublication(publicationId: string): Promise { - const response = await fetch(`/api/v1/test-publications/${encodeURIComponent(publicationId)}/retry`, { method: 'POST', headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() } }) + const response = await fetch(`/api/v1/test-publications/${encodeURIComponent(publicationId)}/retry`, { + method: 'POST', + headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() }, + }) if (!response.ok) { const body = (await response.json().catch(() => null)) as { error?: string } | null throw new Error(body?.error ?? `重试失败(HTTP ${response.status})`) } } -export async function startTestPublications(publicationIds: string[], reason: string): Promise { +export async function startTestPublications( + publicationIds: string[], + reason: string +): Promise { const response = await fetch('/api/v1/test-publications/start', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, @@ -158,8 +204,15 @@ export async function startTestPublications(publicationIds: string[], reason: st const body = (await response.json().catch(() => null)) as { error?: string } | null throw new Error(body?.error ?? `开始处理失败(HTTP ${response.status})`) } - const value = await response.json() as unknown - if (!isRecord(value) || !isRecord(value.data) || !isCount(value.data.selected) || !isCount(value.data.started) || !isCount(value.data.already_started) || !isCount(value.data.unavailable)) { + const value = (await response.json()) as unknown + if ( + !isRecord(value) || + !isRecord(value.data) || + !isCount(value.data.selected) || + !isCount(value.data.started) || + !isCount(value.data.already_started) || + !isCount(value.data.unavailable) + ) { throw new Error('invalid processing start response') } return { @@ -169,10 +222,24 @@ export async function startTestPublications(publicationIds: string[], reason: st unavailable: value.data.unavailable, } } -export interface RetryOutcome { publication_id: string; result: 'started' | 'already_running' | 'not_retryable'; detail?: string } -export interface RetryPublicationsBatchResult { batch_key: string; total: number; started: number; already_running: number; not_retryable: number; outcomes: RetryOutcome[] } +export interface RetryOutcome { + publication_id: string + result: 'started' | 'already_running' | 'not_retryable' + detail?: string +} +export interface RetryPublicationsBatchResult { + batch_key: string + total: number + started: number + already_running: number + not_retryable: number + outcomes: RetryOutcome[] +} -export async function retryPublicationsBatch(publicationIds: string[], reason: string): Promise { +export async function retryPublicationsBatch( + publicationIds: string[], + reason: string +): Promise { const response = await fetch('/api/v1/test-publications/retry-batch', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, @@ -182,8 +249,9 @@ export async function retryPublicationsBatch(publicationIds: string[], reason: s const body = (await response.json().catch(() => null)) as { error?: string } | null throw new Error(body?.error ?? `批量重试失败(HTTP ${response.status})`) } - const value = await response.json() as unknown - if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.outcomes)) throw new Error('批量重试响应无效') + const value = (await response.json()) as unknown + if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.outcomes)) + throw new Error('批量重试响应无效') const data = value.data as Record const outcomes = Array.isArray(data.outcomes) ? data.outcomes : [] return { @@ -194,15 +262,37 @@ export async function retryPublicationsBatch(publicationIds: string[], reason: s not_retryable: isCount(data.not_retryable) ? data.not_retryable : 0, outcomes: outcomes.filter(isRecord).map((item) => ({ publication_id: typeof item.publication_id === 'string' ? item.publication_id : '', - result: item.result === 'started' || item.result === 'already_running' || item.result === 'not_retryable' ? item.result : 'not_retryable', + result: + item.result === 'started' || item.result === 'already_running' || item.result === 'not_retryable' + ? item.result + : 'not_retryable', detail: typeof item.detail === 'string' ? item.detail : undefined, })), } } -export interface JobFailure { id: string; job_id: string; job_type: string; publication_id?: string; source_item_id?: string; error_code: string; attempt: number; max_attempts_at_failure: number; change_set_id?: string; action?: string; target_kb_id?: string; state: 'open' | 'requeued' | 'abandoned'; created_at: string; doc_name?: string; last_error?: string } +export interface JobFailure { + id: string + job_id: string + job_type: string + publication_id?: string + source_item_id?: string + error_code: string + attempt: number + max_attempts_at_failure: number + change_set_id?: string + action?: string + target_kb_id?: string + state: 'open' | 'requeued' | 'abandoned' + created_at: string + doc_name?: string + last_error?: string +} -export async function cancelPublicationsBatch(publicationIds: string[], reason: string): Promise { +export async function cancelPublicationsBatch( + publicationIds: string[], + reason: string +): Promise { const response = await fetch('/api/v1/test-publications/cancel-batch', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, @@ -212,8 +302,9 @@ export async function cancelPublicationsBatch(publicationIds: string[], reason: const body = (await response.json().catch(() => null)) as { error?: string } | null throw new Error(body?.error ?? `批量取消失败(HTTP ${response.status})`) } - const value = await response.json() as unknown - if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.outcomes)) throw new Error('批量取消响应无效') + const value = (await response.json()) as unknown + if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.outcomes)) + throw new Error('批量取消响应无效') const data = value.data as Record const outcomes = Array.isArray(data.outcomes) ? data.outcomes : [] return { @@ -224,21 +315,34 @@ export async function cancelPublicationsBatch(publicationIds: string[], reason: not_retryable: isCount(data.not_retryable) ? data.not_retryable : 0, outcomes: outcomes.filter(isRecord).map((item) => ({ publication_id: typeof item.publication_id === 'string' ? item.publication_id : '', - result: item.result === 'started' || item.result === 'already_running' || item.result === 'not_retryable' ? item.result : 'not_retryable', + result: + item.result === 'started' || item.result === 'already_running' || item.result === 'not_retryable' + ? item.result + : 'not_retryable', detail: typeof item.detail === 'string' ? item.detail : undefined, })), } } export async function fetchJobFailures(signal?: AbortSignal): Promise { - const response = await fetch('/api/v1/job-failures?state=open&limit=50', { headers: { Accept: 'application/json' }, signal }) + const response = await fetch('/api/v1/job-failures?state=open&limit=50', { + headers: { Accept: 'application/json' }, + signal, + }) if (!response.ok) throw new Error(`加载失败队列失败(HTTP ${response.status})`) - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.items)) throw new Error('失败队列响应无效') return value.data.items as JobFailure[] } -export interface RequeuedArtifactFetch { failure_id: string; job_id: string; version_id: string; round: number; doc_name?: string; already_queued: boolean } +export interface RequeuedArtifactFetch { + failure_id: string + job_id: string + version_id: string + round: number + doc_name?: string + already_queued: boolean +} // 源头取件死信重排:取件任务的幂等键绑在版本上,失败那次已占住它,所以重新标注 // 同一文件不会再入队;这里让后端按新轮次重新排队(新键),并复位意图状态。 @@ -252,7 +356,7 @@ export async function requeueJobFailure(failureId: string, reason: string): Prom const body = (await response.json().catch(() => null)) as { error?: string } | null throw new Error(body?.error ?? `重新取件失败(HTTP ${response.status})`) } - const value = await response.json() as unknown + const value = (await response.json()) as unknown if (!isRecord(value) || !isRecord(value.data)) throw new Error('重新取件响应无效') const data = value.data as Record return { diff --git a/web/src/uiSettings.test.ts b/web/src/uiSettings.test.ts index 8443d58..7ea9a17 100644 --- a/web/src/uiSettings.test.ts +++ b/web/src/uiSettings.test.ts @@ -1,69 +1,166 @@ import { describe, expect, it, vi } from 'vitest' -import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings, parseServiceTargetVerification, parseUISettingsResponse, settingsRefreshDelays, UISettingsError } from './uiSettings' +import { + activateUISettings, + createUISettingsCandidate, + fetchActiveUISettings, + parseServiceTargetVerification, + parseUISettingsResponse, + settingsRefreshDelays, + UISettingsError, +} from './uiSettings' const candidateInput = { - document_refresh_seconds: 15, resource_refresh_seconds: 30, stalled_after_seconds: 1800, - finalizing_after_seconds: 7200, ingestion_concurrency: 2, - test_weknora_base_url: '', production_weknora_base_url: '', production_tenant_id: '', production_knowledge_base_id: '', + document_refresh_seconds: 15, + resource_refresh_seconds: 30, + stalled_after_seconds: 1800, + finalizing_after_seconds: 7200, + ingestion_concurrency: 2, + test_weknora_base_url: '', + production_weknora_base_url: '', + production_tenant_id: '', + production_knowledge_base_id: '', } as const const active = { - id: 'settings-default', state: 'active', document_refresh_seconds: 15, - resource_refresh_seconds: 30, stalled_after_seconds: 1800, - finalizing_after_seconds: 7200, ingestion_concurrency: 2, production_weknora_base_url: '', - test_weknora_base_url: '', production_tenant_id: '', production_knowledge_base_id: '', + id: 'settings-default', + state: 'active', + document_refresh_seconds: 15, + resource_refresh_seconds: 30, + stalled_after_seconds: 1800, + finalizing_after_seconds: 7200, + ingestion_concurrency: 2, + production_weknora_base_url: '', + test_weknora_base_url: '', + production_tenant_id: '', + production_knowledge_base_id: '', updated_by: 'system:migration', - created_at: '2026-09-10T08:00:00Z', activated_at: '2026-09-10T08:00:00Z', - retired_at: null, error_code: '', + created_at: '2026-09-10T08:00:00Z', + activated_at: '2026-09-10T08:00:00Z', + retired_at: null, + error_code: '', } describe('UI settings API', () => { it('strictly rebuilds the safe revision projection', () => { expect(parseUISettingsResponse({ data: { ...active, secret: 'drop' } })).toEqual(active) - expect(() => parseUISettingsResponse({ data: { ...active, document_refresh_seconds: 31 } })).toThrow('invalid UI settings response') + expect(() => parseUISettingsResponse({ data: { ...active, document_refresh_seconds: 31 } })).toThrow( + 'invalid UI settings response' + ) }) it('accepts only the four service fields with their own rules', () => { - const parsed = parseUISettingsResponse({ data: { ...active, test_weknora_base_url: 'https://weknora.test.example:8443/kb', production_tenant_id: '10000', production_knowledge_base_id: 'kb-abc_123' } }) + const parsed = parseUISettingsResponse({ + data: { + ...active, + test_weknora_base_url: 'https://weknora.test.example:8443/kb', + production_tenant_id: '10000', + production_knowledge_base_id: 'kb-abc_123', + }, + }) expect(parsed.test_weknora_base_url).toBe('https://weknora.test.example:8443/kb') expect(parsed.production_tenant_id).toBe('10000') expect(parsed.production_knowledge_base_id).toBe('kb-abc_123') - for (const bad of ['weknora.test.example', 'https://user:pass@weknora.test.example', 'https://weknora.test.example?token=abc']) - expect(() => parseUISettingsResponse({ data: { ...active, test_weknora_base_url: bad } })).toThrow('invalid UI settings response') + for (const bad of [ + 'weknora.test.example', + 'https://user:pass@weknora.test.example', + 'https://weknora.test.example?token=abc', + ]) + expect(() => parseUISettingsResponse({ data: { ...active, test_weknora_base_url: bad } })).toThrow( + 'invalid UI settings response' + ) for (const bad of ['abc', '10 000', '-1', '0', '10000000000000000000000', '10000.5']) - expect(() => parseUISettingsResponse({ data: { ...active, production_tenant_id: bad } })).toThrow('invalid UI settings response') + expect(() => parseUISettingsResponse({ data: { ...active, production_tenant_id: bad } })).toThrow( + 'invalid UI settings response' + ) for (const bad of ['kb/abc', 'kb abc', 'kb-abc?x', 'https://weknora.prod.example/kb']) - expect(() => parseUISettingsResponse({ data: { ...active, production_knowledge_base_id: bad } })).toThrow('invalid UI settings response') + expect(() => parseUISettingsResponse({ data: { ...active, production_knowledge_base_id: bad } })).toThrow( + 'invalid UI settings response' + ) }) it('keeps a web-configured production endpoint only when it is a bare http(s) origin', () => { - expect(parseUISettingsResponse({ data: { ...active, production_weknora_base_url: 'https://weknora.prod.example:8443/kb' } }).production_weknora_base_url).toBe('https://weknora.prod.example:8443/kb') - for (const bad of ['weknora.prod.example', 'https://user:pass@weknora.prod.example', 'https://weknora.prod.example?token=abc', 'https://weknora.prod.example#frag', ' https://weknora.prod.example']) - expect(() => parseUISettingsResponse({ data: { ...active, production_weknora_base_url: bad } })).toThrow('invalid UI settings response') + expect( + parseUISettingsResponse({ + data: { ...active, production_weknora_base_url: 'https://weknora.prod.example:8443/kb' }, + }).production_weknora_base_url + ).toBe('https://weknora.prod.example:8443/kb') + for (const bad of [ + 'weknora.prod.example', + 'https://user:pass@weknora.prod.example', + 'https://weknora.prod.example?token=abc', + 'https://weknora.prod.example#frag', + ' https://weknora.prod.example', + ]) + expect(() => parseUISettingsResponse({ data: { ...active, production_weknora_base_url: bad } })).toThrow( + 'invalid UI settings response' + ) }) it('converts the active revision into independent monitor delays', () => { - expect(settingsRefreshDelays({ ...active, document_refresh_seconds: 30, resource_refresh_seconds: 60 })).toEqual({ documentMs: 30000, resourceMs: 60000 }) + expect(settingsRefreshDelays({ ...active, document_refresh_seconds: 30, resource_refresh_seconds: 60 })).toEqual({ + documentMs: 30000, + resourceMs: 60000, + }) }) it('creates a validated candidate then activates it through fixed endpoints', async () => { - const candidate = { ...active, id: 'uis-candidate', state: 'validated', updated_by: 'engineer-1', activated_at: null } - const fetchMock = vi.fn() + const candidate = { + ...active, + id: 'uis-candidate', + state: 'validated', + updated_by: 'engineer-1', + activated_at: null, + } + const fetchMock = vi + .fn() .mockResolvedValueOnce(new Response(JSON.stringify({ data: active }), { status: 200 })) .mockResolvedValueOnce(new Response(JSON.stringify({ data: candidate }), { status: 201 })) - .mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...candidate, state: 'active', activated_at: '2026-09-10T08:01:00Z' } }), { status: 200 })) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ data: { ...candidate, state: 'active', activated_at: '2026-09-10T08:01:00Z' } }), + { status: 200 } + ) + ) vi.stubGlobal('fetch', fetchMock) await fetchActiveUISettings() - await createUISettingsCandidate({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400, ingestion_concurrency: 3, test_weknora_base_url: '', production_weknora_base_url: '', production_tenant_id: '', production_knowledge_base_id: '' }) + await createUISettingsCandidate({ + document_refresh_seconds: 30, + resource_refresh_seconds: 60, + stalled_after_seconds: 3600, + finalizing_after_seconds: 14400, + ingestion_concurrency: 3, + test_weknora_base_url: '', + production_weknora_base_url: '', + production_tenant_id: '', + production_knowledge_base_id: '', + }) await activateUISettings('uis-candidate') expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/ui-settings') expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/ui-settings/candidates') - expect(fetchMock.mock.calls[1][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400, ingestion_concurrency: 3, test_weknora_base_url: '', production_weknora_base_url: '', production_tenant_id: '', production_knowledge_base_id: '' }) }) + expect(fetchMock.mock.calls[1][1]).toMatchObject({ + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + document_refresh_seconds: 30, + resource_refresh_seconds: 60, + stalled_after_seconds: 3600, + finalizing_after_seconds: 14400, + ingestion_concurrency: 3, + test_weknora_base_url: '', + production_weknora_base_url: '', + production_tenant_id: '', + production_knowledge_base_id: '', + }), + }) expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/ui-settings/uis-candidate/activate') - expect(fetchMock.mock.calls[2][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }) + expect(fetchMock.mock.calls[2][1]).toMatchObject({ + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: '{}', + }) vi.unstubAllGlobals() }) @@ -71,13 +168,23 @@ describe('UI settings API', () => { it('returns the real verification block produced while saving', async () => { const candidate = { ...active, id: 'uis-candidate', state: 'validated', activated_at: null } const verification = { - status: 'verified', message: '已核验:生产地址上存在知识库「生产知识库」,租户 10000 一致', blocked: false, - knowledge_base_name: '生产知识库', observed_tenant_id: '10000', + status: 'verified', + message: '已核验:生产地址上存在知识库「生产知识库」,租户 10000 一致', + blocked: false, + knowledge_base_name: '生产知识库', + observed_tenant_id: '10000', test_endpoint: { status: 'reachable', message: '测试地址可达(可列出 7 个知识库)' }, production_endpoint: { status: 'reachable', message: '生产地址可达(可列出 7 个知识库)' }, checked_at: '2026-09-18T09:00:00Z', } - vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: candidate, operation: 'created', verification }), { status: 201 }))) + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + new Response(JSON.stringify({ data: candidate, operation: 'created', verification }), { status: 201 }) + ) + ) const saved = await createUISettingsCandidate(candidateInput) expect(saved.settings.id).toBe('uis-candidate') expect(saved.verification).toEqual(verification) @@ -87,13 +194,25 @@ describe('UI settings API', () => { // 被拒绝时保留服务器那句话,并带上核验详情,而不是退化成 "request failed (400)"。 it('keeps a refusal sentence and its detail instead of a status code', async () => { const verification = { - status: 'missing', message: '未通过:生产地址上找不到知识库 ID「kb-prod-1」;该地址现有 1 个知识库:生产知识库(kb-prod-1)', blocked: true, - knowledge_base_name: '', observed_tenant_id: '', + status: 'missing', + message: '未通过:生产地址上找不到知识库 ID「kb-prod-1」;该地址现有 1 个知识库:生产知识库(kb-prod-1)', + blocked: true, + knowledge_base_name: '', + observed_tenant_id: '', test_endpoint: { status: 'reachable', message: '测试地址可达' }, production_endpoint: { status: 'reachable', message: '生产地址可达' }, checked_at: '2026-09-18T09:00:00Z', } - vi.stubGlobal('fetch', vi.fn().mockImplementation(() => Promise.resolve(new Response(JSON.stringify({ error: '未通过:生产地址上找不到知识库 ID「kb-prod-1」', verification }), { status: 400 })))) + vi.stubGlobal( + 'fetch', + vi.fn().mockImplementation(() => + Promise.resolve( + new Response(JSON.stringify({ error: '未通过:生产地址上找不到知识库 ID「kb-prod-1」', verification }), { + status: 400, + }) + ) + ) + ) await expect(createUISettingsCandidate(candidateInput)).rejects.toThrow('找不到知识库 ID') const failure = await createUISettingsCandidate(candidateInput).catch((cause: unknown) => cause) expect(failure).toBeInstanceOf(UISettingsError) @@ -106,9 +225,17 @@ describe('UI settings API', () => { it('treats a missing or malformed verification block as no verification', () => { expect(parseServiceTargetVerification(undefined)).toBeNull() expect(parseServiceTargetVerification({ status: 'verified' })).toBeNull() - expect(parseServiceTargetVerification({ status: 'verified', message: 'x', blocked: false, test_endpoint: 'nope' })).toEqual({ - status: 'verified', message: 'x', blocked: false, knowledge_base_name: '', observed_tenant_id: '', - test_endpoint: { status: '', message: '' }, production_endpoint: { status: '', message: '' }, checked_at: '', + expect( + parseServiceTargetVerification({ status: 'verified', message: 'x', blocked: false, test_endpoint: 'nope' }) + ).toEqual({ + status: 'verified', + message: 'x', + blocked: false, + knowledge_base_name: '', + observed_tenant_id: '', + test_endpoint: { status: '', message: '' }, + production_endpoint: { status: '', message: '' }, + checked_at: '', }) }) }) diff --git a/web/src/uiSettings.ts b/web/src/uiSettings.ts index ee726b3..194b61d 100644 --- a/web/src/uiSettings.ts +++ b/web/src/uiSettings.ts @@ -30,7 +30,7 @@ export interface UISettingsCandidateInput { production_knowledge_base_id: string } -// 保存服务配置时后端会用生产地址真查一次:找到了才写入,并把知识库名回显; +// 保存连接配置时后端会用生产地址真查一次:找到了才写入,并把知识库名回显; // 端点明确回答"不存在"会拒绝保存(HTTP 400 + 这句 message),端点抖动只警告不拦。 export interface ServiceEndpointStatus { status: string @@ -98,7 +98,9 @@ export function validKnowledgeBaseID(value: string): boolean { return !/[\x00\r\n\t /?#\\]/.test(value) } -export function settingsRefreshDelays(settings: Pick) { +export function settingsRefreshDelays( + settings: Pick +) { return { documentMs: settings.document_refresh_seconds * 1000, resourceMs: settings.resource_refresh_seconds * 1000 } } @@ -107,25 +109,43 @@ const documentRefresh = new Set([15, 30, 60]) const resourceRefresh = new Set([30, 60]) const stalledAfter = new Set([1800, 3600]) const finalizingAfter = new Set([7200, 14400]) -const isRecord = (value: unknown): value is Record => Boolean(value) && typeof value === 'object' && !Array.isArray(value) +const isRecord = (value: unknown): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value) export function parseUISettingsResponse(value: unknown): UISettings { if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid UI settings response') const item = value.data - if (typeof item.id !== 'string' || !/^[A-Za-z0-9._:-]{2,36}$/.test(item.id) || - typeof item.state !== 'string' || !states.has(item.state) || - typeof item.document_refresh_seconds !== 'number' || !documentRefresh.has(item.document_refresh_seconds) || - typeof item.resource_refresh_seconds !== 'number' || !resourceRefresh.has(item.resource_refresh_seconds) || - typeof item.stalled_after_seconds !== 'number' || !stalledAfter.has(item.stalled_after_seconds) || - typeof item.finalizing_after_seconds !== 'number' || !finalizingAfter.has(item.finalizing_after_seconds) || - typeof item.ingestion_concurrency !== 'number' || !Number.isInteger(item.ingestion_concurrency) || item.ingestion_concurrency < 1 || item.ingestion_concurrency > 16 || - typeof item.test_weknora_base_url !== 'string' || !validServiceEndpoint(item.test_weknora_base_url) || - typeof item.production_weknora_base_url !== 'string' || !validServiceEndpoint(item.production_weknora_base_url) || - typeof item.production_tenant_id !== 'string' || !validProductionTenantID(item.production_tenant_id) || - typeof item.production_knowledge_base_id !== 'string' || !validKnowledgeBaseID(item.production_knowledge_base_id) || - typeof item.updated_by !== 'string' || typeof item.created_at !== 'string' || - (item.activated_at !== null && typeof item.activated_at !== 'string') || - (item.retired_at !== null && typeof item.retired_at !== 'string') || typeof item.error_code !== 'string') { + if ( + typeof item.id !== 'string' || + !/^[A-Za-z0-9._:-]{2,36}$/.test(item.id) || + typeof item.state !== 'string' || + !states.has(item.state) || + typeof item.document_refresh_seconds !== 'number' || + !documentRefresh.has(item.document_refresh_seconds) || + typeof item.resource_refresh_seconds !== 'number' || + !resourceRefresh.has(item.resource_refresh_seconds) || + typeof item.stalled_after_seconds !== 'number' || + !stalledAfter.has(item.stalled_after_seconds) || + typeof item.finalizing_after_seconds !== 'number' || + !finalizingAfter.has(item.finalizing_after_seconds) || + typeof item.ingestion_concurrency !== 'number' || + !Number.isInteger(item.ingestion_concurrency) || + item.ingestion_concurrency < 1 || + item.ingestion_concurrency > 16 || + typeof item.test_weknora_base_url !== 'string' || + !validServiceEndpoint(item.test_weknora_base_url) || + typeof item.production_weknora_base_url !== 'string' || + !validServiceEndpoint(item.production_weknora_base_url) || + typeof item.production_tenant_id !== 'string' || + !validProductionTenantID(item.production_tenant_id) || + typeof item.production_knowledge_base_id !== 'string' || + !validKnowledgeBaseID(item.production_knowledge_base_id) || + typeof item.updated_by !== 'string' || + typeof item.created_at !== 'string' || + (item.activated_at !== null && typeof item.activated_at !== 'string') || + (item.retired_at !== null && typeof item.retired_at !== 'string') || + typeof item.error_code !== 'string' + ) { throw new Error('invalid UI settings response') } return { @@ -149,13 +169,20 @@ export function parseUISettingsResponse(value: unknown): UISettings { } function parseEndpointStatus(value: unknown): ServiceEndpointStatus { - if (!isRecord(value) || typeof value.status !== 'string' || typeof value.message !== 'string') return { status: '', message: '' } + if (!isRecord(value) || typeof value.status !== 'string' || typeof value.message !== 'string') + return { status: '', message: '' } return { status: value.status, message: value.message } } // 核验块是诚实声明,解析失败按"没有核验"处理,绝不编造"已核验"。 export function parseServiceTargetVerification(value: unknown): ServiceTargetVerification | null { - if (!isRecord(value) || typeof value.status !== 'string' || typeof value.message !== 'string' || typeof value.blocked !== 'boolean') return null + if ( + !isRecord(value) || + typeof value.status !== 'string' || + typeof value.message !== 'string' || + typeof value.blocked !== 'boolean' + ) + return null return { status: value.status, message: value.message, @@ -176,7 +203,10 @@ async function readPayload(response: Response): Promise> // 拒绝保存时服务器给的就是要展示的那句话,别再退化成状态码。 const failure: unknown = await response.json().catch(() => null) const record = isRecord(failure) ? failure : {} - const message = typeof record.error === 'string' && record.error.trim() !== '' ? record.error : `UI settings request failed (${response.status})` + const message = + typeof record.error === 'string' && record.error.trim() !== '' + ? record.error + : `UI settings request failed (${response.status})` throw new UISettingsError(message, parseServiceTargetVerification(record.verification)) } @@ -186,7 +216,10 @@ async function readSettings(response: Response): Promise { async function readSettingsSave(response: Response): Promise { const payload = await readPayload(response) - return { settings: parseUISettingsResponse(payload), verification: parseServiceTargetVerification(payload.verification) } + return { + settings: parseUISettingsResponse(payload), + verification: parseServiceTargetVerification(payload.verification), + } } export async function fetchActiveUISettings(signal?: AbortSignal): Promise { @@ -194,14 +227,30 @@ export async function fetchActiveUISettings(signal?: AbortSignal): Promise { - return readSettingsSave(await fetch('/api/v1/ui-settings/candidates', { - method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'ui-settings', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(input), - })) + return readSettingsSave( + await fetch('/api/v1/ui-settings/candidates', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Governance-Action': 'ui-settings', + 'Idempotency-Key': newOperationID(), + }, + body: JSON.stringify(input), + }) + ) } export async function activateUISettings(revisionID: string): Promise { if (!/^[A-Za-z0-9._:-]{2,36}$/.test(revisionID)) throw new Error('invalid UI settings revision') - return readSettingsSave(await fetch(`/api/v1/ui-settings/${encodeURIComponent(revisionID)}/activate`, { - method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'ui-settings', 'Idempotency-Key': newOperationID() }, body: '{}', - })) -} \ No newline at end of file + return readSettingsSave( + await fetch(`/api/v1/ui-settings/${encodeURIComponent(revisionID)}/activate`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Governance-Action': 'ui-settings', + 'Idempotency-Key': newOperationID(), + }, + body: '{}', + }) + ) +} diff --git a/web/src/versionHistory.css b/web/src/versionHistory.css index e2127f6..476092b 100644 --- a/web/src/versionHistory.css +++ b/web/src/versionHistory.css @@ -4,28 +4,17 @@ flex-direction: column; gap: 18px; min-width: 0; - padding: 24px; + padding: 22px 24px 40px; color: var(--ink-base); } -.version-history-header, .version-history-current-card, .version-history-records { - background: var(--bg-panel, #fff); - border: 1px solid var(--border-base, #e2e8f0); + background: var(--bg-panel); + border: 1px solid var(--border-base); border-radius: 10px; padding: 20px; min-width: 0; } -.version-history-header { - display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; -} -.version-history h2 { - margin: 0 0 4px; - font-size: 22px; -} .version-history h3 { margin: 0; font-size: 18px; @@ -33,7 +22,7 @@ .version-history-header p, .version-history-records-heading p { margin: 0; - color: var(--ink-mute, #64748b); + color: var(--ink-mute); font-size: 13px; } .version-history-actions { @@ -48,19 +37,19 @@ display: grid; grid-template-columns: 0.8fr 0.8fr 2fr 1.3fr; margin: 16px 0 0; - border: 1px solid var(--border-base, #e2e8f0); - background: var(--bg-page, #f8fafc); + border: 1px solid var(--border-base); + background: var(--bg-page); } .version-history-build-grid > div { padding: 12px 14px; min-width: 0; - border-right: 1px solid var(--border-base, #e2e8f0); + border-right: 1px solid var(--border-base); } .version-history-build-grid > div:last-child { border-right: 0; } .version-history dt { - color: var(--ink-mute, #64748b); + color: var(--ink-mute); font-size: 12px; margin-bottom: 5px; } @@ -76,7 +65,7 @@ } .version-history-running-state { margin: 12px 0 0; - color: var(--ink-mute, #64748b); + color: var(--ink-mute); font-size: 12px; overflow-wrap: anywhere; } @@ -93,13 +82,13 @@ flex-wrap: wrap; gap: 8px; margin: 10px 0 14px; - color: var(--ink-mute, #64748b); + color: var(--ink-mute); font-size: 12px; } .version-history-notice { padding: 10px 14px; border-radius: 6px; - background: var(--c-run-bg, #eff6ff); + background: var(--c-run-bg); font-size: 13px; } .version-history-filters { @@ -116,9 +105,9 @@ } .version-history-filters button.active { font-weight: 600; - color: var(--c-run, #2563eb); - background: var(--c-run-bg, #eff6ff); - border-color: var(--c-run-border, #bfdbfe); + color: var(--c-run); + background: var(--c-run-bg); + border-color: var(--c-run-border); } .version-history-timeline { list-style: none; @@ -130,9 +119,9 @@ min-width: 0; } .version-history-entry { - border: 1px solid var(--border-base, #e2e8f0); + border: 1px solid var(--border-base); border-radius: 8px; - background: var(--bg-panel, #fff); + background: var(--bg-panel); min-width: 0; overflow: hidden; } @@ -155,14 +144,14 @@ font-weight: 400; } .version-history-entry-head:hover { - background: var(--bg-hover, #f8fafc); + background: var(--bg-hover); } .version-history-entry-head[aria-expanded='true'] { - background: var(--bg-page, #f8fafc); - border-bottom: 1px solid var(--border-base, #e2e8f0); + background: var(--bg-page); + border-bottom: 1px solid var(--border-base); } .version-history-entry-head:focus-visible { - outline: 2px solid var(--c-run, #2563eb); + outline: 2px solid var(--c-run); outline-offset: -3px; } .version-history-version { @@ -170,14 +159,14 @@ flex-shrink: 0; font-size: 13px; padding: 3px 8px; - border: 1px solid var(--border-strong, #cbd5e1); + border: 1px solid var(--border-strong); border-radius: 5px; font-weight: 500; color: var(--ink-mute); } .version-history-version.development { - border-color: #b4d1f5; - color: #2465aa; + border-color: var(--c-run-border); + color: var(--c-run); } .version-history-version.release { border-color: #b1d7bd; @@ -199,8 +188,8 @@ } .version-history-badge.pending, .version-history-badge.development { - color: #2465aa; - background: #eff6ff; + color: var(--c-run); + background: var(--c-run-bg); } .version-history-badge.release { color: #24814e; @@ -217,7 +206,7 @@ } .version-history-entry-head > .version-history-sha, .version-history-entry-head time { - color: var(--ink-faint, #7c8c9f); + color: var(--ink-faint); flex-shrink: 0; font-size: 12px; } @@ -231,7 +220,7 @@ .version-history-toggle { flex-shrink: 0; font-size: 13px; - color: var(--c-run, #2563eb); + color: var(--c-run); } .version-history-detail { padding: 16px; @@ -260,7 +249,7 @@ font-size: 12px; line-height: 1.6; background: #eef2f6; - color: #536275; + color: var(--ink-mute); } .version-history-change-tag.added { background: #eaf7ef; @@ -271,8 +260,8 @@ color: #986000; } .version-history-change-tag.changed { - background: #eff6ff; - color: #2465aa; + background: var(--c-run-bg); + color: var(--c-run); } .version-history-change-tag.security { background: #fff1ef; diff --git a/web/src/versionHistory.test.ts b/web/src/versionHistory.test.ts index 2684a2f..6032ec7 100644 --- a/web/src/versionHistory.test.ts +++ b/web/src/versionHistory.test.ts @@ -6,6 +6,11 @@ const jsonResponse = (body: unknown, status = 200) => afterEach(() => vi.unstubAllGlobals()) +// 用真实 Response(Node 全局):正文只能读一次,重复 json() 必然抛 TypeError。 +// 依赖"可重复 json()"的伪 mock 会把 double-read 的 bug 掩盖成绿。 +const realResponse = (body: unknown, status: number) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) + const pageBody = { items: [ { @@ -48,6 +53,18 @@ const pageBody = { }, } +describe('fetchVersionHistory 服务端错误详情', () => { + it('500 时把服务端的 error 与 code 带进异常消息(真实 Response,正文只能读一次)', async () => { + const errBody = { error: '读取版本记录失败', code: 'version_history_unavailable' } + const fetchMock = vi.fn(() => Promise.resolve(realResponse(errBody, 500))) + vi.stubGlobal('fetch', fetchMock) + await expect(fetchVersionHistory({ kind: 'all', cursor: '' })).rejects.toThrow( + /HTTP 500.*读取版本记录失败.*version_history_unavailable/s + ) + expect(fetchMock).toHaveBeenCalledOnce() + }) +}) + describe('versionHistory client', () => { it('loads a page, keeps the cursor and reads sync/current-running facts', async () => { const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse(pageBody)) diff --git a/web/src/versionHistory.ts b/web/src/versionHistory.ts index 4a38fc4..38f3aba 100644 --- a/web/src/versionHistory.ts +++ b/web/src/versionHistory.ts @@ -133,7 +133,11 @@ export async function fetchVersionHistory( if (response.status === 409 || code === 'cursor_expired') { throw new Error('这次翻页依据的记录快照已被清理,请刷新页面重新加载。') } - throw new Error(`加载版本记录失败(HTTP ${response.status})`) + // 正文在上面已经解析进 value 了;再调一次 response.json() 会抛 TypeError + // (Body already read),被吞掉后用户只能看到状态码。直接复用 value。 + const message = record(value) ? text(value.error) : '' + const detail = message || code ? `:${message || '无错误描述'}${code ? `(${code})` : ''}` : '' + throw new Error(`加载版本记录失败(HTTP ${response.status})${detail}`) } if (!record(value) || !Array.isArray(value.items) || !record(value.sync) || !record(value.current_running)) { throw new Error('版本记录响应无效') diff --git a/web/src/weknoraMonitor.css b/web/src/weknoraMonitor.css index 241df89..b93b676 100644 --- a/web/src/weknoraMonitor.css +++ b/web/src/weknoraMonitor.css @@ -1,68 +1,992 @@ -.weknora-monitor{max-width:1800px}.simulation-banner{display:flex;align-items:center;gap:14px;margin-bottom:14px;border:1px solid var(--c-warn);border-radius:10px;padding:10px 14px;background:var(--c-warn-bg);color:var(--c-warn)}.simulation-banner strong{padding:4px 7px;border-radius:5px;background:var(--c-warn);color:var(--c-warn);font-size:12px}.simulation-banner span{font-size:12px}.monitor-health{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;margin-bottom:16px}.monitor-health article{display:grid;gap:5px;border:1px solid var(--border-base);border-radius:11px;padding:13px;background:var(--bg-panel)}.monitor-health span{color:var(--ink-mute);font-size:11px}.monitor-health strong{color:var(--ink-strong);font-size:17px}.monitor-health small{color:var(--ink-mute);font-size:9px;line-height:1.5}.monitor-health .service-healthy{box-shadow:inset 0 3px var(--c-done)}.monitor-health .service-degraded,.monitor-health .service-unhealthy{box-shadow:inset 0 3px var(--c-warn)}.monitor-kb-layout{display:grid;grid-template-columns:285px minmax(0,1fr);gap:18px}.monitor-kb-list,.monitor-kb-detail{min-width:0;border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.monitor-kb-list{padding:12px}.monitor-kb-list h2{margin:5px 8px 12px;color:var(--ink-base);font-size:13px}.monitor-kb-list button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;border:1px solid transparent;border-radius:9px;padding:12px;background:transparent;box-shadow:none;color:var(--ink-base);text-align:left}.monitor-kb-list button.active{border-color:var(--c-run-border);background:var(--c-run-bg);color:var(--c-run)}.monitor-kb-list button>span{display:grid;gap:4px}.monitor-kb-list small{color:var(--ink-mute);font-size:10px}.monitor-kb-list strong{font-size:10px}.monitor-kb-heading{display:flex;align-items:center;justify-content:space-between;gap:15px;border-bottom:1px solid var(--border-base);padding:15px 18px}.monitor-kb-heading>div{display:flex;align-items:center;gap:12px}.monitor-kb-heading h2{margin:0;color:var(--ink-strong);font-size:16px}.monitor-kb-heading span{color:var(--ink-mute);font-size:11px}.monitor-stage-tabs{display:flex;flex-wrap:wrap;gap:7px;padding:13px 18px}.monitor-stage-tabs button{border:1px solid var(--border-base);border-radius:8px;padding:7px 9px;background:var(--bg-soft);box-shadow:none;color:var(--ink-base);font-size:11px}.monitor-stage-tabs button.active{border-color:var(--c-run);background:var(--c-run-bg);color:var(--c-run)}.finalizing-note,.sample-note{margin:0 18px 10px;border-radius:7px;padding:8px 10px;background:var(--bg-soft);color:var(--ink-mute);font-size:10px;line-height:1.6}.sample-note{background:var(--c-warn-bg);color:var(--c-warn)}.monitor-file-wrap{max-height:calc(100vh - 540px);overflow:auto}.monitor-file-table{width:100%;table-layout:fixed}.monitor-file-table thead th{position:sticky;z-index:2;top:0;background:var(--bg-soft)}.monitor-file-table th,.monitor-file-table td{padding:12px 10px;white-space:normal;overflow-wrap:anywhere;font-size:11px}.monitor-file-table th:nth-child(1){width:22%}.monitor-file-table th:nth-child(2){width:20%}.monitor-file-table th:nth-child(3){width:11%}.monitor-file-table th:nth-child(4){width:11%}.monitor-file-table th:nth-child(5){width:9%}.monitor-file-table th:nth-child(6){width:27%}.monitor-file-table small{display:block;margin-top:4px;color:var(--c-warn)}.monitor-status{display:inline-block;border-radius:6px;padding:4px 6px;background:var(--bg-soft);color:var(--ink-mute);white-space:nowrap}.monitor-status.completed{background:var(--c-done-bg);color:var(--c-done)}.monitor-status.finalizing,.monitor-status.processing{background:var(--c-run-bg);color:var(--c-run)}.monitor-status.failed{background:var(--c-warn-bg);color:var(--c-warn)}@media(max-width:1200px){.monitor-health{grid-template-columns:repeat(3,minmax(0,1fr))}.monitor-kb-layout{grid-template-columns:230px minmax(0,1fr)}}@media(max-width:800px){.monitor-health{grid-template-columns:repeat(2,minmax(0,1fr))}.monitor-kb-layout{grid-template-columns:1fr}.monitor-file-table{min-width:800px}.monitor-kb-heading{align-items:flex-start;flex-direction:column}.monitor-kb-heading>div{flex-wrap:wrap}} -.difference-panel{margin-bottom:18px;overflow:hidden;border:1px solid var(--c-run-border);border-radius:14px;background:var(--bg-panel)}.difference-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 16px;background:var(--c-run-bg)}.difference-heading h2{margin:0 0 4px;color:var(--ink-base);font-size:15px}.difference-heading p{margin:0;color:var(--ink-mute);font-size:10px}.difference-counts{display:flex;gap:7px}.difference-counts span{border-radius:7px;padding:7px 9px;background:var(--c-run-bg);color:var(--c-run);font-size:10px;font-weight:750;white-space:nowrap}.difference-panel details{border-top:1px solid var(--border-base)}.difference-panel summary{cursor:pointer;padding:10px 16px;color:var(--ink-base);font-size:10px;font-weight:750}.difference-table-wrap{max-height:260px;overflow:auto}.difference-table{width:100%;table-layout:fixed}.difference-table th,.difference-table td{padding:9px 12px;white-space:normal;overflow-wrap:anywhere;font-size:10px}.difference-confirmation{display:grid;grid-template-columns:minmax(150px,.6fr) minmax(280px,1.4fr) auto;align-items:end;gap:9px;border-top:1px solid var(--border-base);padding:12px 16px}.difference-confirmation label{display:grid;gap:4px;color:var(--ink-mute);font-size:9px}.difference-confirmation input{border:1px solid var(--border-strong);border-radius:7px;padding:8px;color:var(--ink-base)}.difference-confirmation button{padding:8px 11px}.difference-message{margin:0;border-top:1px solid var(--border-base);padding:9px 16px;background:var(--c-done-bg);color:var(--c-done);font-size:10px}@media(max-width:760px){.difference-heading{align-items:flex-start;flex-direction:column}.difference-counts{flex-wrap:wrap}.difference-confirmation{grid-template-columns:1fr}} -.persisted-change-panel{margin-bottom:18px;overflow:hidden;border:1px solid var(--c-run-border);border-radius:12px;background:var(--bg-panel)}.persisted-change-heading{display:flex;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid var(--border-base);padding:13px 16px;background:var(--bg-soft)}.persisted-change-heading h2{margin:0 0 4px;color:var(--ink-base);font-size:15px}.persisted-change-heading p{margin:0;color:var(--ink-mute);font-size:10px}.persisted-change-heading>span{border-radius:6px;padding:6px 8px;background:var(--c-run-bg);color:var(--c-run);font-size:10px;font-weight:750}.persisted-change-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;padding:12px}.persisted-change-grid>article{min-width:0;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-panel)}.persisted-change-grid>article>div:first-child{display:flex;align-items:center;justify-content:space-between;gap:8px}.persisted-change-grid strong{color:var(--ink-base);font-size:11px}.persisted-change-grid small{color:var(--ink-mute);font-size:9px}.persisted-change-counts{display:flex;flex-wrap:wrap;gap:5px;margin-top:8px}.persisted-change-counts span{border-radius:5px;padding:5px 7px;background:var(--border-soft);color:var(--ink-mute);font-size:9px}.persisted-change-counts span:nth-child(1){background:var(--c-done-bg);color:var(--c-done)}.persisted-change-counts span:nth-child(2),.persisted-change-counts span:nth-child(3){background:var(--c-run-bg);color:var(--c-run)}.persisted-change-counts span:nth-child(4){background:var(--c-fail-bg);color:var(--c-fail)}.persisted-change-grid details{margin-top:8px;border-top:1px solid var(--border-base)}.persisted-change-grid summary{cursor:pointer;padding-top:8px;color:var(--c-run);font-size:9px;font-weight:750}.persisted-change-grid details p{display:grid;grid-template-columns:auto minmax(100px,.7fr) minmax(160px,1.3fr);gap:7px;margin:7px 0 0;align-items:center}.persisted-change-grid details b{border-radius:4px;padding:3px 5px;background:var(--border-soft);color:var(--ink-mute);font-size:8px}.persisted-change-grid details span,.persisted-change-grid details small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}@media(max-width:900px){.persisted-change-grid{grid-template-columns:1fr}}@media(max-width:600px){.persisted-change-heading{align-items:flex-start;flex-direction:column}.persisted-change-grid details p{grid-template-columns:auto 1fr}.persisted-change-grid details small{grid-column:1/-1}} -.processing-queue-panel{margin-top:18px;overflow:hidden;border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.queue-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;border-bottom:1px solid var(--border-base);padding:14px 16px}.queue-heading h2{margin:0 0 4px;color:var(--ink-base);font-size:15px}.queue-heading p{margin:0;color:var(--ink-mute);font-size:10px}.queue-heading>div:last-child{display:flex;align-items:end;gap:8px}.queue-heading label{display:grid;gap:4px;color:var(--ink-mute);font-size:9px}.queue-heading select{border:1px solid var(--border-strong);border-radius:7px;padding:7px;background:var(--bg-panel);color:var(--ink-base)}.queue-heading button{padding:8px 10px;box-shadow:none}.pipeline-strip{overflow-x:auto;border-bottom:1px solid var(--border-base);padding:10px 16px;background:var(--bg-soft);color:var(--ink-base);font-size:10px;font-weight:750;white-space:nowrap}.queue-table-wrap{max-height:420px;overflow:auto}.processing-queue-table{min-width:940px;table-layout:fixed}.processing-queue-table th,.processing-queue-table td{padding:10px 8px;white-space:normal;overflow-wrap:anywhere;font-size:10px}.processing-queue-table th:nth-child(1){width:18%}.processing-queue-table th:nth-child(2){width:13%}.processing-queue-table th:nth-child(3){width:10%}.processing-queue-table th:nth-child(4){width:12%}.processing-queue-table th:nth-child(5){width:17%}.processing-queue-table th:nth-child(6){width:6%}.processing-queue-table th:nth-child(7){width:14%}.processing-queue-table th:nth-child(8){width:10%}.processing-queue-table .queue-problem{background:var(--c-fail-bg)}.processing-queue-table button{padding:6px 8px;box-shadow:none;font-size:9px}.monitor-status.stalled{background:var(--c-warn-bg);color:var(--c-warn)}@media(max-width:700px){.queue-heading{align-items:stretch;flex-direction:column}.queue-heading>div:last-child{align-items:stretch;flex-direction:column}}.changeset-selection{display:flex;flex-direction:column;gap:6px;margin-top:8px} -.changeset-choice{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ink-base)} -.changeset-choice b{flex:0 0 78px;font-weight:700;color:var(--ink-base)} -.changeset-choice span{overflow-wrap:anywhere} -.changeset-choice small{color:var(--ink-faint)} -.changeset-confirm{display:flex;align-items:center;gap:10px;margin-top:10px} -.changeset-confirm label{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--ink-mute);font-weight:700} -.changeset-confirm input{border:1px solid var(--border-strong);border-radius:7px;padding:6px 8px;background:var(--bg-panel);color:var(--ink-base);font:inherit} -.queue-batch-controls{display:inline-flex;align-items:center;gap:8px;margin-left:10px} -.queue-batch-controls input{width:130px} -.queue-batch-message{margin:6px 0;color:var(--c-done)} -.dlq-panel{margin-top:14px} -.dlq-list{list-style:none;margin:8px 0 0;padding:0;display:flex;flex-direction:column;gap:6px} -.dlq-list li{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:8px 10px;border:1px solid var(--border-strong);border-radius:8px;background:var(--bg-page)} -.dlq-list li small{flex-basis:100%;margin-left:2px;color:var(--ink-mute)} -.dlq-list small{margin-left:auto;color:var(--c-dead)} -.run-metrics{margin-top:14px} -.run-metrics-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:8px;margin-top:8px} -.run-metrics-grid article{border:1px solid var(--border-strong);border-radius:8px;padding:8px 10px;background:var(--bg-panel);display:flex;flex-direction:column;gap:2px} -.run-metrics-grid span{font-size:12px;color:var(--c-dead)} -.run-metrics-grid strong{font-size:16px} -.run-metrics-grid small{font-size:12px;color:var(--c-dead)} +.weknora-monitor { + max-width: 1800px; +} +.simulation-banner { + display: flex; + align-items: center; + gap: 14px; + margin-bottom: 14px; + border: 1px solid var(--c-warn); + border-radius: 10px; + padding: 10px 14px; + background: var(--c-warn-bg); + color: var(--c-warn); +} +.simulation-banner strong { + padding: 4px 7px; + border-radius: 5px; + background: var(--c-warn); + color: var(--c-warn); + font-size: 12px; +} +.simulation-banner span { + font-size: 12px; +} +.monitor-health { + display: grid; + grid-template-columns: repeat(6, minmax(0, 1fr)); + gap: 10px; + margin-bottom: 16px; +} +.monitor-health article { + display: grid; + gap: 5px; + border: 1px solid var(--border-base); + border-radius: 11px; + padding: 13px; + background: var(--bg-panel); +} +.monitor-health span { + color: var(--ink-mute); + font-size: 11px; +} +.monitor-health strong { + color: var(--ink-strong); + font-size: 17px; +} +.monitor-health small { + color: var(--ink-mute); + font-size: 9px; + line-height: 1.5; +} +.monitor-health .service-healthy { + box-shadow: inset 0 3px var(--c-done); +} +.monitor-health .service-degraded, +.monitor-health .service-unhealthy { + box-shadow: inset 0 3px var(--c-warn); +} +.monitor-kb-layout { + display: grid; + grid-template-columns: 285px minmax(0, 1fr); + gap: 18px; +} +.monitor-kb-list, +.monitor-kb-detail { + min-width: 0; + border: 1px solid var(--border-base); + border-radius: 14px; + background: var(--bg-panel); +} +.monitor-kb-list { + padding: 12px; +} +.monitor-kb-list h2 { + margin: 5px 8px 12px; + color: var(--ink-base); + font-size: 13px; +} +.monitor-kb-list button { + display: flex; + width: 100%; + align-items: center; + justify-content: space-between; + gap: 10px; + border: 1px solid transparent; + border-radius: 9px; + padding: 12px; + background: transparent; + box-shadow: none; + color: var(--ink-base); + text-align: left; +} +.monitor-kb-list button.active { + border-color: var(--c-run-border); + background: var(--c-run-bg); + color: var(--c-run); +} +.monitor-kb-list button > span { + display: grid; + gap: 4px; +} +.monitor-kb-list small { + color: var(--ink-mute); + font-size: 10px; +} +.monitor-kb-list strong { + font-size: 10px; +} +.monitor-kb-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 15px; + border-bottom: 1px solid var(--border-base); + padding: 15px 18px; +} +.monitor-kb-heading > div { + display: flex; + align-items: center; + gap: 12px; +} +.monitor-kb-heading h2 { + margin: 0; + color: var(--ink-strong); + font-size: 16px; +} +.monitor-kb-heading span { + color: var(--ink-mute); + font-size: 11px; +} +.monitor-stage-tabs { + display: flex; + flex-wrap: wrap; + gap: 7px; + padding: 13px 18px; +} +.monitor-stage-tabs button { + border: 1px solid var(--border-base); + border-radius: 8px; + padding: 7px 9px; + background: var(--bg-soft); + box-shadow: none; + color: var(--ink-base); + font-size: 11px; +} +.monitor-stage-tabs button.active { + border-color: var(--c-run); + background: var(--c-run-bg); + color: var(--c-run); +} +.finalizing-note, +.sample-note { + margin: 0 18px 10px; + border-radius: 7px; + padding: 8px 10px; + background: var(--bg-soft); + color: var(--ink-mute); + font-size: 10px; + line-height: 1.6; +} +.sample-note { + background: var(--c-warn-bg); + color: var(--c-warn); +} +.monitor-file-wrap { + max-height: calc(100vh - 540px); + overflow: auto; +} +.monitor-file-table { + width: 100%; + table-layout: fixed; +} +.monitor-file-table thead th { + position: sticky; + z-index: 2; + top: 0; + background: var(--bg-soft); +} +.monitor-file-table th, +.monitor-file-table td { + padding: 12px 10px; + white-space: normal; + overflow-wrap: anywhere; + font-size: 11px; +} +.monitor-file-table th:nth-child(1) { + width: 22%; +} +.monitor-file-table th:nth-child(2) { + width: 20%; +} +.monitor-file-table th:nth-child(3) { + width: 11%; +} +.monitor-file-table th:nth-child(4) { + width: 11%; +} +.monitor-file-table th:nth-child(5) { + width: 9%; +} +.monitor-file-table th:nth-child(6) { + width: 27%; +} +.monitor-file-table small { + display: block; + margin-top: 4px; + color: var(--c-warn); +} +.monitor-status { + display: inline-block; + border-radius: 6px; + padding: 4px 6px; + background: var(--bg-soft); + color: var(--ink-mute); + white-space: nowrap; +} +.monitor-status.completed { + background: var(--c-done-bg); + color: var(--c-done); +} +.monitor-status.finalizing, +.monitor-status.processing { + background: var(--c-run-bg); + color: var(--c-run); +} +.monitor-status.failed { + background: var(--c-warn-bg); + color: var(--c-warn); +} +@media (max-width: 1200px) { + .monitor-health { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .monitor-kb-layout { + grid-template-columns: 230px minmax(0, 1fr); + } +} +@media (max-width: 800px) { + .monitor-health { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .monitor-kb-layout { + grid-template-columns: 1fr; + } + .monitor-file-table { + min-width: 800px; + } + .monitor-kb-heading { + align-items: flex-start; + flex-direction: column; + } + .monitor-kb-heading > div { + flex-wrap: wrap; + } +} +.difference-panel { + margin-bottom: 18px; + overflow: hidden; + border: 1px solid var(--c-run-border); + border-radius: 14px; + background: var(--bg-panel); +} +.difference-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 14px 16px; + background: var(--c-run-bg); +} +.difference-heading h2 { + margin: 0 0 4px; + color: var(--ink-base); + font-size: 15px; +} +.difference-heading p { + margin: 0; + color: var(--ink-mute); + font-size: 10px; +} +.difference-counts { + display: flex; + gap: 7px; +} +.difference-counts span { + border-radius: 7px; + padding: 7px 9px; + background: var(--c-run-bg); + color: var(--c-run); + font-size: 10px; + font-weight: 750; + white-space: nowrap; +} +.difference-panel details { + border-top: 1px solid var(--border-base); +} +.difference-panel summary { + cursor: pointer; + padding: 10px 16px; + color: var(--ink-base); + font-size: 10px; + font-weight: 750; +} +.difference-table-wrap { + max-height: 260px; + overflow: auto; +} +.difference-table { + width: 100%; + table-layout: fixed; +} +.difference-table th, +.difference-table td { + padding: 9px 12px; + white-space: normal; + overflow-wrap: anywhere; + font-size: 10px; +} +.difference-confirmation { + display: grid; + grid-template-columns: minmax(150px, 0.6fr) minmax(280px, 1.4fr) auto; + align-items: end; + gap: 9px; + border-top: 1px solid var(--border-base); + padding: 12px 16px; +} +.difference-confirmation label { + display: grid; + gap: 4px; + color: var(--ink-mute); + font-size: 9px; +} +.difference-confirmation input { + border: 1px solid var(--border-strong); + border-radius: 7px; + padding: 8px; + color: var(--ink-base); +} +.difference-confirmation button { + padding: 8px 11px; +} +.difference-message { + margin: 0; + border-top: 1px solid var(--border-base); + padding: 9px 16px; + background: var(--c-done-bg); + color: var(--c-done); + font-size: 10px; +} +@media (max-width: 760px) { + .difference-heading { + align-items: flex-start; + flex-direction: column; + } + .difference-counts { + flex-wrap: wrap; + } + .difference-confirmation { + grid-template-columns: 1fr; + } +} +.persisted-change-panel { + margin-bottom: 18px; + overflow: hidden; + border: 1px solid var(--c-run-border); + border-radius: 12px; + background: var(--bg-panel); +} +.persisted-change-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + border-bottom: 1px solid var(--border-base); + padding: 13px 16px; + background: var(--bg-soft); +} +.persisted-change-heading h2 { + margin: 0 0 4px; + color: var(--ink-base); + font-size: 15px; +} +.persisted-change-heading p { + margin: 0; + color: var(--ink-mute); + font-size: 10px; +} +.persisted-change-heading > span { + border-radius: 6px; + padding: 6px 8px; + background: var(--c-run-bg); + color: var(--c-run); + font-size: 10px; + font-weight: 750; +} +.persisted-change-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; + padding: 12px; +} +.persisted-change-grid > article { + min-width: 0; + border: 1px solid var(--border-base); + border-radius: 9px; + padding: 11px; + background: var(--bg-panel); +} +.persisted-change-grid > article > div:first-child { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} +.persisted-change-grid strong { + color: var(--ink-base); + font-size: 11px; +} +.persisted-change-grid small { + color: var(--ink-mute); + font-size: 9px; +} +.persisted-change-counts { + display: flex; + flex-wrap: wrap; + gap: 5px; + margin-top: 8px; +} +.persisted-change-counts span { + border-radius: 5px; + padding: 5px 7px; + background: var(--border-soft); + color: var(--ink-mute); + font-size: 9px; +} +.persisted-change-counts span:nth-child(1) { + background: var(--c-done-bg); + color: var(--c-done); +} +.persisted-change-counts span:nth-child(2), +.persisted-change-counts span:nth-child(3) { + background: var(--c-run-bg); + color: var(--c-run); +} +.persisted-change-counts span:nth-child(4) { + background: var(--c-fail-bg); + color: var(--c-fail); +} +.persisted-change-grid details { + margin-top: 8px; + border-top: 1px solid var(--border-base); +} +.persisted-change-grid summary { + cursor: pointer; + padding-top: 8px; + color: var(--c-run); + font-size: 9px; + font-weight: 750; +} +.persisted-change-grid details p { + display: grid; + grid-template-columns: auto minmax(100px, 0.7fr) minmax(160px, 1.3fr); + gap: 7px; + margin: 7px 0 0; + align-items: center; +} +.persisted-change-grid details b { + border-radius: 4px; + padding: 3px 5px; + background: var(--border-soft); + color: var(--ink-mute); + font-size: 8px; +} +.persisted-change-grid details span, +.persisted-change-grid details small { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +@media (max-width: 900px) { + .persisted-change-grid { + grid-template-columns: 1fr; + } +} +@media (max-width: 600px) { + .persisted-change-heading { + align-items: flex-start; + flex-direction: column; + } + .persisted-change-grid details p { + grid-template-columns: auto 1fr; + } + .persisted-change-grid details small { + grid-column: 1/-1; + } +} +.processing-queue-panel { + margin-top: 18px; + overflow: hidden; + border: 1px solid var(--border-base); + border-radius: 14px; + background: var(--bg-panel); +} +.queue-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + border-bottom: 1px solid var(--border-base); + padding: 14px 16px; +} +.queue-heading h2 { + margin: 0 0 4px; + color: var(--ink-base); + font-size: 15px; +} +.queue-heading p { + margin: 0; + color: var(--ink-mute); + font-size: 10px; +} +.queue-heading > div:last-child { + display: flex; + align-items: end; + gap: 8px; +} +.queue-heading label { + display: grid; + gap: 4px; + color: var(--ink-mute); + font-size: 9px; +} +.queue-heading select { + border: 1px solid var(--border-strong); + border-radius: 7px; + padding: 7px; + background: var(--bg-panel); + color: var(--ink-base); +} +.queue-heading button { + padding: 8px 10px; + box-shadow: none; +} +.pipeline-strip { + overflow-x: auto; + border-bottom: 1px solid var(--border-base); + padding: 10px 16px; + background: var(--bg-soft); + color: var(--ink-base); + font-size: 10px; + font-weight: 750; + white-space: nowrap; +} +.queue-table-wrap { + max-height: 420px; + overflow: auto; +} +.processing-queue-table { + min-width: 940px; + table-layout: fixed; +} +.processing-queue-table th, +.processing-queue-table td { + padding: 10px 8px; + white-space: normal; + overflow-wrap: anywhere; + font-size: 10px; +} +.processing-queue-table th:nth-child(1) { + width: 18%; +} +.processing-queue-table th:nth-child(2) { + width: 13%; +} +.processing-queue-table th:nth-child(3) { + width: 10%; +} +.processing-queue-table th:nth-child(4) { + width: 12%; +} +.processing-queue-table th:nth-child(5) { + width: 17%; +} +.processing-queue-table th:nth-child(6) { + width: 6%; +} +.processing-queue-table th:nth-child(7) { + width: 14%; +} +.processing-queue-table th:nth-child(8) { + width: 10%; +} +.processing-queue-table .queue-problem { + background: var(--c-fail-bg); +} +.processing-queue-table button { + padding: 6px 8px; + box-shadow: none; + font-size: 9px; +} +.monitor-status.stalled { + background: var(--c-warn-bg); + color: var(--c-warn); +} +@media (max-width: 700px) { + .queue-heading { + align-items: stretch; + flex-direction: column; + } + .queue-heading > div:last-child { + align-items: stretch; + flex-direction: column; + } +} +.changeset-selection { + display: flex; + flex-direction: column; + gap: 6px; + margin-top: 8px; +} +.changeset-choice { + display: flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: var(--ink-base); +} +.changeset-choice b { + flex: 0 0 78px; + font-weight: 700; + color: var(--ink-base); +} +.changeset-choice span { + overflow-wrap: anywhere; +} +.changeset-choice small { + color: var(--ink-faint); +} +.changeset-confirm { + display: flex; + align-items: center; + gap: 10px; + margin-top: 10px; +} +.changeset-confirm label { + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + color: var(--ink-mute); + font-weight: 700; +} +.changeset-confirm input { + border: 1px solid var(--border-strong); + border-radius: 7px; + padding: 6px 8px; + background: var(--bg-panel); + color: var(--ink-base); + font: inherit; +} +.queue-batch-controls { + display: inline-flex; + align-items: center; + gap: 8px; + margin-left: 10px; +} +.queue-batch-controls input { + width: 130px; +} +.queue-batch-message { + margin: 6px 0; + color: var(--c-done); +} +.dlq-panel { + margin-top: 14px; +} +.dlq-list { + list-style: none; + margin: 8px 0 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 6px; +} +.dlq-list li { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + padding: 8px 10px; + border: 1px solid var(--border-strong); + border-radius: 8px; + background: var(--bg-page); +} +.dlq-list li small { + flex-basis: 100%; + margin-left: 2px; + color: var(--ink-mute); +} +.dlq-list small { + margin-left: auto; + color: var(--c-dead); +} +.run-metrics { + margin-top: 14px; +} +.run-metrics-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 8px; + margin-top: 8px; +} +.run-metrics-grid article { + border: 1px solid var(--border-strong); + border-radius: 8px; + padding: 8px 10px; + background: var(--bg-panel); + display: flex; + flex-direction: column; + gap: 2px; +} +.run-metrics-grid span { + font-size: 12px; + color: var(--c-dead); +} +.run-metrics-grid strong { + font-size: 16px; +} +.run-metrics-grid small { + font-size: 12px; + color: var(--c-dead); +} /* P7 direction B: task-inbox layout */ -.inbox-layout .hero.compact{display:flex;align-items:center;gap:14px} -.monitor-meta{color:var(--c-dead);font-size:12px;margin-left:auto} -.inbox-grid{display:grid;grid-template-columns:230px minmax(0,1fr);gap:14px;align-items:start;margin-top:12px} -.inbox-nav{background:var(--bg-panel);border:1px solid var(--border-strong);border-radius:8px;position:sticky;top:14px;overflow:hidden} -.inbox-nav h2{font-size:13px;margin:0;padding:10px 14px;border-bottom:1px solid var(--border-strong);color:var(--c-dead);font-weight:600} -.inbox-nav button{display:flex;justify-content:space-between;align-items:center;width:100%;padding:9px 14px;border:none;border-bottom:1px solid var(--bg-soft);background:none;color:var(--ink-strong);font:inherit;font-size:13px;cursor:pointer;text-align:left} -.inbox-nav button.active{background:var(--c-run-bg);border-left:3px solid var(--ink-strong);padding-left:11px;font-weight:600} -.inbox-nav .lane-count{font-style:normal;font-size:12px;padding:0 8px;border-radius:999px;background:var(--c-dead-bg);color:var(--c-dead)} -.inbox-nav button.blocked .lane-count{background:var(--c-fail-bg);color:var(--c-fail)} -.inbox-nav button.okall .lane-count{background:var(--c-done-bg);color:var(--c-done)} -.inbox-work{display:flex;flex-direction:column;gap:14px;min-width:0} -.inbox-section{background:var(--bg-panel);border:1px solid var(--border-strong);border-radius:8px;padding-bottom:4px} -.section-head{display:flex;align-items:center;gap:10px;padding:10px 14px;border-bottom:1px solid var(--border-strong);flex-wrap:wrap} -.section-head h2{font-size:14px;margin:0} -.section-head h3{font-size:13px;margin:0} -.section-head .spacer{flex:1} -.inbox-task{display:grid;grid-template-columns:28px minmax(0,1fr) auto;gap:12px;padding:12px 14px;border-bottom:1px solid var(--bg-soft);align-items:start} -.inbox-task:last-child{border-bottom:none} -.inbox-task h4{margin:0;font-size:14px;display:flex;align-items:center;gap:6px;flex-wrap:wrap} -.inbox-task .why{font-size:12px;color:var(--c-dead);margin-top:3px} -.task-chain{margin-top:8px;display:flex;gap:4px;align-items:center;flex-wrap:wrap;font-size:11px;color:var(--c-dead)} -.chain-step{padding:2px 8px;border-radius:4px;border:1px solid var(--border-strong);background:var(--bg-page);white-space:nowrap} -.chain-step.done{background:var(--c-done-bg);border-color:var(--c-done-border);color:var(--c-done)} -.chain-step.bad{background:var(--c-fail-bg);border-color:var(--c-fail-border);color:var(--c-fail);font-weight:600} -.chain-step.active{color:var(--c-run);border-color:var(--c-run-border);background:var(--c-run-bg)} -.errline{margin-top:6px;font-size:12px;color:var(--c-fail)} -.task-badge{font-size:12px;padding:1px 8px;border-radius:4px;border:1px solid var(--border-strong);white-space:nowrap} -.task-badge.add{color:var(--c-done)}.task-badge.update{color:var(--c-run)} -.inbox-task-actions{display:flex;flex-direction:column;gap:6px;align-items:flex-end} -.inbox-task-actions .primary{background:var(--ink-strong);color:var(--bg-panel);border-color:var(--ink-strong)} -button.danger{background:var(--c-fail);color:#fff;border-color:var(--c-fail)} -button.danger:hover:not(:disabled){background:#991b1b;border-color:#991b1b} -button.danger:disabled{background:var(--c-fail-border);color:#fff;border-color:var(--c-fail-border)} -.queue-more{display:flex;align-items:center;gap:12px;justify-content:center;padding:12px 0;font-size:13px;color:var(--c-dead)} -.operator-input{font:inherit;padding:5px 8px;border:1px solid var(--border-strong);border-radius:6px;width:120px} -.tiny{font-size:12px;color:var(--c-dead)} -.monitor-strip{display:flex;overflow-x:auto;background:var(--bg-panel);border:1px solid var(--border-strong);border-radius:8px;font-size:12px} -.monitor-strip div{padding:8px 16px;border-right:1px solid var(--border-strong);white-space:nowrap} -.monitor-strip div:last-child{border-right:none} -.monitor-strip .bad{color:var(--c-fail)}.monitor-strip .good{color:var(--c-done)} -.dlq-list button{margin-left:auto;padding:2px 10px;border:1px solid var(--border-strong);border-radius:6px;background:var(--bg-panel);cursor:pointer;font-size:12px} -@media (max-width: 900px){.inbox-grid{grid-template-columns:1fr}.inbox-nav{position:static}} +.inbox-layout .hero.compact { + display: flex; + align-items: center; + gap: 14px; +} +.monitor-meta { + color: var(--c-dead); + font-size: 12px; + margin-left: auto; +} +.inbox-grid { + display: grid; + grid-template-columns: 230px minmax(0, 1fr); + gap: 14px; + align-items: start; + margin-top: 12px; +} +.inbox-nav { + background: var(--bg-panel); + border: 1px solid var(--border-strong); + border-radius: 8px; + position: sticky; + top: 14px; + overflow: hidden; +} +.inbox-nav h2 { + font-size: 13px; + margin: 0; + padding: 10px 14px; + border-bottom: 1px solid var(--border-strong); + color: var(--c-dead); + font-weight: 600; +} +.inbox-nav button { + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; + padding: 9px 14px; + border: none; + border-bottom: 1px solid var(--bg-soft); + background: none; + color: var(--ink-strong); + font: inherit; + font-size: 13px; + cursor: pointer; + text-align: left; +} +.inbox-nav button.active { + background: var(--c-run-bg); + border-left: 3px solid var(--ink-strong); + padding-left: 11px; + font-weight: 600; +} +.inbox-nav .lane-count { + font-style: normal; + font-size: 12px; + padding: 0 8px; + border-radius: 999px; + background: var(--c-dead-bg); + color: var(--c-dead); +} +.inbox-nav button.blocked .lane-count { + background: var(--c-fail-bg); + color: var(--c-fail); +} +.inbox-nav button.okall .lane-count { + background: var(--c-done-bg); + color: var(--c-done); +} +.inbox-work { + display: flex; + flex-direction: column; + gap: 14px; + min-width: 0; +} +.inbox-section { + background: var(--bg-panel); + border: 1px solid var(--border-strong); + border-radius: 8px; + padding-bottom: 4px; +} +.section-head { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 14px; + border-bottom: 1px solid var(--border-strong); + flex-wrap: wrap; +} +.section-head h2 { + font-size: 14px; + margin: 0; +} +.section-head h3 { + font-size: 13px; + margin: 0; +} +.section-head .spacer { + flex: 1; +} +.inbox-task { + display: grid; + grid-template-columns: 28px minmax(0, 1fr) auto; + gap: 12px; + padding: 12px 14px; + border-bottom: 1px solid var(--bg-soft); + align-items: start; +} +.inbox-task:last-child { + border-bottom: none; +} +.inbox-task h4 { + margin: 0; + font-size: 14px; + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; +} +.inbox-task .why { + font-size: 12px; + color: var(--c-dead); + margin-top: 3px; +} +.task-chain { + margin-top: 8px; + display: flex; + gap: 4px; + align-items: center; + flex-wrap: wrap; + font-size: 11px; + color: var(--c-dead); +} +.chain-step { + padding: 2px 8px; + border-radius: 4px; + border: 1px solid var(--border-strong); + background: var(--bg-page); + white-space: nowrap; +} +.chain-step.done { + background: var(--c-done-bg); + border-color: var(--c-done-border); + color: var(--c-done); +} +.chain-step.bad { + background: var(--c-fail-bg); + border-color: var(--c-fail-border); + color: var(--c-fail); + font-weight: 600; +} +.chain-step.active { + color: var(--c-run); + border-color: var(--c-run-border); + background: var(--c-run-bg); +} +.errline { + margin-top: 6px; + font-size: 12px; + color: var(--c-fail); +} +.task-badge { + font-size: 12px; + padding: 1px 8px; + border-radius: 4px; + border: 1px solid var(--border-strong); + white-space: nowrap; +} +.task-badge.add { + color: var(--c-done); +} +.task-badge.update { + color: var(--c-run); +} +.inbox-task-actions { + display: flex; + flex-direction: column; + gap: 6px; + align-items: flex-end; +} +.inbox-task-actions .primary { + background: var(--ink-strong); + color: var(--bg-panel); + border-color: var(--ink-strong); +} +button.danger { + background: var(--c-fail); + color: #fff; + border-color: var(--c-fail); +} +button.danger:hover:not(:disabled) { + background: #991b1b; + border-color: #991b1b; +} +button.danger:disabled { + background: var(--c-fail-border); + color: #fff; + border-color: var(--c-fail-border); +} +.queue-more { + display: flex; + align-items: center; + gap: 12px; + justify-content: center; + padding: 12px 0; + font-size: 13px; + color: var(--c-dead); +} +.operator-input { + font: inherit; + padding: 5px 8px; + border: 1px solid var(--border-strong); + border-radius: 6px; + width: 120px; +} +.tiny { + font-size: 12px; + color: var(--c-dead); +} +.monitor-strip { + display: flex; + overflow-x: auto; + background: var(--bg-panel); + border: 1px solid var(--border-strong); + border-radius: 8px; + font-size: 12px; +} +.monitor-strip div { + padding: 8px 16px; + border-right: 1px solid var(--border-strong); + white-space: nowrap; +} +.monitor-strip div:last-child { + border-right: none; +} +.monitor-strip .bad { + color: var(--c-fail); +} +.monitor-strip .good { + color: var(--c-done); +} +.dlq-list button { + margin-left: auto; + padding: 2px 10px; + border: 1px solid var(--border-strong); + border-radius: 6px; + background: var(--bg-panel); + cursor: pointer; + font-size: 12px; +} +@media (max-width: 900px) { + .inbox-grid { + grid-template-columns: 1fr; + } + .inbox-nav { + position: static; + } +} diff --git a/web/src/workspace.test.ts b/web/src/workspace.test.ts index 9408482..55791ed 100644 --- a/web/src/workspace.test.ts +++ b/web/src/workspace.test.ts @@ -14,19 +14,13 @@ describe('openModule', () => { describe('closeModule', () => { it('activates the nearest tab on the left after closing the active tab', () => { - const result = closeModule( - { openTabs: ['dashboard', 'releases', 'tasks'], activeTab: 'tasks' }, - 'tasks', - ) + const result = closeModule({ openTabs: ['dashboard', 'releases', 'tasks'], activeTab: 'tasks' }, 'tasks') expect(result).toEqual({ openTabs: ['dashboard', 'releases'], activeTab: 'releases' }) }) it('keeps the dashboard tab pinned', () => { - const result = closeModule( - { openTabs: ['dashboard', 'tasks'], activeTab: 'dashboard' }, - 'dashboard', - ) + const result = closeModule({ openTabs: ['dashboard', 'tasks'], activeTab: 'dashboard' }, 'dashboard') expect(result).toEqual({ openTabs: ['dashboard', 'tasks'], activeTab: 'dashboard' }) }) @@ -35,7 +29,7 @@ describe('closeModule', () => { describe('restoreWorkspace', () => { it('restores open tabs and the active tab from saved state', () => { const result = restoreWorkspace( - JSON.stringify({ openTabs: ['dashboard', 'tasks', 'releases'], activeTab: 'tasks' }), + JSON.stringify({ openTabs: ['dashboard', 'tasks', 'releases'], activeTab: 'tasks' }) ) expect(result).toEqual({ openTabs: ['dashboard', 'tasks', 'releases'], activeTab: 'tasks' }) @@ -43,7 +37,7 @@ describe('restoreWorkspace', () => { it('drops superseded source-link and pending-file tabs from saved state', () => { const result = restoreWorkspace( - JSON.stringify({ openTabs: ['dashboard', 'sources', 'knowledge', 'settings'], activeTab: 'knowledge' }), + JSON.stringify({ openTabs: ['dashboard', 'sources', 'knowledge', 'settings'], activeTab: 'knowledge' }) ) expect(result).toEqual({ openTabs: ['dashboard', 'settings'], activeTab: 'dashboard' }) diff --git a/web/src/workspace.ts b/web/src/workspace.ts index ff6f0bd..66f4205 100644 --- a/web/src/workspace.ts +++ b/web/src/workspace.ts @@ -1,12 +1,4 @@ -export type ModuleId = - | 'dashboard' - | 'sources' - | 'knowledge' - | 'tasks' - | 'releases' - | 'settings' - | 'versions' - | 'qaops' +export type ModuleId = 'dashboard' | 'sources' | 'knowledge' | 'tasks' | 'releases' | 'settings' | 'versions' | 'qaops' export interface WorkspaceState { openTabs: ModuleId[] diff --git a/web/src/workspaceContext.test.tsx b/web/src/workspaceContext.test.tsx index 8eb5da5..192286b 100644 --- a/web/src/workspaceContext.test.tsx +++ b/web/src/workspaceContext.test.tsx @@ -2,14 +2,18 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it, vi } from 'vitest' import { WorkspaceContextTabsBar } from './workspaceContext' -describe('WorkspaceContextTabsBar',()=>{ - it('renders clickable source directory and file context after module tabs',()=>{ - const html=renderToStaticMarkup() - expect(html).toContain('aria-label="当前来源目录和文件"') - for(const label of ['PP公开文档','产品介绍','手册.pdf']) expect(html).toContain(label) - }) +describe('WorkspaceContextTabsBar', () => { + it('renders clickable source directory and file context after module tabs', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('aria-label="当前来源目录和文件"') + for (const label of ['PP公开文档', '产品介绍', '手册.pdf']) expect(html).toContain(label) + }) }) diff --git a/web/src/workspaceContext.tsx b/web/src/workspaceContext.tsx index 71dded4..4959af3 100644 --- a/web/src/workspaceContext.tsx +++ b/web/src/workspaceContext.tsx @@ -1,10 +1,27 @@ import { createContext } from 'react' import type { Dispatch, SetStateAction } from 'react' -export interface WorkspaceContextTab {key:string;label:string;onActivate:()=>void} -export const WorkspaceContextTabsSetter=createContext>>(()=>undefined) - -export function WorkspaceContextTabsBar({tabs}:{tabs:WorkspaceContextTab[]}){ - if(!tabs.length)return null - return
    {tabs.map((tab,index)=>{index?:null})}
    +export interface WorkspaceContextTab { + key: string + label: string + onActivate: () => void +} +export const WorkspaceContextTabsSetter = createContext>>( + () => undefined +) + +export function WorkspaceContextTabsBar({ tabs }: { tabs: WorkspaceContextTab[] }) { + if (!tabs.length) return null + return ( +
    + {tabs.map((tab, index) => ( + + {index ? : null} + + + ))} +
    + ) }