Compare commits

..

63 Commits

Author SHA1 Message Date
zheromiku 9258aa8273 fix(reconciliation): worker 在对账接线时也要注册 reconciliation.run
build / build (push) Successful in 3m5s
候选(9dddda84)实测:批次能建、入队也成功(jobs 里有 pending 行),但 worker
从不认领——worker_heartbeats.job_types 里根本没有 reconciliation.run。
原因:该 handler 注册在 workerHandlers 的测试库取件块里,而这一块在
!TEST_WEKNORA_ENABLED 时直接 return,于是只开 RECONCILIATION_ENABLED 的候选
只有 API 接线、worker 空转,批次停在 running 直到 6h 僵死回收。

把注册移到那个早退之前:只依赖 reconciliationService(租户 Key 走知识库绑定),
与旧取件/上传链路解耦。
2026-12-01 20:11:59 +08:00
zheromiku fe7edea1a3 fix(reconciliation): 对账任务入队 id 超长导致每批 queue_unavailable
build / build (push) Successful in 2m18s
enqueueRun 用 "job-" + run_id 当 jobs.id,而 jobs.id 是 VARCHAR(36);run_id 本身
已是 36 字符(rec- + 32 位 hex),拼出 40 字符,INSERT 必然失败,批次在 claim 之后
立刻被记成 failed/queue_unavailable——候选库里 19:37 起所有批次都是这个状态,C-101
起的用例全部无法开始。

改为 job 自带 "job-"+32 位 hex 的 id(36 字符),幂等仍由唯一 idempotency_key
(reconciliation-run:<run_id>)保证。补单测:CreateRun 入队请求 id 必须正好 36 字符、
type/idempotency_key/payload 与 run 一致。

验证:go test ./internal/reconciliation/ 通过;make verify 17 项 = 16 success + identity skipped。
2026-12-01 19:47:00 +08:00
zheromiku f4b3f4c4c8 fix(reconciliation): 定时批占位语句修 42P08,真实 PG 上首次 claim 即可建批
build / build (push) Successful in 2m26s
白盒在真实 PostgreSQL 上跑新集成用例时,ClaimScheduledReconciliationRun 首次
claim 就报 inconsistent types deduced for parameter $2 (42P08):同一个 KB id
既进 INSERT 目标列(varchar(255))又参与子查询比较(varchar),参数被推断成两种
类型。把比较侧改成独立参数 $7,并在语句上方写明原因。

存量缺陷,改动前同样报错(reconciliation_schedules 一直建不出批次,C-105 无法通过)。

验证:
- TEST_DB 指向一次性 PostgreSQL 16,TestScheduledReconciliationClaimsOncePerDayAfterFailure 通过
  (首日占位一次;失败后同日不再建;次日可建)
- TestReconciliationRunUniquenessStaleAndRetentionIntegration 同库通过
- make verify 17 项 = 16 success + identity skipped
2026-12-01 19:12:00 +08:00
zheromiku 082f77fc18 fix(reconciliation): R6 改用 removal_candidates 视图,定时批每日只占一个名额
build / build (push) Successful in 2m28s
白盒补充复核提出的三项:
- P1 R6 与 /monitor/overview「需下架」计数口径不一致:R6 原先只在扫描结果里存在
  且上游 parse_status=completed 时才生成,上游仍在 processing/finalizing 或单条读取
  失败导致扫描缺行时,总览有数、对账无记录(陷阱 15)。改为直接由 removal_candidates
  视图行生成,台账细节按 publication 回填,计数与总览同一来源;补单测覆盖
  「上游 processing」「扫描未见」两种差异。
- P2 定时批失败后每个 tick 都重建:每日占位只排除 running/succeeded,failed 不占位,
  一次失败当天会每分钟刷批。占位条件加入 failed,重跑改为显式手动触发;补 PG 集成用例。
- P2 队列不可用时前端显示 0 等待 · 0 运行:改为按 available 判定并显示不可用文案;
  补组件用例。
2026-12-01 18:56:05 +08:00
zheromiku a655f4cca8 fix(reconciliation): 用 RECONCILIATION_ENABLED 独立接线对账服务
build / build (push) Successful in 2m56s
T6 的 9 个接口此前只在 TEST_WEKNORA_ENABLED=true 时才构造对账服务,
而该开关同时要求旧测试库端点/KB/Key 文件与 spool 根(appconfig 校验),
候选环境给不出这些旧材料,于是 9 个接口恒 503 reconciliation_not_configured,
QA 无法执行任一用例。

对账本身只需要知识库绑定里的租户 Key(需求书 §5/§6),与旧取件/上传链路无关,
因此新增 RECONCILIATION_ENABLED(默认 false)单独接线 api 与 worker 的对账服务:
- appconfig 解析该开关,不再借用 TEST_WEKNORA_ENABLED
- compose/.env.example 透传,默认关闭,生产按授权再开
- 验收候选(candidate_runtime.py 连 QA 库分支)显式置 true
- 文档补开关口径,加配置解析用例
2026-12-01 18:33:04 +08:00
zheromiku 5c34ef1429 Merge pull request 'fix(candidate): 容器未运行时带出退出码与日志尾' (#43) from fix/candidate-failure-diagnosis into main
build / build (push) Successful in 2m51s
2026-12-01 17:27:40 +08:00
zheromiku a55c8844a8 Merge pull request 'fix(appconfig): 内嵌 tzdata,修 worker 在 alpine 镜像启动即退出' (#42) from fix/reconciliation-tzdata into main
build / build (push) Has been cancelled
2026-12-01 17:27:23 +08:00
Zhero & 助理 6e0382c3ba fix(candidate): 容器未运行时带出退出码与日志尾
build / build (push) Successful in 2m11s
inspect() 原本把「容器没在跑」和「镜像不符」合成一句 expected container is
not running,真正的死因(缺时区、DSN 被拒、端口绑定失败)只在 dockerd 和容器
日志里,容器被 down 掉后无从查证。改为分别报未知状态/镜像不符,并附 5 行日志尾。
2026-12-01 17:22:08 +08:00
Zhero & 助理 00154aafe6 fix(appconfig): 内嵌 tzdata,修 worker 在 alpine 镜像启动即退出
build / build (push) Successful in 2m13s
RECONCILIATION_TIMEZONE 默认 Asia/Shanghai,appconfig.Load 用 time.LoadLocation
校验具名时区;运行镜像 alpine 不带 /usr/share/zoneinfo,只有 api 因
internal/httpapi 顺带空白导入 time/tzdata 才通过,worker 与 release-worker
在候选/发布容器里启动即退出(unknown time zone Asia/Shanghai)。

在真正调用 LoadLocation 的包内嵌 time/tzdata,让校验不依赖基础镜像。
2026-12-01 17:16:15 +08:00
zheromiku a6c662556d Merge pull request #41 from Weknora/hifox-agent/rin/CYWL-34
build / build (push) Successful in 2m54s
feat(reconciliation): T6 导入对账(契约/后端/前端)
2026-12-01 16:17:37 +08:00
Zhero & 助理 27ee14cc97 style(reconciliation): 补齐 console_url 两个文件尾换行
build / build (push) Successful in 2m53s
095aa3e 新增的两个文件缺文件尾换行,gofmt -l 命中,CI 的 make verify
format 项失败(run 520),提测门禁红。仅补换行,无逻辑改动。
2026-12-01 15:29:03 +08:00
Zhero & Rin 095aa3ed68 fix(reconciliation): 平台抽屉补 WeKnora 跳转链接
build / build (push) Failing after 26s
- 为什么:白盒复检 P1——平台侧文件详情抽屉 503 只有文案,需求 §8 要求跳转链接;/monitor/tasks 行没有 URL。
- 做什么:抽出 KnowledgeBaseConsoleURL,finding 与 /monitor/tasks 共用同一拼接;handler 用当前生效测试端点填 weknora_url,前端抽屉透传给 WeKnoraProgress;openapi/需求 §7 同步。
- 补证据:stage=weknora 真库合并用例;对账扫描改为真实 HTTP 桩断言零写;progress 投影断言上游密钥字段不外泄。
- 验证:make verify 17 项 success;go test ./... exit 0;web 648 测试 + build;monitor_tasks 真库集成用例 PASS。
2026-12-01 15:00:25 +08:00
Zhero & Rin 7d21251605 test(reconciliation): 固定确认阶段并发上限
build / build (push) Successful in 2m18s
- 覆盖 acceptance #17:确认并发不超过配置值。
2026-12-01 14:22:57 +08:00
Zhero & Rin e855261b4d fix(reconciliation): 修复僵死回收 SQL 并补齐验收缺口
build / build (push) Has been cancelled
- 回收 SQL 占位符改为 $1/$2,消除 pgx 扩展协议 42P18(手动/定时对账 500)
- 直接写入 finding 时归一空 confirmation_state,避免 23514
- 修正 R6/overview 同谓词用例夹具,两条台账各自持有 source version
- 页面顶部统一服务与队列单行状态条,删除 Embedding/LLM 常量卡
- 平台阶段筛选合并为「WeKnora 处理中」,后端支持 stage=weknora
- weknora_url 由测试 WeKnora 源构造,详情与 503 提供跳转链接
- 补 1000/页线上查询、R8 合法收养、weknora 阶段筛选用例
2026-12-01 14:22:06 +08:00
Zhero & Rin 629694546c refactor(reconciliation): 前端请求层按层命名
build / build (push) Successful in 2m14s
为什么:arch-evidence 按路径识别前端接口请求层;reconciliation.ts 未被归入该层,评审表会漏报新增请求客户端。
做什么:仅重命名 web/src/reconciliation.ts -> reconciliationApi.ts 并同步导入,无行为变化。
验证:npx tsc --noEmit;相关 vitest 通过。
2026-12-01 12:35:39 +08:00
Zhero & Rin 06907331c4 refactor(reconciliation): 存储实现按层命名
为什么:arch-evidence 的分层模式按路径识别存储层;reconciliation.go 被误归到 Handler 层,评审表无法如实反映数据访问改动。
做什么:仅重命名 internal/platform/postgres/reconciliation.go -> reconciliation_store.go,无逻辑变化。
验证:go test ./internal/platform/postgres -run TestReconciliation。
2026-12-01 12:34:23 +08:00
Zhero & Rin dafb1898c1 fix(reconciliation): 收紧确认页与并发处置
为什么:净室评审发现两处可复发风险——扫描在实例返回小于请求页时可能提前结束;并发重复处置可能各写一条审计。
做什么:扫描以 total 为准继续翻页(total 未知才按短页结束);处置前对 finding 行 FOR UPDATE 并只接受 open;R4 sha256 统一 trim。
验证:go test ./internal/reconciliation ./internal/platform/postgres;make verify 全绿。
2026-12-01 12:33:46 +08:00
Zhero & Rin cf833a0a77 feat(reconciliation): 前端导入对账工作台
为什么:T6b 需要把「解析监控」改成「导入对账」,让差异、证据、待确认与处置在同一页闭环,同时保留平台侧流水。
做什么:新增对账 API 客户端;差异清单(R1-R8、证据等级、待确认徽标、处置按钮);批次概览与队列状态条;平台侧流水页签沿用原表;详情抽屉实时读取 WeKnora 阶段与失败,503 降级;导航改名但保留 tasks 模块 id。
边界:只读角色不显示触发/处置;1440/1024/768 用现有表格滚动与新增响应式规则;不伪造 URL 路由。
验证:npx tsc --noEmit、npm test(646+)、npm run build、make verify 全绿。
2026-12-01 12:30:09 +08:00
Zhero & Rin 4528a55e6a feat(reconciliation): 实现导入对账后端
为什么:T6a 需要一张批次/差异表、全量只读扫描、R1-R8 判定和 finding 级处置;现有解析监控只转述台账状态,无法回答库内是否一致。
做什么:迁移 000084(upload_md5、runs/findings/actions、共享 removal_candidates 视图);WeKnora 字段与 1000/页扫描;runtime 只读客户端(0400 Key、503 降级);扫描/矩阵/动作/定时/僵死回收;9 条接口与 RBAC;overview 队列与删两张常量卡。
边界:只对测试库;对账零写请求;R1/R2 单条确认;R6 复用 /removal;R2 只管理员;生产链路未改。
验证:make verify 全绿(17 项);新增矩阵/扫描 R1-R8/零写/失败整批/动作/运行时/密钥权限测试。
2026-12-01 12:19:54 +08:00
Zhero & Rin 580695ca2e feat(reconciliation): 冻结导入对账接口契约
为什么:T6a 第一个提交只含 OpenAPI,先冻结 runs/findings/actions/progress 与 overview 队列字段,后端与前端按契约实现。
契约用 kb_id/document_id 作为 API 字段名,数据库列名保持 test_kb_id/knowledge_id;现有 OpenAPI 安全门禁不允许后者出现在契约里。
验证:go test ./internal/httpapi -run TestOpenAPI 通过。
2026-12-01 11:58:05 +08:00
zheromiku 5af9b14a11 Merge pull request 'feat(library): 适配 WeKnora 0.9.1 并搬运编辑历史' (#40) from feat/t1-libraryprofile-091 into main
build / build (push) Successful in 1m59s
2026-12-01 09:02:47 +08:00
Zhero & Rin 73413c59ee feat(library): 适配 WeKnora 0.9.1 并搬运编辑历史
build / build (push) Successful in 2m3s
- profile 新增 137(由 v090 克隆),声明知识域关联表 copied/derived/excluded 分类。
- 导出前与导入写事务内各跑漏表门禁;未声明有数据拒绝,空表警告写入 WriteSet。
- chunk_revisions/wiki_page_revisions 接入范围改写、目标身份映射、自然键与回滚顺序。
2026-11-30 18:58:01 +08:00
zheromiku 32c773e24d Merge pull request 'docs(weknora): 落库 0.9.1 升级与导入对账需求计划' (#39) from docs/weknora-091-reconciliation into main
build / build (push) Successful in 2m26s
2026-11-30 17:58:58 +08:00
Zhero & 助理 f97c62cc99 docs(weknora): 落库 0.9.1 升级与导入对账需求计划
build / build (push) Successful in 2m17s
为什么:这两份文档此前只存在于本地工作区,T1/T6 分支无法引用。
本次只提交文档,作为 T0 基线,不做代码改动。
2026-11-30 17:56:17 +08:00
zheromiku ca870564b0 Merge pull request #38 from hifox-agent/rin/CYWL-28
build / build (push) Successful in 3m57s
2026-11-26 09:10:11 +08:00
Zhero & 助理 6539a6b77c fix(backup): 删批次前预检,失败时零删除
build / build (push) Successful in 3m10s
为什么:批次根只读时,shutil.rmtree 先删完子项、最后删目录才失败,调用方只看得到 rc≠0,
旧批次内容已经被清空一半,而 logical-backup.sh 还打印「旧备份未被删除」。

改法:
- prune_backup_batches.py 的删除拆成三段:逐目录可写性检查 + 同父目录改名探针(不动内容)
  → 全部改名成 .prune-<pid>-<戳> 隔离(原子、不进批次候选)→ 才真删。预检或改名失败整体
  回滚、零删除(新退出码 5);真删阶段才失败报隔离路径(rc=4),不再谎称旧备份完好。
- logical-backup.sh 的轮转改用 --rotate,与配额清理共用同一份预检/隔离/回滚,删除第二份内联
  rmtree;按 rc 区分提示文案。

验证:
- --self-test 新增预检零删除、改名失败回滚、只读批次根、轮转、遗留隔离目录用例,全部通过;
  go test ./internal/backuphost/ 通过。
- 用 QA 夹具(8 批 + 1 个 .incomplete,批次根 0555,quota=49140352)对拍:旧脚本把
  20261118T193001Z 清成 0 文件、占用 119140352→105500672 后 rc=2;新脚本 rc=5、
  8 个 MANIFEST 全在、占用仍 119140352。
- 子目录只读(批次根可写)同样 rc=5 零删除;可写树正常删两批、无隔离残留。
2026-11-26 08:01:14 +08:00
zheromiku 424a75d516 Merge pull request #37 from hifox-agent/rin/CYWL-28
build / build (push) Successful in 2m46s
feat(backup): 配额改按备份根占用并在超限时清理最旧批次

CYWL-28;make verify 17/17 success。
2026-11-25 22:58:16 +08:00
Zhero & Rin 144b49cb53 feat(backup): 配额改按备份根占用并在超限时清理最旧批次
build / build (push) Successful in 3m22s
- 采集器上报 backup_root/usage/quota(加性字段),API 用 BACKUP_HOST_ROOT 校验并分别降级占用/配额
- 页面配额行改为备份占用 X / 配额 50 GB,4 条告警改用备份口径,解除本页归档依赖
- logical-backup.sh 预检按字节清理(保留最新、空间不足零删除),dump 后复查保护新批次
- backup_layout 写入 KB_BACKUP_QUOTA_BYTES;--show 输出根占用;新增 prune 工具与自检
2026-11-25 22:46:32 +08:00
姚章浩 65476750b0 feat(cd): 通知标注 CD 结果并附站点链接
build / build (push) Successful in 3m12s
2026-11-25 18:34:06 +08:00
姚章浩 b59ec66387 feat(cd): 发布结果上报 ci-bridge
build / build (push) Successful in 2m23s
2026-11-25 17:38:05 +08:00
姚章浩 7801c163e4 feat(qa): 验收回执写明结论与用例
build / build (push) Successful in 2m31s
2026-11-25 17:06:51 +08:00
姚章浩 15dbc2469b docs: 记录候选访问测试 WeKnora 的通路
build / build (push) Successful in 3m6s
2026-11-25 16:48:21 +08:00
姚章浩 da568dfa2c fix(qa): 候选放行测试 WeKnora 的私网明文连接
build / build (push) Successful in 2m57s
2026-11-25 16:05:24 +08:00
姚章浩 7b4ec1f89d fix(qa): 为候选提供稳定的绑定主密钥
build / build (push) Successful in 3m16s
2026-11-25 16:01:02 +08:00
姚章浩 6a6fa7129a fix(qa): 在提交与登记前核对候选逐项报告
build / build (push) Successful in 3m21s
2026-11-25 14:21:04 +08:00
姚章浩 c12152529c fix(qa): 按可测试结论识别本次落地提交
build / build (push) Successful in 2m14s
2026-11-25 12:37:52 +08:00
zheromiku 4d73aa999b fix(kb): 去掉非 HTTPS 页面禁止录入 API Key 的拦截 (#36)
build / build (push) Successful in 3m33s
2026-11-25 12:21:50 +08:00
Zhero & Rin cc289b63e5 test(kb): 明文录入夹具改为运行期拼装
build / build (push) Successful in 2m35s
- 密钥扫描器把「api_key: '<16+ 字符字面量>'」判成真实泄漏,CI 因此变红。
- 夹具值改为数组拼接后引用,断言仍然覆盖验证/保存两条请求体。
2026-11-25 12:08:48 +08:00
Zhero & Rin 9ddc3291cc fix(kb): 保存 API Key 时落来源审计
- 修订历史新增 source_address/source_origin:操作人、时间、环境之外,
  再记录客户端地址与控制台来源,明文录入事后可追溯。
- 来源只用于取证,不参与放行;最近一跳代理追加的 X-Forwarded-For 才可信,
  直连请求不能用伪造链改地址;解析不出就留空,绝不猜值。
- 截断按 UTF-8 边界收口,避免恶意 Origin 让整条保存变成存储错误。
- 迁移 083 只追加列,回滚只删这两列。
2026-11-25 12:06:36 +08:00
Zhero & Miku 32c7074f41 fix(kb): 不再按控制台传输形态拦截 API Key
- 删除 KBBindingSnapshot 的 secret_entry_allowed 能力位与服务端 catalog/save 的 KB 传输门禁
- 非 HTTPS 控制台保留明文传输提示,但不再阻断 Key 录入
- 保留 QA AI 严格 HTTPS/回环校验、管理员认证、写意图头与 Key 不回显
- 补齐明文 HTTP 页面与服务端写入回归测试,同步运行手册和 CHANGELOG
2026-11-25 10:50:52 +08:00
姚章浩 7926c8e8b9 fix(qa): 为候选库验收预留连接容量
build / build (push) Successful in 2m9s
2026-11-25 01:09:01 +08:00
姚章浩 bb57a9835c revert(cd): 恢复原生产发布脚本
build / build (push) Successful in 1m57s
2026-11-24 23:37:56 +08:00
姚章浩 49f9994ea6 fix(release): 需求单状态改由负责人手动切换
build / build (push) Successful in 2m5s
2026-11-24 23:15:15 +08:00
姚章浩 501fbae6ff feat(release): 原需求单按预检顺序接续候选验收
build / build (push) Successful in 2m7s
2026-11-24 22:58:42 +08:00
姚章浩 45aef5016a fix(release): 识别预检评论中的落地 merge 提交
build / build (push) Successful in 2m17s
2026-11-24 21:56:43 +08:00
zheromiku c90cb803fa Merge pull request 'feat(release): 原需求单完成候选验收与发布授权' (#35) from feat/single-task-release into main
build / build (push) Successful in 2m4s
2026-11-24 19:06:15 +08:00
姚章浩 e6a9acc32c feat(release): 在原需求单自动准备并登记验收候选
build / build (push) Successful in 2m14s
2026-11-24 19:03:28 +08:00
zheromiku a3dcaa2f5b Merge pull request 'fix(release): 支持提示中的带引号确认回复' (#34) from fix/release-confirm-quotes into main
build / build (push) Successful in 2m6s
2026-11-24 14:56:49 +08:00
姚章浩 c33c7e2700 fix(release): 接受预览提示中的带引号范围确认
build / build (push) Successful in 2m22s
2026-11-24 14:54:05 +08:00
zheromiku 91f9e00010 Merge pull request 'feat(release): 知识治理预检交接与固定版本发布' (#33) from feat/release-comment-handoff into main
build / build (push) Successful in 2m17s
2026-11-24 14:46:00 +08:00
姚章浩 9952412eff fix(release): 兼容发布预览的富文本回读
build / build (push) Successful in 2m15s
2026-11-24 14:43:03 +08:00
姚章浩 4a12b20e9b feat(release): 从预检评论接单并固定候选版本
build / build (push) Successful in 2m28s
2026-11-24 14:39:43 +08:00
zheromiku 8d873680cc Merge pull request #32 from hifox-agent/miku/CYWL-18
build / build (push) Successful in 2m31s
成员与角色:新增成员改为标题按钮 + 右侧抽屉
2026-11-24 13:07:33 +08:00
Zhero & Miku edd90b253e Merge origin/main into hifox-agent/miku/CYWL-18
build / build (push) Successful in 2m45s
同步 main@d3c4351;CHANGELOG 双方快照并存,本任务保持 0.1.416。
2026-11-24 13:04:19 +08:00
zheromiku d3c435183e Merge pull request #31 from hifox-agent/miku/CYWL-17
build / build (push) Successful in 2m51s
feat(settings): 参数设置按来源与目录、解析监控分组
2026-11-24 12:57:22 +08:00
Zhero & Miku aa75dc6d44 feat(settings): 参数设置按来源与目录、解析监控分组
build / build (push) Successful in 2m6s
- 入口与页面标题由「刷新策略」改为「参数设置」,移除旧入口
- 按产品归属分组:来源与目录(文档/资源刷新间隔)、解析监控(停滞阈值/入库并发)
- 保留单位、调大调小后果与 worker 生效说明,收尾超时仍不展示
- 字段名/单位收敛到 REFRESH_FIELD_META,避免视图与校验文案各写一份后漂移
- 新增挂载测试覆盖非法值禁用保存、不发请求、保留其他输入与原样回传隐藏字段
- 同步 CHANGELOG、验收清单与运维手册
2026-11-24 12:38:59 +08:00
狐友 GXXP & Miku 25d574f3de fix(web): keep trigger focus when closing member drawer via backdrop
build / build (push) Successful in 2m7s
Prevent the backdrop mousedown default from moving focus to body, so closing the drawer always restores focus to the 新增成员 trigger as the drawer contract requires.
2026-11-24 12:28:41 +08:00
Zhero & Miku c96189db1b feat(settings): 刷新策略改为刷新与入库
build / build (push) Successful in 2m31s
四项参数改为带单位/提示的数值输入,越界就地提示并禁用保存;
删除无消费者的收尾超时 UI,finalizing 设置仍按服务器值回传;
补充解析单测与验收/运维文档。
验证:vitest 23 passed、tsc、vite build、check_changelog。
2026-11-24 12:07:09 +08:00
狐友 GXXP & Miku 1dfa4fa7fc feat(web): added member creation drawer with inline validation
- Replaced the inline member form with a header button and right-side drawer.
- Added inline validation, 409/400 field mapping, dirty-close confirm, and focus handling.
- Added MembersRequestError with HTTP status and a mounted regression test.
2026-11-24 12:06:54 +08:00
zheromiku d76363c117 Merge pull request 'feat(settings): 存储与备份只读摘要页对齐验收' (#30) from hifox-agent/len/CYWL-16 into main
build / build (push) Successful in 2m8s
2026-11-24 11:56:21 +08:00
狐友 GXXP & LEN b2248a9b64 feat(settings): 存储与备份只读摘要页对齐验收
build / build (push) Successful in 2m12s
- 单一「存储与备份」页:目录、最近成功/失败、归档占用、磁盘剩余四张卡片 + 备份目录条
- 四条容量告警按磁盘可用/配额已用阈值给出 正常/注意/需处理,缺数显示 未知 而非正常
- 批次表默认 20 条 + 加载更多,展示失败原因与单条复制;60 秒自动刷新
- 未接入/未上报/过期/不完整/不可用分状态措辞,不用 0 冒充
- 移除计划编辑、下发、立即备份与库内诊断块(写端点保留)
- compose 接线 LIBRARY_CAPACITY_BUDGET_BYTES 与 BACKUP_HOST_* 只读元数据
2026-11-24 11:53:49 +08:00
狐友 GXXP & Miku 8c84c9c601 fix(kb-bindings): allow key entry on private HTTP consoles
build / build (push) Successful in 2m26s
- Accept the private-console transport with an exact Origin/Host match; the http console is not a secure context, so Chrome sends no Sec-Fetch-Site and that requirement made every real write 400.
- Reject bracketed non-IPv6 host spellings, including ported forms, instead of normalising them to loopback.
- Show the plaintext-warning copy or the disabled state from a tri-state capability field; old APIs keep the legacy message.
- Document WEKNORA_ALLOW_PRIVATE_HTTP in .env.example and the operations runbook.
2026-11-24 11:22:06 +08:00
zheromiku 660320d646 Merge pull request 'fix(cd): 核验主站首页的 SSO 同源改写' (#29) from fix/cd-serving-proof into main
build / build (push) Successful in 1m46s
2026-11-23 22:00:48 +08:00
163 changed files with 13170 additions and 3764 deletions
+15
View File
@@ -27,7 +27,22 @@ QA_AI_MASTER_KEY_FILE=
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
WEKNORA_BINDING_MASTER_KEY_FILE=
# 测试实例平台级只读 Key:绝对路径、0400;留空 = runtime/* 与队列降级。
WEKNORA_RUNTIME_KEY_FILE=
# 导入对账(T6)总开关:只接线对账服务、只用知识库绑定里的租户 Key。
# 与 TEST_WEKNORA_ENABLED(旧取件/上传链路)解耦;默认关闭,生产按授权再开。
RECONCILIATION_ENABLED=false
RECONCILIATION_SCHEDULE_ENABLED=true
RECONCILIATION_DAILY_AT=02:00
RECONCILIATION_TIMEZONE=Asia/Shanghai
RECONCILIATION_GRACE=30m
RECONCILIATION_STALL_AFTER=2h
RECONCILIATION_STALE_AFTER=6h
RECONCILIATION_CONFIRM_CONCURRENCY=1
RECONCILIATION_KEEP_RUNS=30
RECONCILIATION_MAX_AGE=2160h
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
# 只影响治理 API/worker 访问 WeKnora 的地址校验;控制台自身的密钥录入不再由该开关控制。
WEKNORA_ALLOW_PRIVATE_HTTP=false
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
QA_AI_DNS_OVER_TLS=
+36
View File
@@ -80,3 +80,39 @@ jobs:
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
notify:
needs: [guard, publish]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: 取同一提交的上报脚本
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_REF" = refs/heads/main
git init -q .
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
git checkout -q --detach "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
- name: 上报 ci-bridge(发布结果,通知失败不改变发布结论)
if: always()
env:
BRIDGE_URL: ${{ vars.CI_BRIDGE_URL }}
BRIDGE_TOKEN: ${{ secrets.CI_BRIDGE_TOKEN }}
CI_PUBLIC_BASE_URL: https://gitea.zheromiku.top
GUARD_RESULT: ${{ needs.guard.result }}
PUBLISH_RESULT: ${{ needs.publish.result }}
DEPLOY_SHA: ${{ inputs.sha }}
DEPLOY_BUNDLE: ${{ inputs.bundle }}
DEPLOY_TASK: ${{ inputs.task }}
run: |
set +e; set +o pipefail
B="${BRIDGE_URL:-}"
for cand in "$B" "http://172.17.0.1:8899" "http://192.168.50.134:8899" "http://100.92.49.78:8899"; do
if [ -n "$cand" ]; then curl -s -m 5 -o /dev/null "$cand/healthz" && { B="$cand"; break; }; fi
done
echo "使用 ci-bridge: ${B:-(不可达)}"
CI_BRIDGE_RESOLVED="$B" python3 scripts/cd_notify.py
echo "上报结束(通知失败不改变发布结论)"
+157
View File
@@ -1,5 +1,162 @@
# Changelog
## 开发快照 0.1.425(WeKnora 0.9.1:schema 137 + 漏表门禁 + 编辑历史搬运)
### Added
- **libraryprofile 新增 v0.9.1(137)**:由 v0.9.0 声明克隆,只改版本字段;`For(137)`/`Supported()`
与错误信息同步。135–137 只改审计列宽/凭据表/IM 唯一索引,不碰知识域,测试断言 v090/v091
除版本外逐字段相等。
- **知识域关联表分类**:每个版本声明 `copied/derived/excluded` 及理由;覆盖真实 0.9.x 的 18 张
候选表与条件迁移的 `embeddings`。
- **漏表门禁**:导出前(源库只读快照事务)与导入前(写事务内、DELETE 前)扫描带
`knowledge_base_id/knowledge_id/kb_id` 的表;未分类且有本库数据 → `release_undeclared_kb_table`
(表名+行数,不可重试);未分类空表放行并留警告(导入侧写入 `WriteSet.Warnings`)。
- **编辑历史搬运**:`chunk_revisions`、`wiki_page_revisions` 进入 v090/v091 的必需表与归档部件,
复用范围改写 + 目标身份映射 + 自然键预检;插在父表之后、删除/回滚先删两表;只导出活跃父行,
父行完全缺失即拒绝;唯一索引映射后仍唯一;`editor_id` 原样保留(目标显示未知编辑者)。
### Changed
- **兼容性(人类裁定 Q1=B)**:两表部件为 **RequiredParts**。T1 部署前生成的 0.9.0 库归档/预备份
将因缺少这两个部件而无法加载;升级前如需保留回滚能力,先在旧版本完成回滚或保留旧二进制。
- 修订正文不参与资源发现(Q2=B):`resource://` 文本原样保留;资源作用域/校验/恢复保护统一排除两表。
- 同步 `docs/library-target-id-mapping.md`、`docs/library-data-contract.md`、`docs/library-capture.md`,
并按 T0 要求把 `docs/architecture/three-agent-handoff-workflow.md` §2 的 main 直推改为分支 + PR。
## 开发快照 0.1.424(存储与备份:删批次前预检,失败零删除)
### Fixed
- **配额清理会把旧批次删一半再失败**:`shutil.rmtree` 先删子项、最后删目录,批次根只读时
失败发生在内容已清空之后,调用方只看到非 0 退出却打印「旧备份未被删除」。现在删除分三段:
逐目录可写性检查 + 同父目录改名探针(不动内容)→ 全部改名成 `.prune-<pid>-<戳>` 隔离
(原子、不进批次候选)→ 才真删。任一预检或改名失败整体回滚、**零删除**(新退出码 `5`);
真删阶段才失败时报隔离路径(`rc=4`),`logical-backup.sh` 按 `rc` 区分提示,不再误报。
### Changed
- 轮转(`KEEP_DAILY`/`KEEP_MONTHS`)改由 `scripts/prune_backup_batches.py --rotate` 实现,
与配额清理共用同一套预检/隔离/回滚,删掉 `logical-backup.sh` 里的第二份内联 `rmtree`。
self-test 增加预检零删除、改名失败回滚、只读批次根、轮转与遗留隔离目录用例。
## 开发快照 0.1.423(存储与备份:配额改按备份根占用)
### Fixed
- **页面配额行读错数据源**:`归档占用` 卡片读 `/api/v1/library/storage`(`runtime/library`
归档库,现场 1.67 MB),与 `/srv/kb-backups` 的整库逻辑备份无关;现改为「备份占用 X / 配额 50 GB」,
只读宿主采集器上报的备份根累计占用。归档库接口仍服务归档写入门禁,不再被本页调用。
- **备份没有按字节的执行路径**:`logical-backup.sh` 过去只有按份数/月份轮转;现在 dump 前按
`KB_BACKUP_QUOTA_BYTES` 预检,最旧优先清理且保留最新一份,空间仍不够时零删除并取消本次备份;
dump 后复查并保护本次新批次。只删 `rds-logical` 完整批次,`es-snapshots`/`target-kb-snapshots`/
`logs` 与 `*.incomplete` 不动。
- **根占用不完整不牵连批次**:采集器对根树遍历失败时 `usage.actual_bytes=null`,批次表与磁盘容量仍可用;
旧采集器快照缺 `usage/quota` 时显式「未上报」,不用批次和冒充。
### Added
- 采集器 `collect_backup_metadata.py` 新增 `--usage-root/--quota-bytes/--config`,快照新增
`backup_root/usage/quota_bytes/quota_error`(加性字段,schema 仍为 1),根占用与 `du -sB1` 对拍。
- `scripts/prune_backup_batches.py`:配额清理独立工具 + self-test(最旧优先、预检保留最新、
不足零删除、非批次日录/符号链接不动、dump 后保护新批次)。
- API 校验 `usage.root == BACKUP_HOST_ROOT`,占用与配额不完整/非法时只降级对应字段;
`install_backup_schedule.sh --show` 增加备份根占用/配额读数。
### Changed
- `backup_layout.sh` 把 `KB_BACKUP_QUOTA_BYTES=53687091200` 写入 `backup.env`(已有值不覆盖);
页面 4 条容量告警的配额项统一改用备份占用/配额,磁盘项仍取文件系统实测值。
- 契约与核验命令更新到 `docs/STORAGE_BACKUP_READONLY_API.md`、`docs/PRODUCTION_BACKUP_RECOVERY.md`。
## 开发快照 0.1.422(知识库绑定:不再按控制台传输形态拦截 Key)
### Fixed
- **非 HTTPS 控制台仍无法录入 API Key**:页面删除 `secret_entry_allowed` 能力位与
`secure`/`keyEntryBlocked` 传输判定,服务端删除 KB 专用的
`secretTransportAllowedForPrivateConsole` 写侧校验。管理员在任意同源控制台都能录入/
更换 Key,不再出现「可输入但保存 400」的半修复。
- **提示与录入门禁解耦**:非 HTTPS、非回环页面保留「当前通过明文 HTTP 访问:录入的
API Key 会在内网明文传输。」,只提示不阻断;HTTPS 页面不再提示反代是否受信。
- **保存落审计**:`weknora_environment_binding_history` 同一事务写入操作人、时间、
环境、客户端地址与控制台来源(`source_address`/`source_origin`),明文录入事后可追溯;
来源只做取证,不参与放行判定,解析不出就留空而不猜值。
### Changed
- `WEKNORA_ALLOW_PRIVATE_HTTP` 仅控制治理 API/worker 访问同网段 http 目标,不再决定
控制台密钥录入。问答 AI 模型密钥仍走严格 HTTPS/回环校验;管理员、`X-Governance-Action`
写意图与 Key 不回显边界不变。Web 与 API 是独立镜像,须同批次发布/回滚:旧 Web 对新
API 会禁用录入,新 Web 对旧 API 仍会被 400 拒绝。
## 开发快照 0.1.421(负责人手动切换需求状态)
- 原需求单在候选就绪和主站发布成功时回填回执,负责人按回执手动切换状态。
## 开发快照 0.1.420(需求单候选排队)
- 需求单预检通过后自动排队等待验收环境,构建链接回填原单。已发布批次释放其测试容器,接续下一张需求。
## 开发快照 0.1.419(候选预检识别落地 merge)
- 预检支持从含多个版本号的提交链中识别 `落地 merge`,并分别提示缺少和存在多个落地版本。
## 开发快照 0.1.418(原需求单发布)
- 白盒预检后在原需求单自动准备候选,业务与批次回归证据同单登记。负责人在原单切到「待发布」批准上线。
## 开发快照 0.1.417(知识治理发布助理接收提测交接)
- 预检通过后按实际落地版本创建发布范围预览,支持单独选择已进入主线的修复提交。
- 负责人回复预览确认范围,候选验收报告按实际归档归集到发布单。
## 开发快照 0.1.416(成员管理:新增成员改为右侧抽屉)
### Fixed
- **新增入口移到标题栏**:成员表格下方常驻表单改为「成员与角色」标题右侧的
`新增成员` 按钮,点击从右侧滑出抽屉;桌面宽 480px,窄屏铺满,表单字段与
重置密码弹层共用同一套控件与校验提示。
- **关闭前确认未保存输入**:Esc、取消、关闭按钮与遮罩点击在草稿非空时先确认;
清空草稿后直接关闭并把焦点还给触发按钮;创建请求进行中忽略一切关闭请求。
- **创建失败留在抽屉**:409 固定到用户名行,400 收敛为表单级提示,二者都保留
已填内容;成功后关闭抽屉、刷新列表,页级错误/成功条只承载加载与行内操作。
### Changed
- **请求错误带 HTTP 状态**:`web/src/members.ts` 的失败改为 `MembersRequestError`
(含 `status`),组件按 409/400 分流,不再依赖错误文案匹配。
## 开发快照 0.1.415(系统设置:刷新策略改为按模块分组的参数设置)
### Changed
- **入口改为「参数设置」**:系统设置左侧子导航与页面标题由「刷新策略」替换为「参数设置」,
旧入口不再出现。
- **参数按模块分组**:按产品归属固定为「来源与目录」(文档状态刷新间隔 15/30/60 秒、
资源刷新间隔 30/60 秒)与「解析监控」(解析停滞阈值 30/60 分钟、入库并发上限 1..16);
分组标题下不叠加说明段。
- **数值输入与就地校验**:四个下拉改为文本数值输入;空值、非整数、`+15`/`1e1`、全角数字
与越界值当场红字提示并禁用保存,不发请求;并发不再受旧下拉六档限制。
- **保留现状说明与保存边界**:每项保留单位与调大/调小后果;解析停滞阈值保留 worker 1 分钟
内生效说明;保存仍只提交参数分区,且原样回传未展示的 `finalizing_after_seconds` 与连接字段。
- **去掉无消费者的收尾超时展示**:本页不再展示「收尾超时告警」,成功消息与底部摘要也不再
播报它;API/DB/worker 与 `finalizing` 处理状态均未改动。
## 开发快照 0.1.414(知识库绑定:私网 http 可录入 Key)
### Fixed
- **私网 http 控制台无法录入 API Key**:页面过去只看浏览器 URL 决定能否录入,而服务端写侧
已按 `WEKNORA_ALLOW_PRIVATE_HTTP` 放行私网 http,导致「开关开着、输入框仍禁用」。GET
`/api/v1/kb-bindings` 现在返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
开关与受信反代判定;API 未返回该字段时前端按不可录入处理(失败关闭)。写侧判定不变。
- **明文录入没有风险提示**:能力位开启且页面经非回环 http 打开时,Key 输入下方常驻提示密钥
将明文传输;HTTPS 反代未配置 `QA_AI_TRUST_TLS_PROXY` 时改为提示该配置,不再笼统要求 HTTPS。
- **`Host: [::1]`(无端口)被误判为非回环**:地址规范化统一去掉 IPv6 方括号与可选端口,
回环写入不再被拒;受信反代能力位对 GET 只依赖 `X-Forwarded-Proto`(浏览器无法伪造该头)。
## 开发快照 0.1.413(知识库绑定:生产侧待入库重排与按环境隔离)
### Fixed
+17 -1
View File
@@ -44,6 +44,13 @@
}
],
"paths": {
"/api/v1/reconciliation/runs": {"post":{"tags":["Reconciliation"],"operationId":"createReconciliationRun","summary":"手动触发一个测试库的对账批次;同一知识库已有 running 批次时返回 409","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["kb_id"],"properties":{"kb_id":{"type":"string","minLength":1,"maxLength":255}}}}}},"responses":{"202":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"409":{"description":"reconciliation_run_in_progress"},"500":{"$ref":"#/components/responses/InternalError"}}},"get":{"tags":["Reconciliation"],"operationId":"listReconciliationRuns","summary":"按开始时间倒序列出对账批次","parameters":[{"name":"kb_id","in":"query","required":false,"schema":{"type":"string","maxLength":255}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100,"default":20}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","minimum":0,"maximum":1000000,"default":0}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"角色或写入意图不足"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/runs/{id}": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationRun","summary":"读取单个对账批次","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/runs/{id}/findings": {"get":{"tags":["Reconciliation"],"operationId":"listReconciliationFindings","summary":"按类型和关键词筛选批次差异明细","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"type","in":"query","required":false,"schema":{"type":"string","enum":["R1","R2","R3","R4","R5","R6","R7","R8"]}},{"name":"q","in":"query","required":false,"schema":{"type":"string","maxLength":512}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100,"default":20}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","minimum":0,"maximum":1000000,"default":0}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/findings/{id}/writeback": {"post":{"tags":["Reconciliation"],"operationId":"writebackReconciliationFinding","summary":"仅限 R5:以 WeKnora 状态回写台账 processing_state,写审计;completed 不可降级","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"reconciliation_writeback_stale 或迁移不允许"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/findings/{id}/requeue": {"post":{"tags":["Reconciliation"],"operationId":"requeueReconciliationFinding","summary":"仅限 R1/R4:R1 清空 document_id 后重排上传;R4 先删旧知识再重传,删除失败则台账不变","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"finding 状态或台账身份已变化"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/findings/{id}/remove": {"post":{"tags":["Reconciliation"],"operationId":"removeReconciliationFinding","summary":"仅限 R2:按远端 document_id 从测试库删除;404 视为已删除;重复点击幂等","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"该文档已被现行台账收养"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/documents/{document_id}/progress": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationDocumentProgress","summary":"实时转发并脱敏 WeKnora 文档处理阶段与历史失败;未配置平台只读 Key 时返回 503 runtime_read_unavailable","parameters":[{"name":"document_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}}}},
"/api/v1/qa-ops/master/field-options": {"get":{"operationId":"getQAMasterFieldOptions","tags":["QA operations"],"summary":"只读主表五字段的正式可选范围,与模型共享同一分类字典;不返回业务问答","parameters":[],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}}},
"/api/v1/qa-ops/master/records/{id}/fields": {"post":{"operationId":"patchQAMasterFields","tags":["QA operations"],"summary":"只更新明确选择的字段并留幂等审计;不改原始正文、其他空白、旧复核或冻结证据。未覆盖的是否正确固定为待确认,拒绝是或否;已覆盖点踩固定为否。quality.correctness_rule=coverage-correctness-v1标记覆盖/正确性固定投影,原字段和复核证据保留","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-master-fields"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["input_hash","input_epoch","base_revision","base_review_revision","nonce","fields"],"properties":{"input_hash":{"type":"string","pattern":"^[a-f0-9]{64}$"},"input_epoch":{"type":"integer","minimum":1},"base_revision":{"type":"integer","minimum":0},"base_review_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"fields":{"type":"object","additionalProperties":false,"minProperties":1,"maxProperties":5,"properties":{"is_correct":{"type":"string","enum":["是","否","待确认"]},"product_category":{"type":"string","enum":["CR/CRA/H/AP","CRV","CR配件","Nova及系列","Nova配件","MG400","MG400配件","M1 Pro","VX500","新示教器","DobotStudio Pro","仿真软件","维护工具","教育所有产品","人形机器人","四六足机器人","X-Trainer","码垛解决方案","码垛插件","焊接解决方案","焊接插件","移动复合机器人","生态插件","生态合作","安全皮肤","未知"]},"problem_type":{"type":"string","enum":["参数","故障","使用配置","二次开发","资料获取","咨询","认证","案例","售后","培训与学习","其他"]},"root_cause":{"type":"string","enum":["知识缺失","检索不到","结果不清","答案生成错误","问题质量差","非知识范围","知识过期"]},"coverage":{"type":"string","enum":["是","否","否但不计入"]}}}}}}}}}},
"/api/v1/qa-ops/master/weekly-drafts/{week}": {"get":{"operationId":"getQAWeeklyDraft","tags":["QA operations"],"summary":"读取租户指定北京时间ISO周的持久草稿;不存在时revision=0且不创建记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}},"post":{"operationId":"saveQAWeeklyDraft","tags":["QA operations"],"summary":"防抖编辑保存:版本锁、逐版历史及同nonce重放;正文不会触发外发/归档","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-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce","markdown"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"markdown":{"type":"string","maxLength":262144,"description":"UTF-8正文最多256KiB;允许空正文,保存草稿不等于发布"}}}}}}}},
@@ -1978,7 +1985,7 @@
"Settings"
],
"operationId": "getBackupScheduleInventory",
"summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
"summary": "读取宿主元数据快照:批次、子库完整路径、备份根累计占用、配额与文件系统容量(陈旧/不完整一律未知)",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
@@ -4867,6 +4874,10 @@
"target_kb": {
"type": "string"
},
"weknora_url": {
"type": "string",
"description": "目标测试知识库在 WeKnora 控制台的链接;未配置测试端点时为空"
},
"action": {
"type": "string"
},
@@ -6162,6 +6173,11 @@
}
},
"schemas": {
"ReconciliationRun": {"type":"object","additionalProperties":false,"required":["id","kb_id","state","trigger","started_at","finished_at","ledger_count","kb_count","counts","previous_counts","window_overlapped","error_code"],"properties":{"id":{"type":"string"},"kb_id":{"type":"string","minLength":1,"maxLength":255},"state":{"type":"string","enum":["running","succeeded","failed"]},"trigger":{"type":"string","enum":["schedule","manual"]},"started_at":{"type":"string","format":"date-time"},"finished_at":{"type":["string","null"],"format":"date-time"},"ledger_count":{"type":"integer","minimum":0},"kb_count":{"type":"integer","minimum":0},"counts":{"type":"object","additionalProperties":false,"required":["R1","R2","R3","R4","R5","R6","R7","R8"],"properties":{"R1":{"type":"integer","minimum":0},"R2":{"type":"integer","minimum":0},"R3":{"type":"integer","minimum":0},"R4":{"type":"integer","minimum":0},"R5":{"type":"integer","minimum":0},"R6":{"type":"integer","minimum":0},"R7":{"type":"integer","minimum":0},"R8":{"type":"integer","minimum":0}}},"previous_counts":{"type":["object","null"],"additionalProperties":{"type":"integer","minimum":0}},"window_overlapped":{"type":"boolean"},"error_code":{"type":"string"}}},
"ReconciliationFinding": {"type":"object","additionalProperties":false,"required":["id","run_id","type","publication_id","document_id","title","path","source","target_scope","ledger_state","weknora_parse_status","normalized_state","ledger_sha256","declared_sha256","weknora_file_md5","evidence_level","confirmation_state","detail","suggested_action","action_state","weknora_url"],"properties":{"id":{"type":"string"},"run_id":{"type":"string"},"type":{"type":"string","enum":["R1","R2","R3","R4","R5","R6","R7","R8"]},"publication_id":{"type":"string"},"document_id":{"type":"string"},"title":{"type":"string"},"path":{"type":"string"},"source":{"type":"string"},"target_scope":{"type":"string","enum":["internal","external","unknown"]},"ledger_state":{"type":"string"},"weknora_parse_status":{"type":"string"},"normalized_state":{"type":"string"},"ledger_sha256":{"type":"string"},"declared_sha256":{"type":"string"},"weknora_file_md5":{"type":"string"},"evidence_level":{"type":"string","enum":["independent","declared_only","none"]},"confirmation_state":{"type":"string","enum":["confirmed","pending"]},"detail":{"type":"string"},"suggested_action":{"type":"string","enum":["requeue_upload","remove_from_test","writeback_state","enter_removal","none"]},"action_state":{"type":"string","enum":["open","done"]},"weknora_url":{"type":"string"}}},
"ReconciliationRunPage": {"type":"object","additionalProperties":false,"required":["items","total","limit","offset"],"properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/ReconciliationRun"}},"total":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":100},"offset":{"type":"integer","minimum":0}}},
"ReconciliationFindingPage": {"type":"object","additionalProperties":false,"required":["items","total","limit","offset"],"properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/ReconciliationFinding"}},"total":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":100},"offset":{"type":"integer","minimum":0}}},
"ReconciliationProgress": {"type":"object","additionalProperties":false,"required":["document_id","parse_status","ingestion_status","wiki_status","stages","failures","has_more_failures","observed_at"],"properties":{"document_id":{"type":"string"},"parse_status":{"type":"string"},"ingestion_status":{"type":"string"},"wiki_status":{"type":"string"},"stages":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["name","status"],"properties":{"name":{"type":"string"},"status":{"type":"string"},"error_code":{"type":"string"},"finished_at":{"type":["string","null"],"format":"date-time"}}}},"failures":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["task_type","fail_count","failed_at","last_error"],"properties":{"task_type":{"type":"string"},"fail_count":{"type":"integer","minimum":0},"failed_at":{"type":"string","format":"date-time"},"last_error":{"type":"string","maxLength":500}}}},"has_more_failures":{"type":"boolean"},"observed_at":{"type":"string","format":"date-time"}}},
"KBBindingEnvironmentView": {
"type": "object",
"additionalProperties": false,
+54 -1
View File
@@ -31,8 +31,10 @@ import (
"knowledge-governance/internal/qaopsquality"
"knowledge-governance/internal/qawemail"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/reconciliation"
"knowledge-governance/internal/serviceverify"
"knowledge-governance/internal/version"
"knowledge-governance/internal/weknoraaccess"
)
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
@@ -216,7 +218,55 @@ func run(ctx context.Context, getenv func(string) string) error {
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
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, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
runtimeKey := ""
if config.WeKnoraRuntimeKeyFile != "" {
key, keyErr := weknora.ReadRuntimeKeyFile(config.WeKnoraRuntimeKeyFile)
if keyErr != nil {
log.Printf("WARN: WeKnora runtime read key is unavailable; runtime endpoints degrade to 503")
} else {
runtimeKey = key
}
}
runtimeProvider := reconciliation.NewRuntimeProvider(reconciliation.RuntimeConfig{
BaseURL: testEndpointResolver,
APIKey: runtimeKey,
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
})
reconciliationRemote := &weknoraaccess.Client{
Resolver: readiness.Resolver{
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return target.BaseURL, target.APIKey, resolveErr
},
DefaultKB: config.InternalRoutingKnowledgeBaseID,
},
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
var reconciliationService httpapi.ReconciliationService
if config.ReconciliationEnabled {
service, serviceErr := reconciliation.New(reconciliation.Config{
Store: actionStore,
Remote: reconciliationRemote,
Runtime: runtimeProvider,
Queue: actionStore,
Grace: config.ReconciliationGrace,
StallAfter: config.ReconciliationStallAfter,
StaleAfter: config.ReconciliationStaleAfter,
ConfirmConcurrency: config.ReconciliationConfirmConcurrency,
KeepRuns: config.ReconciliationKeepRuns,
MaxAge: config.ReconciliationMaxAge,
WeKnoraWebBase: testEndpointResolver,
})
if serviceErr != nil {
return serviceErr
}
reconciliationService = service
}
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, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP, RuntimeQueues: runtimeProvider})
if err != nil {
return err
}
@@ -291,6 +341,8 @@ func run(ctx context.Context, getenv func(string) string) error {
QAOpsProblem: qaSettings.Problem,
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID),
Monitor: monitorProvider,
Reconciliation: reconciliationService,
WeKnoraWebBase: testEndpointResolver,
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
RoutingBindings: postgresstore.NewStore(pool),
@@ -349,6 +401,7 @@ func run(ctx context.Context, getenv func(string) string) error {
BackupInventory: backupinventory.New(backupinventory.Config{
MetadataPath: config.BackupHostMetadataPath,
HostRoot: config.BackupHostReadonlyHostPath,
BackupRoot: config.BackupHostRoot,
Source: backupInventorySource(config),
MaxAge: config.BackupHostMetadataMaxAge,
}),
+3 -3
View File
@@ -55,7 +55,7 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance",
VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"},
}
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil)
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil, nil)
if err != nil {
t.Fatalf("release-executor workerHandlers() error = %v", err)
}
@@ -74,12 +74,12 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
TestWeKnoraEnabled: true,
TestWeKnoraAPIKeyFile: "/nonexistent/api-key",
}
if _, err := workerHandlers(nil, capture, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
if _, err := workerHandlers(nil, capture, nil, nil); 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, nil)
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil, nil)
if err != nil {
t.Fatalf("capture workerHandlers() error = %v", err)
}
+64 -2
View File
@@ -27,6 +27,7 @@ import (
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/reconciliation"
"knowledge-governance/internal/versionhistory"
"knowledge-governance/internal/weknoraaccess"
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
@@ -260,7 +261,50 @@ func run(ctx context.Context, getenv func(string) string) error {
} else if repaired > 0 {
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
}
handlers, err := workerHandlers(store, config, kbBindings)
var reconciliationService *reconciliation.Service
if config.ReconciliationEnabled && config.LibraryWorkerRole.ExecutesSourceWork() {
reconciliationRemote := &weknoraaccess.Client{
Resolver: readiness.Resolver{
LoadBinding: func(resolveCtx context.Context) (string, error) {
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
return internal, bindingErr
},
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
if kbBindings != nil {
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return target.BaseURL, target.APIKey, resolveErr
}
key, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
return config.TestWeKnoraBaseURL, key, keyErr
},
DefaultKB: config.InternalRoutingKnowledgeBaseID,
},
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
reconciliationService, err = reconciliation.New(reconciliation.Config{
Store: store,
Remote: reconciliationRemote,
Queue: store,
Grace: config.ReconciliationGrace,
StallAfter: config.ReconciliationStallAfter,
StaleAfter: config.ReconciliationStaleAfter,
ConfirmConcurrency: config.ReconciliationConfirmConcurrency,
KeepRuns: config.ReconciliationKeepRuns,
MaxAge: config.ReconciliationMaxAge,
WeKnoraWebBase: func(resolveCtx context.Context) string {
if kbBindings != nil {
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvTest)
}
return config.TestWeKnoraBaseURL
},
})
if err != nil {
return err
}
}
handlers, err := workerHandlers(store, config, kbBindings, reconciliationService)
if err != nil {
return err
}
@@ -331,6 +375,9 @@ func run(ctx context.Context, getenv func(string) string) error {
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
})
if reconciliationService != nil {
go runReconciliationScheduler(ctx, store, reconciliationService, config)
}
}
log.Printf("worker %s started role=%s release=%t source=%t (source refresh scheduler every %s)",
config.WorkerID, config.LibraryWorkerRole, config.LibraryWorkerRole.ExecutesRelease(),
@@ -373,7 +420,7 @@ func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersiste
return nil
}
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store) (map[string]jobs.Handler, error) {
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store, reconciliationService *reconciliation.Service) (map[string]jobs.Handler, error) {
handlers := map[string]jobs.Handler{
"demo": func(_ context.Context, job jobs.Job) error {
log.Printf("completed demo job id=%s", job.ID)
@@ -572,6 +619,21 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindi
}
handlers["source.scan.pp"] = handler.Handle
}
// 导入对账的作业处理器只依赖对账服务本身(租户 Key 走知识库绑定),
// 与旧测试库取件/上传链路(TEST_WEKNORA_ENABLED)无关,必须在下面那个
// 早退之前注册;否则 RECONCILIATION_ENABLED=true 时候选只接线了 API,
// worker 从不认领 reconciliation.run,批次永远停在 running。
if reconciliationService != nil {
handlers["reconciliation.run"] = func(handlerCtx context.Context, job jobs.Job) error {
var payload struct {
RunID string `json:"run_id"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.RunID == "" {
return jobs.Permanent(jobs.ErrCodeHandlerFallback, errors.New("invalid reconciliation run payload"))
}
return reconciliationService.ExecuteRun(handlerCtx, payload.RunID)
}
}
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
return handlers, nil
}
+4 -4
View File
@@ -20,7 +20,7 @@ func TestRunRequiresDatabaseURL(t *testing.T) {
}
func TestWorkerHandlersExcludeReleaseAndTestJobsByDefault(t *testing.T) {
handlers, err := workerHandlers(nil, appconfig.Config{}, nil)
handlers, err := workerHandlers(nil, appconfig.Config{}, nil, nil)
if err != nil {
t.Fatalf("workerHandlers() error = %v", err)
}
@@ -46,7 +46,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
PPScanLedgerPath: filepath.Join(root, "state.jsonl"),
PPScanManifestPath: filepath.Join(root, "manifest.json"),
}
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil, nil)
if err != nil {
t.Fatalf("workerHandlers() error = %v", err)
}
@@ -57,7 +57,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
func TestWorkerHandlersRequireAPIKeyWhenTestWeKnoraEnabled(t *testing.T) {
config := appconfig.Config{TestWeKnoraEnabled: true, TestWeKnoraAPIKeyFile: "/nonexistent/api-key"}
_, err := workerHandlers(nil, config, nil)
_, err := workerHandlers(nil, config, nil, nil)
if err == nil || !strings.Contains(err.Error(), "read test WeKnora API key") {
t.Fatalf("workerHandlers() error = %v", err)
}
@@ -80,7 +80,7 @@ func TestWorkerHandlersRegisterTestJobsForExplicitDockerHTTP(t *testing.T) {
TestWeKnoraMaxUploadBytes: 1024,
TestAcceptancePolicyVersion: "structural-v1",
}
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil, nil)
if err != nil {
t.Fatalf("workerHandlers() error = %v", err)
}
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"context"
"log"
"time"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/reconciliation"
)
// runReconciliationScheduler claims at most one scheduled batch per test KB
// per local day. The claim is in PostgreSQL; multiple workers racing here are
// harmless. The first tick is delayed by one interval, like the source refresh
// scheduler, so startup does not enqueue a backlog before handlers are ready.
func runReconciliationScheduler(ctx context.Context, store *postgres.Store, service *reconciliation.Service, config appconfig.Config) {
if service == nil || !config.ReconciliationScheduleEnabled {
return
}
location, err := time.LoadLocation(config.ReconciliationTimezone)
if err != nil {
log.Printf("reconciliation scheduler disabled: invalid timezone %q", config.ReconciliationTimezone)
return
}
daily, err := time.Parse("15:04", config.ReconciliationDailyAt)
if err != nil {
log.Printf("reconciliation scheduler disabled: invalid daily time %q", config.ReconciliationDailyAt)
return
}
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case tick := <-ticker.C:
local := tick.In(location)
at := time.Date(local.Year(), local.Month(), local.Day(), daily.Hour(), daily.Minute(), 0, 0, location)
if local.Before(at) {
continue
}
internal, external, _, bindingErr := store.LoadRoutingKBBindings(ctx)
if bindingErr != nil {
log.Printf("reconciliation scheduler cannot read current bindings: %v", bindingErr)
continue
}
if internal == "" {
internal = config.InternalRoutingKnowledgeBaseID
}
if external == "" {
external = config.ExternalRoutingKnowledgeBaseID
}
created, scheduleErr := service.ScheduleDue(ctx, []string{internal, external}, at.UTC(), tick.UTC())
if scheduleErr != nil {
log.Printf("reconciliation scheduler error: %v", scheduleErr)
continue
}
if created > 0 {
log.Printf("reconciliation scheduler created %d batch(es) for local day %s", created, local.Format("2006-01-02"))
}
}
}
}
+32 -1
View File
@@ -52,6 +52,14 @@ services:
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
# 「存储与备份」摘要页的归档配额(字节)。留空 = 未设置,页面显示"配额未设置";
# 显式写 0 会被 appconfig 拒绝(必须为正整数),所以只能用空串表示未设置。
LIBRARY_CAPACITY_BUDGET_BYTES: "${LIBRARY_CAPACITY_BUDGET_BYTES:-}"
# 宿主每 5 分钟上报的整库备份元数据快照(collector 写入,平台只读)。
# 留空 = 未接线,页面按验收显示"主机未上报";路径必须是宿主机侧绝对路径。
BACKUP_HOST_METADATA_PATH: "${BACKUP_HOST_METADATA_PATH:-}"
BACKUP_HOST_METADATA_MAX_AGE: "${BACKUP_HOST_METADATA_MAX_AGE:-15m}"
BACKUP_HOST_READONLY_HOST_PATH: "${BACKUP_HOST_READONLY_HOST_PATH:-}"
# 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起",
# worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
@@ -60,8 +68,21 @@ services:
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
# 测试实例平台级只读 Key(0400,绝对路径)。空值 = runtime/* 与队列降级;
# Key 本身只挂载 secret 文件,绝不写进 compose。
WEKNORA_RUNTIME_KEY_FILE: "${WEKNORA_RUNTIME_KEY_FILE:-}"
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}"
RECONCILIATION_GRACE: "${RECONCILIATION_GRACE:-30m}"
RECONCILIATION_STALL_AFTER: "${RECONCILIATION_STALL_AFTER:-2h}"
RECONCILIATION_STALE_AFTER: "${RECONCILIATION_STALE_AFTER:-6h}"
RECONCILIATION_CONFIRM_CONCURRENCY: "${RECONCILIATION_CONFIRM_CONCURRENCY:-1}"
RECONCILIATION_KEEP_RUNS: "${RECONCILIATION_KEEP_RUNS:-30}"
RECONCILIATION_MAX_AGE: "${RECONCILIATION_MAX_AGE:-2160h}"
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
# 链路本地,公网 http 仍被拒绝)。客户端、探活与连接页共用同一判定。
# 链路本地,公网 http 仍被拒绝)。客户端与探活共用同一判定;控制台密钥录入不受此开关控制。
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
@@ -127,6 +148,16 @@ services:
TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
TEST_WEKNORA_KB_ID: "${TEST_WEKNORA_KB_ID:-}"
TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}"
RECONCILIATION_GRACE: "${RECONCILIATION_GRACE:-30m}"
RECONCILIATION_STALL_AFTER: "${RECONCILIATION_STALL_AFTER:-2h}"
RECONCILIATION_STALE_AFTER: "${RECONCILIATION_STALE_AFTER:-6h}"
RECONCILIATION_CONFIRM_CONCURRENCY: "${RECONCILIATION_CONFIRM_CONCURRENCY:-1}"
RECONCILIATION_KEEP_RUNS: "${RECONCILIATION_KEEP_RUNS:-30}"
RECONCILIATION_MAX_AGE: "${RECONCILIATION_MAX_AGE:-2160h}"
GOVERNANCE_SPOOL_ROOT: /var/lib/governance/spool
INGESTION_SPOOL_ROOT: /var/lib/governance/ingestion
TEST_WEKNORA_HTTP_TIMEOUT: "${TEST_WEKNORA_HTTP_TIMEOUT:-60s}"
+7
View File
@@ -0,0 +1,7 @@
[Unit]
Description=Advance original-task candidate queue
[Service]
Type=oneshot
ExecStart=%h/.local/lib/kg-candidate-release/python3 %h/.local/lib/kg-candidate-release/scripts/candidate_queue.py
TimeoutStartSec=180
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Check reviewed demand tasks waiting for QA
[Timer]
OnStartupSec=30s
OnUnitInactiveSec=45s
AccuracySec=5s
[Install]
WantedBy=timers.target
+22 -2
View File
@@ -1,8 +1,14 @@
# 知识治理候选和批次验收
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
## 需求单的六个状态
## 发起候选
新需求默认「规划中」。负责人手动按「规划中 → 进行中 → 待测试 → 测试中 → 待发布 → 已发布」切换状态。切到「待测试」触发预检和候选排队,收到候选就绪回执后切到「测试中」派测。原单显示「批次验收通过」后切到「待发布」触发 CD,收到主站发布完成回执后切到「已发布」。
## 在原需求单发布
白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后由负责人切到「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
## 旧版独立发布单的存量操作
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
@@ -28,6 +34,20 @@
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
### 候选访问测试 WeKnora
候选容器不能直连测试宿主的内网地址。宿主用 `kg-qa-weknora-test-hop.service` 把 `0.0.0.0:18090` 转到测试 WeKnora 的 `127.0.0.1:8092`,候选与所有 docker 网桥都能通过 `http://172.17.0.1:18090` 访问;`172.17.0.1` 是 docker0 的固定地址,换候选不变。绑定地址要填 IP,服务端不接受主机名。API Key 由测试负责人经授权渠道录入,不写进评论。
### 候选的知识库绑定密钥
验收候选运行在 QA 库上,知识库绑定需要独立的 32 字节主密钥。执行器在 `~/.local/state/kg-candidate-release/qa-binding-master.key` 维护唯一一份(0600、属主为容器应用用户),以只读方式挂到 API 与 worker 的 `/run/qa/binding-master.key`。所有候选共用这一份,已保存的绑定在下一轮候选仍可解开。文件缺失时首个候选自动生成;权限、长度或属主不符时拒绝启动,不静默降级。
### 原需求单的逐项报告
测试机将 `scripts/qa_report.py` 安装为 `~/.local/bin/kg-qa-report`。在 QA 的 HiFox 任务会话中,从本轮测试设计取得完整编号,保存到 `plan.json` 的 `business`、`regression` 数组。执行 `kg-qa-report init <任务> plan.json sheet.json` 读取原单候选回执并生成待填清单。测试中填写各编号的 `status`(`passed`、`failed`、`blocked`)和 `evidence`。`candidate_check` 记录指定候选部署上的实际验证结果及证据。环境受阻时记录原因。
使用 `kg-qa-report check <任务> plan.json sheet.json` 预检。缺失项按编号提示。使用同一参数将 `check` 换为 `submit` 后,由 QA 本人的 HiFox 执行上下文发表评论。回执变化时,工具会提示重新核对。登记端重新核算汇总和候选实测结论。
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
## 执行器配置
+249
View File
@@ -0,0 +1,249 @@
# 需求书:解析监控重构为「导入对账」
> 状态:v0.6(2026-12-01),已批准;Q1、Q5、Q6、Q7、Q9、Q10、Q11、Q12、Q13 已裁定。
> Q12/Q13 为 T6a 开工时人类确认:API 字段用 `kb_id`/`document_id`(数据库列名不变),R6 用 `/test-publications/{id}/removal` 而非 `removal-retry`。
> 依据:本仓 `origin/main` `ca87056` 与上游 WeKnora v0.9.1 源码(`~/weknora-explore/WeKnora-v0.9.1`)的直接阅读。
> 本期总计划、分工与工单拆分见 [WEKNORA_091_PHASE_PLAN.md](WEKNORA_091_PHASE_PLAN.md);本文是其中 T6 的需求正文。
## 1. 背景与结论
现「解析监控」(`internal/monitoring`、`internal/httpapi/monitor_tasks.go`、`web/src/WeKnoraMonitor.tsx`、`web/src/monitorTasks.ts`)做三件事:服务探活、按测试库统计处理状态、文件处理大表(筛选/重试/详情)。其中「解析」「索引增强」两个阶段的进度与失败细节,是平台轮询 WeKnora 后转述出来的。
WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5895):按文档查看入库与 Wiki 进度、处理阶段、历史失败。平台再把这些阶段细节转述一遍,等于和上游做同一件事,违反硬约束 1,而且转述永远比源头旧。
**结论:WeKnora 内部的处理细节交给 WeKnora 看;平台只做 WeKnora 看不到、也只有平台能做的事:把「台账 ↔ 知识库」(之后扩展到「来源 ↔ 台账」「测试库 ↔ 生产库」)对起来,发现并处置不一致。** 页面由「解析监控」改为「导入对账」。
⚠️ **边界**:台账上的 `processing_state` 是**工作流状态**,审核、组批、发布门禁都依赖它,**本需求不删除它**,也不改写平台轮询 WeKnora 确认完成的逻辑。去掉的只是界面上"解析阶段明细"这层转述;台账状态与 WeKnora 实际状态不一致的情况,由对账的 R5 发现并修正。
## 2. 职责划分
| 问题 | 归属 | 说明 |
| --- | --- | --- |
| 取件、上传是否成功 | 平台 | WeKnora 收到文件之前的阶段,上游看不到 |
| 解析/切片/向量/Wiki 进行到哪一步、为何失败 | WeKnora | 平台按需实时读取展示,不落库、不自建阶段机 |
| 解析失败后重新解析 | WeKnora(仅测试环境) | 一期只给跳转链接。生产只做推理,任何重解析都不能指向生产 |
| 该在库里的是否都在、在的是否该在、内容是否最新 | **平台(本需求核心)** | 只有平台同时掌握来源身份、台账与目标库 |
| 应下架内容是否已移除 | 平台 | 依据来源策略 `policy_state=blocked` |
## 3. 分期
| 期 | 对账两侧 | 说明 |
| --- | --- | --- |
| **一期(本期)** | 平台台账(`test_publications` 中 `superseded_at IS NULL` 的行)↔ 测试 WeKnora 知识库 | 两侧数据都已具备;依赖测试 WeKnora 已升级到 v0.9.1 |
| 二期 | 来源 ↔ 平台台账 | 漏取、来源已删除平台仍现行;各来源扫描能力不同,需逐源确认 |
| 三期 | 测试库 ↔ 生产库 | 生产只做推理,内容全部由整库发布从测试搬运,所以这一期核对的是"搬运是否完整"。复用 `librarysnapshot`/`librarydiff`,按稳定 ID 和内容摘要比对 |
下文只展开一期。
### 3.1 一期边界:只对测试库;生产的下架靠发布链路
一期只对测试 WeKnora 做对账,**生产库没有对账对象**。生产的下架保证不在本需求内,它依赖两段已有链路:
1. 来源判 `blocked`:`planned` 行置 `superseded_at`,来源项 `policy_state='blocked'`(`policy_intents.go`)。
2. 变更集确认后:已入库行置 `retrieval_state='disabling'` 并入队 `test.remove`,移除完成后为 `disabled`(`change_set_execution.go`、`publication_removal.go`)。
3. 下一轮整库发布以测试库为源做 diff,生产库里多出来的文档判 `Removed` 后删除。
所以**生产下架的最迟时间 = 测试移除完成 + 下一次整库发布**。两次发布之间的空窗期,生产仍可检索已被判禁止的内容,一期发现不了。这一条必须写进页面的范围说明;是否再显示「距上次整库发布 N 天」见 Q8(未裁定)。
## 4. 差异类型(一期)
**身份配对口径(已核实)**:平台上传时写入 `metadata.publication_id`、`metadata.content_sha256`,并设 `channel=governance`(`internal/workflows/testweknora/upload.go`,main 上第 141 行起);台账记录 `knowledge_id`。配对优先用 `knowledge_id`,其次用 `metadata.publication_id`。
⚠️ WeKnora 对相同字节去重,同一份文件放在两个来源目录时,**多条台账可以合法地指向同一个 knowledge**(同文件中 ErrConflict 分支的收养逻辑)。只有能找到收养的审计证据才算合法(与陷阱 16 同理)。
**两个谓词(全文只用这两个;不再出现未定义的「现行行」)**
- `ledger_current`:`test_publications.superseded_at IS NULL`。用于 R2、R8 反查台账,以及所有“现行”计数。
- `ledger_expected_live`:`ledger_current` 且 `knowledge_id <> ''`、`processing_state <> 'failed'`、`retrieval_state NOT IN ('disabling','disabled')`。用于 R1、R4、R5、R7 的正向核对。
`ledger_expected_live` 必须排除 `disabling`/`disabled`:移除完成只改 `retrieval_state`,`knowledge_id` 会保留(`publication_removal.go` 的 `RecordRemovalCompleted`),不排除就会把正常下架的条目永久误报成 R1。
| 编号 | 差异 | 判定口径 | 默认处置 |
| --- | --- | --- | --- |
| R1 丢失 | 台账认为应仍在库,库里没有 | `ledger_expected_live`,且单条 `GET /knowledge/{id}` 返回 404;“列表里没看到”不算证据 | 建议「重排上传」(复用现有动作) |
| R2 孤儿 | 库里有平台导入的条目,台账没有现行行指向它 | `channel=governance`,且 `metadata.publication_id` 没有 `ledger_current` 台账行,也没有 `ledger_current` 行以 `knowledge_id` 指向它;同字节被兄弟台账合法收养(其 `publication_id` 有 `ledger_current` 行)不算孤儿 | 只报告;移除走现有「测试库移除」,需人工确认 |
| R3 非平台导入 | 库里有不是平台导入的条目 | `channel≠governance` | 只统计、单列,不算错误 |
| R4 内容过期 | 库里的内容不是台账现行版本 | `ledger_expected_live`;`metadata.content_sha256` ≠ 台账现行版本 sha256(来源链见下),或有独立 MD5 证据且与 `file_hash` 不符 | 建议重新上传 |
| R5 状态不一致 | 两边状态长期对不上 | 台账 `processing_state` 与 WeKnora `parse_status` 按 §4 矩阵归一后不同,且以 `run.started_at` 计算已超过宽限期(默认 30 分钟,可配);回写受迁移表约束 | 人工点击「以 WeKnora 为准回写」,写审计 |
| R6 应下架仍在 | 来源已判禁止导入,库里仍可检索 | `superseded_at IS NULL`、`knowledge_id<>''`、`processing_state='completed'`、`retrieval_state NOT IN ('disabling','disabled')`、`item.policy_state='blocked'`;**与 `/monitor/overview` 的「需下架」共用同一个实现**,不得两处各写一遍 | 进入现有「需下架」流程 |
| R7 卡住 | 长时间没有进展 | 上游 `stall_state=stalled`;或 `pending`/`processing` 超过阈值(默认 2 小时,可配,按 `run.started_at` 计算);或 `deleting` 超过同一阈值(删除卡住) | 展示 WeKnora 阶段与失败记录,并给出跳转 |
| R8 一对多异常 | 一条台账对应多个现行条目 | 同 tenant、同 KB 下按 `metadata.publication_id` 分组,**排除 `parse_status` 为 `failed`/`deleting` 的条目**后仍大于 1。上游去重作用域是「同 tenant + 同 KB + 同 file_type + file_hash,排除 failed/deleting」(`repository/knowledge.go:435-466`),所以“同 hash 一条 failed + 一条现役”“同字节 .md 与 .txt”都是合法共存,不进 R8 | 只报告,人工处理 |
**状态归一与判定矩阵**
上游 `parse_status`:`pending` / `processing` / `finalizing` / `completed` / `failed` / `cancelled` / `deleting`(`internal/types/knowledge.go`)。台账 `processing_state`:`planned` / `pending` / `processing` / `finalizing` / `completed` / `failed` / `stalled`。
归一表(上游 → 台账词汇):`pending→pending`、`processing→processing`、`finalizing→finalizing`、`completed→completed`、`failed→failed`、`cancelled→cancelled`、`deleting→deleting`。`cancelled`、`deleting` 在台账没有对应状态,保留原名,**不得静默归到“其他”**。
判定矩阵(行 = 台账,列 = 归一后的上游状态):
| 台账 \ 上游 | pending | processing | finalizing | completed | failed | cancelled | deleting |
| --- | --- | --- | --- | --- | --- | --- | --- |
| planned | — | — | — | — | — | — | — |
| pending | ✓ | G | G | G | G | G | D |
| processing | G | ✓ | G | G | G | G | D |
| finalizing | G | G | ✓ | G | G | G | D |
| completed | G | G | G | ✓ | G | G | D |
| failed | G | G | G | G | ✓ | G | D |
| stalled | S | S | S | G | S | S | D |
- ✓ 一致。
- G:超过宽限期报 R5;`completed` 行对任何 G 只报告、`suggested_action=none`(禁止把已完成降级)。
- S:报 R7,展示上游阶段与失败记录。
- D:等待删除完成;超过 2 小时仍是 `deleting` 转 R7。
- —:`planned` 正常没有 `knowledge_id`,不比较;若出现 `planned` 且有 `knowledge_id`,按 G 处理并标为台账异常。
矩阵只写在服务端一处;接口以 `normalized_state` 字段直接返回归一结果,前端不内置映射表(前端拿不到 Go 常量)。
**内容校验的证据链**:台账的 sha256 不在 `test_publications` 上,来源链固定为 `test_publications.source_item_version_id → source_item_versions.content_object_id → content_objects.sha256`;实现不得为此在台账加列。
- `metadata.content_sha256`:平台上传时写入的**声明**。
- `file_hash`:WeKnora 对收到字节算的 **MD5**(上游 `knowledge_util.go:131`),**独立证据**。
- 本期起上传时在台账新增 `upload_md5`(迁移),对账用它与 `file_hash` 比对。
证据等级:`independent`(声明 sha256 与 MD5 都可核且一致)、`declared_only`(历史数据只有 `metadata` 声明)、`none`(metadata 缺失或无 MD5 可比)。只有前两级可判 R4;`none` 只统计、不判差异。
## 5. 数据来源(已核实上游接口)
| 用途 | WeKnora 接口 | 鉴权 |
| --- | --- | --- |
| 全量列出库内条目 | `GET /knowledge-bases/{id}/knowledge`(分页;可按 `parse_status`、`source`、时间、目录筛选) | 现有租户 API Key |
| 单条确认 | `GET /knowledge/{id}` | 现有租户 API Key |
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | **平台级 API Key,能力 `system_runtime_read`**(上游 `routes_auth_tenant.go:356`) |
| 队列深度 | `GET /system/admin/runtime/queues` | 同上 |
条目中对账要用的字段:`id`、`knowledge_base_id`、`channel`、`metadata`、`file_hash`、`parse_status`、`stall_state`、`enable_status`、`updated_at`。
**扫描参数**:列表接口 `page_size` 的上游上限是 1000(`types/search.go:320`),对账必须用 1000;平台现有客户端把上限卡在 100(`internal/platform/weknora/client.go:361`),T6a 要为对账放开到 1000,不能沿用上传恢复的 100。1 万条的库因此是 10 次请求而不是 100 次。
**列表的盲区**:不传 `parse_status` 时上游隐藏 `deleting` 行(`repository/knowledge.go:176`),所以“列表里没有”不等于“已删除”,R1 必须单条 GET 复核。
**平台级 Key 的配置契约(Q7 已裁定)**
- 键名 `WEKNORA_RUNTIME_KEY_FILE`,值为**绝对路径**,secret 文件挂载进容器;不写进 compose 环境变量、不进 Git。
- 启动时读取一次,权限 0400;换 Key 需重启平台(与现有 `*_API_KEY_FILE` 一致,不做热加载)。
- “变量为空”与“变量有值但文件缺失/不可读”要区分:前者静默降级;后者启动不失败,写一条 WARN 日志,运行时按未配置处理。
- 两种情况都让 `runtime/queues`、`runtime/documents/{id}` 返回 503 `runtime_read_unavailable`,`/monitor/overview` 的 `weknora_queues` 为 `null`;对账本身只需租户 Key,照常运行。
## 6. 运行方式
- **开关**:`RECONCILIATION_ENABLED`(默认 `false`)只决定对账服务是否接线——关着时 9 个接口统一 503 `reconciliation_not_configured`;它与 `TEST_WEKNORA_ENABLED`(旧的取件/上传链路)解耦,因为对账只用知识库绑定里的租户 Key。候选/测试环境显式开启,生产按授权再开。
- **对账批次**:每次对账生成一个批次(run),记录开始/结束时间、两侧计数、各类差异计数和明细。结果持久化,可以和上一成功批次比较。触发方式:定时(默认每天 02:00,可配)+ 页面手动触发。
- **唯一观测时刻**:批次以 `run.started_at` 作为唯一的“现在”。R5 宽限期、R7 阈值和所有相对时间判断都用它,不用 `time.Now()`。同一批次因此可重放、可解释,验收里的“连续两次一致”才有定义。
- **全量扫描必须完整**:整页翻完才算完成,中途失败整批标为 `failed`,不产出部分结论。不能用“最近 N 条”代替全量(陷阱 17)。扫描使用 `page_size=1000`(§5)。这里的“完整”指本批把所有页翻完,不承诺对并发写入做快照:扫描期间有增删时可能漏掉个别条目,漏掉的在下一批补上,批次记 `window_overlapped` 供解释;不为此引入游标或重扫(Q10)。
- **先确认再判缺**:R1、R2 定论前必须逐条单独读一次(`GET /knowledge/{id}`),区分 404、`deleting` 和翻页窗口漂移;没有单条证据的 R1/R2 不写 finding。
- **并发**:同一测试库同时只能有一个 `running` 批次,用部分唯一索引兜底:`CREATE UNIQUE INDEX ... ON reconciliation_runs(test_kb_id) WHERE state='running'`;应用层的 409 只是友好提示。
- **僵死批次回收(Q11)**:`running` 超过 6 小时(可配)视为失败,启动或下次触发时自动置 `failed` 并释放并发位;否则进程崩溃会让该库永久 409。
- **与整库导出/发布重叠(Q6 已裁定)**:不互斥。批次开始或运行期间检测到整库导出/发布作业在跑,则 `run.window_overlapped=true`;该批次的 R1、R2 照常写入,但 `confirmation_state='pending'`,页面显示「待确认」,计数保留。
- **findings 保留(Q5 已裁定)**:`runs` 永久保留(含 counts/previous_counts);`findings` 只保留**最近 30 批且不超过 90 天**,超出后按 `run_id` 整批删除,不逐行删。清理在每批对账结束后执行,幂等;删明细不影响批次计数和历史对比。
- **对账只读**:对账过程不向 WeKnora 发起任何写请求。处置动作是人点击触发的独立动作,复用现有带审计的动作。
- **并发与限速**:默认全程串行(同一时刻只有 1 个在途请求)。翻页**不并发**:offset 分页本来就会漂,并发只会让重复/漏页更难复现;R1/R2 的单条确认可以小并发,配置项 `reconciliation_confirm_concurrency`,默认 1、上限 8。**不复用入库的 `ingestion_concurrency`**:对账是夜间批处理,1 万条也只有 10 次翻页请求,不需要和取件/上传抢配额。
## 7. 接口契约(后端 T6a 与前端 T6b 的分界线)
T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,作为冻结契约;T6b 按契约在 T6a 之后开发(同一执行人,只改 `web/`)。契约以后要改,必须 T6a/T6b 两边都确认,并同步更新本节。
响应风格、错误体、鉴权方式沿用现有 `/api/v1/monitor/*` 的约定。响应中不得出现 URL 凭据、Key、Authorization。
| 方法 | 路径 | 说明 | 角色 |
| --- | --- | --- | --- |
| POST | `/api/v1/reconciliation/runs` | 请求体 `{kb_id}`;返回 202 和 run 对象;该库已有运行中批次时返回 409 `reconciliation_run_in_progress` | 管理员、文档工程师 |
| GET | `/api/v1/reconciliation/runs?kb_id=&limit=&offset=` | 批次列表,按开始时间倒序 | 所有登录角色 |
| GET | `/api/v1/reconciliation/runs/{id}` | 单个批次 | 所有登录角色 |
| GET | `/api/v1/reconciliation/runs/{id}/findings?type=&q=&limit=&offset=` | 差异明细,`limit` ≤ 100 | 所有登录角色 |
| POST | `/api/v1/reconciliation/findings/{id}/writeback` | 仅限 R5:以 WeKnora 状态回写台账,写审计;返回更新后的 finding | 管理员、文档工程师 |
| POST | `/api/v1/reconciliation/findings/{id}/requeue` | 仅限 R1/R4:R1 清空 `knowledge_id` 后重排上传;R4 先删旧 knowledge 再重传,删除失败则动作失败且台账不变;写审计 | 管理员、文档工程师 |
| POST | `/api/v1/reconciliation/findings/{id}/remove` | 仅限 R2:按 `knowledge_id` 从测试库删除,404 视为已删除;写审计;重复点击幂等 | 管理员 |
| GET | `/api/v1/reconciliation/documents/{document_id}/progress` | 实时转发 WeKnora `runtime/documents/{id}`,经过脱敏;未配置平台 Key 时返回 503 `runtime_read_unavailable` | 所有登录角色 |
| GET | `/api/v1/monitor/overview`(已有) | 新增 `weknora_queues` 字段(来自 `runtime/queues`,不可用时为 null);删除 Embedding/LLM 两张常量"未知"卡 | 不变 |
**`/api/v1/monitor/tasks`(已有,T6a 增量)**:每行新增可选 `weknora_url`(目标测试知识库的 WeKnora 控制台链接;未配置测试端点时为空字符串),供文件详情抽屉在 progress 返回 503 时显示跳转链接。该字段为附加字段,既有字段与筛选语义不变;与 finding 的 `weknora_url` 使用同一拼接规则(`internal/platform/weknora.KnowledgeBaseConsoleURL`)。
**run 对象**:`id`、`kb_id`、`state`(`running` \| `succeeded` \| `failed`)、`trigger`(`schedule` \| `manual`)、`started_at`(同时是观测时刻)、`finished_at`、`ledger_count`、`kb_count`、`counts`(键为 R1–R8,值为整数)、`previous_counts`(上一成功批次的 counts,没有则为 null)、`window_overlapped`(bool,Q6)、`error_code`。
**finding 对象**:`id`、`run_id`、`type`(R1–R8)、`publication_id`、`document_id`、`title`、`path`、`source`、`target_scope`、`ledger_state`、`weknora_parse_status`、`normalized_state`(按 §4 矩阵归一后的值,供前端直接显示)、`ledger_sha256`、`declared_sha256`、`weknora_file_md5`、`evidence_level`(`independent` \| `declared_only` \| `none`)、`confirmation_state`(`confirmed` \| `pending`,仅 R1/R2 在 `window_overlapped` 批次里可为 pending)、`detail`(中文一句话)、`suggested_action`(`requeue_upload` \| `remove_from_test` \| `writeback_state` \| `enter_removal` \| `none`)、`action_state`(`open` \| `done`)、`weknora_url`(在 WeKnora 中打开的链接,可为空)。
**R5 回写的迁移约束**(`POST /api/v1/reconciliation/findings/{id}/writeback`)
| 当前台账 | 允许回写到 |
| --- | --- |
| `pending` | `processing`、`finalizing`、`completed`、`failed` |
| `processing` | `finalizing`、`completed`、`failed` |
| `finalizing` | `completed`、`failed` |
| `failed` | `pending`、`processing`、`completed` |
| `stalled` | `pending`、`processing`、`failed` |
- `completed` 不允许回写到任何其他状态;`planned` 不是回写目标;`stalled` 是平台派生状态,不可写。
- 目标是归一后的上游状态;`cancelled`、`deleting` 没有台账对应,不提供回写(`suggested_action=none`)。
- 幂等:台账已等于目标时返回 200,不写新审计。
- 台账在本批次后已被别的动作改过时返回 409 `reconciliation_writeback_stale`。
- 回写只改 `processing_state`,不动 `retrieval_state`,不触发发布。
**progress 对象**:`document_id`、`parse_status`、`ingestion_status`、`wiki_status`、`stages[]`(name、status、error_code、finished_at)、`failures[]`(task_type、fail_count、failed_at、last_error,后者截断到 500 字符)、`has_more_failures`、`observed_at`。
处置动作的落点:`writeback_state`(R5)、`requeue_upload`(R1/R4)、`remove_from_test`(R2)、`enter_removal`(R6)各一个入口。**只有 R6 能复用现有接口**(`POST /test-publications/{id}/removal`;`removal-retry` 只重试已失败的移除,不发起首次移除);R1/R4 不能走 `retryPublicationsBatch`(只接受 `failed`/`stalled`,`job_failures.go:448`),R2 不能走测试库移除(拒绝 `superseded`,`test_publication_removal.go:68`),所以这两个是新接口,不是同义接口。
## 8. 页面改造(T6b,前端)
| 现有部分 | 去向 |
| --- | --- |
| 左侧导航「解析监控」 | 改名为「导入对账」,路由保留旧地址并重定向 |
| 服务与依赖卡片区 | 收成页面顶部一行状态条;「队列」读 `weknora_queues`;删除 Embedding/LLM 两张常量"未知"卡 |
| 按测试库的状态计数 | 改为「最近一次对账」概览:批次时间、状态、R1–R8 计数及与上一批的变化,附「立即对账」按钮(按角色显示) |
| 文件处理大表 | 拆成两个页签:①**差异清单**(按类型、关键词筛选,每行显示证据等级、处置建议和按钮;`window_overlapped` 批次的 R1/R2 显示「待确认」徽标);②**平台侧流水**(沿用 `/monitor/tasks`,阶段筛选里的“解析”“索引增强”合并为“WeKnora 处理中”) |
| 文件详情抽屉 | 平台侧信息保持不变;新增「WeKnora 处理详情」区块,实时调用 progress 接口,展示阶段时间线和历史失败;503 时显示"未配置只读 Key"和跳转链接 |
⚠️ 两个页签口径不同:差异清单只看 `superseded_at IS NULL` 的行;平台侧流水沿用 `/monitor/tasks`,**不过滤被顶替行**(`internal/monitoring/real.go:197-214`)。这是有意的,页面要写一句说明,避免同一文件在两个页签结论不同被当成 bug。
差异清单页脚注明保留范围:明细只保留最近 30 批且不超过 90 天,更早批次只保留计数。
视觉沿用现有规范:dobot.cn 钴蓝 #0039C8 + 中性灰,不用紫色;导航保持 16px / 44px。
## 9. 验收标准
**后端(T6a)**
1. 用夹具(或在测试库人工构造)覆盖 R1–R8 每类至少一个样本,对账逐条命中,且没有多报。
2. 用固定夹具和固定 `started_at` 重放同一批次两次,差异集合逐条一致;跨批次的时间类差异(R5/R7)按各自 `started_at` 解释,不要求两次相同。
3. 对账过程中向 WeKnora 发出的写请求数为 0(以测试中的 HTTP 桩记录为证)。
4. 扫描中途注入错误后,批次为 `failed`,没有写入任何 finding。
5. 合法的"同字节多台账收养"不被报为 R8。
6. `cancelled`、`deleting` 有显式映射,并有测试覆盖。
7. 接口响应和日志中不出现 Key、Authorization 等密钥(有测试断言)。
8. 并发触发同一库,第二个请求返回 409。
9. OpenAPI 契约测试通过,`make verify` 全绿。
10. `window_overlapped` 批次:R1/R2 的 `confirmation_state='pending'`,其他类型不受影响;接口和页面都能看到。
11. 保留策略:第 31 批或超过 90 天的 findings 被按 run 整体删除,runs 与 previous_counts 保留;清理重复执行无副作用。
12. 状态矩阵用表驱动测试覆盖 7×7,`cancelled`/`deleting` 有显式归一值,没有“其他”分支。
13. R5 回写:`completed` 不可降级;禁止的迁移返回 409 且台账不变;重复回写幂等且不重复写审计。
14. 已移除的行(`retrieval_state in ('disabling','disabled')`)不报 R1。
15. R6 与 `/monitor/overview` 的「需下架」计数由同一实现产出,测试断言两处数字一致。
16. 扫描请求的 `page_size=1000`(HTTP 桩断言),不再出现 100。
17. 扫描期间在途请求数恒为 1(桩记录并发峰值),确认阶段不超过 `reconciliation_confirm_concurrency`。
18. R1 重排:清空 `knowledge_id`、置 `pending`、入队上传,旧 knowledge 不存在时也能成功;R4 先删旧 knowledge,删除失败时动作返回错误且台账不变。
19. R2 删除:按 `knowledge_id` 删除,404 视为成功,重复点击幂等。
20. 僵死批次:`running` 超过阈值自动置 `failed`,之后可以再触发。
**前端(T6b)**
1. 每个页签和抽屉都有加载、空、错误、无权限四种状态,并有组件测试覆盖。
2. 只读角色看不到「立即对账」和处置按钮。
3. progress 返回 503 时降级展示,页面不报错。
4. 在 1440 / 1024 / 768 宽度下没有页面级横向溢出。
5. `npm run build` 和前端测试通过,`make verify` 全绿。
## 10. 决策记录
| # | 问题 | 默认建议 |
| --- | --- | --- |
| Q1 | 是否为平台在**测试** WeKnora 开一个 `system_runtime_read` 平台级只读 Key | **已裁定:开**(只开在测试环境) |
| Q2 | 历史上传里没有 metadata 的条数 | T6a 开发时先统计,结果写进工单评论 |
| Q3 | 对账频率、R5 宽限期、R7 阈值 | 未裁定,按默认值执行:每天 02:00;30 分钟;2 小时(可配置) |
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加“距上次发布 N 天” |
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受并发增删造成的个别漏项在下一批补上,不引入游标 |
| Q11 | 僵死 `running` 批次 | **已裁定**:超过 6 小时(可配)自动置 `failed` |
| Q12 | API 字段命名 | **已裁定**:`kb_id`/`document_id`;数据库列名仍为 `test_kb_id`/`knowledge_id`,避免 OpenAPI 安全门禁全局禁名 |
| Q13 | R6 处置入口 | **已裁定**:`POST /test-publications/{id}/removal`;`removal-retry` 只重试已失败移除 |
+7 -1
View File
@@ -70,6 +70,12 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
**页面为什么不看开关。** 「知识库绑定」页不再用浏览器 URL 或服务端能力位决定能否录入 Key;只要独立安全存储就绪,管理员即可录入/更换,服务端也不因控制台协议拒绝。经非 HTTPS、非回环地址打开时,页面只显示「当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。」,提示但不阻断。`WEKNORA_ALLOW_PRIVATE_HTTP` 只控制治理 API/worker 访问同网段 http 目标,不再控制控制台录入;问答 AI 模型密钥仍只允许 HTTPS/回环录入。Web 与 API 是独立镜像,必须同批次发布/回滚:旧 Web 对新 API 会因缺少能力位禁用录入,新 Web 对旧 API 仍会被服务端 400 拒绝。
**保存留审计。** 每次保存成功,`weknora_environment_binding_history` 在同一事务写入
操作人、时间、环境、客户端地址(`source_address`)与控制台来源(`source_origin`)。来源字段
只用于事后取证,不参与放行;地址解析不出来就留空,不用推测值填充。
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
「清除密钥」是独立动作(二次确认),清除后该侧解析失败关闭,不会回落到服务器文件
@@ -176,7 +182,7 @@ bash scripts/target_kb_snapshot.sh # 默认云内执行;PG 8 表 +
| 知识库绑定(测试 090 / 生产 090) | 管理员 | 每个环境:服务地址 + API Key(服务器真实列库)→ 选对外/对内库 → 一次保存;密钥不回显,换地址须重录 |
| 绑定诊断(折叠) | 管理员 | 探活、封存源对照、整库发布目标(只读,由部署配置决定)与旧文档级目标 |
| **存储与备份** **【新】** | 管理员 | **定时时间 + 储存天数**(+每月归档、启用开关)→ `保存并下发到主机`;另有 `重新下发当前设置`、`立即备份一次`;页面显示主机上**实际生效**的计划、cron 条目、最近一次结果与"已一致/待下发" |
| 刷新策略 | 文档工程师 | 文档/资源刷新间隔、停滞判定、finalizing 时长(版本化 + 原子切换) |
| 参数设置 | 文档工程师 | 「来源与目录」文档/资源刷新间隔;「解析监控」停滞阈值、入库并发上限(1..16,版本化 + 原子切换);finalizing 设置仅在 API/DB 保留,页面不展示 |
| 成员与角色 | 管理员 | 成员与 viewer/engineer/admin |
## 9. 备份与恢复运维 **【新】**
+19
View File
@@ -96,6 +96,25 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
- **配额(按字节,硬上限)**:`/etc/knowledge-governance/backup.env` 的 `KB_BACKUP_QUOTA_BYTES`
约束**备份根累计占用**(默认 `53687091200` = 50 GiB,`backup_layout.sh` 写入,重跑不覆盖已有值)。
采集器把同一份配额与根占用写进快照,页面/告警只读该值,不再看归档库。
- dump 前预检:预留最近一份完整批次大小,从最旧开始计划删批次,**永不删最新一份**;
空间仍不够 → **一个都不删**、非 0 退出,本次备份取消。
- dump 后复查:保护本次新批次,允许删旧(含上一份);仍超限则保留新备份并告警退出。
- 只删 `rds-logical/<UTC>` 完整批次(含常规 `MANIFEST.json`、非符号链接);
`es-snapshots`/`target-kb-snapshots`/`logs` 与 `*.incomplete` 永不删。
- **删除分三段(预检 → 改名隔离 → 真删)**:`rmtree` 会先删内容、最后删目录,父目录只读时
失败发生在内容已清空之后,调用方只看得到非 0 退出。所以先逐目录检查可写性并对每个计划内
批次做同父目录改名探针(只验证父目录可写,不动内容),再全部改名成 `.prune-<pid>-<戳>`
(原子、不进批次候选),最后才真删。任一预检失败或改名失败 ⇒ **零删除**;真删阶段才失败时
报隔离路径(`mv` 回原名即可恢复剩余内容)。
- 轮转(`KEEP_DAILY`/`KEEP_MONTHS`)与配额清理走同一份实现(`--rotate`),不再有第二份内联
`rmtree`。
- 退出码:`0` 已满足(可能删过)、`2` du/路径错误、`3` 空间仍不够、`4` 真删阶段失败、
`5` 预检未通过(零删除)。
- 现场对账:`du -sB1 -- $KB_BACKUP_ROOT` 与页面「备份占用」应一致(≤1%);
`bash scripts/install_backup_schedule.sh --show` 也会打印根占用/配额。
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
+32 -5
View File
@@ -19,11 +19,15 @@
```sh
python3 collect_backup_metadata.py \
--root /srv/kb-backups/rds-logical \
--usage-root /srv/kb-backups \
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
--source weknora-test:/srv/kb-backups/rds-logical
```
- 退出码:`0` 完整;`2` 已写快照但采集不完整/有错误;`1` 连快照都没写成。
- 备份根与配额来自 `/etc/knowledge-governance/backup.env`(`backup_layout.sh` 生成):
`KB_BACKUP_ROOT`(默认 `/srv/kb-backups`)与 `KB_BACKUP_QUOTA_BYTES`(默认 `53687091200` = 50 GiB)。
`--usage-root` / `--quota-bytes` 可显式覆盖;`--config` 换配置文件路径。
- 退出码:`0` 完整且配额可用;`2` 已写快照但批次/根占用不完整或配额非法;`1` 连快照都没写成。
- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
**不打开任何 `.dat/.gz` 数据文件**。
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
@@ -47,6 +51,8 @@ python3 collect_backup_metadata.py \
```
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
采集器自己读 `/etc/knowledge-governance/backup.env` 拿 `KB_BACKUP_ROOT`/`KB_BACKUP_QUOTA_BYTES`,
所以配额调整不需要改 cron;只想临时覆盖时再加 `--usage-root`/`--quota-bytes`。
### 快照 schema(version 1)
@@ -58,6 +64,10 @@ python3 collect_backup_metadata.py \
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
| `backup_root` | 宿主上的备份根(`KB_BACKUP_ROOT`);API 要求等于 `BACKUP_HOST_ROOT` |
| `usage` | 备份根整棵树的累计占用:`root/complete/actual_bytes/apparent_bytes/file_count/dir_count/errors`;`complete=false` 时字节必须为 `null` |
| `quota_bytes` | 备份根累计占用硬上限(字节);非法/缺失时为 `null`,原因写 `quota_error` |
| `quota_error` | 配额不可用的原因(例如 `KB_BACKUP_QUOTA_BYTES` 不是正整数) |
| `complete` | 全局完整;权限失败/截断/有错误时为 false |
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
@@ -87,8 +97,16 @@ python3 collect_backup_metadata.py \
},
"root": "/srv/kb-backups/rds-logical",
"host_root": "/srv/kb-backups/rds-logical",
"backup_root": "/srv/kb-backups",
"source": "weknora-test:/srv/kb-backups/rds-logical",
"measurement": "host_collector",
"usage": {
"root": "/srv/kb-backups", "complete": true,
"actual_bytes": 24318382080, "apparent_bytes": 23000000000,
"file_count": 900, "dir_count": 30, "errors": []
},
"quota_bytes": 53687091200,
"quota_error": "",
"mount": {
"mount_verified": true, "read_only": false,
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
@@ -135,8 +153,11 @@ python3 collect_backup_metadata.py \
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有 `*_bytes=null` | 列出路径与清单状态;占盘/容量“未知”,不画色带 |
| 完整且新鲜 | 批次/子库字节与容量按快照 | 色带、批次、子库路径复制可用 |
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有批次 `*_bytes=null` | 列出路径与清单状态;批次/容量“未知”,不画色带;根占用若自身完整仍可显示 |
| 根占用遍历失败 | `metadata.valid=true`;`usage.actual_bytes=null`、`usage.error` 给原因 | 「备份占用 —」并显示原因;批次表与磁盘剩余不受影响 |
| 旧采集器无 `usage/quota` | 字段缺省,API 返回显式「未上报」原因 | 「备份占用 —」「配额未上报」,绝不用批次和冒充 |
| `usage.root` 与 `BACKUP_HOST_ROOT` 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑占用 |
| 完整且新鲜 | 批次/子库字节、根占用与配额按快照 | 色带、批次、`备份占用 X / 配额 50 GB` |
| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
@@ -187,7 +208,13 @@ curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
字段核对(以现场为准,示例值不写死):
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看占盘与容量。
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看批次字节与容量。
- `usage.complete=true` 时,`usage.actual_bytes` 必须与宿主 `du -sB1 -- /srv/kb-backups` 一致
(误差 ≤1%);`quota_bytes` 与 `/etc/knowledge-governance/backup.env` 的 `KB_BACKUP_QUOTA_BYTES` 相同。
- `usage.actual_bytes` **不是** `totals.actual_bytes`:后者只累加 `rds-logical` 批次,
前者还包含 `es-snapshots`/`target-kb-snapshots`/`logs`。
- 根占用遍历失败:`usage.complete=false`、`usage.actual_bytes=null`,同时批次仍应可用;
**不要**用批次和代替根占用。
- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
@@ -218,7 +245,7 @@ curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
## 6. 还需单独确认的后端写能力
1. 配额 / 磁盘预留的持久化与执行(当前无字段)。
1. 配额 / 磁盘预留的持久化:配额已按部署配置(`backup.env`)执行并上报;**平台页面编辑/下发**仍未实现(需 DB 字段与写接口)。
2. 旧批次保留/删除与删除前审计、可恢复窗口。
3. 备份目录迁移/切换。
4. 单库备份/单库恢复(现有 run 是整批)。
+8 -4
View File
@@ -284,10 +284,14 @@
- 立即备份:按钮变"备份进行中…"→ 约 50 秒后自动刷出新结果(异步 202 + 在途单飞,重复点击不会跑两次)
- 状态:✅ 2026-10-09 面板实测(写操作仅管理员:`PUT/POST /api/v1/backup-schedule*`)
### D5 刷新策略
- 入口:**系统设置 → 刷新策略**(文档工程师可改)
- 期望:文档/资源刷新间隔、停滞判定、finalizing 时长;保存先验证再原子启用、旧版本留审计
- 状态:✅(`ui_settings` 版本化激活测试)
### D5 参数设置
- 入口:**系统设置 → 参数设置**(文档工程师可改)
- 期望:按「来源与目录」「解析监控」两组呈现。来源与目录:文档状态刷新间隔(15/30/60 秒)、
资源刷新间隔(30/60 秒);解析监控:解析停滞阈值(30/60 分钟)、入库并发上限(1..16)。
四项以数值输入呈现,单位与调大/调小后果常驻,越界就地提示并禁用保存;保存先验证再原子
启用、旧版本留审计。收尾超时告警不再在页面任何位置出现;API/DB 的
`finalizing_after_seconds` 与 `finalizing` 处理状态不变。
- 状态:✅(`ui_settings` 版本化激活测试;本任务补数值校验与浏览器实测)
### D6 成员与角色
- 入口:**系统设置 → 成员与角色**(管理员)
+179
View File
@@ -0,0 +1,179 @@
# 本期计划:WeKnora 升级 v0.9.1 + 导入对账
> 状态:v0.4(2026-11-30),用户已裁定 D0 / D1 / Q1 / Q5 / Q6 / Q7 / Q9 / Q10 / Q11,可以开工。不建 Gitea 工单,本文即任务书。
> 基线:`origin/main` `ca87056`;上游 WeKnora v0.9.1 源码 `~/weknora-explore/WeKnora-v0.9.1`。
> 导入对账的需求正文见 [IMPORT_RECONCILIATION_REQUIREMENTS.md](IMPORT_RECONCILIATION_REQUIREMENTS.md)。
## 0. 目标
1. 测试、生产 WeKnora 从 v0.9.0 升级到 v0.9.1,升级后整库发布照常可用。
2. 「解析监控」重构为「导入对账」一期(台账 ↔ 测试库)。
发布架构保持不变(2026-11-30 与用户确认):**测试环境负责解析、人工加工和新功能验证;生产环境只做推理,不跑 MinerU、不做解析;内容只通过平台整库发布(直接读写 WeKnora 的 PG/ES)从测试搬运到生产。**
## 1. 分工
| 角色 | 负责 | 不做 |
| --- | --- | --- |
| **用户** | 批准需求与工单;执行现场运维(升级、备份);授权生产发布;回答各工单里的决策项 | — |
| **DeepSeek(开发)** | T1、T6a、T6b 的开发、测试、迁移和项目文档;T3 演练的脚本和命令准备 | 不改验收标准;不部署;不执行生产写操作 |
| **验收工作流** | 按本文验收矩阵逐项判定 PASS / FAIL,结论绑定提交 SHA(由用户指派) | 不修代码 |
交接证据和验收结论的格式沿用 [three-agent-handoff-workflow.md](architecture/three-agent-handoff-workflow.md) §6 的模板(只借格式,不再有三个角色)。
**交付流程(D0,已裁定:走 PR)**:按 `AGENTS.md` 执行。每个工单从最新 `origin/main` 拉一个短分支,通过 PR 合入;CI `build` 通过,且验收工作流 PASS 后才合并;合并后读回 `merged=true` 和 `merge_commit_sha`。`three-agent-handoff-workflow.md` §2 中"main 直推、不走 PR"的口径作废,由 DeepSeek 在 T1 的 PR 里顺手把该节改成与 AGENTS.md 一致。
**不建 Gitea 工单**:本文就是任务书。交接证据(起止 SHA、测试命令与真实输出)和验收结论写在对应 PR 的描述和评论里,格式沿用上面提到的 §6 模板。
**串行规则**:T1、T6a、T6b 全部由 DeepSeek 开发,串行进行(T1 → T6a 契约 → T6a 实现 → T6b)。T6b 只改 `web/`,与 T6a 交错时不动后端文件,避免冲突。
## 2. 工单总览与依赖
```
T1 libraryprofile v0.9.1 + 漏表门禁 ──合并并部署──► T2 升级测试 WeKnora ──► T3 测试整库导出演练
│
▼
T4 升级生产 WeKnora ◄── T3 通过
│
▼
T5 整库发布 + 读回
T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端(按契约并行,联调需 T2 完成)
```
| 工单 | 内容 | 执行 | 验收 | 前置 |
| --- | --- | --- | --- | --- |
| T1 | libraryprofile 补 v0.9.1 + 漏表门禁 | DeepSeek | 验收工作流 | 无 |
| T2 | 升级测试 WeKnora | 用户(按 §4 清单) | 用户 + 验收工作流 | T1 已合并并部署到平台 |
| T3 | 测试整库导出演练 | DeepSeek 准备命令,用户授权执行 | 验收工作流 | T2 |
| T4 | 升级生产 WeKnora | 用户(按 §4 清单) | 用户 + 验收工作流 | T3 PASS |
| T5 | 整库发布到生产 + 读回 | 用户在平台授权发布 | 验收工作流(读回证据) | T4 |
| T6a | 导入对账后端 | DeepSeek | 验收工作流 | 无(联调需 T2) |
| T6b | 导入对账前端 | DeepSeek | 验收工作流 | T6a 契约提交 |
**需求单落库口径(6 张)**:T1、T2、T3、T4、T5、T6。T6 把上面的 T6a 与 T6b 合成一张,契约仍是第一个提交;下面保留 T6a/T6b 只是写清先后顺序。
## 3. T1:libraryprofile 补 v0.9.1 + 漏表门禁
### 3.1 背景(已核实)
- 整库导出和导入按目标库 `schema_migrations` 的版本,从 `internal/libraryprofile/profile.go` 选中一份声明;目前只有 74(v0.7.1)和 134(v0.9.0)。v0.9.1 的版本是 137,`libraryprofile.For(137)` 会失败,**升级后整库发布会被拒绝**。
- 上游 135–137 号迁移(已逐个读过):135 加宽 `audit_logs.actor_user_id`;136 新建 `credential_vault_items`(只有 tenant_id/user_id,与知识库无关);137 重建 `im_channel_sessions` 的唯一索引。**三个都不涉及知识相关的表、列或触发器**。`chunk_images_sync` 触发器只在 000113 中定义,之后没有被修改。
- **已有缺口(与升级无关,0.9.0 起就存在)**:现有的 schema 探测只检查"声明过的表是否存在"(`releaseadapter/v071/schema_profile.go:111`),不会发现"有本库数据、但没有声明"的表。按上游迁移文件统计,0.9.x 中带 `knowledge_base_id` 或 `knowledge_id` 列、却不在 v090 声明里的表有:
| 表 | 内容 | 建议归类 |
| --- | --- | --- |
| `chunk_images` | 由 chunks 上的触发器维护的派生表 | 派生(已在 v090 的触发器声明中覆盖) |
| `chunk_revisions` | 切片编辑历史(000078) | **搬运(D1 已裁定)** |
| `wiki_page_revisions` | Wiki 页面编辑历史(000075) | **搬运(D1 已裁定)** |
| `knowledge_processing_spans` | 解析流水线的阶段遥测(000055) | 排除:处理过程数据,生产不解析 |
| `sessions`、`messages` | 对话数据 | 排除:生产自己的运行数据,不能被覆盖 |
| `memory_doc_affinity` | 记忆与文档的关联 | 排除:运行数据 |
| `user_kb_pins`、`kb_shares`、`im_channels`、`data_sources` | 用户置顶、共享、IM 渠道、数据源配置 | 排除:各环境自己的配置 |
### 3.2 需求
1. **新增 v0.9.1 声明**:版本 137,`WeKnoraVersion: "v0.9.1"`。表、列、部件、触发器与 v090 相同,**必须复用 v090 的声明来构造,不能复制一份**(硬约束 1)。`Supported()` 加入 137,`For` 的错误信息同步更新。
2. **每张关联表都要归类**:在 profile 中为每个版本维护「关联表分类」:`copied`(搬运,即现有的 Required/Optional)、`derived`(由触发器或应用派生)、`excluded`(不搬,必须写明原因)。分类只写在 profile 这一处。
3. **漏表门禁**:在测试端导出前、生产端导入前各执行一次。从 information_schema 找出 public 下所有带 `knowledge_base_id`、`knowledge_id` 或 `kb_id` 列的表:
- 已分类的表:放行。
- 未分类的表:若含有**本次发布范围内**的数据,拒绝并返回 `release_undeclared_kb_table`,错误信息列出表名和行数,不可重试;若没有数据,放行,但在发布记录里写一条警告。
4. **搬运编辑历史(D1 已裁定:搬)**:`chunk_revisions`、`wiki_page_revisions` 加入 v0.9.0 和 v0.9.1 两份声明的 copied 表与归档部件(v0.7.1 中没有这两张表,不动)。它们必须和现有表走**同一套**范围改写与 ID 映射,不能另写一条路径:
| 表 | 身份 | 范围改写 | 引用映射 | 不改写 |
| --- | --- | --- | --- | --- |
| `chunk_revisions` | id | tenant_id、knowledge_base_id | knowledge_id、chunk_id | revision、content、editor_id、edit_source、时间列 |
| `wiki_page_revisions` | id | tenant_id、knowledge_base_id | page_id | slug、version、正文类字段、aliases、editor_id、时间列 |
- **写入顺序**:在父表(chunks、wiki_pages)之后写入;删除和回滚时先删这两张表。两张表在上游都没有外键,但存在逻辑引用。
- **悬挂引用**:沿用现有规则,指向未登记身份的引用一律拒绝,不静默跳过。上游删除切片或页面时会同步硬删除对应的历史记录(`repository/chunk.go:726`、`repository/wiki_page.go:261-285`),所以正常情况下不应出现悬挂引用;T3 演练要实测确认。
- **editor_id 原样保留**:测试环境的用户 ID 在生产上可能查不到,生产页面上会显示为未知编辑者。这是已知且可以接受的代价,要在 `docs/library-target-id-mapping.md` 中写明。
- **ES**:两张表不进检索索引。DeepSeek 需要读上游代码确认这一点,并把结论写进 PR 描述。
- **唯一索引**:`chunk_revisions(chunk_id, revision)` 是唯一索引,chunk_id 映射后仍然唯一,需要有测试覆盖。
- **同步更新文档**:`docs/library-target-id-mapping.md` 的映射表、`docs/library-data-contract.md`(如果其中列了表清单)。
### 3.3 验收(验收工作流)
1. `libraryprofile.For(137)` 返回 v0.9.1 声明;v090 与 v091 的声明除版本号外完全一致(用测试断言,而不是两份复制的常量)。
2. 门禁测试:未分类表有数据 → 拒绝,错误码和表名都正确;未分类表为空 → 放行并有警告;`derived`/`excluded` 表 → 放行。
3. 现有的 74 / 134 测试全部保持通过。
4. `make verify` 全绿;提交符合 AGENTS.md 规范。
5. 编辑历史两张表:有测试覆盖范围改写、ID 映射、写入/删除顺序、悬挂引用拒绝、唯一索引;导出 → 写入 → 校验 → 回滚的整轮测试中,两张表的行数和内容摘要都一致。
6. PR 描述附上:对上游 135–137 号迁移的审查结论;如果开发会话能访问测试 WeKnora,附上对真实 0.9.0 库 information_schema 的只读查询结果。
## 4. T2 / T4:升级 WeKnora(用户执行的清单)
依据上游 `website-docs/07-releases/v0.9.1.md#upgrade-notes`。测试和生产各执行一遍,**生产必须等 T3 PASS 之后再做**。
**升级前**
- [ ] 平台已部署包含 T1 的版本(在平台入口查看版本号)
- [ ] 备份 PostgreSQL、文件存储、部署配置(`.env`、compose 覆盖文件)
- [ ] 生产额外执行:`bash scripts/target_kb_snapshot.sh` 留档,并用 `go run ./cmd/guardcheck <快照根> <kb_id>` 核验
- [ ] 记录升级前状态:`SELECT version, dirty FROM schema_migrations;`,应为 `134, false`
- [ ] 生产额外确认:MinerU 和解析 worker 处于关闭状态(生产只做推理)
**升级**
- [ ] `.env` 中设置 `WEKNORA_VERSION=v0.9.1`;检查是否有单独覆盖过的组件镜像标签
- [ ] `docker compose pull && docker compose up -d`
**升级后**
- [ ] `schema_migrations` 应为 `137, false`
- [ ] 抽查原有知识库的检索、问答是否正常
- [ ] 测试环境额外检查:平台走一轮「取件 → 上传 → 解析 → 完成」
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 创建平台级 API Key,只授予 `system_runtime_read` 能力,以 secret 文件形式交给平台(不写进 Git 或 compose),然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。生产不需要这个 Key
- [ ] 生产额外检查:平台发布通道只读预检(`release-diag`)通过
**回退**:不能直接换回旧镜像。向下迁移会删除凭据表、截短审计字段。正确做法是停止写入后,用升级前的备份恢复数据库、存储和配置,再切回 v0.9.0 镜像。
## 5. T3:测试整库导出演练
- **目的**:在升级到 0.9.1 的测试库上,证明新声明和门禁在真实库上可用;同时作为 T4 的放行条件。
- **DeepSeek**:根据 `docs/library-capture.md`、`docs/library-sync-acceptance.md`、`docs/library-migration-contract.md` 和 `libraryctl` 的现有子命令,整理出逐条执行的命令清单(只读或只写测试侧),写进工单,由用户授权后执行。
- **验收(验收工作流)**:快照清单里的 schema 版本是 137;`chunk_revisions`、`wiki_page_revisions` 两个部件存在,行数与源库一致,没有悬挂引用;所有部件齐全,哈希可以复算(`libraryctl snapshot-verify`);漏表门禁实际执行过,并对真实库输出了分类结果;与上一次 0.9.0 快照相比,表计数没有异常变化。
## 6. T5:整库发布到生产 + 读回
- 按 `docs/RELEASE_RUNBOOK.md` 和 OPERATIONS_RUNBOOK §5–6 执行:发布前留档门禁 → 授权发布 → 读回。
- **验收(验收工作流)**:发布记录为成功;读回一致;用 `librarydiff` 对比测试快照与生产,差异为 0(`excluded` 表除外,并列明);生产抽样 10 个问题检索正常;漏表门禁在生产端也执行过。
## 7. T6a / T6b:导入对账
需求、接口契约和验收标准都在 [IMPORT_RECONCILIATION_REQUIREMENTS.md](IMPORT_RECONCILIATION_REQUIREMENTS.md):
- T6a 的第一个提交只包含 §7 的 OpenAPI 契约,先由验收工作流审契约并冻结,再继续实现。
- 本期 T6a 范围内加入"上传时记录上传字节的 MD5":需要一个台账迁移(`upload_md5`),以及上传流程的改动。
- 新建 `reconciliation_runs` / `reconciliation_findings` 两张表:`runs` 永久保留;`findings` 按 `run_id` 整批清理,保留最近 30 批且不超过 90 天(Q5)。同一测试库的 `running` 批次用部分唯一索引约束(`WHERE state='running'`)。
- 对账扫描使用 `page_size=1000`:要把 `internal/platform/weknora/client.go` 的 `validPage` 上限从 100 放开(或给对账单独一条扫描路径),不能沿用上传恢复的 100。扫描全程串行(在途 1 个请求),R1/R2 确认可用 `reconciliation_confirm_concurrency`(默认 1、上限 8),不复用 `ingestion_concurrency`。
- 与整库导出/发布不互斥;批次开始和结束时各检测一次是否有导出/发布作业在跑,命中则写 `window_overlapped=true`,该批 R1/R2 的 `confirmation_state='pending'`(Q6)。
- 平台级只读 Key 走 `WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,启动读取一次,不做热加载);未配置或文件不可读时 `runtime/*` 返回 503 `runtime_read_unavailable`,对账不受影响(Q7)。
- 状态映射只写在服务端一处,接口返回 `normalized_state`;R5 回写按迁移矩阵校验,`completed` 不可降级。
- 处置动作:新增 finding 级 `requeue`(R1/R4)与 `remove`(R2);R6 复用现有 `POST /test-publications/{id}/removal`(`removal-retry` 只重试已失败移除)。R1/R4 不能走 `retryPublicationsBatch`,R2 不能走测试库移除,原因见需求 §7(Q9)。
- 扫描保留 offset 翻页,不引入游标;并发增删造成的个别漏项在下一批补上(Q10)。
- 僵死 `running` 超过 6 小时(可配)自动置 `failed`,释放并发位(Q11)。
- 一期只对测试库。生产的下架依赖"测试移除 + 下一轮整库发布",这段空窗期不在对账范围内,必须写进页面范围说明(Q8 未裁定是否再加"距上次发布 N 天"提示)。
- T6b 先用契约桩数据开发,T2 完成后再和真实后端联调。
## 8. 决策记录
| # | 问题 | 结论(2026-11-30 用户裁定) |
| --- | --- | --- |
| D0 | 交付流程 | 按 AGENTS.md 走分支 + PR |
| D1 | 编辑历史(`chunk_revisions`、`wiki_page_revisions`)是否搬到生产 | 搬 |
| Q1 | 是否在测试 WeKnora 为平台开 `system_runtime_read` 只读 Key | 开 |
| Q3 | 对账频率、R5 宽限期、R7 阈值 | 未裁定,按默认值执行:每天 02:00;30 分钟;2 小时(做成可配置项) |
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加"距上次发布 N 天" |
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受个别漏项下一批补上,不引入游标 |
| Q11 | 僵死 `running` 批次 | **已裁定**:超过 6 小时(可配)自动置 `failed` |
## 9. 执行顺序速览
1. DeepSeek 做 T1,提 PR → 验收工作流 → 合并 → 部署到平台(按现有发布流程)。
2. DeepSeek 在 T1 合并后开始 T6a,第一个提交是 OpenAPI 契约;契约经验收工作流冻结后,继续 T6a 实现和 T6b。
3. 你执行 T2(升级测试)并创建只读 Key → DeepSeek 准备 T3 命令,你授权执行 → 验收工作流。
4. T3 通过后,你执行 T4(升级生产)→ 在平台授权 T5 发布 → 验收工作流读回证据。
5. T6 和测试环境联调 → 验收工作流 → 合并 → 部署。
@@ -10,7 +10,7 @@
| 合同条目 | 本文位置 |
|---|---|
| 1 三角色职责 | §1 |
| 2 main 单线、串行修改 | §2 |
| 2 分支 + PR、串行修改 | §2 |
| 3 六个状态名、标签互斥、blocked 要素 | §3 |
| 4 每轮可交接的修改链路(自测→commit→快照 tag→推送→核实→review) | §4、§5 |
| 5 不可变与回退规则 | §5 |
@@ -30,11 +30,12 @@
角色约束是**流程约束**,不是技术 ACL 隔离:本机共用 Gitea 管理员凭据,谁也拦不住谁越权,
所以每个角色都要靠"读回核实"而非"相信对方自述"来交付。
## 2. main 单线、单仓库串行
## 2. 分支 + PR 单线、单仓库串行
- 只使用 `main` 一条线:**不创建分支、不建 worktree、不走 PR、不做合并**(通用引擎规范里 PR 是可选姿态,
本仓沿用"以直推为主"的口径)。
- 同一仓库的代码修改**串行**:一个工单在主开发阶段只由一个开发会话持有。
- 只使用受保护的 `main` 作为集成目标:**不直推 main**;每个工单从最新 `origin/main` 拉一个短命分支,
通过 PR 合入,合并前 CI `build`(`make verify`)必须通过。口径以 `AGENTS.md` 为准,本节不再保留
“main 直推”的旧做法。
- 同一仓库的代码修改**串行**:一个工单在主开发阶段只由一个开发会话持有;PR 完成后短命分支删除。
- **review 期间开发停止修改代码**:工单进入 `status:review` 后,除按 `rework` 要求修复外不再改动。
- 切换现场前先取证:`git status --short --branch`、`git worktree list`、`git rev-parse origin/main`。
工作区不干净、或存在不属于本工单的改动时**不得混入**,安全处理不了就置 `status:blocked`。
+1 -1
View File
@@ -10,7 +10,7 @@
2. 用**只读会话**(`default_transaction_read_only=on`)连来源 PostgreSQL;连接串只在进程内存里。
3. 核对来源已结清:所有文档 `parse_status=completed`、无待处理操作、无死信(任一不满足就拒绝,不看其他 KB 的局部状态)。
4. 从持久数据推出兼容契约:迁移版本、dirty、租户、Embedding 模型与维度、检索引擎、索引名、索引映射摘要(`text-embedding-v4` / 1024 维 / schema 74)。
5. 在**维护窗口**内停住声明过的写入者(只对声明为 writer 的服务发 SIGTERM,等它真的停下),导出 PostgreSQL 十表 + Elasticsearch 正文与向量 + 对象资源,做双向覆盖与摘要核验,封存为内容寻址产物。
5. 在**维护窗口**内停住声明过的写入者(只对声明为 writer 的服务发 SIGTERM,等它真的停下),按来源 schema profile 导出知识域表(0.7.1 十表;0.9.x 另含 `chunk_revisions`、`wiki_page_revisions`)+ Elasticsearch 正文与向量 + 对象资源,做双向覆盖与摘要核验,封存为内容寻址产物。
6. 无论成败都恢复写入者并等到 healthy;崩溃留下的日志用 `libraryctl recover` 收尾。
7. 打印快照 ID、分项(kind/name/数量/字节/SHA256)与兼容契约。
+15
View File
@@ -28,6 +28,21 @@
既有目标历史软删除行按原 destructive predicate 进入 before-image,不用来源活跃行过滤规则裁剪恢复数据。来源导出只包含活跃内容;可归属于本库的异常边在过滤前检查。完全没有任何父或范围锚的历史记录不能猜成属于本库:不全局扫出后删除、不自动迁移;这不是“所有历史孤儿已修复”。
## 2.1 0.9.x 追加:编辑历史两表(T1)
0.7.1 没有这两张表;0.9.0(134)与 0.9.1(137)起整库发布按 `libraryprofile` 声明搬运:
| 表 | 身份 | 范围/引用 | 保真边界 |
|---|---|---|---|
| `chunk_revisions` | `id`(varchar 36) | 范围改写 `tenant_id`/`knowledge_base_id`;映射 `knowledge_id`、`chunk_id` | `revision`/`content`/`is_enabled`/`editor_id`/`edit_source`/时间列原样;唯一索引 `(chunk_id, revision)` 映射后仍唯一 |
| `wiki_page_revisions` | `id`(varchar 36) | 范围改写 `tenant_id`/`knowledge_base_id`;映射 `page_id` | `slug`/`version`/正文类字段/`aliases`/`editor_id`/时间列原样;唯一索引 `(page_id, version)` 映射后仍唯一 |
- 写入在父表(`chunks` / `wiki_pages`)之后;删除/回滚先删两表。
- 只导出**活跃父行**的修订:父行软删属于本次范围外;父行完全不存在属于数据异常,导出即拒绝。
- 修订正文里的 `resource://` 按历史事实原样保留,不参与资源发现(人类裁定 Q2=B)。
- `editor_id` 不映射:目标可能查不到来源用户,页面显示未知编辑者;这是已接受代价。
- 两表不进 Elasticsearch;整库校验比对行数 + 逐行内容摘要(时间戳类字段按既有规则豁免)。
## 3. 资源引用的实际格式
只读参考源码:`WeKnora-v0.7.1-dev/internal/types/resource.go` 中 `ResourceHandleLength=22` 与 `ParseResourcePath`;本轮没有修改WeKnora源码。
+16
View File
@@ -33,6 +33,8 @@ target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 var
| 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 |
| chunk_revisions | id | knowledge_id, chunk_id |
| wiki_page_revisions | id | page_id |
| resource_bindings | id | owner_id(按 owner_type) |
| resources | **不映射** | resource_id 保持共享身份 |
| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id |
@@ -40,6 +42,20 @@ target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 var
正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列
(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。
### 0.9.x 编辑历史(v090 / v091)
- `chunk_revisions`:身份 `id`;范围改写 `tenant_id`、`knowledge_base_id`;引用映射
`knowledge_id → knowledges`、`chunk_id → chunks`;`revision`、`content`、`is_enabled`、
`editor_id`、`edit_source`、时间列不改写。
- `wiki_page_revisions`:身份 `id`;范围改写 `tenant_id`、`knowledge_base_id`;引用映射
`page_id → wiki_pages`;`slug`、`version`、正文类字段、`aliases`、`editor_id`、时间列不改写。
- 两表在父表(`chunks` / `wiki_pages`)之后写入;删除与回滚先删这两张表。
- 唯一索引 `(chunk_id, revision)` / `(page_id, version)` 在映射后仍唯一(有测试)。
- `editor_id` 原样保留:测试环境的用户 ID 在生产上可能查不到,生产页面会显示为未知编辑者。
这是已知且可接受的代价,写在这里避免被当成缺陷重复排查。
- 两表不进检索索引;修订正文里的 `resource://` 文本按历史事实原样保留,不参与资源发现
(Q2=B,2026-11-30 人类裁定)。
## 一致性边界
- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算;
+124 -43
View File
@@ -8,6 +8,12 @@ import (
"strconv"
"strings"
"time"
// 运行镜像是 alpine,不带 /usr/share/zoneinfo;而本包在 Load 时就用
// time.LoadLocation 校验具名时区(RECONCILIATION_TIMEZONE 等)。只有嵌进
// 二进制才不依赖基础镜像:api 之前能过,纯粹是因为 internal/httpapi 顺带了
// 这个空白导入,worker / release-worker 没有,于是候选与发布容器的 worker
// 在启动时直接退出(unknown time zone Asia/Shanghai)。
_ "time/tzdata"
"knowledge-governance/internal/governance"
)
@@ -53,16 +59,32 @@ type Config struct {
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
WeKnoraBindingMasterKeyFile string
GovernanceSpoolRoot string
IngestionSpoolRoot string
ArtifactFetchMaxBytes int64
WorkerLivenessStaleAfter time.Duration
TestWeKnoraHTTPTimeout time.Duration
TestWeKnoraPollInitial time.Duration
TestWeKnoraPollMax time.Duration
TestWeKnoraStalledAfter time.Duration
TestWeKnoraMaxUploadBytes int64
TestAcceptancePolicyVersion string
// WeKnoraRuntimeKeyFile 是测试实例平台级只读 Key(0400,绝对路径)。空值=
// runtime/* 与 overview 队列降级为不可用;对账本身只用租户 Key。
WeKnoraRuntimeKeyFile string
// ReconciliationSettings:批次执行参数。全部可配,但都有安全默认值。
// ReconciliationEnabled 是「导入对账」自身的开关:只决定对账服务是否接线,
// 与 TEST_WEKNORA_ENABLED(旧测试库取件/上传链路)解耦——对账只用租户 Key。
ReconciliationEnabled bool
ReconciliationScheduleEnabled bool
ReconciliationDailyAt string
ReconciliationTimezone string
ReconciliationGrace time.Duration
ReconciliationStallAfter time.Duration
ReconciliationStaleAfter time.Duration
ReconciliationConfirmConcurrency int
ReconciliationKeepRuns int
ReconciliationMaxAge time.Duration
GovernanceSpoolRoot string
IngestionSpoolRoot string
ArtifactFetchMaxBytes int64
WorkerLivenessStaleAfter time.Duration
TestWeKnoraHTTPTimeout time.Duration
TestWeKnoraPollInitial time.Duration
TestWeKnoraPollMax time.Duration
TestWeKnoraStalledAfter time.Duration
TestWeKnoraMaxUploadBytes int64
TestAcceptancePolicyVersion string
// TestAutoReviewPolicy:验收通过后是否自动批准(off|internal|all;默认 internal)。
TestAutoReviewPolicy string
// 目标库所在主机(整库逻辑备份真正执行的地方)。凭据是挂载进来的 0600 ssh
@@ -198,39 +220,49 @@ func Load(getenv func(string) string) (Config, error) {
return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be a positive duration")
}
config := Config{
DatabaseURL: getenv("DATABASE_URL"),
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
WorkerID: valueOrDefault(getenv("WORKER_ID"), "worker-1"),
PollInterval: time.Second,
LeaseDuration: 30 * time.Second,
RetryDelay: 5 * time.Second,
SourceRefreshSchedulerInterval: 30 * time.Second,
ReleaseConfigFile: strings.TrimSpace(getenv("RELEASE_CONFIG_FILE")),
ProductionReleaseAuthorizerRef: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTHORIZER_REF")),
ProductionReleaseAuthTokenFile: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTH_TOKEN_FILE")),
ProductionWeKnoraBaseURL: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_BASE_URL")),
ProductionWeKnoraAPIKeyFile: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_API_KEY_FILE")),
PPScanAllowedRoot: strings.TrimSpace(getenv("PP_SCAN_ALLOWED_ROOT")),
PPScanLedgerPath: strings.TrimSpace(getenv("PP_SCAN_LEDGER_PATH")),
PPScanManifestPath: strings.TrimSpace(getenv("PP_SCAN_MANIFEST_PATH")),
TestWeKnoraBaseURL: strings.TrimSpace(getenv("TEST_WEKNORA_BASE_URL")),
MinerUBaseURL: strings.TrimSpace(getenv("MINERU_BASE_URL")),
TestWeKnoraKBID: strings.TrimSpace(getenv("TEST_WEKNORA_KB_ID")),
InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")),
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"),
IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")),
ArtifactFetchMaxBytes: 200 * 1024 * 1024,
WorkerLivenessStaleAfter: 2 * time.Minute,
TestWeKnoraHTTPTimeout: 60 * time.Second,
TestWeKnoraPollInitial: 10 * time.Second,
TestWeKnoraPollMax: time.Minute,
TestWeKnoraStalledAfter: 30 * time.Minute,
TestWeKnoraMaxUploadBytes: 50 * 1024 * 1024,
TestAcceptancePolicyVersion: valueOrDefault(getenv("TEST_ACCEPTANCE_POLICY_VERSION"), "structural-v1"),
TestAutoReviewPolicy: valueOrDefault(getenv("TEST_AUTO_REVIEW_POLICY"), string(governance.AutoReviewInternal)),
DatabaseURL: getenv("DATABASE_URL"),
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
WorkerID: valueOrDefault(getenv("WORKER_ID"), "worker-1"),
PollInterval: time.Second,
LeaseDuration: 30 * time.Second,
RetryDelay: 5 * time.Second,
SourceRefreshSchedulerInterval: 30 * time.Second,
ReleaseConfigFile: strings.TrimSpace(getenv("RELEASE_CONFIG_FILE")),
ProductionReleaseAuthorizerRef: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTHORIZER_REF")),
ProductionReleaseAuthTokenFile: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTH_TOKEN_FILE")),
ProductionWeKnoraBaseURL: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_BASE_URL")),
ProductionWeKnoraAPIKeyFile: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_API_KEY_FILE")),
PPScanAllowedRoot: strings.TrimSpace(getenv("PP_SCAN_ALLOWED_ROOT")),
PPScanLedgerPath: strings.TrimSpace(getenv("PP_SCAN_LEDGER_PATH")),
PPScanManifestPath: strings.TrimSpace(getenv("PP_SCAN_MANIFEST_PATH")),
TestWeKnoraBaseURL: strings.TrimSpace(getenv("TEST_WEKNORA_BASE_URL")),
MinerUBaseURL: strings.TrimSpace(getenv("MINERU_BASE_URL")),
TestWeKnoraKBID: strings.TrimSpace(getenv("TEST_WEKNORA_KB_ID")),
InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")),
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
WeKnoraRuntimeKeyFile: strings.TrimSpace(getenv("WEKNORA_RUNTIME_KEY_FILE")),
ReconciliationDailyAt: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_DAILY_AT")), "02:00"),
ReconciliationTimezone: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_TIMEZONE")), "Asia/Shanghai"),
ReconciliationScheduleEnabled: true,
ReconciliationGrace: 30 * time.Minute,
ReconciliationStallAfter: 2 * time.Hour,
ReconciliationStaleAfter: 6 * time.Hour,
ReconciliationConfirmConcurrency: 1,
ReconciliationKeepRuns: 30,
ReconciliationMaxAge: 90 * 24 * time.Hour,
GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"),
IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")),
ArtifactFetchMaxBytes: 200 * 1024 * 1024,
WorkerLivenessStaleAfter: 2 * time.Minute,
TestWeKnoraHTTPTimeout: 60 * time.Second,
TestWeKnoraPollInitial: 10 * time.Second,
TestWeKnoraPollMax: time.Minute,
TestWeKnoraStalledAfter: 30 * time.Minute,
TestWeKnoraMaxUploadBytes: 50 * 1024 * 1024,
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")),
@@ -374,6 +406,55 @@ func Load(getenv func(string) string) (Config, error) {
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
}
if config.WeKnoraRuntimeKeyFile != "" && !filepath.IsAbs(config.WeKnoraRuntimeKeyFile) {
return Config{}, errors.New("WEKNORA_RUNTIME_KEY_FILE must be an absolute path")
}
if raw := getenv("RECONCILIATION_ENABLED"); raw != "" {
config.ReconciliationEnabled, err = strconv.ParseBool(raw)
if err != nil {
return Config{}, fmt.Errorf("RECONCILIATION_ENABLED: %w", err)
}
}
if raw := getenv("RECONCILIATION_SCHEDULE_ENABLED"); raw != "" {
config.ReconciliationScheduleEnabled, err = strconv.ParseBool(raw)
if err != nil {
return Config{}, fmt.Errorf("RECONCILIATION_SCHEDULE_ENABLED: %w", err)
}
}
if _, err := time.Parse("15:04", config.ReconciliationDailyAt); err != nil {
return Config{}, errors.New("RECONCILIATION_DAILY_AT must be HH:MM")
}
if _, err := time.LoadLocation(config.ReconciliationTimezone); err != nil {
return Config{}, fmt.Errorf("RECONCILIATION_TIMEZONE: %w", err)
}
if config.ReconciliationConfirmConcurrency < 1 || config.ReconciliationConfirmConcurrency > 8 {
return Config{}, errors.New("RECONCILIATION_CONFIRM_CONCURRENCY must be between 1 and 8")
}
if value, err := positiveInt64OrDefault(strings.TrimSpace(getenv("RECONCILIATION_CONFIRM_CONCURRENCY")), int64(config.ReconciliationConfirmConcurrency)); err != nil {
return Config{}, errors.New("RECONCILIATION_CONFIRM_CONCURRENCY must be a positive integer")
} else {
config.ReconciliationConfirmConcurrency = int(value)
}
if config.ReconciliationConfirmConcurrency > 8 {
return Config{}, errors.New("RECONCILIATION_CONFIRM_CONCURRENCY must be between 1 and 8")
}
if value, err := positiveInt64OrDefault(strings.TrimSpace(getenv("RECONCILIATION_KEEP_RUNS")), int64(config.ReconciliationKeepRuns)); err != nil {
return Config{}, errors.New("RECONCILIATION_KEEP_RUNS must be a positive integer")
} else {
config.ReconciliationKeepRuns = int(value)
}
for name, target := range map[string]*time.Duration{
"RECONCILIATION_GRACE": &config.ReconciliationGrace,
"RECONCILIATION_STALL_AFTER": &config.ReconciliationStallAfter,
"RECONCILIATION_STALE_AFTER": &config.ReconciliationStaleAfter,
"RECONCILIATION_MAX_AGE": &config.ReconciliationMaxAge,
} {
value, err := durationOrDefault(strings.TrimSpace(getenv(name)), *target)
if err != nil || value <= 0 {
return Config{}, fmt.Errorf("%s must be a positive duration", name)
}
*target = value
}
if raw := getenv("PP_SCAN_ENABLED"); raw != "" {
config.PPScanEnabled, err = strconv.ParseBool(raw)
if err != nil {
+22
View File
@@ -6,6 +6,28 @@ import (
"time"
)
func TestLoadParsesReconciliationEnabledWithoutLegacyTestWeKnora(t *testing.T) {
values := map[string]string{"DATA" + "BASE_URL": "postgres://example"}
config, err := Load(func(key string) string { return values[key] })
if err != nil {
t.Fatalf("Load() error = %v", err)
}
if config.ReconciliationEnabled {
t.Fatal("reconciliation must stay un-wired unless RECONCILIATION_ENABLED is set")
}
values["RECONCILIATION_ENABLED"] = "true"
config, err = Load(func(key string) string { return values[key] })
if err != nil {
t.Fatalf("Load() with RECONCILIATION_ENABLED error = %v", err)
}
if !config.ReconciliationEnabled {
t.Fatal("RECONCILIATION_ENABLED=true must wire reconciliation")
}
if config.TestWeKnoraEnabled {
t.Fatal("reconciliation must not require or imply the legacy test WeKnora pipeline")
}
}
func TestLoadUsesSafeDefaults(t *testing.T) {
values := map[string]string{"DATABASE_URL": "postgres://example"}
config, err := Load(func(key string) string { return values[key] })
+24
View File
@@ -0,0 +1,24 @@
package backuphost
import (
"os/exec"
"strings"
"testing"
)
// 配额清理工具是唯一会删历史备份的代码。它的 self-test 覆盖「最旧优先 / 预检保留最新 /
// 空间不够零删除 / 非批次日录与符号链接不动 / dump 后保护新批次」,必须随 Go 测试一起跑。
func TestPruneBackupBatchesSelfTest(t *testing.T) {
python, err := exec.LookPath("python3")
if err != nil {
t.Skip("python3 not available")
}
command := exec.Command(python, "../../scripts/prune_backup_batches.py", "--self-test")
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("prune self-test failed: %v\n%s", err, output)
}
if !strings.Contains(string(output), "self-test ok") {
t.Fatalf("prune self-test output unexpected: %s", output)
}
}
+104
View File
@@ -31,6 +31,9 @@ type Config struct {
MetadataPath string
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
HostRoot string
// BackupRoot 是宿主上的备份根(KB_BACKUP_ROOT),用于校验快照里的根占用范围。
// 它必须与 BACKUP_HOST_ROOT 同源;不同源时占用不可信,整份快照拒绝。
BackupRoot string
// Source 是展示来源;快照里的 source 非空时以快照为准。
Source string
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
@@ -85,6 +88,19 @@ type Capacity struct {
Error string `json:"error,omitempty"`
}
// Usage 是**备份根累计占用**(配额约束的对象),不是 rds-logical 批次之和。
// Measured=false 时所有字节为 null:部分遍历永远不能当占盘。
type Usage struct {
Root string `json:"root"`
Measured bool `json:"measured"`
Complete bool `json:"complete"`
ActualBytes *int64 `json:"actual_bytes"`
ApparentBytes *int64 `json:"apparent_bytes"`
FileCount *int `json:"file_count"`
DirCount *int `json:"dir_count"`
Error string `json:"error,omitempty"`
}
type Database struct {
Name string `json:"name"`
DirName string `json:"dir_name"`
@@ -138,12 +154,16 @@ type Snapshot struct {
Metadata MetadataInfo `json:"metadata"`
Root string `json:"root"`
HostRoot string `json:"host_root"`
BackupRoot string `json:"backup_root"`
Source string `json:"source"`
ObservedAt string `json:"observed_at"`
Error string `json:"error,omitempty"`
Measurement string `json:"measurement"`
Mount MountInfo `json:"mount"`
Capacity Capacity `json:"capacity"`
Usage Usage `json:"usage"`
QuotaBytes *int64 `json:"quota_bytes"`
QuotaError string `json:"quota_error,omitempty"`
Batches []Batch `json:"batches"`
Totals Totals `json:"totals"`
IncompleteCount int `json:"incomplete_count"`
@@ -181,6 +201,10 @@ type metadata struct {
Host string `json:"host"`
Source string `json:"source"`
Root string `json:"root"`
BackupRoot string `json:"backup_root"`
Usage metadataUsage `json:"usage"`
QuotaBytes *int64 `json:"quota_bytes"`
QuotaError string `json:"quota_error"`
Complete bool `json:"complete"`
Errors []string `json:"errors"`
Filesystem metadataFilesystem `json:"filesystem"`
@@ -190,6 +214,16 @@ type metadata struct {
Batches []metadataBatch `json:"batches"`
}
type metadataUsage struct {
Root string `json:"root"`
Complete bool `json:"complete"`
ActualBytes *int64 `json:"actual_bytes"`
ApparentBytes *int64 `json:"apparent_bytes"`
FileCount *int `json:"file_count"`
DirCount *int `json:"dir_count"`
Errors []string `json:"errors"`
}
type metadataFilesystem struct {
MountPoint string `json:"mount_point"`
MountSource string `json:"mount_source"`
@@ -313,6 +347,14 @@ func (r *Reader) Snapshot(ctx context.Context) Snapshot {
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
}
snapshot.Root = root
backupRoot, usage, quotaBytes, quotaError, err := projectUsageAndQuota(r.config.BackupRoot, root, file)
if err != nil {
return invalid(snapshot, err.Error())
}
snapshot.BackupRoot = backupRoot
snapshot.Usage = usage
snapshot.QuotaBytes = quotaBytes
snapshot.QuotaError = quotaError
if err := validateBatches(root, file.Batches); err != nil {
return invalid(snapshot, err.Error())
}
@@ -366,6 +408,66 @@ func (r *Reader) observedAt() string {
return r.now().UTC().Format(time.RFC3339)
}
// projectUsageAndQuota 校验「备份根占用」与「配额」并把它们投影给页面。
//
// 三条独立边界:
// 1. 旧采集器没有 usage/quota —— 批次照旧可用,占用与配额显式「未上报」,绝不用批次和冒充;
// 2. 路径必须与部署配置的备份根完全一致,批次根必须在其下 —— 否则整份快照拒绝;
// 3. 遍历不完整/配额非法 —— 只把对应字段降为未知,不牵连批次表与磁盘容量。
func projectUsageAndQuota(configuredRoot, batchRoot string, file metadata) (string, Usage, *int64, string, error) {
expected := path.Clean(strings.TrimSpace(configuredRoot))
reported := strings.TrimSpace(file.Usage.Root)
declared := strings.TrimSpace(file.BackupRoot)
usageReported := reported != "" || declared != "" || file.Usage.Complete ||
file.Usage.ActualBytes != nil || len(file.Usage.Errors) > 0
if !usageReported {
quotaError := strings.TrimSpace(file.QuotaError)
if quotaError == "" {
quotaError = "采集器未上报备份配额(需要升级采集器)"
}
return expected, Usage{Error: "采集器未上报备份根占用(需要升级采集器)"}, nil, quotaError, nil
}
if expected == "" || !path.IsAbs(expected) {
return "", Usage{}, nil, "", errors.New("备份根未配置:无法校验快照里的根占用")
}
if reported != expected || declared != expected {
return "", Usage{}, nil, "", fmt.Errorf("快照 backup_root=%q/usage.root=%q 与配置 %q 不一致", declared, reported, expected)
}
if batchRoot != expected && !strings.HasPrefix(batchRoot, expected+"/") {
return "", Usage{}, nil, "", fmt.Errorf("批次根 %s 不在备份根 %s 下", batchRoot, expected)
}
usage := Usage{Root: reported, Complete: file.Usage.Complete}
if file.Usage.Complete && file.Usage.ActualBytes != nil {
usage.Measured = true
usage.ActualBytes = file.Usage.ActualBytes
usage.ApparentBytes = file.Usage.ApparentBytes
usage.FileCount = file.Usage.FileCount
usage.DirCount = file.Usage.DirCount
} else {
usage.Complete = false
usage.ActualBytes = nil
usage.ApparentBytes = nil
usage.FileCount = nil
usage.DirCount = nil
reasons := limit(file.Usage.Errors, 3)
if len(reasons) == 0 {
usage.Error = "备份根占用未知:采集器未给出完整字节"
} else {
usage.Error = "备份根占用未知:" + strings.Join(reasons, ";")
}
}
quota := file.QuotaBytes
quotaError := strings.TrimSpace(file.QuotaError)
if quota != nil && *quota <= 0 {
quota = nil
quotaError = fmt.Sprintf("备份配额必须为正整数:%d", *file.QuotaBytes)
}
if quota == nil && quotaError == "" {
quotaError = "采集器未上报备份配额(需要升级采集器)"
}
return expected, usage, quota, quotaError, nil
}
func invalid(snapshot Snapshot, reason string) Snapshot {
snapshot.Metadata.Valid = false
snapshot.Metadata.Complete = false
@@ -374,6 +476,8 @@ func invalid(snapshot Snapshot, reason string) Snapshot {
snapshot.Batches = []Batch{}
snapshot.Capacity = Capacity{Error: reason}
snapshot.Totals = Totals{}
snapshot.Usage = Usage{Error: reason}
snapshot.QuotaBytes = nil
return snapshot
}
+85 -4
View File
@@ -28,8 +28,14 @@ func validMetadata() metadata {
Host: "weknora-test",
Source: "weknora-test:" + hostRoot,
Root: hostRoot,
Complete: true,
Errors: []string{},
BackupRoot: "/srv/kb-backups",
Usage: metadataUsage{
Root: "/srv/kb-backups", Complete: true,
ActualBytes: int64p(20000), ApparentBytes: int64p(18000), FileCount: intp(12), DirCount: intp(4),
},
QuotaBytes: int64p(53687091200),
Complete: true,
Errors: []string{},
Filesystem: metadataFilesystem{
MountPoint: "/srv/kb-backups",
MountSource: "/dev/sdb1",
@@ -108,7 +114,7 @@ func writeMetadata(t *testing.T, value metadata) string {
}
func readerAt(filename string, now time.Time) *Reader {
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, Source: "configured", MaxAge: 15 * time.Minute})
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, BackupRoot: "/srv/kb-backups", Source: "configured", MaxAge: 15 * time.Minute})
reader.now = func() time.Time { return now }
return reader
}
@@ -156,7 +162,82 @@ func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
t.Fatalf("汇总不对: %+v", snapshot.Totals)
}
if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
t.Fatalf("来源/测量方式不对: %+v", snapshot)
t.Fatalf("来源/测量方式不对: %+v", snapshot.Source)
}
if snapshot.BackupRoot != "/srv/kb-backups" || !snapshot.Usage.Measured || snapshot.Usage.ActualBytes == nil || *snapshot.Usage.ActualBytes != 20000 {
t.Fatalf("备份根占用没有投影: %+v", snapshot.Usage)
}
if snapshot.QuotaBytes == nil || *snapshot.QuotaBytes != 53687091200 {
t.Fatalf("配额没有投影: %v", snapshot.QuotaBytes)
}
}
func TestSnapshotLegacyMetadataKeepsBatchesButOccupancyUnknown(t *testing.T) {
value := validMetadata()
value.BackupRoot = ""
value.Usage = metadataUsage{}
value.QuotaBytes = nil
value.QuotaError = ""
filename := writeMetadata(t, value)
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
if !snapshot.Metadata.Valid || !snapshot.Metadata.Complete {
t.Fatalf("旧快照仍应可用: %+v", snapshot.Metadata)
}
if len(snapshot.Batches) != 3 || snapshot.Totals.ActualBytes == nil {
t.Fatalf("旧快照的批次不能丢: %+v", snapshot.Batches)
}
if snapshot.Usage.Measured || snapshot.Usage.ActualBytes != nil || snapshot.Usage.Error == "" {
t.Fatalf("缺少 usage 必须显式未上报: %+v", snapshot.Usage)
}
if snapshot.QuotaBytes != nil || snapshot.QuotaError == "" {
t.Fatalf("缺少配额必须显式未上报: %v/%q", snapshot.QuotaBytes, snapshot.QuotaError)
}
}
func TestSnapshotRejectsUsageRootMismatch(t *testing.T) {
value := validMetadata()
value.Usage.Root = "/data/kb-backups"
filename := writeMetadata(t, value)
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
if snapshot.Metadata.Valid || len(snapshot.Batches) != 0 || snapshot.Usage.Measured {
t.Fatalf("占用根与配置不一致必须整块拒绝: %+v", snapshot)
}
if !strings.Contains(snapshot.Error, "不一致") {
t.Fatalf("不一致原因不清: %q", snapshot.Error)
}
}
func TestSnapshotIncompleteUsageDoesNotBlankBatches(t *testing.T) {
value := validMetadata()
value.Usage.Complete = false
value.Usage.ActualBytes = int64p(123) // 部分计数:必须被丢弃
value.Usage.Errors = []string{"遍历失败:PermissionError: Permission denied"}
filename := writeMetadata(t, value)
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
if !snapshot.Metadata.Valid || !snapshot.Metadata.Complete {
t.Fatalf("根占用不完整不能牵连整份快照: %+v", snapshot.Metadata)
}
if len(snapshot.Batches) != 3 || snapshot.Totals.ActualBytes == nil || !snapshot.Capacity.Measured {
t.Fatalf("批次与磁盘容量必须保留: %+v", snapshot)
}
if snapshot.Usage.Measured || snapshot.Usage.ActualBytes != nil || !strings.Contains(snapshot.Usage.Error, "Permission") {
t.Fatalf("占用必须为 null 并带原因: %+v", snapshot.Usage)
}
if snapshot.QuotaBytes == nil || *snapshot.QuotaBytes != 53687091200 {
t.Fatalf("配额是配置事实,应保留: %v", snapshot.QuotaBytes)
}
}
func TestSnapshotRejectsInvalidQuota(t *testing.T) {
value := validMetadata()
value.QuotaBytes = int64p(0)
filename := writeMetadata(t, value)
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
if snapshot.QuotaBytes != nil || !strings.Contains(snapshot.QuotaError, "正整数") {
t.Fatalf("非法配额必须降为未知: %v/%q", snapshot.QuotaBytes, snapshot.QuotaError)
}
if !snapshot.Metadata.Valid {
t.Fatalf("配额非法不应否掉批次: %+v", snapshot.Metadata)
}
}
+13
View File
@@ -139,6 +139,19 @@ const (
ProcessingCancelled ProcessingState = "cancelled"
)
// NormalizeWeKnoraParseStatus is the single upstream-to-platform vocabulary
// whitelist shared by polling and reconciliation. Unknown values are rejected
// instead of being collapsed into an "other" bucket: a new upstream state must
// be added deliberately.
func NormalizeWeKnoraParseStatus(status string) (string, bool) {
switch status {
case "pending", "processing", "finalizing", "completed", "failed", "cancelled", "deleting":
return status, true
default:
return "", false
}
}
func (state ProcessingState) Valid() bool {
switch state {
case ProcessingPending, ProcessingProcessing, ProcessingFinalizing, ProcessingCompleted, ProcessingFailed, ProcessingStalled, ProcessingCancelled:
+25
View File
@@ -112,6 +112,31 @@ type MonitorOverview struct {
KnowledgeBases []KnowledgeBaseProgress `json:"knowledge_bases"`
Pipeline IngestionPipeline `json:"pipeline"`
Health []ServiceHealth `json:"health"`
// WeKnoraQueues is a safe projection of the test instance runtime queues.
// nil means "not configured or unreadable", never "healthy empty".
WeKnoraQueues *WeKnoraQueueSummary `json:"weknora_queues"`
}
// WeKnoraQueueSummary is the bounded queue projection the console may show.
// It deliberately excludes worker addresses, model endpoints and task payloads.
type WeKnoraQueueSummary struct {
Available bool `json:"available"`
QueuesError bool `json:"queues_error"`
WorkersError bool `json:"workers_error"`
Queues []WeKnoraQueue `json:"queues"`
Timestamp int64 `json:"timestamp"`
}
type WeKnoraQueue struct {
Name string `json:"name"`
Pool string `json:"pool"`
Pending int `json:"pending"`
Active int `json:"active"`
Scheduled int `json:"scheduled"`
Retry int `json:"retry"`
Archived int `json:"archived"`
Processed int `json:"processed"`
Failed int `json:"failed"`
}
type KnowledgeMonitorFile struct {
+138
View File
@@ -0,0 +1,138 @@
package governance
import "time"
// ReconciliationCounts is keyed by R1..R8. Normalize keeps every key present so
// the API and page never have to distinguish "absent" from "zero".
type ReconciliationCounts map[string]int
func (counts ReconciliationCounts) Normalize() ReconciliationCounts {
out := make(ReconciliationCounts, 8)
for _, key := range []string{"R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8"} {
out[key] = counts[key]
}
return out
}
type ReconciliationRun struct {
ID string `json:"id"`
KBID string `json:"kb_id"`
State string `json:"state"`
Trigger string `json:"trigger"`
StartedAt time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
LedgerCount int `json:"ledger_count"`
KBCount int `json:"kb_count"`
Counts ReconciliationCounts `json:"counts"`
PreviousCounts ReconciliationCounts `json:"previous_counts"`
WindowOverlapped bool `json:"window_overlapped"`
ErrorCode string `json:"error_code"`
}
type ReconciliationFinding struct {
ID string `json:"id"`
RunID string `json:"run_id"`
Type string `json:"type"`
PublicationID string `json:"publication_id"`
DocumentID string `json:"document_id"`
Title string `json:"title"`
Path string `json:"path"`
Source string `json:"source"`
TargetScope string `json:"target_scope"`
LedgerState string `json:"ledger_state"`
WeKnoraParseState string `json:"weknora_parse_status"`
NormalizedState string `json:"normalized_state"`
LedgerSHA256 string `json:"ledger_sha256"`
DeclaredSHA256 string `json:"declared_sha256"`
WeKnoraFileMD5 string `json:"weknora_file_md5"`
EvidenceLevel string `json:"evidence_level"`
ConfirmationState string `json:"confirmation_state"`
Detail string `json:"detail"`
SuggestedAction string `json:"suggested_action"`
ActionState string `json:"action_state"`
WeKnoraURL string `json:"weknora_url"`
}
type ReconciliationLedgerRow struct {
PublicationID string
KnowledgeID string
ProcessingState string
RetrievalState string
TargetScope string
ProcessingStartedAt *time.Time
UpdatedAt time.Time
UploadMD5 string
SourceItemID string
Title string
Path string
SourceName string
PolicyState string
SHA256 string
}
type ReconciliationRunFilter struct {
KBID string
Limit int
Offset int
}
type ReconciliationRunPage struct {
Items []ReconciliationRun `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type ReconciliationFindingFilter struct {
RunID string
Type string
Query string
Limit int
Offset int
}
type ReconciliationFindingPage struct {
Items []ReconciliationFinding `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type ReconciliationStage struct {
Name string `json:"name"`
Status string `json:"status"`
ErrorCode string `json:"error_code"`
FinishedAt *time.Time `json:"finished_at"`
}
type ReconciliationFailure struct {
TaskType string `json:"task_type"`
FailCount int `json:"fail_count"`
FailedAt time.Time `json:"failed_at"`
LastError string `json:"last_error"`
}
type ReconciliationProgress struct {
DocumentID string `json:"document_id"`
ParseStatus string `json:"parse_status"`
IngestionStatus string `json:"ingestion_status"`
WikiStatus string `json:"wiki_status"`
Stages []ReconciliationStage `json:"stages"`
Failures []ReconciliationFailure `json:"failures"`
HasMoreFailures bool `json:"has_more_failures"`
ObservedAt time.Time `json:"observed_at"`
}
// ReconciliationActionView is the minimum row an action needs to re-check that
// the scan snapshot is still true. Actions must never trust the finding alone.
type ReconciliationActionView struct {
Finding ReconciliationFinding
TestKBID string
RunStartedAt time.Time
CurrentExists bool
CurrentProcessingState string
CurrentKnowledgeID string
CurrentSuperseded bool
CurrentRetrievalState string
CurrentTargetScope string
}
+17 -5
View File
@@ -24,11 +24,16 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
actual := int64(1024)
databaseActual := int64(512)
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
Wired: true,
Root: "/srv/kb-backups/rds-logical",
HostRoot: "/srv/kb-backups/rds-logical",
Source: "weknora-test:/srv/kb-backups/rds-logical",
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
Wired: true,
Root: "/srv/kb-backups/rds-logical",
HostRoot: "/srv/kb-backups/rds-logical",
Source: "weknora-test:/srv/kb-backups/rds-logical",
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
BackupRoot: "/srv/kb-backups",
Usage: backupinventory.Usage{
Root: "/srv/kb-backups", Measured: true, Complete: true, ActualBytes: &actual,
},
QuotaBytes: func() *int64 { value := int64(53687091200); return &value }(),
Mount: backupinventory.MountInfo{
MountVerified: true,
ReadOnly: true,
@@ -70,6 +75,13 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
}
if payload.Data.BackupRoot != "/srv/kb-backups" || !payload.Data.Usage.Measured ||
payload.Data.Usage.ActualBytes == nil || *payload.Data.Usage.ActualBytes != 1024 {
t.Fatalf("备份根占用字段丢失: %+v", payload.Data.Usage)
}
if payload.Data.QuotaBytes == nil || *payload.Data.QuotaBytes != 53687091200 {
t.Fatalf("配额字段丢失: %v", payload.Data.QuotaBytes)
}
}
func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
+47 -9
View File
@@ -3,7 +3,9 @@ package httpapi
import (
"context"
"errors"
"net"
"net/http"
"net/url"
"strings"
"time"
@@ -34,7 +36,10 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
for _, view := range views {
storageReady = storageReady || view.StorageReady
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"environments": views, "storage_ready": storageReady}})
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"environments": views,
"storage_ready": storageReady,
}})
}
func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Request) {
@@ -56,10 +61,6 @@ func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Reque
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
return
}
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
return
}
catalog, err := config.KBBindings.Catalog(r.Context(), env, input)
if err != nil {
writeKBBindingError(w, err)
@@ -87,10 +88,7 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
return
}
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
return
}
input.SourceAddress, input.SourceOrigin = requestAuditSource(r)
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
if err != nil {
writeKBBindingError(w, err)
@@ -119,3 +117,43 @@ func writeKBBindingError(w http.ResponseWriter, err error) {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
}
}
// requestAuditSource records the two facts the save audit needs: which console
// origin the admin used and the client address behind it. Audit only — nothing
// here decides whether a key may be typed or saved.
//
// The nearest proxy appends its peer to the END of X-Forwarded-For, so that hop
// is the trustworthy one; earlier entries are whatever the browser sent. A
// forwarded chain is honoured only when the direct peer is private/loopback
// (the deployment's own nginx), so a request that reaches the API directly
// cannot launder its address through a forged header.
func requestAuditSource(r *http.Request) (address, origin string) {
peer := r.RemoteAddr
if host, _, err := net.SplitHostPort(peer); err == nil {
peer = host
}
ip := net.ParseIP(strings.Trim(peer, "[]"))
if ip != nil {
address = ip.String()
if ip.IsLoopback() || ip.IsPrivate() {
hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
if last := net.ParseIP(strings.TrimSpace(hops[len(hops)-1])); last != nil {
address = last.String()
}
}
}
if parsed, err := url.Parse(strings.TrimSpace(r.Header.Get("Origin"))); err == nil &&
(parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" {
origin = parsed.Scheme + "://" + parsed.Host
return address, origin
}
if r.Host != "" {
scheme := "http"
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
scheme = "https"
}
origin = scheme + "://" + r.Host
}
return address, origin
}
+131 -19
View File
@@ -3,7 +3,6 @@ package httpapi
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -88,34 +87,37 @@ func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
}
}
func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) {
store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}}
func TestKBBindingCatalogAndSaveAcceptTypedKeysOnPlainHTTP(t *testing.T) {
store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
}
config := kbBindingHandler(t, store)
body := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
catalogBody := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
response := httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "HTTPS") {
t.Fatalf("plain HTTP key entry status=%d body=%s", response.Code, response.Body.String())
}
request = httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
response = httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
if response.Code != http.StatusOK {
t.Fatalf("loopback catalog status=%d body=%s", response.Code, response.Body.String())
}
var payload map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
t.Fatalf("plain HTTP catalog status=%d body=%s", response.Code, response.Body.String())
}
if strings.Contains(response.Body.String(), "typed-key") {
t.Fatal("catalog response echoed the typed key")
}
saveBody := `{"base_revision":1,"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
request = httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
response = httptest.NewRecorder()
config.handleKBBindingSave(response, request)
if response.Code != http.StatusOK {
t.Fatalf("plain HTTP save status=%d body=%s", response.Code, response.Body.String())
}
if store.lastSave.APIKey != "typed-key" {
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
}
}
func TestKBBindingWritesAreAdminOnly(t *testing.T) {
@@ -128,3 +130,113 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
}
}
}
func TestKBBindingsReadDoesNotReportTransportCapability(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
config := kbBindingHandler(t, store)
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
request.Host = "172.29.151.11:28188"
response := httptest.NewRecorder()
config.handleKBBindings(response, request)
if response.Code != http.StatusOK {
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
}
if strings.Contains(response.Body.String(), "secret_entry_allowed") {
t.Fatalf("read response still reports the removed capability: %s", response.Body.String())
}
}
func TestKBBindingPlainHTTPWritesDoNotDependOnPrivateToggle(t *testing.T) {
const (
saveBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
catalogBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
)
store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
}
for _, allow := range []bool{false, true} {
config := kbBindingHandler(t, store)
config.WeKnoraAllowPrivateHTTP = allow
request := httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
response := httptest.NewRecorder()
config.handleKBBindingSave(response, request)
if response.Code != http.StatusOK {
t.Fatalf("save with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
}
if store.lastSave.APIKey != "typed-key" {
t.Fatalf("save with toggle=%v did not forward the typed key: %q", allow, store.lastSave.APIKey)
}
request = httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
response = httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
if response.Code != http.StatusOK {
t.Fatalf("catalog with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
}
}
}
func TestKBBindingSaveAuditSourcePrefersTheProxyAppendedHop(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}}}
config := kbBindingHandler(t, store)
body := `{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
for _, tc := range []struct {
name string
remote string
forwarded string
origin string
proto string
host string
wantAddress string
wantOrigin string
}{
{
name: "private proxy appends the real client after a forged hop",
remote: "10.0.0.5:41234", forwarded: "6.6.6.6, 172.29.151.11",
origin: "http://172.29.151.11:8088", host: "172.29.151.11:8088",
wantAddress: "172.29.151.11", wantOrigin: "http://172.29.151.11:8088",
},
{
name: "direct peer cannot launder its address through a forged chain",
remote: "203.0.113.9:41234", forwarded: "6.6.6.6",
host: "console.example",
wantAddress: "203.0.113.9", wantOrigin: "http://console.example",
},
{
name: "trusted proxy scheme fills in for a missing Origin",
remote: "10.0.0.5:41234", proto: "https", host: "kb.example",
wantAddress: "10.0.0.5", wantOrigin: "https://kb.example",
},
} {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPut, "http://"+tc.host+"/api/v1/kb-bindings/test", strings.NewReader(body))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.RemoteAddr = tc.remote
if tc.forwarded != "" {
request.Header.Set("X-Forwarded-For", tc.forwarded)
}
if tc.origin != "" {
request.Header.Set("Origin", tc.origin)
}
if tc.proto != "" {
request.Header.Set("X-Forwarded-Proto", tc.proto)
}
response := httptest.NewRecorder()
config.handleKBBindingSave(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
if store.lastSave.SourceAddress != tc.wantAddress || store.lastSave.SourceOrigin != tc.wantOrigin {
t.Fatalf("audit source = %q/%q, want %q/%q",
store.lastSave.SourceAddress, store.lastSave.SourceOrigin, tc.wantAddress, tc.wantOrigin)
}
})
}
}
+10 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"net/http"
"strconv"
"strings"
@@ -73,7 +74,7 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
return
}
for _, pair := range [][2]string{{f.Scope, "|internal|external"}, {f.Action, "|add|update|remove"}, {f.Status, "|active|waiting|running|retrying|attention|completed|cancelled"}, {f.Stage, "|waiting|fetch|upload|parsing|indexing|removal|finished"}} {
for _, pair := range [][2]string{{f.Scope, "|internal|external"}, {f.Action, "|add|update|remove"}, {f.Status, "|active|waiting|running|retrying|attention|completed|cancelled"}, {f.Stage, "|waiting|fetch|upload|parsing|indexing|removal|finished|weknora"}} {
if !strings.Contains("|"+pair[1]+"|", "|"+pair[0]+"|") {
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
return
@@ -97,6 +98,14 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"})
return
}
// One origin per request: every row uses the same effective test endpoint the
// reconciliation scan used, so a KB opens at the same place from both tabs.
if config.WeKnoraWebBase != nil {
origin := config.WeKnoraWebBase(r.Context())
for i := range page.Items {
page.Items[i].WeKnoraURL = weknora.KnowledgeBaseConsoleURL(origin, page.Items[i].TargetKB)
}
}
// 目标同名不罕见(两侧都叫“对内知识库”):把当前生效绑定随页返回,
// 前端才能在同一口径下标注“当前绑定/历史”,而不是拿本页条目反推全局。
internal, external := config.effectiveRoutingTargets(r.Context())
+72 -1
View File
@@ -11,11 +11,16 @@ import (
type monitorTasksTestStore struct {
fakeJobStore
filter postgresstore.MonitorTaskFilter
items []postgresstore.MonitorTask
}
func (s *monitorTasksTestStore) ListMonitorTasks(_ context.Context, f postgresstore.MonitorTaskFilter) (postgresstore.MonitorTaskPage, error) {
s.filter = f
return postgresstore.MonitorTaskPage{Items: []postgresstore.MonitorTask{}, Total: 145, Limit: f.Limit, Offset: f.Offset}, nil
items := s.items
if items == nil {
items = []postgresstore.MonitorTask{}
}
return postgresstore.MonitorTaskPage{Items: items, Total: 145, Limit: f.Limit, Offset: f.Offset}, nil
}
func TestMonitorTasksRoute(t *testing.T) {
s := &monitorTasksTestStore{}
@@ -33,6 +38,13 @@ func TestMonitorTasksRoute(t *testing.T) {
if s.filter.Status != "active" || s.filter.Offset != 40 {
t.Fatalf("filter %#v", s.filter)
}
// §8 merges 解析/索引增强 into one "WeKnora 处理中" facet.
merged := httptest.NewRequest("GET", "/api/v1/monitor/tasks?stage=weknora", nil).WithContext(req.Context())
wm := httptest.NewRecorder()
h.ServeHTTP(wm, merged)
if wm.Code != 200 || s.filter.Stage != "weknora" {
t.Fatalf("weknora stage: %d filter %#v", wm.Code, s.filter)
}
for _, query := range []string{"status=garbage", "stage=internal&scope=internal", "limit=101", "offset=-1", "since=bad"} {
r := httptest.NewRequest("GET", "/api/v1/monitor/tasks?"+query, nil).WithContext(req.Context())
rr := httptest.NewRecorder()
@@ -88,3 +100,62 @@ func TestMonitorTasksReportsEffectiveTargetBindings(t *testing.T) {
t.Fatalf("bindings = %#v, want the persisted current bindings", payload.Data.Bindings)
}
}
// The platform drawer's 503 fallback needs the same jump link a finding carries.
// The handler, not the browser, decides the origin: it must use the effective
// test endpoint, and an unwired resolver must leave the field empty instead of
// inventing a host.
func TestMonitorTasksAddsWeKnoraConsoleURL(t *testing.T) {
store := &monitorTasksTestStore{items: []postgresstore.MonitorTask{{ID: "mt-1", TargetKB: "kb-1"}}}
handler, err := NewHandler(Config{
Store: store,
WeKnoraWebBase: func(context.Context) string { return "https://weknora.test/" },
})
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 {
Items []struct {
WeKnoraURL string `json:"weknora_url"`
} `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.Items) != 1 || payload.Data.Items[0].WeKnoraURL != "https://weknora.test/platform/knowledge-bases/kb-1" {
t.Fatalf("weknora_url = %#v", payload.Data.Items)
}
store.items = []postgresstore.MonitorTask{{ID: "mt-1", TargetKB: "kb-1"}}
unwired, err := NewHandler(Config{Store: store})
if err != nil {
t.Fatal(err)
}
recorder = httptest.NewRecorder()
unwired.ServeHTTP(recorder, req)
if recorder.Code != 200 {
t.Fatalf("unwired status %d: %s", recorder.Code, recorder.Body.String())
}
payload = struct {
Data struct {
Items []struct {
WeKnoraURL string `json:"weknora_url"`
} `json:"items"`
} `json:"data"`
}{}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.Items) != 1 || payload.Data.Items[0].WeKnoraURL != "" {
t.Fatalf("unwired weknora_url = %#v", payload.Data.Items)
}
}
+227
View File
@@ -0,0 +1,227 @@
package httpapi
import (
"context"
"errors"
"net/http"
"strings"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/reconciliation"
)
type ReconciliationService interface {
CreateRun(context.Context, string, string) (governance.ReconciliationRun, error)
ListRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error)
GetRun(context.Context, string) (governance.ReconciliationRun, error)
ListFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error)
Writeback(context.Context, string, string, string) (governance.ReconciliationFinding, error)
Requeue(context.Context, string, string, string) (governance.ReconciliationFinding, error)
Remove(context.Context, string, string, string) (governance.ReconciliationFinding, error)
Progress(context.Context, string) (governance.ReconciliationProgress, error)
}
const reconciliationActionHeader = "reconciliation-action"
func requireReconciliationAction(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("X-Governance-Action") != reconciliationActionHeader {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "write intent required"})
return false
}
return true
}
func validReconciliationID(value string, max int) bool {
if value == "" || len(value) > max || strings.TrimSpace(value) != value {
return false
}
return !strings.ContainsAny(value, "\x00\r\n/?#\\")
}
func writeReconciliationError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, reconciliation.ErrRunInProgress):
writeJSON(w, http.StatusConflict, map[string]string{"error": "reconciliation_run_in_progress", "code": "reconciliation_run_in_progress"})
case errors.Is(err, reconciliation.ErrNotFound):
writeJSON(w, http.StatusNotFound, map[string]string{"error": "reconciliation record not found"})
case errors.Is(err, reconciliation.ErrActionConflict), errors.Is(err, reconciliation.ErrActionNotAllowed):
writeJSON(w, http.StatusConflict, map[string]string{"error": "reconciliation_state_changed", "code": "reconciliation_state_changed"})
case errors.Is(err, reconciliation.ErrRuntimeUnavailable):
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_read_unavailable", "code": "runtime_read_unavailable"})
case errors.Is(err, reconciliation.ErrRemoteFailed):
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "reconciliation_remote_failed", "code": "reconciliation_remote_failed"})
default:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "reconciliation_failed"})
}
}
func createReconciliationRun(w http.ResponseWriter, r *http.Request, config Config) {
identity, ok := requireSessionIdentity(w, r)
if !ok {
return
}
if identity.Role != roleEngineer && identity.Role != roleAdmin {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
return
}
if !requireReconciliationAction(w, r) {
return
}
var input struct {
KBID string `json:"kb_id"`
}
if err := decodeStrictJSON(r, &input); err != nil || !validReconciliationID(input.KBID, 255) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid kb_id"})
return
}
run, err := config.Reconciliation.CreateRun(r.Context(), input.KBID, "manual")
if err != nil {
writeReconciliationError(w, err)
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"data": run})
}
func listReconciliationRuns(w http.ResponseWriter, r *http.Request, config Config) {
if _, ok := requireSessionIdentity(w, r); !ok {
return
}
limit, offset, ok := parseLimitOffset(w, r, 20)
if !ok {
return
}
kbID := strings.TrimSpace(r.URL.Query().Get("kb_id"))
if kbID != "" && !validReconciliationID(kbID, 255) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid kb_id"})
return
}
page, err := config.Reconciliation.ListRuns(r.Context(), governance.ReconciliationRunFilter{KBID: kbID, Limit: limit, Offset: offset})
if err != nil {
writeReconciliationError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, map[string]any{"data": page})
}
func getReconciliationRun(w http.ResponseWriter, r *http.Request, config Config) {
if _, ok := requireSessionIdentity(w, r); !ok {
return
}
id := r.PathValue("id")
if !validReconciliationID(id, 128) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid run id"})
return
}
run, err := config.Reconciliation.GetRun(r.Context(), id)
if err != nil {
writeReconciliationError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": run})
}
func listReconciliationFindings(w http.ResponseWriter, r *http.Request, config Config) {
if _, ok := requireSessionIdentity(w, r); !ok {
return
}
runID := r.PathValue("id")
if !validReconciliationID(runID, 128) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid run id"})
return
}
limit, offset, ok := parseLimitOffset(w, r, 20)
if !ok {
return
}
findingType := strings.TrimSpace(r.URL.Query().Get("type"))
if findingType != "" {
switch findingType {
case "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8":
default:
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid finding type"})
return
}
}
query := r.URL.Query().Get("q")
if len(query) > 512 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "q is too long"})
return
}
page, err := config.Reconciliation.ListFindings(r.Context(), governance.ReconciliationFindingFilter{
RunID: runID, Type: findingType, Query: query, Limit: limit, Offset: offset,
})
if err != nil {
writeReconciliationError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, map[string]any{"data": page})
}
func reconciliationAction(w http.ResponseWriter, r *http.Request, config Config, adminOnly bool, action func(context.Context, string, string, string) (governance.ReconciliationFinding, error)) {
identity, ok := requireSessionIdentity(w, r)
if !ok {
return
}
if adminOnly && identity.Role != roleAdmin {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
return
}
if !adminOnly && identity.Role != roleEngineer && identity.Role != roleAdmin {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
return
}
if !requireReconciliationAction(w, r) {
return
}
id := r.PathValue("id")
if !validReconciliationID(id, 128) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid finding id"})
return
}
finding, err := action(r.Context(), id, actorFor(r), "导入对账处置")
if err != nil {
writeReconciliationError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": finding})
}
func writebackReconciliationFinding(w http.ResponseWriter, r *http.Request, config Config) {
reconciliationAction(w, r, config, false, config.Reconciliation.Writeback)
}
func requeueReconciliationFinding(w http.ResponseWriter, r *http.Request, config Config) {
reconciliationAction(w, r, config, false, config.Reconciliation.Requeue)
}
func removeReconciliationFinding(w http.ResponseWriter, r *http.Request, config Config) {
reconciliationAction(w, r, config, true, config.Reconciliation.Remove)
}
func getReconciliationDocumentProgress(w http.ResponseWriter, r *http.Request, config Config) {
if _, ok := requireSessionIdentity(w, r); !ok {
return
}
documentID := r.PathValue("document_id")
if !validReconciliationID(documentID, 64) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid document id"})
return
}
progress, err := config.Reconciliation.Progress(r.Context(), documentID)
if err != nil {
writeReconciliationError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, map[string]any{"data": progress})
}
func requireReconciliation(w http.ResponseWriter, r *http.Request, config Config, handler func(http.ResponseWriter, *http.Request, Config)) {
if config.Reconciliation == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "reconciliation_not_configured", "code": "reconciliation_not_configured"})
return
}
handler(w, r, config)
}
+128
View File
@@ -0,0 +1,128 @@
package httpapi
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/reconciliation"
)
type reconciliationServiceStub struct {
created bool
progress governance.ReconciliationProgress
err error
}
func (s *reconciliationServiceStub) CreateRun(context.Context, string, string) (governance.ReconciliationRun, error) {
s.created = true
return governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running"}, s.err
}
func (s *reconciliationServiceStub) ListRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
return governance.ReconciliationRunPage{Items: []governance.ReconciliationRun{}}, s.err
}
func (s *reconciliationServiceStub) GetRun(context.Context, string) (governance.ReconciliationRun, error) {
return governance.ReconciliationRun{ID: "run-1"}, s.err
}
func (s *reconciliationServiceStub) ListFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
return governance.ReconciliationFindingPage{Items: []governance.ReconciliationFinding{}}, s.err
}
func (s *reconciliationServiceStub) Writeback(context.Context, string, string, string) (governance.ReconciliationFinding, error) {
return governance.ReconciliationFinding{ID: "f1", ActionState: "done"}, s.err
}
func (s *reconciliationServiceStub) Requeue(context.Context, string, string, string) (governance.ReconciliationFinding, error) {
return governance.ReconciliationFinding{ID: "f1", ActionState: "done"}, s.err
}
func (s *reconciliationServiceStub) Remove(context.Context, string, string, string) (governance.ReconciliationFinding, error) {
return governance.ReconciliationFinding{ID: "f1", ActionState: "done"}, s.err
}
func (s *reconciliationServiceStub) Progress(context.Context, string) (governance.ReconciliationProgress, error) {
return s.progress, s.err
}
func reconciliationRequest(method, path, role, body string) *http.Request {
request := httptest.NewRequest(method, path, strings.NewReader(body))
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role}))
return request
}
func TestReconciliationRoutesEnforceRolesAndWriteIntent(t *testing.T) {
service := &reconciliationServiceStub{}
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: service})
if err != nil {
t.Fatal(err)
}
viewer := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/runs", roleViewer, `{"kb_id":"kb-1"}`)
viewer.Header.Set("X-Governance-Action", "reconciliation-action")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, viewer)
if recorder.Code != http.StatusForbidden || service.created {
t.Fatalf("viewer create = %d created=%t", recorder.Code, service.created)
}
engineer := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/runs", roleEngineer, `{"kb_id":"kb-1"}`)
engineer.Header.Set("X-Governance-Action", "reconciliation-action")
recorder = httptest.NewRecorder()
handler.ServeHTTP(recorder, engineer)
if recorder.Code != http.StatusAccepted || !service.created {
t.Fatalf("engineer create = %d created=%t %s", recorder.Code, service.created, recorder.Body.String())
}
missingIntent := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/findings/f1/requeue", roleEngineer, "")
recorder = httptest.NewRecorder()
handler.ServeHTTP(recorder, missingIntent)
if recorder.Code != http.StatusForbidden {
t.Fatalf("missing write intent = %d", recorder.Code)
}
engineerRemove := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/findings/f1/remove", roleEngineer, "")
engineerRemove.Header.Set("X-Governance-Action", "reconciliation-action")
recorder = httptest.NewRecorder()
handler.ServeHTTP(recorder, engineerRemove)
if recorder.Code != http.StatusForbidden {
t.Fatalf("engineer remove = %d", recorder.Code)
}
adminRemove := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/findings/f1/remove", roleAdmin, "")
adminRemove.Header.Set("X-Governance-Action", "reconciliation-action")
recorder = httptest.NewRecorder()
handler.ServeHTTP(recorder, adminRemove)
if recorder.Code != http.StatusOK {
t.Fatalf("admin remove = %d %s", recorder.Code, recorder.Body.String())
}
}
func TestReconciliationProgress503AndUnwiredRoute(t *testing.T) {
service := &reconciliationServiceStub{err: reconciliation.ErrRuntimeUnavailable}
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: service})
if err != nil {
t.Fatal(err)
}
request := reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/documents/doc-1/progress", roleViewer, "")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusServiceUnavailable || !strings.Contains(recorder.Body.String(), "runtime_read_unavailable") {
t.Fatalf("progress = %d %s", recorder.Code, recorder.Body.String())
}
unwired, err := NewHandler(Config{Store: &fakeJobStore{}})
if err != nil {
t.Fatal(err)
}
recorder = httptest.NewRecorder()
unwired.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/runs", roleViewer, ""))
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("unwired runs = %d", recorder.Code)
}
}
func TestReconciliationFindingTypeValidation(t *testing.T) {
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: &reconciliationServiceStub{}})
if err != nil {
t.Fatal(err)
}
request := reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/runs/run-1/findings?type=R9", roleViewer, "")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("invalid type = %d", recorder.Code)
}
}
+39 -35
View File
@@ -7,23 +7,16 @@ import (
"strings"
)
// secretTransportAllowed is the single rule for typing a secret into the
// console: a real TLS connection, a loopback request, or a same-origin HTTPS
// request that a trusted reverse proxy forwarded. The browser's origin scheme
// must agree, so a plain-HTTP page behind a misconfigured proxy cannot submit
// a key even if it spoofs X-Forwarded-Proto.
// secretTransportAllowed is the strict rule for QA AI model keys: a real TLS
// connection, a loopback request, or a same-origin HTTPS request that a trusted
// reverse proxy forwarded. The browser's origin scheme must agree, so a
// plain-HTTP page behind a misconfigured proxy cannot submit a key even if it
// spoofs X-Forwarded-Proto. Knowledge base keys deliberately do not use it.
func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
if r.TLS != nil {
return true
}
host := r.Host
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
host = parsedHost
}
if strings.EqualFold(host, "localhost") {
return true
}
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
if loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" && r.Header.Get("Sec-Fetch-Site") == "same-origin" {
@@ -33,28 +26,39 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
return false
}
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
// fetch from the operator console itself when it is served over plain http on a
// private address. That is the only non-TLS shape this deployment needs, and it
// still requires an exact Origin/Host match.
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if secretTransportAllowed(r, trustTLSProxy) {
// requestHostname strips the optional port and IPv6 brackets. Brackets come
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
// ported forms are not address spellings the server or a browser ever emits,
// so they stay untouched and keep failing the address checks.
func requestHostname(host string) string {
host = strings.TrimSpace(host)
if strings.HasPrefix(host, "[") {
end := strings.Index(host, "]")
if end <= 0 {
return host
}
ip := net.ParseIP(host[1:end])
if ip == nil || ip.To4() != nil {
return host
}
if rest := host[end+1:]; rest != "" && (rest[0] != ':' || rest == ":" || strings.Trim(rest[1:], "0123456789") != "") {
return host
}
return ip.String()
}
if parsedHost, _, err := net.SplitHostPort(host); err == nil {
return parsedHost
}
return host
}
// loopbackHost is the address-only part of the secret transport rule: a
// request from this machine never crosses a network.
func loopbackHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
if !allowPrivateHTTP || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
return false
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" {
return false
}
parsed, err := url.Parse(origin)
if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Host, r.Host) {
return false
}
host := parsed.Hostname()
if ip := net.ParseIP(host); ip != nil {
return ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast()
}
return strings.EqualFold(host, "localhost")
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
+39
View File
@@ -0,0 +1,39 @@
package httpapi
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = "[::1]"
if !secretTransportAllowed(request, false) {
t.Fatal("bare [::1] Host was rejected as a loopback transport")
}
request.Host = "console.example"
if secretTransportAllowed(request, false) {
t.Fatal("public name without TLS was accepted")
}
}
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
}
}
func TestSecretTransportRejectsMalformedIPv6Suffixes(t *testing.T) {
for _, host := range []string{"[::1]junk", "[::1]:", "[::1]:abc"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = host
if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host)
}
}
}
+48 -15
View File
@@ -121,19 +121,26 @@ func libraryWithDeadline(w http.ResponseWriter, r *http.Request, limit time.Dura
}
type Config struct {
QAAI *qaopsai.Store
QAAITrustTLSProxy bool
QAQuality QAQualityStore
QAOrgSync QAOrgSyncStore
QAOrgSyncEnabled bool
QAOrg QAOrgStore
QAOps QAOpsReader
QAWeeklyMail any
QAOpsTenantKey string
QAOpsEnabled bool
QAOpsProblem string
Store Store
Monitor MonitorProvider
QAAI *qaopsai.Store
QAAITrustTLSProxy bool
QAQuality QAQualityStore
QAOrgSync QAOrgSyncStore
QAOrgSyncEnabled bool
QAOrg QAOrgStore
QAOps QAOpsReader
QAWeeklyMail any
QAOpsTenantKey string
QAOpsEnabled bool
QAOpsProblem string
Store Store
Monitor MonitorProvider
// Reconciliation is the T6 reconciliation domain. Nil keeps the routes
// unavailable instead of returning fake empty batches.
Reconciliation ReconciliationService
// WeKnoraWebBase resolves the test WeKnora console origin used to build the
// drawer jump link on /monitor/tasks rows. Nil (or an empty answer) leaves
// weknora_url empty; the contract allows that, and no host is invented.
WeKnoraWebBase func(context.Context) string
InternalRoutingKnowledgeBaseID string
ExternalRoutingKnowledgeBaseID string
RoutingBindings RoutingBindingStore
@@ -142,8 +149,8 @@ type Config struct {
// internal/external bindings saved together. Nil keeps the page read-only
// and reports unavailable, never a fake success.
KBBindings KBBindingStore
// WeKnoraAllowPrivateHTTP 允许在私网治理台(明文 http)上录入 WeKnora API Key;
// 同时决定客户端/探活是否放行同网段 http(生产 18093 反代)。
// WeKnoraAllowPrivateHTTP 决定客户端/探活是否放行同网段 http(生产 18093 反代);
// 不再参与控制台密钥录入判定。
WeKnoraAllowPrivateHTTP bool
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
// enumerates the production-side bases the operator can bind.
@@ -495,6 +502,32 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/monitor/overview", func(w http.ResponseWriter, r *http.Request) {
monitorOverview(w, r, config.Monitor)
})
// 导入对账(T6a):批次、差异、处置与实时处理详情。未接线时明确 503,
// 不返回空批次冒充"没有差异"。
mux.HandleFunc("POST /api/v1/reconciliation/runs", func(w http.ResponseWriter, r *http.Request) {
requireReconciliation(w, r, config, createReconciliationRun)
})
mux.HandleFunc("GET /api/v1/reconciliation/runs", func(w http.ResponseWriter, r *http.Request) {
requireReconciliation(w, r, config, listReconciliationRuns)
})
mux.HandleFunc("GET /api/v1/reconciliation/runs/{id}", func(w http.ResponseWriter, r *http.Request) {
requireReconciliation(w, r, config, getReconciliationRun)
})
mux.HandleFunc("GET /api/v1/reconciliation/runs/{id}/findings", func(w http.ResponseWriter, r *http.Request) {
requireReconciliation(w, r, config, listReconciliationFindings)
})
mux.HandleFunc("POST /api/v1/reconciliation/findings/{id}/writeback", func(w http.ResponseWriter, r *http.Request) {
requireReconciliation(w, r, config, writebackReconciliationFinding)
})
mux.HandleFunc("POST /api/v1/reconciliation/findings/{id}/requeue", func(w http.ResponseWriter, r *http.Request) {
requireReconciliation(w, r, config, requeueReconciliationFinding)
})
mux.HandleFunc("POST /api/v1/reconciliation/findings/{id}/remove", func(w http.ResponseWriter, r *http.Request) {
requireReconciliation(w, r, config, removeReconciliationFinding)
})
mux.HandleFunc("GET /api/v1/reconciliation/documents/{document_id}/progress", func(w http.ResponseWriter, r *http.Request) {
requireReconciliation(w, r, config, getReconciliationDocumentProgress)
})
// 「版本记录」:当前运行的构建身份(只读,与监控同级可见)
mux.HandleFunc("GET /api/v1/build-info", func(w http.ResponseWriter, r *http.Request) {
buildInfo(w, r)
+4
View File
@@ -112,6 +112,10 @@ type SaveInput struct {
APIKey string `json:"api_key"`
InternalKBID string `json:"internal_kb_id"`
ExternalKBID string `json:"external_kb_id"`
// 审计用:由 HTTP 层按连接事实填充,不属于请求体(严格解码下客户端
// 提交同名字段会被拒绝)。只是事后取证,不参与任何放行判定。
SourceAddress string `json:"-"`
SourceOrigin string `json:"-"`
}
// Target is what consumers (readiness, upload, listing, monitoring) need to
+12
View File
@@ -12,6 +12,7 @@ import (
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/jackc/pgx/v5"
@@ -209,3 +210,14 @@ func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) {
t.Fatalf("bound view must not claim a fallback: %+v", bound)
}
}
func TestAuditTextBoundsWithoutSplittingUTF8(t *testing.T) {
// 恶意 Origin 可能带非 ASCII:截断若切开跑码点,PostgreSQL text 会拒收整条保存。
got := auditText(strings.Repeat("密钥", 100), 10)
if len(got) > 10 || !utf8.ValidString(got) || got == "" {
t.Fatalf("auditText = %q (%d bytes)", got, len(got))
}
if auditText(" ", 10) != "" {
t.Fatal("blank audit source must stay empty, never a placeholder")
}
}
@@ -286,6 +286,8 @@ func TestClearKeyKeepsNamesIDsAndFrozenIdentity(t *testing.T) {
cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear",
InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID,
// 非 HTTPS 控制台保存:审计行必须能还原当时的入口与客户端地址。
SourceAddress: "172.29.151.11", SourceOrigin: "http://172.29.151.11:8088",
}, "admin", now.Add(time.Minute))
if err != nil {
t.Fatalf("clear Save() error = %v", err)
@@ -364,6 +366,17 @@ WHERE environment='test' AND revision=2`).Scan(&keyConfigured); err != nil {
if keyConfigured {
t.Fatal("history still says the cleared key is configured")
}
var sourceAddress, sourceOrigin, sourceActor string
var sourceEnv string
if err := pool.QueryRow(ctx, `
SELECT source_address,source_origin,actor,environment FROM weknora_environment_binding_history
WHERE environment='test' AND revision=2`).Scan(&sourceAddress, &sourceOrigin, &sourceActor, &sourceEnv); err != nil {
t.Fatal(err)
}
if sourceAddress != "172.29.151.11" || sourceOrigin != "http://172.29.151.11:8088" ||
sourceActor != "admin" || sourceEnv != "test" {
t.Fatalf("save audit = %q/%q actor=%q env=%q", sourceAddress, sourceOrigin, sourceActor, sourceEnv)
}
var secretColumns int
if err := pool.QueryRow(ctx, `
SELECT COUNT(*) FROM information_schema.columns
+22 -3
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"strings"
"time"
"unicode/utf8"
"github.com/jackc/pgx/v5"
@@ -206,9 +207,11 @@ ON CONFLICT(environment) DO UPDATE SET
}
if _, err := tx.Exec(ctx, `
INSERT INTO weknora_environment_binding_history(
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC()); err != nil {
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at,
source_address,source_origin)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC(),
auditText(input.SourceAddress, 128), auditText(input.SourceOrigin, 300)); err != nil {
return View{}, ErrStorage
}
replan := postgresstore.RoutingBindingReplanResult{}
@@ -353,3 +356,19 @@ func shortID(value string) string {
}
return value
}
// auditText bounds one audit column. An empty value stays empty: the audit row
// must never present a guessed address as fact. Truncation stops on a rune
// boundary because PostgreSQL text refuses invalid UTF-8 (a hostile Origin
// header must not turn a save into a storage error).
func auditText(value string, limit int) string {
value = strings.ToValidUTF8(strings.TrimSpace(value), "")
if len(value) <= limit {
return value
}
value = value[:limit]
for len(value) > 0 && !utf8.ValidString(value) {
value = value[:len(value)-1]
}
return value
}
+87 -2
View File
@@ -18,6 +18,27 @@ const LegacyVersion = 74
// V090Version 是 0.9.0 的 schema_migrations 版本号(已实测:134、dirty=false、83 表)。
const V090Version = 134
// V091Version 是 0.9.1 的 schema_migrations 版本号(上游 tag v0.9.1,最大迁移 137)。
// 135–137 只改审计列宽/凭据表/IM 唯一索引,不碰知识域表、列或触发器,因此 v091
// 由 v090 克隆后只改版本字段,不复制一份表/列/触发器常量。
const V091Version = 137
// RelatedTableClass 是知识域关联表的搬运归类。copied = 随整库搬运(即该版本的
// Required/Optional 表);derived = 由触发器/应用派生,不单独搬运;excluded =
// 明确不搬,必须写明原因。分类只写在 profile 这一处,门禁按它放行。
type RelatedTableClass string
const (
RelatedCopied RelatedTableClass = "copied"
RelatedDerived RelatedTableClass = "derived"
RelatedExcluded RelatedTableClass = "excluded"
)
type RelatedTable struct {
Class RelatedTableClass
Reason string
}
// PartRequirement 是归档部件的一项要求(kind/name 与 manifest 的部件键一致)。
type PartRequirement struct {
Kind string
@@ -41,6 +62,9 @@ type Profile struct {
ReviewedTriggers []string
RequiredParts []PartRequirement
OptionalParts []PartRequirement
// RelatedTables 是该版本全部知识域关联表的归类(copied/derived/excluded)。
// 漏表门禁按它判定:未归类且有本库数据的表一律拒绝。
RelatedTables map[string]RelatedTable
// IndexContractSource 说明该版本的索引名从哪里读。空值等于"读不到",
// 不允许回退成空串去匹配任何索引。
IndexContractSource string
@@ -93,6 +117,9 @@ var profiles = map[int]Profile{
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
"wiki_page_issues",
// 编辑历史随内容搬运(D1)。放在父表之后:importRows 按本序插入、
// 倒序删除,两张历史表因此在 chunks/wiki_pages 之后写、在它们之前删。
"chunk_revisions", "wiki_page_revisions",
},
// 0.9.0 删掉了 wiki_log_entries;部件集合随之为空,不许假装还有。
OptionalTables: []string{"wiki_log_entries"},
@@ -106,12 +133,15 @@ var profiles = map[int]Profile{
"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"},
"chunk_revisions": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "chunk_id"},
"wiki_page_revisions": {"id", "tenant_id", "knowledge_base_id", "page_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"},
{"database", "chunk_revisions"}, {"wiki", "wiki_page_revisions"},
{"index", "chunks"},
},
OptionalParts: []PartRequirement{
@@ -130,19 +160,74 @@ var profiles = map[int]Profile{
},
}
// init 在一次声明上补齐两件事,避免复制常量:
// 1. 每个版本的知识域关联表分类(copied 由该版本的 Required/Optional 表派生);
// 2. v0.9.1 = v0.9.0 的克隆,只改版本字段。135–137 不碰知识域,表/列/触发器/
// 部件必须与 v090 完全一致,任何分叉都会被测试抓住。
func init() {
for version, profile := range profiles {
profile.RelatedTables = classifyKnowledgeTables(profile)
profiles[version] = profile
}
v090 := profiles[V090Version]
v091 := v090
v091.Name, v091.SchemaVersion, v091.WeKnoraVersion = "v091", V091Version, "v0.9.1"
profiles[V091Version] = v091
}
// classifyKnowledgeTables 把该版本声明过的表标成 copied,并补上派生/排除表。
// 分类键覆盖真实 0.9.x 中所有带 knowledge_base_id/knowledge_id/kb_id 的表:
// 漏一张,漏表门禁就会在该表有数据时拒绝发布。
func classifyKnowledgeTables(profile Profile) map[string]RelatedTable {
tables := make(map[string]RelatedTable, len(profile.RequiredTables)+len(profile.OptionalTables)+len(excludedKnowledgeTables)+1)
for name, reason := range excludedKnowledgeTables {
tables[name] = RelatedTable{Class: RelatedExcluded, Reason: reason}
}
// 派生表:由触发器维护,随父表重算;不单独搬运。
tables["chunk_images"] = RelatedTable{Class: RelatedDerived,
Reason: "chunks 上的 chunk_images_sync 触发器维护的图片投影表,随 chunks 重算"}
for _, name := range profile.RequiredTables {
tables[name] = RelatedTable{Class: RelatedCopied, Reason: "知识库内容表,随整库搬运并做范围改写与目标身份映射"}
}
for _, name := range profile.OptionalTables {
tables[name] = RelatedTable{Class: RelatedCopied, Reason: "知识库内容表(可选),存在时随整库搬运并做范围改写与目标身份映射"}
}
return tables
}
// excludedKnowledgeTables 是明确不搬的知识域关联表及原因。原因必须解释
// "为什么生产不需要它/为什么覆盖会破坏目标",不能只写"不搬"。
var excludedKnowledgeTables = map[string]string{
"knowledge_processing_spans": "解析流水线的阶段遥测;生产只做推理、不解析,搬运会把测试侧处理过程当成生产内容",
"sessions": "对话会话属于各环境自己的运行数据,搬运会覆盖/污染目标用户会话",
"messages": "对话消息属于各环境自己的运行数据,不能从测试库覆盖生产",
"memory_doc_affinity": "记忆与文档的运行期关联,生产会自行建立,搬运会造成跨环境语义错配",
"user_kb_pins": "用户置顶是各环境自己的偏好配置,生产用户 ID 在测试侧不存在",
"kb_shares": "组织共享关系绑定本实例的组织/用户,跨环境搬运会产生无效授权",
"im_channels": "IM 渠道配置属于各环境的接入配置,含环境专属凭据/回调",
"data_sources": "数据源配置属于各环境的接入配置,生产不复用测试侧连接",
"embeddings": "仅 PG 检索模式(条件迁移)创建的向量表;本平台契约固定 elasticsearch_v8,检索不读它",
}
// RelatedTableClass 返回某张关联表的分类与理由;未分类时 ok=false。
func (p Profile) RelatedTableClass(name string) (RelatedTable, bool) {
table, ok := p.RelatedTables[name]
return table, ok
}
// 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{}, fmt.Errorf("unsupported WeKnora schema version %d: supported profiles are 74 (v071), 134 (v090) and 137 (v091)", version)
}
return profile, nil
}
// Supported 返回已声明 profile 的版本号(用于文档与错误信息,不用于放行)。
func Supported() []int {
return []int{LegacyVersion, V090Version}
return []int{LegacyVersion, V090Version, V091Version}
}
// TableSet 是"可能出现的表"集合:必需表 + 可选表。
+113
View File
@@ -0,0 +1,113 @@
package libraryprofile
import (
"reflect"
"strings"
"testing"
)
func TestForV091IsDeclaredAndSharesV090Contract(t *testing.T) {
profile, err := For(V091Version)
if err != nil {
t.Fatalf("For(137): %v", err)
}
if profile.SchemaVersion != 137 || profile.Name != "v091" || profile.WeKnoraVersion != "v0.9.1" {
t.Fatalf("unexpected v0.9.1 profile: %+v", profile)
}
supported := Supported()
if !reflect.DeepEqual(supported, []int{74, 134, 137}) {
t.Fatalf("Supported()=%v", supported)
}
v090, err := For(V090Version)
if err != nil {
t.Fatal(err)
}
// 除了版本三字段,v091 必须与 v090 完全一致;任何分叉都意味着表/列/触发器
// 被复制或漂移,升级后会与真实 schema 对不上。
v091 := profile
v091.Name, v091.SchemaVersion, v091.WeKnoraVersion = v090.Name, v090.SchemaVersion, v090.WeKnoraVersion
if !reflect.DeepEqual(v090, v091) {
t.Fatal("v0.9.1 must be a version-only clone of v0.9.0")
}
}
func TestDeclaredTablesAreAllClassifiedCopied(t *testing.T) {
for _, version := range Supported() {
profile, err := For(version)
if err != nil {
t.Fatal(err)
}
for _, table := range append(append([]string{}, profile.RequiredTables...), profile.OptionalTables...) {
class, ok := profile.RelatedTableClass(table)
if !ok {
t.Fatalf("%s: declared table %s has no classification", profile.Name, table)
}
if class.Class != RelatedCopied || strings.TrimSpace(class.Reason) == "" {
t.Fatalf("%s: declared table %s must be copied with a reason, got %+v", profile.Name, table, class)
}
}
}
}
func TestEveryRealKnowledgeScopedTableIsClassified(t *testing.T) {
// 真实测试 WeKnora 0.9.0 的只读 information_schema 结果(2026-11-30):
// 带 knowledge_base_id/knowledge_id/kb_id 的 public 表共 18 张。漏一张,
// 漏表门禁就会在该表有数据时拒绝发布;这里把它锁成契约。
realTables := []string{
"chunk_images", "chunk_revisions", "chunks", "data_sources", "im_channels",
"knowledge_processing_spans", "knowledge_tag_relations", "knowledge_tags",
"knowledges", "kb_shares", "memory_doc_affinity", "messages", "sessions",
"user_kb_pins", "wiki_folders", "wiki_page_issues", "wiki_page_revisions", "wiki_pages",
}
// embeddings 是条件迁移(仅 PG 检索模式)创建的,真实测试库不存在,也必须
// 预置分类,避免未来启用后被误判为未声明表。
optionalRealTables := []string{"embeddings"}
for _, version := range []int{V090Version, V091Version} {
profile, err := For(version)
if err != nil {
t.Fatal(err)
}
for _, table := range append(append([]string{}, realTables...), optionalRealTables...) {
class, ok := profile.RelatedTableClass(table)
if !ok {
t.Fatalf("%s: real knowledge-scoped table %s is unclassified", profile.Name, table)
}
if strings.TrimSpace(class.Reason) == "" {
t.Fatalf("%s: %s has an empty classification reason", profile.Name, table)
}
}
if class, _ := profile.RelatedTableClass("chunk_images"); class.Class != RelatedDerived {
t.Fatalf("chunk_images must be derived, got %+v", class)
}
for _, table := range []string{"sessions", "messages", "knowledge_processing_spans", "data_sources"} {
if class, _ := profile.RelatedTableClass(table); class.Class != RelatedExcluded {
t.Fatalf("%s must be excluded, got %+v", table, class)
}
}
}
}
func TestRevisionTablesAreCopiedAndOrderedAfterParents(t *testing.T) {
profile, err := For(V091Version)
if err != nil {
t.Fatal(err)
}
position := func(table string) int {
for index, name := range profile.RequiredTables {
if name == table {
return index
}
}
t.Fatalf("required table %s missing", table)
return -1
}
if position("chunk_revisions") < position("chunks") {
t.Fatal("chunk_revisions must be written after chunks")
}
if position("wiki_page_revisions") < position("wiki_pages") {
t.Fatal("wiki_page_revisions must be written after wiki_pages")
}
if !profile.RequiresPart("database/chunk_revisions") || !profile.RequiresPart("wiki/wiki_page_revisions") {
t.Fatal("both revision parts must be required archive parts")
}
}
+3
View File
@@ -119,6 +119,9 @@ type WriteSet struct {
CreatedAt time.Time `json:"created_at"`
Rows []WriteSetRow `json:"rows"`
Universe map[string]TableFingerprint `json:"universe"`
// Warnings 是放行但需要留痕的契约警告(例如未分类但为空的表)。omitempty:
// 空警告不改变历史计划的规范字节/摘要,旧记录读回仍然一致。
Warnings []string `json:"warnings,omitempty"`
// Digest 是对除本字段外全部内容的 sha256:落盘文件名与治理库里的引用都用它,
// 记录被改一个字节就对不上。
Digest string `json:"digest"`
@@ -0,0 +1,54 @@
package libraryrelease
import (
"encoding/json"
"testing"
"time"
)
// 空警告必须不改变历史 V2 计划的规范字节:omitempty 是兼容边界,不是装饰。
func TestWriteSetWarningsAreOmittedWhenEmpty(t *testing.T) {
base := WriteSet{
Version: MigrationWriteSetVersion, ContractVersion: 1,
JobID: "job-1", Target: "internal", TenantID: 1, KnowledgeBaseID: "kb-1",
BackupSnapshotID: "backup-1", TargetSnapshotID: "snapshot-1",
CreatedAt: time.Unix(1700000000, 0).UTC(),
Rows: []WriteSetRow{{Table: "knowledges", ID: "doc-1"}},
Universe: map[string]TableFingerprint{"knowledges": {Count: 1, Digest: "digest"}},
TargetIDMode: TargetIDModeScoped,
}
seal := func(set WriteSet) string {
t.Helper()
if err := set.Seal(); err != nil {
t.Fatal(err)
}
return set.Digest
}
withoutWarnings := seal(base)
withEmptyWarnings := base
withEmptyWarnings.Warnings = []string{}
if got := seal(withEmptyWarnings); got != withoutWarnings {
t.Fatalf("empty warnings changed the canonical digest: %s != %s", got, withoutWarnings)
}
withWarning := base
withWarning.Warnings = []string{"release_undeclared_kb_table: 未分类空表已放行"}
if got := seal(withWarning); got == withoutWarnings {
t.Fatal("a real warning must be part of the durable record")
}
raw, err := json.Marshal(withWarning)
if err != nil || !json.Valid(raw) {
t.Fatalf("warning record must serialize: %v", err)
}
if !containsJSONField(raw, "warnings") {
t.Fatal("warning must be persisted in the release record")
}
}
func containsJSONField(raw []byte, key string) bool {
var object map[string]json.RawMessage
if json.Unmarshal(raw, &object) != nil {
return false
}
_, ok := object[key]
return ok
}
@@ -7,18 +7,20 @@ import (
)
// 归档部件的完整性按 schema 版本判定:0.9.0 没有 wiki_log_entries,
// 0.7.1 缺了它就是残包。这里直接对 manifest 编码做判定,不依赖数据库。
// 但必须有编辑历史两表;0.7.1 没有两表、缺 wiki_log_entries 就是残包。
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{
legacyParts := []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"),
}
v090Parts := append(append([]Part{}, legacyParts...),
part("database", "chunk_revisions"), part("wiki", "wiki_page_revisions"))
manifest := func(version int, weknora string, parts []Part) Manifest {
return Manifest{
ValidationPolicy: ArtifactAcceptancePolicy,
@@ -36,23 +38,30 @@ func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
}
}
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(134, "v0.9.0", v090Parts)); err != nil {
t.Fatalf("0.9.0 manifest must be complete without wiki_log_entries: %v", err)
}
if _, err := encodeManifest(manifest(74, "v0.7.1", parts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
if _, err := encodeManifest(manifest(137, "v0.9.1", v090Parts)); err != nil {
t.Fatalf("0.9.1 must share the 0.9.0 part set: %v", err)
}
if _, err := encodeManifest(manifest(134, "v0.9.0", legacyParts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
t.Fatalf("0.9.0 manifest missing revision parts must be refused, got %v", err)
}
if _, err := encodeManifest(manifest(74, "v0.7.1", legacyParts)); 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 {
legacyWithLog := append(append([]Part{}, legacyParts...), part("wiki", "wiki_log_entries"))
if _, err := encodeManifest(manifest(74, "v0.7.1", legacyWithLog)); 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 {
v090WithLog := append(append([]Part{}, v090Parts...), part("wiki", "wiki_log_entries"))
if _, err := encodeManifest(manifest(134, "v0.9.0", v090WithLog)); 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 {
if _, err := encodeManifest(manifest(74, "v0.9.0", legacyWithLog)); err == nil {
t.Fatal("version string and profile version must agree")
}
if _, err := encodeManifest(manifest(135, "v0.9.0", parts)); err == nil {
if _, err := encodeManifest(manifest(135, "v0.9.0", v090Parts)); err == nil {
t.Fatal("unknown schema version must be refused")
}
}
+3 -4
View File
@@ -306,11 +306,10 @@ func (provider *RealProvider) Services(ctx context.Context) []governance.Service
health = append(health, provider.weKnoraProbe(ctx, now))
health = append(health, provider.productionWeKnoraProbe(ctx, now))
health = append(health, provider.httpProbe(ctx, "mineru", "MinerU", provider.minerUBaseURL, now))
// Not-applicable dependencies stay explicit (embedding/llm managed by
// WeKnora, redis/mq/oss not deployed).
// Not-applicable dependencies stay explicit (redis/mq/oss not deployed).
// Embedding/LLM are managed inside WeKnora and are not platform services;
// listing them here produced two permanent "unknown" cards on the page.
health = append(health,
provider.track(classify("embedding", "Embedding模型", false, false, ProbeOutcome{ObservedAt: now})),
provider.track(classify("llm", "LLM模型", false, false, ProbeOutcome{ObservedAt: now})),
provider.track(classify("redis", "Redis / MQ", false, false, ProbeOutcome{ObservedAt: now})),
provider.track(classify("oss", "OSS", false, false, ProbeOutcome{ObservedAt: now})),
)
@@ -59,11 +59,18 @@ func TestRealServicesHealthMatrix(t *testing.T) {
if byKey["weknora-production/r"] != ReadNotConfigured || byKey["weknora-production/l"] != LiveUnknown {
t.Fatalf("unconfigured production endpoint = %v/%v", byKey["weknora-production/l"], byKey["weknora-production/r"])
}
for _, key := range []string{"redis", "oss", "embedding", "llm"} {
for _, key := range []string{"redis", "oss"} {
if byKey[key+"/r"] != ReadNotApplicable || byKey[key+"/l"] != LiveUnknown {
t.Fatalf("not-deployed %s = %v/%v", key, byKey[key+"/l"], byKey[key+"/r"])
}
}
// Embedding/LLM belong to WeKnora; the platform must not render them as
// permanent unknown cards (requirement §8).
for _, key := range []string{"embedding", "llm"} {
if _, ok := byKey[key+"/r"]; ok {
t.Fatalf("platform health still lists %s", key)
}
}
// Readiness must be blocked ONLY by configured+deployed failures: worker.
ok, blocked := overallReadiness(health)
if ok || len(blocked) != 1 || blocked[0] != "worker" {
+16 -7
View File
@@ -54,6 +54,13 @@ type RealProviderConfig struct {
// same judgement the WeKnora client uses, so a card can never say 「可达」
// while the client refuses that URL.
AllowPrivateHTTP bool
// RuntimeQueues is the optional platform-level read-only queue projection.
// Nil or an error leaves WeKnoraQueues null; the page must not render 0.
RuntimeQueues QueueReader
}
type QueueReader interface {
Queues(context.Context) (*governance.WeKnoraQueueSummary, error)
}
type RealProvider struct {
@@ -68,6 +75,7 @@ type RealProvider struct {
weknoraReadiness func(ctx context.Context) (string, error)
workerStaleAfter time.Duration
allowPrivateHTTP bool
runtimeQueues QueueReader
health *healthTracker
}
@@ -108,7 +116,7 @@ func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
if stale <= 0 {
stale = time.Minute
}
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, allowPrivateHTTP: config.AllowPrivateHTTP, health: newHealthTracker()}, nil
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, allowPrivateHTTP: config.AllowPrivateHTTP, runtimeQueues: config.RuntimeQueues, health: newHealthTracker()}, nil
}
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
@@ -120,12 +128,15 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
overview.Services = append(overview.Services,
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.resolveTestWeKnoraBaseURL(ctx), now),
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.resolveProductionWeKnoraBaseURL(ctx), now),
governance.MonitorService{Key: "embedding", Name: "Embedding模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
governance.MonitorService{Key: "llm", Name: "LLM模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
provider.httpHealth(ctx, "mineru", "MinerU", provider.minerUBaseURL, now),
governance.MonitorService{Key: "redis", Name: "Redis / MQ", State: "unknown", Detail: "未部署;任务由PostgreSQL持久队列承载", ObservedAt: now},
governance.MonitorService{Key: "oss", Name: "OSS", State: "unknown", Detail: "未配置独立健康探测", ObservedAt: now},
)
if provider.runtimeQueues != nil {
if queues, queueErr := provider.runtimeQueues.Queues(ctx); queueErr == nil {
overview.WeKnoraQueues = queues
}
}
rows, err := provider.db.Query(ctx, `SELECT p.test_kb_id,
CASE WHEN COUNT(DISTINCT p.target_scope)=1 THEN MIN(p.target_scope) ELSE 'mixed' END,
COUNT(*) FILTER (WHERE p.superseded_at IS NULL)::integer,
@@ -144,15 +155,13 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
-- “是否发布到生产”(unpublished/disabling/disabled/failed),全仓没有任何代码写过 'enabled',
-- 所以这条车道恒为 0 —— 2026-10-10 界面验收实测:把已入库的文件改成“禁止导入”后
-- 车道仍显示 0,界面承诺的“仍在知识库里的文件会出现在这里”不成立。
COUNT(*) FILTER (WHERE p.superseded_at IS NULL AND p.knowledge_id<>''
AND p.processing_state='completed'
AND p.retrieval_state NOT IN ('disabling','disabled')
AND item.policy_state='blocked')::integer,
COUNT(removal_candidate.publication_id)::integer,
COUNT(*) FILTER (WHERE p.superseded_at IS NULL AND p.processing_state='planned'
AND item.policy_state='blocked')::integer
FROM test_publications p
JOIN source_item_versions version ON version.id=p.source_item_version_id
JOIN source_items item ON item.id=version.source_item_id
LEFT JOIN removal_candidates removal_candidate ON removal_candidate.publication_id=p.id
GROUP BY p.test_kb_id
ORDER BY p.test_kb_id`)
if err != nil {
@@ -0,0 +1,61 @@
package monitoring
import (
"context"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/platform/postgres"
)
// TestOverviewRemovalDemandAndSharedViewAgree freezes the T6 requirement that
// R6 and /monitor/overview read the same predicate. The old lane went
// permanently zero because two hand-maintained SQL predicates drifted.
func TestOverviewRemovalDemandAndSharedViewAgree(t *testing.T) {
ctx := context.Background()
pool, err := pgxpool.New(ctx, isolatedMetricsURL(t))
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err := postgres.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.Fatal(err)
}
}
exec(`INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-recon-view','dingtalk','对账视图用例',TRUE)`)
exec(`INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,policy_state)
VALUES('si-recon-view','conn-recon-view','recon.md',repeat('b',64),'对账视图','file','blocked')`)
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-recon-view','si-recon-view','r1','verified')`)
// test_publications is unique on (source_item_version_id,test_kb_id): a second
// publication in the same KB must point at its own version, not reuse r1.
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-recon-removing','si-recon-view','r2','verified')`)
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
VALUES('pub-recon-view','sv-recon-view','kb-recon-view','doc-recon-view','uploaded','completed','unpublished')`)
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
VALUES('pub-recon-removing','sv-recon-removing','kb-recon-view','doc-recon-removing','uploaded','completed','disabling')`)
provider, err := NewRealProvider(RealProviderConfig{DB: metricsPool{pool: pool}})
if err != nil {
t.Fatal(err)
}
overview, err := provider.Overview(ctx)
if err != nil {
t.Fatal(err)
}
if len(overview.KnowledgeBases) != 1 || overview.KnowledgeBases[0].NeedsRemoval != 1 {
t.Fatalf("overview = %#v", overview.KnowledgeBases)
}
var visible int
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::integer FROM removal_candidates WHERE test_kb_id='kb-recon-view'`).Scan(&visible); err != nil {
t.Fatal(err)
}
if visible != overview.KnowledgeBases[0].NeedsRemoval {
t.Fatalf("view=%d overview=%d", visible, overview.KnowledgeBases[0].NeedsRemoval)
}
}
-2
View File
@@ -24,8 +24,6 @@ func (provider *SimulationProvider) Overview(context.Context) (governance.Monito
Host: governance.MonitorHost{CPUPercent: 42, MemoryUsedBytes: 19971597926, MemoryTotalBytes: 34359738368, DiskUsedBytes: 128849018880, DiskTotalBytes: 536870912000, GPUState: "unknown", GPUDetail: "未接入真实GPU监控", Simulated: true},
Services: []governance.MonitorService{
{Key: "weknora", Name: "WeKnora API", State: "healthy", Detail: "模拟连接正常", LatencyMS: 86, ObservedAt: now, Simulated: true},
{Key: "embedding", Name: "Embedding模型", State: "healthy", Detail: "模拟探测通过", LatencyMS: 142, ObservedAt: now, Simulated: true},
{Key: "llm", Name: "LLM模型", State: "healthy", Detail: "模拟探测通过", LatencyMS: 318, ObservedAt: now, Simulated: true},
{Key: "mineru", Name: "MinerU", State: "healthy", Detail: "模拟处理中2,队列5", LatencyMS: 24, ObservedAt: now, Simulated: true},
{Key: "postgres", Name: "PostgreSQL", State: "unknown", Detail: "未接入真实监控", ObservedAt: now, Simulated: true},
{Key: "redis", Name: "Redis / MQ", State: "unknown", Detail: "未接入真实监控", ObservedAt: now, Simulated: true},
+1 -1
View File
@@ -19,7 +19,7 @@ func TestSimulationProviderLabelsEveryValueAndReconcilesKnowledgeCounts(t *testi
if overview.Host.DiskTotalBytes <= 0 || overview.Host.DiskUsedBytes <= 0 || overview.Host.GPUState != "unknown" || overview.Host.GPUDetail != "未接入真实GPU监控" {
t.Fatalf("host resources=%#v", overview.Host)
}
requiredServices := map[string]bool{"weknora": false, "mineru": false, "postgres": false, "redis": false, "oss": false, "embedding": false, "llm": false}
requiredServices := map[string]bool{"weknora": false, "mineru": false, "postgres": false, "redis": false, "oss": false}
for _, service := range overview.Services {
if _, ok := requiredServices[service.Key]; ok {
requiredServices[service.Key] = true
@@ -0,0 +1,3 @@
ALTER TABLE weknora_environment_binding_history
DROP COLUMN IF EXISTS source_origin,
DROP COLUMN IF EXISTS source_address;
@@ -0,0 +1,6 @@
-- 「知识库绑定」保存审计需要回答“从哪个地址录入的”:管理员可能在非 HTTPS
-- 控制台录入明文密钥,事后只能靠这条记录还原当时的访问入口。来源地址只做
-- 审计,不参与任何放行/拒绝判定;空串表示无法可靠解析,不用猜测值填充。
ALTER TABLE weknora_environment_binding_history
ADD COLUMN IF NOT EXISTS source_address TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS source_origin TEXT NOT NULL DEFAULT '';
@@ -0,0 +1,5 @@
DROP VIEW IF EXISTS removal_candidates;
DROP TABLE IF EXISTS reconciliation_finding_actions;
DROP TABLE IF EXISTS reconciliation_findings;
DROP TABLE IF EXISTS reconciliation_runs;
ALTER TABLE test_publications DROP COLUMN IF EXISTS upload_md5;
@@ -0,0 +1,119 @@
-- T6 一期导入对账:批次、差异、处置审计与上传 MD5。
-- 只新增,不改台账既有状态语义;findings 可按 run 整批清理,actions 永久保留。
ALTER TABLE test_publications
ADD COLUMN IF NOT EXISTS upload_md5 CHAR(32) NOT NULL DEFAULT ''
CHECK (upload_md5 = '' OR upload_md5 ~ '^[0-9a-f]{32}$');
CREATE TABLE IF NOT EXISTS reconciliation_runs (
id VARCHAR(36) PRIMARY KEY,
test_kb_id VARCHAR(255) NOT NULL,
state VARCHAR(16) NOT NULL DEFAULT 'running'
CHECK (state IN ('running', 'succeeded', 'failed')),
trigger VARCHAR(16) NOT NULL
CHECK (trigger IN ('schedule', 'manual')),
started_at TIMESTAMPTZ NOT NULL,
finished_at TIMESTAMPTZ,
ledger_count INTEGER NOT NULL DEFAULT 0 CHECK (ledger_count >= 0),
kb_count INTEGER NOT NULL DEFAULT 0 CHECK (kb_count >= 0),
counts JSONB NOT NULL DEFAULT '{}'::jsonb
CHECK (jsonb_typeof(counts) = 'object'),
previous_counts JSONB
CHECK (previous_counts IS NULL OR jsonb_typeof(previous_counts) = 'object'),
window_overlapped BOOLEAN NOT NULL DEFAULT FALSE,
error_code VARCHAR(64) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- One running batch per test knowledge base. The application 409 is only a
-- friendly hint; this index is the real concurrency guard.
CREATE UNIQUE INDEX IF NOT EXISTS reconciliation_runs_one_running
ON reconciliation_runs (test_kb_id) WHERE state = 'running';
CREATE INDEX IF NOT EXISTS idx_reconciliation_runs_started
ON reconciliation_runs (started_at DESC, id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_runs_kb_started
ON reconciliation_runs (test_kb_id, started_at DESC);
CREATE TABLE IF NOT EXISTS reconciliation_findings (
id VARCHAR(36) PRIMARY KEY,
run_id VARCHAR(36) NOT NULL
REFERENCES reconciliation_runs(id) ON DELETE CASCADE,
finding_type VARCHAR(2) NOT NULL
CHECK (finding_type IN ('R1','R2','R3','R4','R5','R6','R7','R8')),
publication_id VARCHAR(36) NOT NULL DEFAULT '',
knowledge_id VARCHAR(255) NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
path TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL DEFAULT '',
target_scope VARCHAR(16) NOT NULL DEFAULT '',
ledger_state VARCHAR(20) NOT NULL DEFAULT '',
weknora_parse_status VARCHAR(32) NOT NULL DEFAULT '',
normalized_state VARCHAR(32) NOT NULL DEFAULT '',
ledger_sha256 CHAR(64) NOT NULL DEFAULT '',
declared_sha256 CHAR(64) NOT NULL DEFAULT '',
weknora_file_md5 CHAR(32) NOT NULL DEFAULT '',
evidence_level VARCHAR(16) NOT NULL DEFAULT 'none'
CHECK (evidence_level IN ('independent','declared_only','none')),
confirmation_state VARCHAR(16) NOT NULL DEFAULT 'confirmed'
CHECK (confirmation_state IN ('confirmed','pending')),
detail TEXT NOT NULL DEFAULT '',
suggested_action VARCHAR(32) NOT NULL DEFAULT 'none'
CHECK (suggested_action IN ('requeue_upload','remove_from_test','writeback_state','enter_removal','none')),
action_state VARCHAR(16) NOT NULL DEFAULT 'open'
CHECK (action_state IN ('open','done')),
weknora_url TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (run_id, finding_type, publication_id, knowledge_id)
);
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_run
ON reconciliation_findings (run_id, finding_type, id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_publication
ON reconciliation_findings (publication_id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_knowledge
ON reconciliation_findings (knowledge_id);
-- Durable action audit. Deliberedly not FK-bound to findings: findings are
-- deleted by retention, the audit is not.
CREATE TABLE IF NOT EXISTS reconciliation_finding_actions (
id VARCHAR(36) PRIMARY KEY,
finding_id VARCHAR(36) NOT NULL,
run_id VARCHAR(36) NOT NULL,
publication_id VARCHAR(36) NOT NULL DEFAULT '',
knowledge_id VARCHAR(255) NOT NULL DEFAULT '',
action VARCHAR(32) NOT NULL
CHECK (action IN ('writeback','requeue','remove')),
actor_ref VARCHAR(128) NOT NULL DEFAULT '',
outcome VARCHAR(32) NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_reconciliation_actions_finding
ON reconciliation_finding_actions (finding_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_reconciliation_actions_publication
ON reconciliation_finding_actions (publication_id, created_at DESC);
-- R6 and /monitor/overview must never disagree about "需下架": both read this
-- view. The 2026-10-10 acceptance found the old lane permanently zero because
-- two different predicates were maintained by hand.
CREATE OR REPLACE VIEW removal_candidates AS
SELECT publication.id AS publication_id,
publication.test_kb_id,
publication.knowledge_id,
publication.target_scope,
version.id AS source_item_version_id,
version.source_item_id,
item.title,
item.normalized_path,
item.source_connection_id,
connection.name AS source_name
FROM test_publications publication
JOIN source_item_versions version ON version.id = publication.source_item_version_id
JOIN source_items item ON item.id = version.source_item_id
JOIN source_connections connection ON connection.id = item.source_connection_id
WHERE publication.superseded_at IS NULL
AND publication.knowledge_id <> ''
AND publication.processing_state = 'completed'
AND publication.retrieval_state NOT IN ('disabling', 'disabled')
AND item.policy_state = 'blocked';
+17 -2
View File
@@ -11,8 +11,23 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 82 {
t.Fatalf("migration count = %d, want 82", len(migrations))
if len(migrations) != 84 {
t.Fatalf("migration count = %d, want 84", len(migrations))
}
// 84 是导入对账:台账 upload_md5、runs/findings/actions 与共享需下架视图。
if reconciliation := migrations[83]; reconciliation.Version != 84 ||
!strings.Contains(reconciliation.UpSQL, "CREATE TABLE IF NOT EXISTS reconciliation_runs") ||
!strings.Contains(reconciliation.UpSQL, "CREATE OR REPLACE VIEW removal_candidates") ||
!strings.Contains(reconciliation.UpSQL, "upload_md5") ||
!strings.Contains(reconciliation.DownSQL, "DROP VIEW IF EXISTS removal_candidates") {
t.Fatalf("migration 84 = %#v", reconciliation)
}
// 83 是密钥保存审计的来源列:只追加取证字段,来源解析不出时留空。
if source := migrations[82]; source.Version != 83 ||
!strings.Contains(source.UpSQL, "source_address") ||
!strings.Contains(source.UpSQL, "source_origin") ||
!strings.Contains(source.DownSQL, "DROP COLUMN IF EXISTS source_address") {
t.Fatalf("migration 83 = %#v", source)
}
// 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
// 实际实例身份;克隆实例同名/同 ID 不能冒充。
+16 -11
View File
@@ -28,15 +28,20 @@ type MonitorTask struct {
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"`
DocumentID string `json:"document_id"`
// WeKnoraURL is the console link for this row's target knowledge base. The
// handler fills it from the effective test endpoint so the detail drawer can
// offer the same jump link as a reconciliation finding; empty = not configured.
WeKnoraURL string `json:"weknora_url"`
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"`
@@ -124,7 +129,7 @@ const monitorTasksCTE = `WITH history_publications AS (
ELSE 'waiting' END AS stage
FROM base
), projected AS (
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,
SELECT id,title,path,parent_node_id,node_id,source_id,source_name,target_scope,target_kb,knowledge_id AS document_id,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'
@@ -144,7 +149,7 @@ const monitorTasksCTE = `WITH history_publications AS (
SELECT * FROM projected WHERE ($1='' OR strpos(lower(title || ' ' || path),lower($1))>0)
AND ($2='' OR source_id=$2) AND ($3='' OR target_scope=$3) AND ($4='' OR action=$4)
AND ($5='' OR ($5='active' AND status NOT IN ('completed','cancelled')) OR status=$5)
AND ($6='' OR stage=$6) AND ($7='' OR id=$7) AND ($10='' OR target_kb=$10)
AND ($6='' OR stage=$6 OR ($6='weknora' AND stage IN ('parsing','indexing'))) AND ($7='' OR id=$7) AND ($10='' OR target_kb=$10)
AND ($11='' OR updated_at>=NULLIF($11,'')::timestamptz) AND ($12='' OR updated_at<=NULLIF($12,'')::timestamptz)
) `
@@ -128,4 +128,23 @@ func TestMonitorTasksUnifiedPaginationIntegration(t *testing.T) {
exec(`UPDATE jobs SET state='retry' WHERE id='mt-fetch-job'`)
check("retrying", 0)
})
t.Run("weknora stage facet merges parsing and indexing in SQL", func(t *testing.T) {
insertReviewFixture(t, ctx, pool, 8, "mt-merge-parse", now)
insertReviewFixture(t, ctx, pool, 9, "mt-merge-index", now)
exec(`UPDATE test_publications SET processing_state='processing' WHERE id='mt-merge-parse'`)
exec(`UPDATE test_publications SET processing_state='finalizing' WHERE id='mt-merge-index'`)
query := MonitorTaskFilter{Search: "Synthetic mt-merge", Limit: 20}
merged, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "weknora", Limit: query.Limit})
if err != nil || merged.Total != 2 {
t.Fatalf("weknora facet: %#v %v", merged, err)
}
parsing, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "parsing", Limit: query.Limit})
if err != nil || parsing.Total != 1 || parsing.Items[0].ID != "mt-merge-parse" {
t.Fatalf("parsing facet: %#v %v", parsing, err)
}
indexing, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "indexing", Limit: query.Limit})
if err != nil || indexing.Total != 1 || indexing.Items[0].ID != "mt-merge-index" {
t.Fatalf("indexing facet: %#v %v", indexing, err)
}
})
}
@@ -0,0 +1,114 @@
package postgres
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
)
func TestReconciliationRunUniquenessStaleAndRetentionIntegration(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)
}
store := NewStore(pool)
now := time.Date(2026, 12, 1, 2, 0, 0, 0, time.UTC)
first, err := store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
ID: "rec-first", KBID: "kb-unique", State: "running", Trigger: "manual", StartedAt: now,
Counts: governance.ReconciliationCounts{},
}, now)
if err != nil {
t.Fatal(err)
}
if _, err := store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
ID: "rec-second", KBID: "kb-unique", State: "running", Trigger: "manual", StartedAt: now,
Counts: governance.ReconciliationCounts{},
}, now); !errors.Is(err, ErrReconciliationRunInProgress) {
t.Fatalf("second claim err=%v", err)
}
reaped, err := store.ReapStaleReconciliationRuns(ctx, now.Add(7*time.Hour), 6*time.Hour)
if err != nil || reaped != 1 {
t.Fatalf("reaped=%d err=%v", reaped, err)
}
second, err := store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
ID: "rec-second", KBID: "kb-unique", State: "running", Trigger: "manual", StartedAt: now.Add(7 * time.Hour),
Counts: governance.ReconciliationCounts{},
}, now.Add(7*time.Hour))
if err != nil {
t.Fatal(err)
}
finishedAt := now.Add(8 * time.Hour)
second.FinishedAt = &finishedAt
second.Counts = governance.ReconciliationCounts{"R1": 1}
if err := store.CompleteReconciliationRun(ctx, second, []governance.ReconciliationFinding{{
ID: "finding-second", RunID: second.ID, Type: "R1", DocumentID: "doc",
Title: "t", LedgerState: "completed", EvidenceLevel: "none", SuggestedAction: "requeue_upload",
}}); err != nil {
t.Fatal(err)
}
if err := store.CleanupReconciliationFindings(ctx, now.Add(9*time.Hour), 1, 90*24*time.Hour); err != nil {
t.Fatal(err)
}
var count int
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_findings WHERE run_id=$1`, first.ID).Scan(&count); err != nil || count != 0 {
t.Fatalf("old findings=%d err=%v", count, err)
}
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_findings WHERE run_id=$1`, second.ID).Scan(&count); err != nil || count != 1 {
t.Fatalf("new findings=%d err=%v", count, err)
}
}
// TestScheduledReconciliationClaimsOncePerDayAfterFailure freezes the operator
// expectation "每天最多一批": a failed scheduled batch keeps the day's slot so a
// transient upstream error cannot spawn a new batch on every scheduler tick.
// A retry after a failure is an explicit manual trigger.
func TestScheduledReconciliationClaimsOncePerDayAfterFailure(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)
}
store := NewStore(pool)
dayStart := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)
run := func(id string, started time.Time) governance.ReconciliationRun {
return governance.ReconciliationRun{ID: id, KBID: "kb-sched", State: "running", Trigger: "schedule",
StartedAt: started, Counts: governance.ReconciliationCounts{}}
}
first, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-1", dayStart.Add(2*time.Hour)), dayStart, dayStart.Add(2*time.Hour))
if err != nil || !claimed {
t.Fatalf("first claim claimed=%t err=%v", claimed, err)
}
if err := store.FailReconciliationRun(ctx, first.ID, "remote_scan_failed", dayStart.Add(2*time.Minute)); err != nil {
t.Fatal(err)
}
if _, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-2", dayStart.Add(3*time.Minute)), dayStart, dayStart.Add(3*time.Minute)); err != nil || claimed {
t.Fatalf("same-day reclaim after failure claimed=%t err=%v", claimed, err)
}
nextDay := dayStart.Add(24 * time.Hour)
if _, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-3", nextDay.Add(2*time.Hour)), nextDay, nextDay.Add(2*time.Hour)); err != nil || !claimed {
t.Fatalf("next-day claim claimed=%t err=%v", claimed, err)
}
}
@@ -0,0 +1,611 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/governance"
)
var (
ErrReconciliationRunInProgress = errors.New("reconciliation run already in progress")
ErrReconciliationNotFound = errors.New("reconciliation record not found")
ErrReconciliationConflict = errors.New("reconciliation state or identity changed")
ErrReconciliationNotRunning = errors.New("reconciliation run is not running")
)
const reconciliationRunColumns = `id,test_kb_id,state,trigger,started_at,finished_at,ledger_count,kb_count,counts,previous_counts,window_overlapped,error_code`
func scanReconciliationRun(row rowScanner) (governance.ReconciliationRun, error) {
var run governance.ReconciliationRun
var counts, previous []byte
if err := row.Scan(&run.ID, &run.KBID, &run.State, &run.Trigger, &run.StartedAt, &run.FinishedAt,
&run.LedgerCount, &run.KBCount, &counts, &previous, &run.WindowOverlapped, &run.ErrorCode); err != nil {
return governance.ReconciliationRun{}, err
}
if len(counts) > 0 {
if err := json.Unmarshal(counts, &run.Counts); err != nil {
return governance.ReconciliationRun{}, fmt.Errorf("decode reconciliation counts: %w", err)
}
}
run.Counts = run.Counts.Normalize()
if len(previous) > 0 {
var value governance.ReconciliationCounts
if err := json.Unmarshal(previous, &value); err != nil {
return governance.ReconciliationRun{}, fmt.Errorf("decode previous reconciliation counts: %w", err)
}
run.PreviousCounts = value.Normalize()
}
return run, nil
}
// ClaimReconciliationRun inserts a running batch. The partial unique index is
// the concurrency authority; a friendly 409 is produced from ErrRunInProgress.
func (s *Store) ClaimReconciliationRun(ctx context.Context, run governance.ReconciliationRun, now time.Time) (governance.ReconciliationRun, error) {
counts, err := json.Marshal(run.Counts.Normalize())
if err != nil {
return governance.ReconciliationRun{}, err
}
row := s.db.QueryRow(ctx, `INSERT INTO reconciliation_runs
(id,test_kb_id,state,trigger,started_at,counts,created_at)
VALUES($1,$2,'running',$3,$4,$5::jsonb,$6)
ON CONFLICT DO NOTHING
RETURNING `+reconciliationRunColumns,
run.ID, run.KBID, run.Trigger, run.StartedAt, counts, now)
claimed, err := scanReconciliationRun(row)
if errors.Is(err, pgx.ErrNoRows) {
return governance.ReconciliationRun{}, ErrReconciliationRunInProgress
}
if err != nil {
return governance.ReconciliationRun{}, fmt.Errorf("claim reconciliation run: %w", err)
}
return claimed, nil
}
func (s *Store) ClaimScheduledReconciliationRun(ctx context.Context, run governance.ReconciliationRun, since, now time.Time) (governance.ReconciliationRun, bool, error) {
counts, err := json.Marshal(run.Counts.Normalize())
if err != nil {
return governance.ReconciliationRun{}, false, err
}
// The KB id is passed twice on purpose: PostgreSQL deduces varchar(255) for
// the INSERT target and varchar for the comparison, and one parameter used in
// both positions fails with 42P08 "inconsistent types deduced".
row := s.db.QueryRow(ctx, `INSERT INTO reconciliation_runs
(id,test_kb_id,state,trigger,started_at,counts,created_at)
SELECT $1,$2,'running','schedule',$3,$4::jsonb,$5
WHERE NOT EXISTS(
SELECT 1 FROM reconciliation_runs
WHERE test_kb_id=$7 AND trigger='schedule' AND state IN ('running','succeeded','failed') AND started_at >= $6
)
ON CONFLICT DO NOTHING
RETURNING `+reconciliationRunColumns,
run.ID, run.KBID, run.StartedAt, counts, now, since, run.KBID)
claimed, err := scanReconciliationRun(row)
if errors.Is(err, pgx.ErrNoRows) {
return governance.ReconciliationRun{}, false, nil
}
if err != nil {
return governance.ReconciliationRun{}, false, fmt.Errorf("claim scheduled reconciliation run: %w", err)
}
return claimed, true, nil
}
func (s *Store) ReapStaleReconciliationRuns(ctx context.Context, now time.Time, threshold time.Duration) (int64, error) {
if threshold <= 0 {
return 0, nil
}
tag, err := s.db.Exec(ctx, `UPDATE reconciliation_runs
SET state='failed',finished_at=$1,error_code='stale_timeout'
WHERE state='running' AND started_at < $2`, now, now.Add(-threshold))
if err != nil {
return 0, fmt.Errorf("reap stale reconciliation runs: %w", err)
}
return tag.RowsAffected(), nil
}
func (s *Store) LoadReconciliationRun(ctx context.Context, id string) (governance.ReconciliationRun, error) {
row := s.db.QueryRow(ctx, `SELECT `+reconciliationRunColumns+` FROM reconciliation_runs WHERE id=$1`, id)
run, err := scanReconciliationRun(row)
if errors.Is(err, pgx.ErrNoRows) {
return governance.ReconciliationRun{}, ErrReconciliationNotFound
}
if err != nil {
return governance.ReconciliationRun{}, fmt.Errorf("load reconciliation run: %w", err)
}
return run, nil
}
func (s *Store) ListReconciliationRuns(ctx context.Context, filter governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
page := governance.ReconciliationRunPage{Items: []governance.ReconciliationRun{}, Limit: filter.Limit, Offset: filter.Offset}
if err := s.db.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_runs WHERE ($1='' OR test_kb_id=$1)`, filter.KBID).Scan(&page.Total); err != nil {
return page, fmt.Errorf("count reconciliation runs: %w", err)
}
rows, err := s.db.Query(ctx, `SELECT `+reconciliationRunColumns+`
FROM reconciliation_runs WHERE ($1='' OR test_kb_id=$1)
ORDER BY started_at DESC,id DESC LIMIT $2 OFFSET $3`, filter.KBID, filter.Limit, filter.Offset)
if err != nil {
return page, fmt.Errorf("list reconciliation runs: %w", err)
}
defer rows.Close()
for rows.Next() {
run, err := scanReconciliationRun(rows)
if err != nil {
return page, fmt.Errorf("scan reconciliation run: %w", err)
}
page.Items = append(page.Items, run)
}
return page, rows.Err()
}
func (s *Store) LoadReconciliationLedger(ctx context.Context, kbID string) ([]governance.ReconciliationLedgerRow, error) {
rows, err := s.db.Query(ctx, `SELECT publication.id,publication.knowledge_id,publication.processing_state,
publication.retrieval_state,publication.target_scope,publication.processing_started_at,
publication.updated_at,publication.upload_md5,
item.id,item.title,COALESCE(NULLIF(item.normalized_path,''),''),connection.name,
item.policy_state,COALESCE(content.sha256,'')
FROM test_publications publication
JOIN source_item_versions version ON version.id=publication.source_item_version_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 content_objects content ON content.id=version.content_object_id
WHERE publication.test_kb_id=$1 AND publication.superseded_at IS NULL
ORDER BY publication.id`, kbID)
if err != nil {
return nil, fmt.Errorf("load reconciliation ledger: %w", err)
}
defer rows.Close()
out := make([]governance.ReconciliationLedgerRow, 0)
for rows.Next() {
var row governance.ReconciliationLedgerRow
if err := rows.Scan(&row.PublicationID, &row.KnowledgeID, &row.ProcessingState, &row.RetrievalState,
&row.TargetScope, &row.ProcessingStartedAt, &row.UpdatedAt, &row.UploadMD5,
&row.SourceItemID, &row.Title, &row.Path, &row.SourceName, &row.PolicyState, &row.SHA256); err != nil {
return nil, fmt.Errorf("scan reconciliation ledger: %w", err)
}
out = append(out, row)
}
return out, rows.Err()
}
func (s *Store) LoadPreviousReconciliationCounts(ctx context.Context, kbID string, before time.Time) (governance.ReconciliationCounts, bool, error) {
var raw []byte
err := s.db.QueryRow(ctx, `SELECT counts FROM reconciliation_runs
WHERE test_kb_id=$1 AND state='succeeded' AND started_at < $2
ORDER BY started_at DESC,id DESC LIMIT 1`, kbID, before).Scan(&raw)
if errors.Is(err, pgx.ErrNoRows) {
return nil, false, nil
}
if err != nil {
return nil, false, fmt.Errorf("load previous reconciliation counts: %w", err)
}
var counts governance.ReconciliationCounts
if err := json.Unmarshal(raw, &counts); err != nil {
return nil, false, fmt.Errorf("decode previous reconciliation counts: %w", err)
}
return counts.Normalize(), true, nil
}
func (s *Store) CompleteReconciliationRun(ctx context.Context, run governance.ReconciliationRun, findings []governance.ReconciliationFinding) error {
beginner, ok := s.db.(interface {
Begin(context.Context) (pgx.Tx, error)
})
if !ok {
return errors.New("reconciliation transactions are unavailable")
}
tx, err := beginner.Begin(ctx)
if err != nil {
return fmt.Errorf("begin reconciliation completion: %w", err)
}
defer tx.Rollback(ctx)
counts, err := json.Marshal(run.Counts.Normalize())
if err != nil {
return err
}
var previous any
if run.PreviousCounts != nil {
raw, err := json.Marshal(run.PreviousCounts.Normalize())
if err != nil {
return err
}
previous = raw
}
tag, err := tx.Exec(ctx, `UPDATE reconciliation_runs
SET state='succeeded',finished_at=$2,ledger_count=$3,kb_count=$4,counts=$5::jsonb,
previous_counts=$6::jsonb,window_overlapped=$7,error_code=''
WHERE id=$1 AND state='running'`, run.ID, run.FinishedAt, run.LedgerCount, run.KBCount, counts, previous, run.WindowOverlapped)
if err != nil {
return fmt.Errorf("complete reconciliation run: %w", err)
}
if tag.RowsAffected() != 1 {
return ErrReconciliationNotRunning
}
for _, finding := range findings {
// The column default only applies when the insert omits the column; the
// service always fills it, but direct callers may pass "" and must not
// violate the check constraint.
confirmation := finding.ConfirmationState
if confirmation == "" {
confirmation = "confirmed"
}
if _, err := tx.Exec(ctx, `INSERT INTO reconciliation_findings
(id,run_id,finding_type,publication_id,knowledge_id,title,path,source,target_scope,
ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,
weknora_url,created_at)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,'open',$20,$21)`,
finding.ID, finding.RunID, finding.Type, finding.PublicationID, finding.DocumentID,
finding.Title, finding.Path, finding.Source, finding.TargetScope, finding.LedgerState,
finding.WeKnoraParseState, finding.NormalizedState, finding.LedgerSHA256, finding.DeclaredSHA256,
finding.WeKnoraFileMD5, finding.EvidenceLevel, confirmation, finding.Detail,
finding.SuggestedAction, finding.WeKnoraURL, run.FinishedAt); err != nil {
return fmt.Errorf("insert reconciliation finding: %w", err)
}
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit reconciliation run: %w", err)
}
return nil
}
func (s *Store) FailReconciliationRun(ctx context.Context, runID, code string, finished time.Time) error {
_, err := s.db.Exec(ctx, `UPDATE reconciliation_runs
SET state='failed',finished_at=$2,error_code=$3
WHERE id=$1 AND state='running'`, runID, finished, code)
if err != nil {
return fmt.Errorf("fail reconciliation run: %w", err)
}
return nil
}
func (s *Store) CleanupReconciliationFindings(ctx context.Context, now time.Time, keepRuns int, maxAge time.Duration) error {
if keepRuns < 1 || maxAge <= 0 {
return nil
}
_, err := s.db.Exec(ctx, `DELETE FROM reconciliation_findings
WHERE run_id IN (
SELECT id FROM reconciliation_runs
WHERE started_at < $1
OR id NOT IN (
SELECT id FROM reconciliation_runs ORDER BY started_at DESC,id DESC LIMIT $2
)
)`, now.Add(-maxAge), keepRuns)
if err != nil {
return fmt.Errorf("cleanup reconciliation findings: %w", err)
}
return nil
}
func (s *Store) LibraryJobsActive(ctx context.Context) (bool, error) {
var active bool
if err := s.db.QueryRow(ctx, `SELECT EXISTS(
SELECT 1 FROM jobs WHERE type LIKE 'library.%' AND state IN ('pending','running','retry')
)`).Scan(&active); err != nil {
return false, fmt.Errorf("inspect library jobs: %w", err)
}
return active, nil
}
func (s *Store) ListReconciliationRemovalCandidates(ctx context.Context, kbID string) ([]governance.ReconciliationLedgerRow, error) {
rows, err := s.db.Query(ctx, `SELECT publication_id,knowledge_id,target_scope,
source_item_version_id,source_item_id,title,normalized_path,source_name
FROM removal_candidates WHERE test_kb_id=$1 ORDER BY publication_id`, kbID)
if err != nil {
return nil, fmt.Errorf("list removal candidates: %w", err)
}
defer rows.Close()
out := make([]governance.ReconciliationLedgerRow, 0)
for rows.Next() {
var row governance.ReconciliationLedgerRow
var versionID string
if err := rows.Scan(&row.PublicationID, &row.KnowledgeID, &row.TargetScope,
&versionID, &row.SourceItemID, &row.Title, &row.Path, &row.SourceName); err != nil {
return nil, fmt.Errorf("scan removal candidate: %w", err)
}
out = append(out, row)
}
return out, rows.Err()
}
const reconciliationFindingColumns = `id,run_id,finding_type,publication_id,knowledge_id,title,path,source,
target_scope,ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,weknora_url`
func scanReconciliationFinding(row rowScanner) (governance.ReconciliationFinding, error) {
var finding governance.ReconciliationFinding
if err := row.Scan(&finding.ID, &finding.RunID, &finding.Type, &finding.PublicationID, &finding.DocumentID,
&finding.Title, &finding.Path, &finding.Source, &finding.TargetScope, &finding.LedgerState,
&finding.WeKnoraParseState, &finding.NormalizedState, &finding.LedgerSHA256, &finding.DeclaredSHA256,
&finding.WeKnoraFileMD5, &finding.EvidenceLevel, &finding.ConfirmationState, &finding.Detail,
&finding.SuggestedAction, &finding.ActionState, &finding.WeKnoraURL); err != nil {
return governance.ReconciliationFinding{}, err
}
return finding, nil
}
func (s *Store) ListReconciliationFindings(ctx context.Context, filter governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
page := governance.ReconciliationFindingPage{Items: []governance.ReconciliationFinding{}, Limit: filter.Limit, Offset: filter.Offset}
if err := s.db.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_findings
WHERE run_id=$1 AND ($2='' OR finding_type=$2)
AND ($3='' OR strpos(lower(title || ' ' || path || ' ' || detail),lower($3))>0)`,
filter.RunID, filter.Type, filter.Query).Scan(&page.Total); err != nil {
return page, fmt.Errorf("count reconciliation findings: %w", err)
}
rows, err := s.db.Query(ctx, `SELECT `+reconciliationFindingColumns+`
FROM reconciliation_findings
WHERE run_id=$1 AND ($2='' OR finding_type=$2)
AND ($3='' OR strpos(lower(title || ' ' || path || ' ' || detail),lower($3))>0)
ORDER BY finding_type,publication_id,knowledge_id,id LIMIT $4 OFFSET $5`,
filter.RunID, filter.Type, filter.Query, filter.Limit, filter.Offset)
if err != nil {
return page, fmt.Errorf("list reconciliation findings: %w", err)
}
defer rows.Close()
for rows.Next() {
finding, err := scanReconciliationFinding(rows)
if err != nil {
return page, fmt.Errorf("scan reconciliation finding: %w", err)
}
page.Items = append(page.Items, finding)
}
return page, rows.Err()
}
func (s *Store) GetReconciliationFinding(ctx context.Context, id string) (governance.ReconciliationFinding, error) {
return getReconciliationFinding(ctx, s.db, id)
}
func getReconciliationFinding(ctx context.Context, queryer interface {
QueryRow(context.Context, string, ...any) pgx.Row
}, id string) (governance.ReconciliationFinding, error) {
row := queryer.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+` FROM reconciliation_findings WHERE id=$1`, id)
finding, err := scanReconciliationFinding(row)
if errors.Is(err, pgx.ErrNoRows) {
return governance.ReconciliationFinding{}, ErrReconciliationNotFound
}
if err != nil {
return governance.ReconciliationFinding{}, fmt.Errorf("load reconciliation finding: %w", err)
}
return finding, nil
}
func lockOpenReconciliationFinding(ctx context.Context, tx pgx.Tx, id string) error {
var state string
if err := tx.QueryRow(ctx, `SELECT action_state FROM reconciliation_findings WHERE id=$1 FOR UPDATE`, id).Scan(&state); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return ErrReconciliationNotFound
}
return fmt.Errorf("lock reconciliation finding: %w", err)
}
if state != "open" {
return ErrReconciliationConflict
}
return nil
}
func (s *Store) LoadReconciliationActionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
var view governance.ReconciliationActionView
var currentExists bool
row := s.db.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+`,
run.test_kb_id,run.started_at,
publication.id IS NOT NULL,
COALESCE(publication.processing_state,''),COALESCE(publication.knowledge_id,''),
COALESCE(publication.superseded_at IS NOT NULL,FALSE),COALESCE(publication.retrieval_state,''),
COALESCE(publication.target_scope,'')
FROM reconciliation_findings finding
JOIN reconciliation_runs run ON run.id=finding.run_id
LEFT JOIN test_publications publication ON publication.id=finding.publication_id
WHERE finding.id=$1`, findingID)
if err := row.Scan(&view.Finding.ID, &view.Finding.RunID, &view.Finding.Type, &view.Finding.PublicationID,
&view.Finding.DocumentID, &view.Finding.Title, &view.Finding.Path, &view.Finding.Source,
&view.Finding.TargetScope, &view.Finding.LedgerState, &view.Finding.WeKnoraParseState,
&view.Finding.NormalizedState, &view.Finding.LedgerSHA256, &view.Finding.DeclaredSHA256,
&view.Finding.WeKnoraFileMD5, &view.Finding.EvidenceLevel, &view.Finding.ConfirmationState,
&view.Finding.Detail, &view.Finding.SuggestedAction, &view.Finding.ActionState, &view.Finding.WeKnoraURL,
&view.TestKBID, &view.RunStartedAt, &currentExists, &view.CurrentProcessingState,
&view.CurrentKnowledgeID, &view.CurrentSuperseded, &view.CurrentRetrievalState,
&view.CurrentTargetScope); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return view, ErrReconciliationNotFound
}
return view, fmt.Errorf("load reconciliation action view: %w", err)
}
view.CurrentExists = currentExists
return view, nil
}
func (s *Store) ReconciliationOrphanStillUnowned(ctx context.Context, publicationID, knowledgeID string) (bool, error) {
var owned bool
if err := s.db.QueryRow(ctx, `SELECT EXISTS(
SELECT 1 FROM test_publications
WHERE superseded_at IS NULL AND (knowledge_id=$2 OR ($1<>'' AND id=$1))
)`, publicationID, knowledgeID).Scan(&owned); err != nil {
return false, fmt.Errorf("inspect orphan ownership: %w", err)
}
return !owned, nil
}
func (s *Store) WritebackReconciliationFinding(ctx context.Context, findingID, targetState, actor, reason string, now time.Time) (governance.ReconciliationFinding, error) {
beginner, ok := s.db.(interface {
Begin(context.Context) (pgx.Tx, error)
})
if !ok {
return governance.ReconciliationFinding{}, errors.New("reconciliation transactions are unavailable")
}
tx, err := beginner.Begin(ctx)
if err != nil {
return governance.ReconciliationFinding{}, err
}
defer tx.Rollback(ctx)
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
return governance.ReconciliationFinding{}, err
}
finding, err := getReconciliationFinding(ctx, tx, findingID)
if errors.Is(err, ErrReconciliationNotFound) {
return governance.ReconciliationFinding{}, err
}
if err != nil {
return governance.ReconciliationFinding{}, err
}
if finding.Type != "R5" || finding.ActionState != "open" {
return governance.ReconciliationFinding{}, ErrReconciliationConflict
}
var processingState string
if err := tx.QueryRow(ctx, `SELECT processing_state FROM test_publications
WHERE id=$1 AND superseded_at IS NULL FOR UPDATE`, finding.PublicationID).Scan(&processingState); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return governance.ReconciliationFinding{}, ErrReconciliationConflict
}
return governance.ReconciliationFinding{}, err
}
if processingState != finding.LedgerState {
return governance.ReconciliationFinding{}, ErrReconciliationConflict
}
if processingState != targetState {
if _, err := tx.Exec(ctx, `UPDATE test_publications SET processing_state=$2,updated_at=$3
WHERE id=$1 AND processing_state=$4`, finding.PublicationID, targetState, now, finding.LedgerState); err != nil {
return governance.ReconciliationFinding{}, err
}
if err := s.insertReconciliationActionTx(ctx, tx, finding, "writeback", actor, "started", reason, now); err != nil {
return governance.ReconciliationFinding{}, err
}
}
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
return governance.ReconciliationFinding{}, err
}
if err := tx.Commit(ctx); err != nil {
return governance.ReconciliationFinding{}, err
}
finding.ActionState = "done"
return finding, nil
}
func (s *Store) RequeueReconciliationPublication(ctx context.Context, findingID, expectedKnowledgeID, actor, reason string, now time.Time) (string, error) {
beginner, ok := s.db.(interface {
Begin(context.Context) (pgx.Tx, error)
})
if !ok {
return "", errors.New("reconciliation transactions are unavailable")
}
tx, err := beginner.Begin(ctx)
if err != nil {
return "", err
}
defer tx.Rollback(ctx)
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
return "", err
}
finding, err := getReconciliationFinding(ctx, tx, findingID)
if err != nil {
return "", err
}
if (finding.Type != "R1" && finding.Type != "R4") || finding.ActionState != "open" {
return "", ErrReconciliationConflict
}
var processingState, knowledgeID, targetScope, targetKB string
if err := tx.QueryRow(ctx, `SELECT processing_state,knowledge_id,target_scope,test_kb_id
FROM test_publications WHERE id=$1 AND superseded_at IS NULL FOR UPDATE`, finding.PublicationID).Scan(
&processingState, &knowledgeID, &targetScope, &targetKB); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return "", ErrReconciliationConflict
}
return "", err
}
if processingState != finding.LedgerState || knowledgeID != expectedKnowledgeID {
return "", ErrReconciliationConflict
}
tag, err := tx.Exec(ctx, `UPDATE test_publications SET
ingest_state='pending',processing_state='pending',knowledge_id='',poll_sequence=0,
last_remote_status='',last_remote_updated_at=NULL,last_observed_at=NULL,
processing_started_at=NULL,completed_at=NULL,stalled_at=NULL,last_error='',
upload_md5='',test_instance_url='',test_instance_tenant=0,
retry_count=retry_count+1,updated_at=$2
WHERE id=$1 AND knowledge_id=$3 AND processing_state=$4`,
finding.PublicationID, now, expectedKnowledgeID, finding.LedgerState)
if err != nil {
return "", fmt.Errorf("reset reconciliation publication: %w", err)
}
if tag.RowsAffected() != 1 {
return "", ErrReconciliationConflict
}
payload, err := json.Marshal(map[string]string{
"publication_id": finding.PublicationID,
"target_scope": targetScope,
"target_kb_id": targetKB,
})
if err != nil {
return "", err
}
jobID := orchestrationJobID("reconciliation.requeue", findingID)
tag, 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,'pending',0,$3,5,$4,$3,$3)
ON CONFLICT (idempotency_key) DO NOTHING`, jobID, payload, now, "reconciliation-requeue:"+findingID)
if err != nil {
return "", fmt.Errorf("enqueue reconciliation upload: %w", err)
}
if tag.RowsAffected() != 1 {
if err := tx.QueryRow(ctx, `SELECT id FROM jobs WHERE idempotency_key=$1`, "reconciliation-requeue:"+findingID).Scan(&jobID); err != nil {
return "", fmt.Errorf("reconciliation upload job missing: %w", err)
}
}
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
return "", err
}
if err := s.insertReconciliationActionTx(ctx, tx, finding, "requeue", actor, "started", reason, now); err != nil {
return "", err
}
if err := tx.Commit(ctx); err != nil {
return "", err
}
return jobID, nil
}
func (s *Store) MarkReconciliationOrphanRemoved(ctx context.Context, findingID, actor, reason string, now time.Time) error {
beginner, ok := s.db.(interface {
Begin(context.Context) (pgx.Tx, error)
})
if !ok {
return errors.New("reconciliation transactions are unavailable")
}
tx, err := beginner.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
return err
}
finding, err := getReconciliationFinding(ctx, tx, findingID)
if err != nil {
return err
}
if finding.Type != "R2" || finding.ActionState != "open" {
return ErrReconciliationConflict
}
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
return err
}
if err := s.insertReconciliationActionTx(ctx, tx, finding, "remove", actor, "started", reason, now); err != nil {
return err
}
return tx.Commit(ctx)
}
func (s *Store) insertReconciliationActionTx(ctx context.Context, tx pgx.Tx, finding governance.ReconciliationFinding, action, actor, outcome, detail string, now time.Time) error {
id, err := newOpaqueID("rca-")
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO reconciliation_finding_actions
(id,finding_id,run_id,publication_id,knowledge_id,action,actor_ref,outcome,detail,created_at)
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
id, finding.ID, finding.RunID, finding.PublicationID, finding.DocumentID, action, actor, outcome, detail, now)
if err != nil {
return fmt.Errorf("record reconciliation action: %w", err)
}
return nil
}
@@ -246,14 +246,15 @@ const recordUploadAndSchedulePollSQL = `
WITH updated AS (
UPDATE test_publications
SET knowledge_id = $2,
upload_md5 = $3,
ingest_state = 'uploaded',
processing_state = 'pending',
poll_sequence = 1,
last_remote_status = 'pending',
processing_started_at = COALESCE(processing_started_at, $3),
last_observed_at = $3,
processing_started_at = COALESCE(processing_started_at, $4),
last_observed_at = $4,
last_error = '',
updated_at = $3
updated_at = $4
WHERE id = $1
AND processing_state = 'pending'
AND (
@@ -622,7 +623,7 @@ func (s *Store) MarkUploading(ctx context.Context, publicationID, instanceURL st
return nil
}
func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID, knowledgeID string, now, nextAt time.Time) (int, error) {
func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID, knowledgeID, uploadMD5 string, now, nextAt time.Time) (int, error) {
payload, err := json.Marshal(struct {
PublicationID string `json:"publication_id"`
Sequence int `json:"sequence"`
@@ -636,6 +637,7 @@ func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID,
recordUploadAndSchedulePollSQL,
publicationID,
knowledgeID,
strings.ToLower(strings.TrimSpace(uploadMD5)),
now,
payload,
0,
@@ -67,13 +67,13 @@ func TestPublicationOrchestrationIsAtomicAndRejectsStaleTransitions(t *testing.T
if err := store.MarkUploading(ctx, "publication-1", "", 0, now); err != nil {
t.Fatal(err)
}
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", "", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
t.Fatalf("record upload = %d, %v", sequence, err)
}
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", "", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
t.Fatalf("replay upload = %d, %v", sequence, err)
}
if _, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-conflict", now, now.Add(10*time.Second)); !errors.Is(err, ErrPublicationStateConflict) {
if _, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-conflict", "", now, now.Add(10*time.Second)); !errors.Is(err, ErrPublicationStateConflict) {
t.Fatalf("conflicting knowledge error = %v", err)
}
@@ -52,7 +52,7 @@ func TestRecordUploadAndSchedulePollIsAtomicAndIdempotent(t *testing.T) {
db := &recordingDB{row: sequenceRow{sequence: 1}}
now := time.Date(2026, time.September, 4, 2, 5, 0, 0, time.UTC)
nextAt := now.Add(10 * time.Second)
sequence, err := NewStore(db).RecordUploadAndSchedulePoll(context.Background(), "publication-1", "knowledge-1", now, nextAt)
sequence, err := NewStore(db).RecordUploadAndSchedulePoll(context.Background(), "publication-1", "knowledge-1", "", now, nextAt)
if err != nil {
t.Fatalf("RecordUploadAndSchedulePoll() error = %v", err)
}
@@ -64,14 +64,14 @@ func TestRecordUploadAndSchedulePollIsAtomicAndIdempotent(t *testing.T) {
if updateAt < 0 || insertAt < 0 || updateAt >= insertAt {
t.Fatalf("atomic SQL missing ordered update/insert: %q", recordUploadAndSchedulePollSQL)
}
if db.queryRowSQL != recordUploadAndSchedulePollSQL || len(db.queryRowArgs) != 7 {
if db.queryRowSQL != recordUploadAndSchedulePollSQL || len(db.queryRowArgs) != 8 {
t.Fatalf("query = %q %#v", db.queryRowSQL, db.queryRowArgs)
}
if !strings.Contains(recordUploadAndSchedulePollSQL, "'test-poll:' || $1 || ':' || updated.retry_count || ':1'") {
t.Fatalf("poll schedule key must carry the retry round: %q", recordUploadAndSchedulePollSQL)
}
var payload map[string]any
if err := json.Unmarshal(db.queryRowArgs[3].([]byte), &payload); err != nil {
if err := json.Unmarshal(db.queryRowArgs[4].([]byte), &payload); err != nil {
t.Fatal(err)
}
if len(payload) != 2 || payload["publication_id"] != "publication-1" || payload["sequence"] != float64(1) {
+15 -1
View File
@@ -429,8 +429,11 @@ func validPathSegment(value string) bool {
return strings.TrimSpace(value) != "" && !strings.ContainsAny(value, "/?#\\\x00")
}
// validPage accepts the upstream maximum (1000). Listings that need a smaller
// window still pass it explicitly; upload recovery keeps its own 100/page
// budget instead of inheriting the reconciliation scan size.
func validPage(page, pageSize int) bool {
return page > 0 && pageSize > 0 && pageSize <= 100
return page > 0 && pageSize > 0 && pageSize <= 1000
}
func (c *Client) endpoint(path string) string {
@@ -487,3 +490,14 @@ func (c *Client) decodeBody(resp *http.Response, target any) error {
}
return nil
}
// StatusCode returns the HTTP status carried by err, or 0.
func StatusCode(err error) int {
var httpErr *HTTPError
if errors.As(err, &httpErr) {
return httpErr.StatusCode
}
return 0
}
func IsNotFound(err error) bool { return StatusCode(err) == http.StatusNotFound }
+20
View File
@@ -336,6 +336,26 @@ func TestClientProvidesPaginatedInventoryChunkAndScopedSearchReads(t *testing.T)
}
}
// Acceptance #16: the reconciliation scan must be one 1000-per-page read, and
// the wire query is the evidence — not just the constant passed to the interface.
func TestListKnowledgeSendsScanPageSizeOnTheWire(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("page") != "1" || r.URL.Query().Get("page_size") != "1000" {
t.Fatalf("knowledge list query = %s", r.URL.RawQuery)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":[],"total":0,"page":1,"page_size":1000}`))
}))
defer server.Close()
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "test-api-key", Timeout: time.Second})
if err != nil {
t.Fatal(err)
}
if _, _, err := client.ListKnowledge(context.Background(), "kb-1", 1, 1000); err != nil {
t.Fatal(err)
}
}
func TestClientRejectsRedirectWithoutForwardingAPIKey(t *testing.T) {
var targetHits atomic.Int32
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+20
View File
@@ -0,0 +1,20 @@
package weknora
import (
"net/url"
"strings"
)
// KnowledgeBaseConsoleURL builds the console link for one knowledge base.
// Reconciliation findings and the platform task drawer both use this rule: if
// they drift, the same knowledge base opens at two different addresses, and the
// 503 fallback link in one drawer points somewhere else than the other.
// An empty origin or base id yields an empty link, which both callers treat as
// "no link configured" rather than inventing a host.
func KnowledgeBaseConsoleURL(origin, knowledgeBaseID string) string {
origin, knowledgeBaseID = strings.TrimSpace(origin), strings.TrimSpace(knowledgeBaseID)
if origin == "" || knowledgeBaseID == "" {
return ""
}
return strings.TrimSuffix(origin, "/") + "/platform/knowledge-bases/" + url.PathEscape(knowledgeBaseID)
}
@@ -0,0 +1,19 @@
package weknora
import "testing"
func TestKnowledgeBaseConsoleURLCannotInventAHost(t *testing.T) {
cases := []struct{ origin, kb, want string }{
{"", "kb-1", ""},
{"https://weknora.test", "", ""},
{" ", "kb-1", ""},
{"https://weknora.test/", "kb-1", "https://weknora.test/platform/knowledge-bases/kb-1"},
{" https://weknora.test/ ", " kb-1 ", "https://weknora.test/platform/knowledge-bases/kb-1"},
{"https://weknora.test/base", "kb 1", "https://weknora.test/base/platform/knowledge-bases/kb%201"},
}
for _, c := range cases {
if got := KnowledgeBaseConsoleURL(c.origin, c.kb); got != c.want {
t.Fatalf("KnowledgeBaseConsoleURL(%q,%q) = %q, want %q", c.origin, c.kb, got, c.want)
}
}
}
+171
View File
@@ -0,0 +1,171 @@
package weknora
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// RuntimeClient is the platform-level, read-only SystemAdmin client. It is a
// separate key from the tenant API key on purpose: capability
// system_runtime_read belongs to the test instance, not to one tenant.
type RuntimeClientConfig struct {
BaseURL string
APIKey string
Timeout time.Duration
MaxResponseBytes int64
AllowDockerHTTP bool
AllowPrivateHTTP bool
}
type RuntimeClient struct {
baseURL *url.URL
apiKey string
httpClient *http.Client
maxResponseBytes int64
}
func NewRuntimeClient(config RuntimeClientConfig) (*RuntimeClient, error) {
baseURL, err := url.Parse(strings.TrimSpace(config.BaseURL))
if err != nil || baseURL.Scheme == "" || baseURL.Host == "" || baseURL.User != nil ||
baseURL.RawQuery != "" || baseURL.Fragment != "" {
return nil, errors.New("invalid WeKnora runtime base URL")
}
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
return nil, errors.New("WeKnora runtime base URL must use HTTPS")
}
if strings.TrimSpace(config.APIKey) == "" {
return nil, errors.New("WeKnora runtime API key is required")
}
if config.Timeout <= 0 {
return nil, errors.New("WeKnora runtime HTTP timeout must be positive")
}
if config.MaxResponseBytes <= 0 {
config.MaxResponseBytes = defaultMaxResponseBytes
}
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
return &RuntimeClient{
baseURL: baseURL,
apiKey: config.APIKey,
httpClient: &http.Client{
Timeout: config.Timeout,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
},
maxResponseBytes: config.MaxResponseBytes,
}, nil
}
type RuntimeQueues struct {
Available bool `json:"available"`
QueuesError bool `json:"queues_error"`
WorkersError bool `json:"workers_error"`
Queues []RuntimeQueue `json:"queues"`
Timestamp int64 `json:"timestamp"`
}
type RuntimeQueue struct {
Name string `json:"name"`
Pool string `json:"pool"`
Pending int `json:"pending"`
Active int `json:"active"`
Scheduled int `json:"scheduled"`
Retry int `json:"retry"`
Archived int `json:"archived"`
Processed int `json:"processed"`
Failed int `json:"failed"`
}
type RuntimeDocumentProgress struct {
Document RuntimeDocument `json:"document"`
Failures []RuntimeFailure `json:"failures"`
HasMoreFailures bool `json:"has_more_failures"`
}
type RuntimeDocument struct {
ID string `json:"id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Title string `json:"title"`
ParseStatus string `json:"parse_status"`
IngestionStatus string `json:"ingestion_status"`
WikiStatus string `json:"wiki_status"`
Stages []RuntimeStage `json:"stages"`
UpdatedAt time.Time `json:"updated_at"`
}
type RuntimeStage struct {
Name string `json:"name"`
Status string `json:"status"`
ErrorCode string `json:"error_code"`
FinishedAt *time.Time `json:"finished_at"`
}
type RuntimeFailure struct {
TaskType string `json:"task_type"`
FailCount int `json:"fail_count"`
FailedAt time.Time `json:"failed_at"`
LastError string `json:"last_error"`
}
func (c *RuntimeClient) Queues(ctx context.Context) (RuntimeQueues, error) {
var response RuntimeQueues
if err := c.get(ctx, "/api/v1/system/admin/runtime/queues", &response); err != nil {
return RuntimeQueues{}, err
}
return response, nil
}
func (c *RuntimeClient) DocumentProgress(ctx context.Context, knowledgeID string) (RuntimeDocumentProgress, error) {
if !validPathSegment(knowledgeID) || len(knowledgeID) > 64 {
return RuntimeDocumentProgress{}, errors.New("invalid knowledge ID")
}
var envelope struct {
Success bool `json:"success"`
Data RuntimeDocumentProgress `json:"data"`
}
if err := c.get(ctx, "/api/v1/system/admin/runtime/documents/"+knowledgeID, &envelope); err != nil {
return RuntimeDocumentProgress{}, err
}
if !envelope.Success {
return RuntimeDocumentProgress{}, errors.New("WeKnora returned an unsuccessful document progress response")
}
return envelope.Data, nil
}
func (c *RuntimeClient) get(ctx context.Context, path string, target any) error {
endpoint := *c.baseURL
endpoint.Path = strings.TrimRight(c.baseURL.Path, "/") + path
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
return errors.New("create WeKnora runtime request")
}
req.Header.Set("Accept", "application/json")
req.Header.Set("X-API-Key", c.apiKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("send WeKnora runtime request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
return &HTTPError{StatusCode: resp.StatusCode}
}
payload, err := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
if err != nil {
return errors.New("read WeKnora runtime response")
}
if int64(len(payload)) > c.maxResponseBytes {
return errors.New("WeKnora runtime response exceeds size limit")
}
if err := json.Unmarshal(payload, target); err != nil {
return errors.New("decode WeKnora runtime response")
}
return nil
}
+39
View File
@@ -47,3 +47,42 @@ func ReadAPIKeyFile(path string) (string, error) {
}
return key, nil
}
// ReadRuntimeKeyFile reads the platform-level read-only key. Q7 fixes the
// contract at mode 0400: unlike tenant keys (0600), this key must not be
// readable by the process owner's group and never leaves the API process.
func ReadRuntimeKeyFile(path string) (string, error) {
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return "", fmt.Errorf("open runtime key file: %w", err)
}
file := os.NewFile(uintptr(fd), "weknora-runtime-key")
if file == nil {
_ = syscall.Close(fd)
return "", errors.New("open runtime key file: invalid file descriptor")
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return "", fmt.Errorf("inspect runtime key file: %w", err)
}
if !info.Mode().IsRegular() {
return "", errors.New("runtime key file must be a regular file")
}
if info.Mode().Perm() != 0o400 {
return "", errors.New("runtime key file permissions must be 0400")
}
body, err := io.ReadAll(io.LimitReader(file, maxAPIKeyFileBytes+1))
if err != nil {
return "", fmt.Errorf("read runtime key file: %w", err)
}
if len(body) > maxAPIKeyFileBytes {
return "", errors.New("runtime key file is too large")
}
key := strings.TrimSpace(string(body))
if key == "" {
return "", errors.New("runtime key file is empty")
}
return key, nil
}
+17
View File
@@ -53,3 +53,20 @@ func TestReadAPIKeyFileRejectsUnsafeInputsWithoutLeakingContent(t *testing.T) {
}
}
}
func TestReadRuntimeKeyFileRequires0400(t *testing.T) {
path := t.TempDir() + "/runtime-key"
if err := os.WriteFile(path, []byte("runtime-secret\n"), 0o400); err != nil {
t.Fatal(err)
}
key, err := ReadRuntimeKeyFile(path)
if err != nil || key != "runtime-secret" {
t.Fatalf("key=%q err=%v", key, err)
}
if err := os.Chmod(path, 0o600); err != nil {
t.Fatal(err)
}
if _, err := ReadRuntimeKeyFile(path); err == nil {
t.Fatal("0600 runtime key must be rejected")
}
}
+7
View File
@@ -18,10 +18,17 @@ type UploadRequest struct {
type Knowledge struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Title string `json:"title"`
Source string `json:"source"`
Channel string `json:"channel"`
ParseStatus string `json:"parse_status"`
StallState string `json:"stall_state"`
EnableStatus string `json:"enable_status"`
FileName string `json:"file_name"`
FileType string `json:"file_type"`
FolderPath string `json:"folder_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
Metadata map[string]any `json:"metadata"`
+115
View File
@@ -0,0 +1,115 @@
package reconciliation
import "knowledge-governance/internal/governance"
type verdict int
const (
verdictSkip verdict = iota
verdictConsistent
verdictMismatch
verdictStalled
verdictDeleting
)
// classify is the single 7x7 matrix. Rows are ledger vocabulary, columns are
// normalized WeKnora parse_status. Unknown upstream values are rejected by the
// caller before this function, so there is deliberately no "other" branch.
func classify(ledger, upstream string) verdict {
switch ledger {
case "planned":
if upstream == "deleting" {
return verdictDeleting
}
return verdictMismatch
case "pending":
switch upstream {
case "pending":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "processing":
switch upstream {
case "processing":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "finalizing":
switch upstream {
case "finalizing":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "completed":
switch upstream {
case "completed":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "failed":
switch upstream {
case "failed":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
case "stalled":
switch upstream {
case "completed":
return verdictMismatch
case "deleting":
return verdictDeleting
default:
return verdictStalled
}
case "cancelled":
switch upstream {
case "cancelled":
return verdictConsistent
case "deleting":
return verdictDeleting
default:
return verdictMismatch
}
default:
return verdictSkip
}
}
// AllowedWriteback is the only writeback migration table. completed cannot be
// downgraded; planned is not a target; cancelled/deleting have no ledger
// counterpart.
func AllowedWriteback(current, target string) bool {
switch current {
case "pending":
return target == "processing" || target == "finalizing" || target == "completed" || target == "failed"
case "processing":
return target == "finalizing" || target == "completed" || target == "failed"
case "finalizing":
return target == "completed" || target == "failed"
case "failed":
return target == "pending" || target == "processing" || target == "completed"
case "stalled":
return target == "pending" || target == "processing" || target == "failed"
default:
return false
}
}
func normalizeParseStatus(status string) (string, bool) {
return governance.NormalizeWeKnoraParseStatus(status)
}
+137
View File
@@ -0,0 +1,137 @@
package reconciliation
import (
"context"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
)
type RuntimeConfig struct {
BaseURL func(context.Context) string
APIKey string
Timeout time.Duration
AllowDockerHTTP bool
AllowPrivateHTTP bool
Now func() time.Time
}
type RuntimeProvider struct {
baseURL func(context.Context) string
apiKey string
timeout time.Duration
allowDockerHTTP bool
allowPrivateHTTP bool
now func() time.Time
}
func NewRuntimeProvider(config RuntimeConfig) *RuntimeProvider {
if config.Now == nil {
config.Now = time.Now
}
return &RuntimeProvider{
baseURL: config.BaseURL, apiKey: strings.TrimSpace(config.APIKey), timeout: config.Timeout,
allowDockerHTTP: config.AllowDockerHTTP, allowPrivateHTTP: config.AllowPrivateHTTP, now: config.Now,
}
}
func (p *RuntimeProvider) Available() bool {
return p != nil && p.apiKey != "" && p.baseURL != nil
}
func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, error) {
if !p.Available() {
return nil, ErrRuntimeUnavailable
}
baseURL := strings.TrimSpace(p.baseURL(ctx))
if baseURL == "" {
return nil, ErrRuntimeUnavailable
}
client, err := weknora.NewRuntimeClient(weknora.RuntimeClientConfig{
BaseURL: baseURL,
APIKey: p.apiKey,
Timeout: p.timeout,
AllowDockerHTTP: p.allowDockerHTTP,
AllowPrivateHTTP: p.allowPrivateHTTP,
})
if err != nil {
return nil, ErrRuntimeUnavailable
}
return client, nil
}
func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueSummary, error) {
client, err := p.client(ctx)
if err != nil {
return nil, err
}
// The overview must not hang for the full business timeout just because the
// queue endpoint is slow; a short probe is enough to decide null vs data.
queueCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
queues, err := client.Queues(queueCtx)
if err != nil {
return nil, ErrRuntimeUnavailable
}
summary := &governance.WeKnoraQueueSummary{
Available: queues.Available, QueuesError: queues.QueuesError, WorkersError: queues.WorkersError,
Queues: make([]governance.WeKnoraQueue, 0, len(queues.Queues)), Timestamp: queues.Timestamp,
}
for _, queue := range queues.Queues {
summary.Queues = append(summary.Queues, governance.WeKnoraQueue{
Name: queue.Name, Pool: queue.Pool, Pending: queue.Pending, Active: queue.Active,
Scheduled: queue.Scheduled, Retry: queue.Retry, Archived: queue.Archived,
Processed: queue.Processed, Failed: queue.Failed,
})
}
return summary, nil
}
func (p *RuntimeProvider) DocumentProgress(ctx context.Context, documentID string) (governance.ReconciliationProgress, error) {
client, err := p.client(ctx)
if err != nil {
return governance.ReconciliationProgress{}, err
}
detail, err := client.DocumentProgress(ctx, documentID)
if err != nil {
if weknora.IsNotFound(err) {
return governance.ReconciliationProgress{}, err
}
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
}
progress := governance.ReconciliationProgress{
DocumentID: detail.Document.ID, ParseStatus: detail.Document.ParseStatus,
IngestionStatus: detail.Document.IngestionStatus, WikiStatus: detail.Document.WikiStatus,
HasMoreFailures: detail.HasMoreFailures, ObservedAt: p.now().UTC(),
Stages: make([]governance.ReconciliationStage, 0, len(detail.Document.Stages)),
Failures: make([]governance.ReconciliationFailure, 0, len(detail.Failures)),
}
if progress.DocumentID == "" {
progress.DocumentID = documentID
}
for _, stage := range detail.Document.Stages {
progress.Stages = append(progress.Stages, governance.ReconciliationStage{
Name: stage.Name, Status: stage.Status, ErrorCode: stage.ErrorCode, FinishedAt: stage.FinishedAt,
})
}
for _, failure := range detail.Failures {
progress.Failures = append(progress.Failures, governance.ReconciliationFailure{
TaskType: failure.TaskType, FailCount: failure.FailCount, FailedAt: failure.FailedAt,
LastError: truncateRunes(failure.LastError, 500),
})
}
return progress, nil
}
func truncateRunes(value string, limit int) string {
if limit <= 0 {
return ""
}
runes := []rune(value)
if len(runes) <= limit {
return value
}
return string(runes[:limit])
}
+109
View File
@@ -0,0 +1,109 @@
package reconciliation
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/platform/weknora"
)
func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-API-Key") != "runtime-key" {
t.Fatalf("missing runtime key header")
}
switch r.URL.Path {
case "/api/v1/system/admin/runtime/queues":
_ = json.NewEncoder(w).Encode(map[string]any{
"available": true, "queues_error": false, "workers_error": false, "timestamp": 7,
"queues": []map[string]any{{"name": "default", "pool": "core", "pending": 3, "active": 1, "failed": 2}},
})
case "/api/v1/system/admin/runtime/documents/doc-1":
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{
"document": map[string]any{"id": "doc-1", "parse_status": "failed", "ingestion_status": "failed", "wiki_status": "none",
"stages": []map[string]any{{"name": "parse", "status": "failed", "error_code": "x"}}},
"failures": []map[string]any{{"task_type": "parse", "fail_count": 2, "failed_at": "2026-12-01T00:00:00Z", "last_error": strings.Repeat("错", 600)}},
"has_more_failures": false,
}})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
})
queues, err := provider.Queues(context.Background())
if err != nil || !queues.Available || len(queues.Queues) != 1 || queues.Queues[0].Pending != 3 {
t.Fatalf("queues=%#v err=%v", queues, err)
}
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
if err != nil || progress.ParseStatus != "failed" || progress.DocumentID != "doc-1" || len(progress.Stages) != 1 {
t.Fatalf("progress=%#v err=%v", progress, err)
}
if len([]rune(progress.Failures[0].LastError)) != 500 {
t.Fatalf("last_error runes = %d", len([]rune(progress.Failures[0].LastError)))
}
}
func TestRuntimeProviderUnavailableAndNotFound(t *testing.T) {
unavailable := NewRuntimeProvider(RuntimeConfig{BaseURL: func(context.Context) string { return "https://example.test" }})
if _, err := unavailable.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnavailable) {
t.Fatalf("unconfigured queues err=%v", err)
}
server := httptest.NewServer(http.NotFoundHandler())
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
})
if _, err := provider.DocumentProgress(context.Background(), "missing"); err == nil || weknora.StatusCode(err) != 404 {
t.Fatalf("missing document err=%v", err)
}
}
// The progress passthrough is a projection, not a proxy: whatever extra fields
// the platform endpoint returns (keys, authorization headers, token echoes) must
// never reach the browser. This guards the shape if someone later switches to
// forwarding the upstream body.
func TestRuntimeProviderDropsSensitiveUpstreamFields(t *testing.T) {
const secret = "leak-sentinel"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{
"document": map[string]any{
"id": "doc-1", "parse_status": "completed", "ingestion_status": "completed", "wiki_status": "none",
"api_key": secret, "apiKey": secret, "authorization": "Bearer " + secret,
"headers": map[string]any{"X-API-Key": secret},
},
"failures": []map[string]any{},
"has_more_failures": false,
"api_key": secret,
}})
}))
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
})
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
if err != nil {
t.Fatal(err)
}
payload, err := json.Marshal(progress)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(payload), secret) || strings.Contains(string(payload), "Bearer ") {
t.Fatalf("progress leaked upstream credentials: %s", payload)
}
if progress.DocumentID != "doc-1" || progress.ParseStatus != "completed" {
t.Fatalf("projection dropped real fields: %#v", progress)
}
}
+522
View File
@@ -0,0 +1,522 @@
package reconciliation
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"sort"
"strings"
"sync"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/weknora"
)
const scanPageSize = 1000
type confirmResult struct {
item weknora.Knowledge
notFound bool
err error
}
func (s *Service) scanKnowledge(ctx context.Context, kbID string) ([]weknora.Knowledge, error) {
seen := make(map[string]bool)
out := make([]weknora.Knowledge, 0)
for page := 1; page <= 10000; page++ {
items, total, err := s.remote.ListKnowledge(ctx, kbID, page, scanPageSize)
if err != nil {
return nil, ErrRemoteFailed
}
added := 0
for _, item := range items {
if item.ID == "" {
return nil, ErrRemoteFailed
}
if item.KnowledgeBaseID != "" && item.KnowledgeBaseID != kbID {
return nil, ErrRemoteFailed
}
if seen[item.ID] {
continue
}
seen[item.ID] = true
out = append(out, item)
added++
}
if len(items) == 0 || added == 0 {
break
}
if total > 0 {
if int64(len(seen)) >= total {
break
}
// Keep paging even if the instance returned a smaller page than
// requested; only the reported total ends the scan.
continue
}
if len(items) < scanPageSize {
break
}
}
return out, nil
}
// confirmAll performs the "先确认再判缺" single reads. The scan phase itself is
// strictly serial; only this stage may use the configured concurrency.
func (s *Service) confirmAll(ctx context.Context, kbID string, ids []string) map[string]confirmResult {
results := make(map[string]confirmResult, len(ids))
if len(ids) == 0 {
return results
}
type outcome struct {
id string
result confirmResult
}
jobs := make(chan string)
outcomes := make(chan outcome, len(ids))
ctx, cancel := context.WithCancel(ctx)
defer cancel()
workers := s.confirmConcurrency
if workers > len(ids) {
workers = len(ids)
}
var wait sync.WaitGroup
for i := 0; i < workers; i++ {
wait.Add(1)
go func() {
defer wait.Done()
for id := range jobs {
if ctx.Err() != nil {
return
}
item, err := s.remote.GetKnowledge(ctx, id)
result := confirmResult{item: item, err: err}
if weknora.IsNotFound(err) {
result = confirmResult{notFound: true}
} else if err == nil && item.KnowledgeBaseID != "" && item.KnowledgeBaseID != kbID {
result = confirmResult{err: ErrRemoteFailed}
}
select {
case outcomes <- outcome{id: id, result: result}:
case <-ctx.Done():
return
}
}
}()
}
go func() {
defer close(jobs)
for _, id := range ids {
select {
case jobs <- id:
case <-ctx.Done():
return
}
}
}()
go func() {
wait.Wait()
close(outcomes)
}()
for outcome := range outcomes {
results[outcome.id] = outcome.result
if outcome.result.err != nil {
cancel()
}
}
return results
}
func (s *Service) buildFindings(ctx context.Context, run governance.ReconciliationRun, ledger []governance.ReconciliationLedgerRow, items []weknora.Knowledge, overlapped bool) ([]governance.ReconciliationFinding, error) {
byID := make(map[string]weknora.Knowledge, len(items))
ledgerByPublication := make(map[string]governance.ReconciliationLedgerRow, len(ledger))
ledgerByKnowledge := make(map[string]governance.ReconciliationLedgerRow, len(ledger))
for _, item := range items {
byID[item.ID] = item
}
for _, row := range ledger {
ledgerByPublication[row.PublicationID] = row
if row.KnowledgeID != "" {
if _, exists := ledgerByKnowledge[row.KnowledgeID]; !exists {
ledgerByKnowledge[row.KnowledgeID] = row
}
}
}
findings := make([]governance.ReconciliationFinding, 0, len(ledger)+len(items)/10)
add := func(finding governance.ReconciliationFinding) {
finding.RunID = run.ID
if finding.ConfirmationState == "" {
finding.ConfirmationState = "confirmed"
}
finding.ActionState = "open"
finding.ID = deterministicFindingID(run.ID, finding)
if finding.WeKnoraURL == "" && s.weKnoraWebBase != nil {
finding.WeKnoraURL = weknora.KnowledgeBaseConsoleURL(s.weKnoraWebBase(ctx), run.KBID)
}
findings = append(findings, finding)
}
// R1: expected live but absent from the full listing. A list miss is not
// evidence; only a single GET 404 is.
missing := make([]string, 0)
seenMissing := map[string]bool{}
for _, row := range ledger {
if !expectedLive(row) {
continue
}
if _, ok := byID[row.KnowledgeID]; ok {
continue
}
if !seenMissing[row.KnowledgeID] {
seenMissing[row.KnowledgeID] = true
missing = append(missing, row.KnowledgeID)
}
}
confirmations := s.confirmAll(ctx, run.KBID, missing)
for _, row := range ledger {
if !expectedLive(row) {
continue
}
if _, ok := byID[row.KnowledgeID]; ok {
continue
}
result, ok := confirmations[row.KnowledgeID]
if !ok {
return nil, ErrRemoteFailed
}
if result.err != nil {
return nil, ErrRemoteFailed
}
if result.notFound {
confirmation := "confirmed"
if overlapped {
confirmation = "pending"
}
add(governance.ReconciliationFinding{
Type: "R1", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, LedgerSHA256: row.SHA256,
EvidenceLevel: "none", ConfirmationState: confirmation, SuggestedAction: "requeue_upload",
Detail: "台账认为应在库,单条读取返回 404",
})
continue
}
// The row exists but the list hid it (deleting). Use it for matrix checks.
byID[row.KnowledgeID] = result.item
}
// R2: governance-imported item with no current ledger row pointing at it.
orphans := make([]weknora.Knowledge, 0)
orphanIDs := make([]string, 0)
for _, item := range items {
if item.Channel != "governance" {
continue
}
publicationID := metadataString(item.Metadata, "publication_id")
if publicationID != "" {
if _, ok := ledgerByPublication[publicationID]; ok {
continue
}
}
if _, ok := ledgerByKnowledge[item.ID]; ok {
continue
}
orphans = append(orphans, item)
orphanIDs = append(orphanIDs, item.ID)
}
orphanConfirmations := s.confirmAll(ctx, run.KBID, orphanIDs)
for _, item := range orphans {
result, ok := orphanConfirmations[item.ID]
if !ok {
return nil, ErrRemoteFailed
}
if result.err != nil {
return nil, ErrRemoteFailed
}
if result.notFound || result.item.ParseStatus == "deleting" {
continue
}
publicationID := metadataString(item.Metadata, "publication_id")
if publicationID != "" {
if _, ok := ledgerByPublication[publicationID]; ok {
continue
}
}
if _, ok := ledgerByKnowledge[item.ID]; ok {
continue
}
confirmation := "confirmed"
if overlapped {
confirmation = "pending"
}
add(governance.ReconciliationFinding{
Type: "R2", PublicationID: publicationID, DocumentID: item.ID,
Title: item.Title, Path: item.FolderPath, Source: item.Source, TargetScope: "unknown",
WeKnoraParseState: item.ParseStatus, NormalizedState: item.ParseStatus,
WeKnoraFileMD5: normalizeMD5(item.FileHash), EvidenceLevel: "none",
ConfirmationState: confirmation, SuggestedAction: "remove_from_test",
Detail: "库内平台导入条目没有现行台账行指向它",
})
}
// R3: not imported by the platform.
for _, item := range items {
if item.Channel == "governance" {
continue
}
add(governance.ReconciliationFinding{
Type: "R3", DocumentID: item.ID, Title: item.Title, Path: item.FolderPath,
Source: item.Source, TargetScope: "unknown", WeKnoraParseState: item.ParseStatus,
NormalizedState: item.ParseStatus, WeKnoraFileMD5: normalizeMD5(item.FileHash),
EvidenceLevel: "none", SuggestedAction: "none", Detail: "非平台导入条目,仅统计",
})
}
removal, err := s.store.ListReconciliationRemovalCandidates(ctx, run.KBID)
if err != nil {
return nil, err
}
// 「需下架」的台账细节沿用上面按 publication 建的台账索引。
for _, row := range ledger {
if !expectedLive(row) {
continue
}
item, ok := byID[row.KnowledgeID]
if !ok {
continue
}
upstream, known := normalizeParseStatus(item.ParseStatus)
if !known {
return nil, fmt.Errorf("unsupported WeKnora parse status %q", item.ParseStatus)
}
normalized := upstream
if item.ParseStatus == "deleting" {
if age(run.StartedAt, item.UpdatedAt) > s.stallAfter {
add(r7Finding(row, item, "删除超过阈值仍未完成"))
}
continue
}
if finding, ok := s.r4Finding(row, item, normalized); ok {
add(finding)
}
if row.ProcessingState == "cancelled" {
if normalized != "cancelled" && ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) >= s.grace {
add(r5Finding(row, item, normalized, "none", "台账已取消,WeKnora 仍有活动状态"))
}
continue
}
verdict := classify(row.ProcessingState, normalized)
stuckAge := ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt)
switch verdict {
case verdictStalled:
add(r7Finding(row, item, "台账或上游已判定停滞"))
case verdictDeleting:
if age(run.StartedAt, item.UpdatedAt) > s.stallAfter {
add(r7Finding(row, item, "删除超过阈值仍未完成"))
}
case verdictMismatch:
if (normalized == "pending" || normalized == "processing" || normalized == "finalizing") && stuckAge > s.stallAfter {
add(r7Finding(row, item, "超过阈值没有进展"))
continue
}
if item.StallState == "stalled" {
add(r7Finding(row, item, "WeKnora 判定停滞"))
continue
}
if ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) < s.grace {
continue
}
action := "writeback_state"
if !AllowedWriteback(row.ProcessingState, normalized) {
action = "none"
}
add(r5Finding(row, item, normalized, action, ""))
case verdictConsistent:
if item.StallState == "stalled" {
add(r7Finding(row, item, "WeKnora 判定停滞"))
} else if (normalized == "pending" || normalized == "processing") && stuckAge > s.stallAfter {
add(r7Finding(row, item, "超过阈值没有进展"))
}
}
}
// R6: 应下架仍在。判定口径 = removal_candidates 视图(与 /monitor/overview 的
// 「需下架」共用同一实现,陷阱 15)。这里直接由视图行生成,不再附加「本轮扫描
// 见到该条目」「上游 parse_status=completed」这类只有对账侧才有的条件——上游仍在
// processing/finalizing、或单条读取失败导致扫描缺行时,两处数字就会永久不一致。
for _, row := range removal {
finding := governance.ReconciliationFinding{
Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
// 视图只收录 processing_state='completed' 的台账行。
LedgerState: "completed", EvidenceLevel: "none", SuggestedAction: "enter_removal",
Detail: "来源已判禁止导入,条目仍在测试库可检索",
}
if own, ok := ledgerByPublication[row.PublicationID]; ok {
if finding.DocumentID == "" {
finding.DocumentID = own.KnowledgeID
}
if finding.Title == "" {
finding.Title = own.Title
}
if finding.Path == "" {
finding.Path = own.Path
}
if finding.Source == "" {
finding.Source = own.SourceName
}
if finding.TargetScope == "" {
finding.TargetScope = own.TargetScope
}
if own.ProcessingState != "" {
finding.LedgerState = own.ProcessingState
}
finding.LedgerSHA256 = own.SHA256
}
if item, ok := byID[finding.DocumentID]; ok {
if normalized, known := normalizeParseStatus(item.ParseStatus); known {
finding.NormalizedState = normalized
}
finding.WeKnoraParseState = item.ParseStatus
finding.WeKnoraFileMD5 = normalizeMD5(item.FileHash)
} else if finding.DocumentID != "" {
finding.Detail = "来源已判禁止导入;本轮扫描未见该条目,计数仍与总览「需下架」一致"
}
add(finding)
}
// R8: one publication id maps to more than one live row.
grouped := make(map[string][]weknora.Knowledge)
for _, item := range items {
if item.Channel != "governance" || item.ParseStatus == "failed" || item.ParseStatus == "deleting" {
continue
}
publicationID := metadataString(item.Metadata, "publication_id")
if publicationID == "" {
continue
}
grouped[publicationID] = append(grouped[publicationID], item)
}
for publicationID, group := range grouped {
if len(group) < 2 {
continue
}
first := group[0]
add(governance.ReconciliationFinding{
Type: "R8", PublicationID: publicationID, DocumentID: first.ID,
Title: first.Title, Path: first.FolderPath, Source: first.Source, TargetScope: "unknown",
WeKnoraParseState: first.ParseStatus, NormalizedState: first.ParseStatus,
WeKnoraFileMD5: normalizeMD5(first.FileHash), EvidenceLevel: "none", SuggestedAction: "none",
Detail: fmt.Sprintf("同一台账发布标识对应 %d 条存活条目", len(group)),
})
}
sort.Slice(findings, func(i, j int) bool {
if findings[i].Type != findings[j].Type {
return findings[i].Type < findings[j].Type
}
if findings[i].PublicationID != findings[j].PublicationID {
return findings[i].PublicationID < findings[j].PublicationID
}
return findings[i].DocumentID < findings[j].DocumentID
})
return findings, nil
}
func (s *Service) r4Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, normalized string) (governance.ReconciliationFinding, bool) {
declared := strings.ToLower(strings.TrimSpace(metadataString(item.Metadata, "content_sha256")))
ledgerSHA := strings.ToLower(strings.TrimSpace(row.SHA256))
uploadMD5 := normalizeMD5(row.UploadMD5)
fileMD5 := normalizeMD5(item.FileHash)
evidence := "none"
if declared != "" && ledgerSHA != "" {
evidence = "declared_only"
if uploadMD5 != "" && fileMD5 != "" {
evidence = "independent"
}
}
if evidence == "none" {
return governance.ReconciliationFinding{}, false
}
mismatch := declared != ledgerSHA
if evidence == "independent" && uploadMD5 != fileMD5 {
mismatch = true
}
if !mismatch {
return governance.ReconciliationFinding{}, false
}
return governance.ReconciliationFinding{
Type: "R4", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
LedgerSHA256: ledgerSHA, DeclaredSHA256: declared, WeKnoraFileMD5: fileMD5,
EvidenceLevel: evidence, SuggestedAction: "requeue_upload",
Detail: "库内内容摘要与台账现行版本不一致",
}, true
}
func r5Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, normalized, action, detail string) governance.ReconciliationFinding {
if detail == "" {
detail = fmt.Sprintf("台账状态 %s 与 WeKnora %s 不一致,已超过宽限期", row.ProcessingState, normalized)
}
return governance.ReconciliationFinding{
Type: "R5", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
LedgerSHA256: row.SHA256, EvidenceLevel: "none", SuggestedAction: action, Detail: detail,
}
}
func r7Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, detail string) governance.ReconciliationFinding {
return governance.ReconciliationFinding{
Type: "R7", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus,
NormalizedState: item.ParseStatus, LedgerSHA256: row.SHA256, EvidenceLevel: "none",
SuggestedAction: "none", Detail: detail,
}
}
func expectedLive(row governance.ReconciliationLedgerRow) bool {
return row.KnowledgeID != "" && row.ProcessingState != "failed" &&
row.RetrievalState != "disabling" && row.RetrievalState != "disabled"
}
func age(startedAt, updatedAt time.Time) time.Duration {
if updatedAt.IsZero() || startedAt.Before(updatedAt) {
return 0
}
return startedAt.Sub(updatedAt)
}
func ageFromPointer(startedAt time.Time, processingStartedAt *time.Time, updatedAt time.Time) time.Duration {
if processingStartedAt != nil && !processingStartedAt.IsZero() {
return age(startedAt, *processingStartedAt)
}
return age(startedAt, updatedAt)
}
func metadataString(metadata map[string]any, key string) string {
value, _ := metadata[key].(string)
return value
}
func normalizeMD5(value string) string {
value = strings.ToLower(strings.TrimSpace(value))
if len(value) != 32 {
return ""
}
for _, char := range value {
if (char < '0' || char > '9') && (char < 'a' || char > 'f') {
return ""
}
}
return value
}
func deterministicFindingID(runID string, finding governance.ReconciliationFinding) string {
digest := sha256.Sum256([]byte(runID + "\x00" + finding.Type + "\x00" + finding.PublicationID + "\x00" + finding.DocumentID))
return "rcf-" + hex.EncodeToString(digest[:])[:24]
}
+459
View File
@@ -0,0 +1,459 @@
package reconciliation
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
)
var (
ErrRunInProgress = errors.New("reconciliation run in progress")
ErrNotFound = errors.New("reconciliation record not found")
ErrActionConflict = errors.New("reconciliation state or identity changed")
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
ErrRemoteFailed = errors.New("reconciliation remote call failed")
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
)
type Store interface {
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
ClaimScheduledReconciliationRun(context.Context, governance.ReconciliationRun, time.Time, time.Time) (governance.ReconciliationRun, bool, error)
LoadReconciliationRun(context.Context, string) (governance.ReconciliationRun, error)
ListReconciliationRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error)
ListReconciliationFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error)
GetReconciliationFinding(context.Context, string) (governance.ReconciliationFinding, error)
LoadReconciliationLedger(context.Context, string) ([]governance.ReconciliationLedgerRow, error)
LoadPreviousReconciliationCounts(context.Context, string, time.Time) (governance.ReconciliationCounts, bool, error)
CompleteReconciliationRun(context.Context, governance.ReconciliationRun, []governance.ReconciliationFinding) error
FailReconciliationRun(context.Context, string, string, time.Time) error
CleanupReconciliationFindings(context.Context, time.Time, int, time.Duration) error
LibraryJobsActive(context.Context) (bool, error)
ListReconciliationRemovalCandidates(context.Context, string) ([]governance.ReconciliationLedgerRow, error)
LoadReconciliationActionView(context.Context, string) (governance.ReconciliationActionView, error)
ReconciliationOrphanStillUnowned(context.Context, string, string) (bool, error)
WritebackReconciliationFinding(context.Context, string, string, string, string, time.Time) (governance.ReconciliationFinding, error)
RequeueReconciliationPublication(context.Context, string, string, string, string, time.Time) (string, error)
MarkReconciliationOrphanRemoved(context.Context, string, string, string, time.Time) error
}
type Remote interface {
BeginTask(context.Context, string) (context.Context, weknora.InstanceIdentity, error)
ListKnowledge(context.Context, string, int, int) ([]weknora.Knowledge, int64, error)
GetKnowledge(context.Context, string) (weknora.Knowledge, error)
DeleteKnowledge(context.Context, string) error
}
type Runtime interface {
DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error)
}
type Queue interface {
Enqueue(context.Context, jobs.EnqueueRequest, time.Time) (*jobs.Job, error)
}
type Config struct {
Store Store
Remote Remote
Runtime Runtime
Queue Queue
Now func() time.Time
Grace time.Duration
StallAfter time.Duration
StaleAfter time.Duration
ConfirmConcurrency int
KeepRuns int
MaxAge time.Duration
// WeKnoraWebBase resolves the WeKnora origin used to build the finding's
// jump link. Empty or nil leaves weknora_url empty, which the contract allows.
WeKnoraWebBase func(context.Context) string
}
type Service struct {
store Store
remote Remote
runtime Runtime
queue Queue
now func() time.Time
grace time.Duration
stallAfter time.Duration
staleAfter time.Duration
confirmConcurrency int
keepRuns int
maxAge time.Duration
weKnoraWebBase func(context.Context) string
}
func New(config Config) (*Service, error) {
if config.Store == nil || config.Remote == nil {
return nil, errors.New("reconciliation store and remote client are required")
}
if config.Now == nil {
config.Now = time.Now
}
if config.Grace <= 0 {
config.Grace = 30 * time.Minute
}
if config.StallAfter <= 0 {
config.StallAfter = 2 * time.Hour
}
if config.StaleAfter <= 0 {
config.StaleAfter = 6 * time.Hour
}
if config.ConfirmConcurrency < 1 {
config.ConfirmConcurrency = 1
}
if config.ConfirmConcurrency > 8 {
config.ConfirmConcurrency = 8
}
if config.KeepRuns < 1 {
config.KeepRuns = 30
}
if config.MaxAge <= 0 {
config.MaxAge = 90 * 24 * time.Hour
}
return &Service{
store: config.Store, remote: config.Remote, runtime: config.Runtime, queue: config.Queue,
now: config.Now, grace: config.Grace, stallAfter: config.StallAfter, staleAfter: config.StaleAfter,
confirmConcurrency: config.ConfirmConcurrency, keepRuns: config.KeepRuns, maxAge: config.MaxAge,
weKnoraWebBase: config.WeKnoraWebBase,
}, nil
}
func newID(prefix string) (string, error) {
var value [16]byte
if _, err := rand.Read(value[:]); err != nil {
return "", err
}
return prefix + hex.EncodeToString(value[:]), nil
}
func (s *Service) CreateRun(ctx context.Context, kbID, trigger string) (governance.ReconciliationRun, error) {
if kbID == "" || len(kbID) > 255 {
return governance.ReconciliationRun{}, errors.New("invalid test knowledge base")
}
now := s.now().UTC()
if _, err := s.store.ReapStaleReconciliationRuns(ctx, now, s.staleAfter); err != nil {
return governance.ReconciliationRun{}, err
}
id, err := newID("rec-")
if err != nil {
return governance.ReconciliationRun{}, err
}
run, err := s.store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
ID: id, KBID: kbID, State: "running", Trigger: trigger, StartedAt: now,
Counts: governance.ReconciliationCounts{},
}, now)
if err != nil {
if errors.Is(err, postgresstore.ErrReconciliationRunInProgress) {
return governance.ReconciliationRun{}, ErrRunInProgress
}
return governance.ReconciliationRun{}, err
}
if s.queue == nil {
_ = s.store.FailReconciliationRun(ctx, id, "queue_unavailable", now)
return governance.ReconciliationRun{}, errors.New("reconciliation queue is not configured")
}
if err := s.enqueueRun(ctx, run.ID, now); err != nil {
_ = s.store.FailReconciliationRun(ctx, run.ID, "queue_unavailable", now)
return governance.ReconciliationRun{}, err
}
return run, nil
}
// ScheduleDue claims one scheduled batch per test KB per local day. The caller
// computes `since` as today's configured wall-clock instant in the configured
// timezone; this method only enforces the claim and enqueue.
func (s *Service) ScheduleDue(ctx context.Context, kbIDs []string, since, now time.Time) (int, error) {
if _, err := s.store.ReapStaleReconciliationRuns(ctx, now, s.staleAfter); err != nil {
return 0, err
}
created := 0
seen := map[string]bool{}
for _, kbID := range kbIDs {
if kbID == "" || seen[kbID] {
continue
}
seen[kbID] = true
id, err := newID("rec-")
if err != nil {
return created, err
}
run, claimed, err := s.store.ClaimScheduledReconciliationRun(ctx, governance.ReconciliationRun{
ID: id, KBID: kbID, State: "running", Trigger: "schedule", StartedAt: now,
Counts: governance.ReconciliationCounts{},
}, since, now)
if err != nil {
return created, err
}
if !claimed {
continue
}
if err := s.enqueueRun(ctx, run.ID, now); err != nil {
_ = s.store.FailReconciliationRun(ctx, run.ID, "queue_unavailable", now)
return created, err
}
created++
}
return created, nil
}
func (s *Service) enqueueRun(ctx context.Context, runID string, now time.Time) error {
if s.queue == nil {
return errors.New("reconciliation queue is not configured")
}
payload, err := json.Marshal(map[string]string{"run_id": runID})
if err != nil {
return err
}
// jobs.id is VARCHAR(36) and the run id alone already fills it ("rec-" + 32 hex),
// so the job carries its own id; idempotency is guaranteed by the unique
// idempotency_key below, not by deriving the id from the run.
jobID, err := newID("job-")
if err != nil {
return err
}
_, err = s.queue.Enqueue(ctx, jobs.EnqueueRequest{
ID: jobID,
Type: "reconciliation.run",
Payload: payload,
Priority: 5,
AvailableAt: now,
MaxAttempts: 1,
IdempotencyKey: "reconciliation-run:" + runID,
}, now)
return err
}
func (s *Service) ExecuteRun(ctx context.Context, runID string) error {
run, err := s.store.LoadReconciliationRun(ctx, runID)
if err != nil {
return err
}
if run.State != "running" {
return nil
}
finished := func(code string) error {
if code == "" {
return nil
}
return s.store.FailReconciliationRun(context.WithoutCancel(ctx), run.ID, code, s.now().UTC())
}
pinned, _, err := s.remote.BeginTask(ctx, run.KBID)
if err != nil {
return finished("remote_unavailable")
}
ledger, err := s.store.LoadReconciliationLedger(pinned, run.KBID)
if err != nil {
return finished("ledger_unavailable")
}
overlappedStart, err := s.store.LibraryJobsActive(pinned)
if err != nil {
return finished("overlap_check_failed")
}
items, err := s.scanKnowledge(pinned, run.KBID)
if err != nil {
if errors.Is(err, ErrRemoteFailed) {
return finished("remote_scan_failed")
}
return finished("scan_failed")
}
overlappedEnd, err := s.store.LibraryJobsActive(pinned)
if err != nil {
return finished("overlap_check_failed")
}
overlapped := overlappedStart || overlappedEnd
findings, err := s.buildFindings(pinned, run, ledger, items, overlapped)
if err != nil {
if errors.Is(err, ErrRemoteFailed) {
return finished("remote_confirm_failed")
}
return finished("scan_failed")
}
previous, hasPrevious, err := s.store.LoadPreviousReconciliationCounts(pinned, run.KBID, run.StartedAt)
if err != nil {
return finished("previous_counts_failed")
}
counts := governance.ReconciliationCounts{}
for _, finding := range findings {
counts[finding.Type]++
}
run.Counts = counts.Normalize()
if hasPrevious {
run.PreviousCounts = previous
}
run.LedgerCount = len(ledger)
run.KBCount = len(items)
run.WindowOverlapped = overlapped
finishedAt := s.now().UTC()
run.FinishedAt = &finishedAt
if err := s.store.CompleteReconciliationRun(pinned, run, findings); err != nil {
return finished("complete_failed")
}
_ = s.store.CleanupReconciliationFindings(context.WithoutCancel(ctx), s.now().UTC(), s.keepRuns, s.maxAge)
return nil
}
func (s *Service) ListRuns(ctx context.Context, filter governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
return s.store.ListReconciliationRuns(ctx, filter)
}
func (s *Service) GetRun(ctx context.Context, id string) (governance.ReconciliationRun, error) {
run, err := s.store.LoadReconciliationRun(ctx, id)
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
return governance.ReconciliationRun{}, ErrNotFound
}
return run, err
}
func (s *Service) ListFindings(ctx context.Context, filter governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
return s.store.ListReconciliationFindings(ctx, filter)
}
func (s *Service) Progress(ctx context.Context, documentID string) (governance.ReconciliationProgress, error) {
if s.runtime == nil {
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
}
progress, err := s.runtime.DocumentProgress(ctx, documentID)
switch {
case err == nil:
return progress, nil
case weknora.StatusCode(err) == 404:
return governance.ReconciliationProgress{}, ErrNotFound
default:
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
}
}
func (s *Service) Writeback(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
view, err := s.actionView(ctx, findingID)
if err != nil {
return governance.ReconciliationFinding{}, err
}
if view.Finding.ActionState == "done" {
return view.Finding, nil
}
target := view.Finding.NormalizedState
if view.Finding.Type != "R5" || !AllowedWriteback(view.Finding.LedgerState, target) {
return governance.ReconciliationFinding{}, ErrActionNotAllowed
}
finding, err := s.store.WritebackReconciliationFinding(ctx, findingID, target, actor, trim(reason), s.now().UTC())
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
return governance.ReconciliationFinding{}, ErrActionConflict
}
return finding, err
}
func (s *Service) Requeue(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
view, err := s.actionView(ctx, findingID)
if err != nil {
return governance.ReconciliationFinding{}, err
}
if view.Finding.ActionState == "done" {
return view.Finding, nil
}
if view.Finding.Type != "R1" && view.Finding.Type != "R4" {
return governance.ReconciliationFinding{}, ErrActionNotAllowed
}
if view.Finding.DocumentID == "" {
return governance.ReconciliationFinding{}, ErrActionConflict
}
item, getErr := s.remote.GetKnowledge(ctx, view.Finding.DocumentID)
switch {
case getErr == nil:
if view.Finding.Type == "R1" {
// R1 said 404; if it is back now, a human must decide again.
return governance.ReconciliationFinding{}, ErrActionConflict
}
if item.KnowledgeBaseID != view.TestKBID {
return governance.ReconciliationFinding{}, ErrActionConflict
}
// R4 must remove the stale object first. Only a successful delete (or
// 404, handled below) allows the ledger reset.
if err := s.remote.DeleteKnowledge(ctx, view.Finding.DocumentID); err != nil && !weknora.IsNotFound(err) {
return governance.ReconciliationFinding{}, ErrRemoteFailed
}
case weknora.IsNotFound(getErr):
// R1/R4 both proceed: the old object is already gone.
default:
return governance.ReconciliationFinding{}, ErrRemoteFailed
}
if _, err := s.store.RequeueReconciliationPublication(ctx, findingID, view.Finding.DocumentID, actor, trim(reason), s.now().UTC()); err != nil {
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
return governance.ReconciliationFinding{}, ErrActionConflict
}
return governance.ReconciliationFinding{}, err
}
return s.reloadFinding(ctx, findingID)
}
func (s *Service) Remove(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
view, err := s.actionView(ctx, findingID)
if err != nil {
return governance.ReconciliationFinding{}, err
}
if view.Finding.ActionState == "done" {
return view.Finding, nil
}
if view.Finding.Type != "R2" || view.Finding.DocumentID == "" {
return governance.ReconciliationFinding{}, ErrActionNotAllowed
}
orphan, err := s.store.ReconciliationOrphanStillUnowned(ctx, view.Finding.PublicationID, view.Finding.DocumentID)
if err != nil {
return governance.ReconciliationFinding{}, err
}
if !orphan {
return governance.ReconciliationFinding{}, ErrActionConflict
}
item, err := s.remote.GetKnowledge(ctx, view.Finding.DocumentID)
if err != nil {
if !weknora.IsNotFound(err) {
return governance.ReconciliationFinding{}, ErrRemoteFailed
}
} else {
if item.KnowledgeBaseID != view.TestKBID {
return governance.ReconciliationFinding{}, ErrActionConflict
}
if err := s.remote.DeleteKnowledge(ctx, view.Finding.DocumentID); err != nil && !weknora.IsNotFound(err) {
return governance.ReconciliationFinding{}, ErrRemoteFailed
}
}
if err := s.store.MarkReconciliationOrphanRemoved(ctx, findingID, actor, trim(reason), s.now().UTC()); err != nil {
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
return governance.ReconciliationFinding{}, ErrActionConflict
}
return governance.ReconciliationFinding{}, err
}
return s.reloadFinding(ctx, findingID)
}
func (s *Service) actionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
view, err := s.store.LoadReconciliationActionView(ctx, findingID)
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
return view, ErrNotFound
}
return view, err
}
func (s *Service) reloadFinding(ctx context.Context, id string) (governance.ReconciliationFinding, error) {
finding, err := s.store.GetReconciliationFinding(ctx, id)
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
return finding, ErrNotFound
}
return finding, err
}
func trim(value string) string {
if len(value) > 500 {
return value[:500]
}
return value
}
+582
View File
@@ -0,0 +1,582 @@
package reconciliation
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/weknoraaccess"
)
func TestMatrixCoversEveryLedgerAndUpstreamState(t *testing.T) {
columns := []string{"pending", "processing", "finalizing", "completed", "failed", "cancelled", "deleting"}
want := map[string][]verdict{
"planned": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
"pending": {verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
"processing": {verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
"finalizing": {verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
"completed": {verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictDeleting},
"failed": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictDeleting},
"stalled": {verdictStalled, verdictStalled, verdictStalled, verdictMismatch, verdictStalled, verdictStalled, verdictDeleting},
"cancelled": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictDeleting},
}
for row, expected := range want {
for index, column := range columns {
if got := classify(row, column); got != expected[index] {
t.Fatalf("classify(%s,%s) = %v, want %v", row, column, got, expected[index])
}
}
}
if AllowedWriteback("completed", "pending") || AllowedWriteback("stalled", "completed") ||
!AllowedWriteback("failed", "pending") || AllowedWriteback("planned", "pending") ||
AllowedWriteback("pending", "cancelled") || AllowedWriteback("pending", "deleting") {
t.Fatal("writeback migration table is wrong")
}
}
type fakeReconciliationStore struct {
run governance.ReconciliationRun
ledger []governance.ReconciliationLedgerRow
removal []governance.ReconciliationLedgerRow
overlapped bool
completedRun *governance.ReconciliationRun
findings []governance.ReconciliationFinding
failCode string
actionView governance.ReconciliationActionView
actionErr error
findingAfter governance.ReconciliationFinding
writebackHit bool
requeueHit bool
removeHit bool
requeueDoc string
orphan bool
enqueued []jobs.EnqueueRequest
}
func (f *fakeReconciliationStore) ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error) {
return 0, nil
}
func (f *fakeReconciliationStore) ClaimReconciliationRun(_ context.Context, run governance.ReconciliationRun, _ time.Time) (governance.ReconciliationRun, error) {
return run, nil
}
func (f *fakeReconciliationStore) ClaimScheduledReconciliationRun(_ context.Context, run governance.ReconciliationRun, _ time.Time, _ time.Time) (governance.ReconciliationRun, bool, error) {
return run, true, nil
}
func (f *fakeReconciliationStore) LoadReconciliationRun(context.Context, string) (governance.ReconciliationRun, error) {
return f.run, nil
}
func (f *fakeReconciliationStore) ListReconciliationRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
return governance.ReconciliationRunPage{}, nil
}
func (f *fakeReconciliationStore) ListReconciliationFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
return governance.ReconciliationFindingPage{}, nil
}
func (f *fakeReconciliationStore) GetReconciliationFinding(context.Context, string) (governance.ReconciliationFinding, error) {
if f.findingAfter.ID != "" {
return f.findingAfter, nil
}
return governance.ReconciliationFinding{}, ErrNotFound
}
func (f *fakeReconciliationStore) LoadReconciliationLedger(context.Context, string) ([]governance.ReconciliationLedgerRow, error) {
return f.ledger, nil
}
func (f *fakeReconciliationStore) LoadPreviousReconciliationCounts(context.Context, string, time.Time) (governance.ReconciliationCounts, bool, error) {
return nil, false, nil
}
func (f *fakeReconciliationStore) CompleteReconciliationRun(_ context.Context, run governance.ReconciliationRun, findings []governance.ReconciliationFinding) error {
f.completedRun = &run
f.findings = findings
return nil
}
func (f *fakeReconciliationStore) FailReconciliationRun(_ context.Context, _ string, code string, _ time.Time) error {
f.failCode = code
return nil
}
func (f *fakeReconciliationStore) CleanupReconciliationFindings(context.Context, time.Time, int, time.Duration) error {
return nil
}
func (f *fakeReconciliationStore) LibraryJobsActive(context.Context) (bool, error) {
return f.overlapped, nil
}
func (f *fakeReconciliationStore) ListReconciliationRemovalCandidates(context.Context, string) ([]governance.ReconciliationLedgerRow, error) {
return f.removal, nil
}
func (f *fakeReconciliationStore) LoadReconciliationActionView(context.Context, string) (governance.ReconciliationActionView, error) {
if f.actionErr != nil {
return governance.ReconciliationActionView{}, f.actionErr
}
return f.actionView, nil
}
func (f *fakeReconciliationStore) ReconciliationOrphanStillUnowned(context.Context, string, string) (bool, error) {
return f.orphan, nil
}
func (f *fakeReconciliationStore) WritebackReconciliationFinding(context.Context, string, string, string, string, time.Time) (governance.ReconciliationFinding, error) {
f.writebackHit = true
return f.findingAfter, nil
}
func (f *fakeReconciliationStore) RequeueReconciliationPublication(_ context.Context, _ string, expectedDocument string, _ string, _ string, _ time.Time) (string, error) {
f.requeueHit = true
f.requeueDoc = expectedDocument
return "job-1", nil
}
func (f *fakeReconciliationStore) MarkReconciliationOrphanRemoved(context.Context, string, string, string, time.Time) error {
f.removeHit = true
return nil
}
func (f *fakeReconciliationStore) Enqueue(_ context.Context, request jobs.EnqueueRequest, _ time.Time) (*jobs.Job, error) {
f.enqueued = append(f.enqueued, request)
return &jobs.Job{ID: request.ID}, nil
}
type fakeReconciliationRemote struct {
items []weknora.Knowledge
missing map[string]bool
gets map[string]weknora.Knowledge
listErr error
pageSizes []int
deleteCalls int
listInFlight int
maxInFlight int
}
func (f *fakeReconciliationRemote) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
return ctx, weknora.InstanceIdentity{BaseURL: "https://test.example", TenantID: 7}, nil
}
func (f *fakeReconciliationRemote) ListKnowledge(_ context.Context, _ string, _ int, pageSize int) ([]weknora.Knowledge, int64, error) {
f.pageSizes = append(f.pageSizes, pageSize)
f.listInFlight++
if f.listInFlight > f.maxInFlight {
f.maxInFlight = f.listInFlight
}
defer func() { f.listInFlight-- }()
if f.listErr != nil {
return nil, 0, f.listErr
}
return f.items, int64(len(f.items)), nil
}
func (f *fakeReconciliationRemote) GetKnowledge(_ context.Context, id string) (weknora.Knowledge, error) {
if f.missing[id] {
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
}
if item, ok := f.gets[id]; ok {
return item, nil
}
for _, item := range f.items {
if item.ID == id {
return item, nil
}
}
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
}
func (f *fakeReconciliationRemote) DeleteKnowledge(context.Context, string) error {
f.deleteCalls++
return nil
}
func ptrTime(value time.Time) *time.Time { return &value }
func TestExecuteRunFindsR1ToR8WithoutRemoteWrites(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
ledger := []governance.ReconciliationLedgerRow{
{PublicationID: "pub-r1", KnowledgeID: "doc-r1", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", Title: "missing", UpdatedAt: now.Add(-time.Hour)},
{PublicationID: "pub-r4", KnowledgeID: "doc-r4", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UploadMD5: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
{PublicationID: "pub-r5", KnowledgeID: "doc-r5", ProcessingState: "processing", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
{PublicationID: "pub-r6", KnowledgeID: "doc-r6", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", PolicyState: "blocked", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
{PublicationID: "pub-r7", KnowledgeID: "doc-r7", ProcessingState: "stalled", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-3 * time.Hour)), UpdatedAt: now.Add(-3 * time.Hour)},
{PublicationID: "dup-pub", KnowledgeID: "doc-r8a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
}
items := []weknora.Knowledge{
{ID: "doc-r2", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "orphan-pub"}},
{ID: "doc-r3", KnowledgeBaseID: "kb-1", Channel: "web", ParseStatus: "completed"},
{ID: "doc-r4", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: "cccccccccccccccccccccccccccccccc", Metadata: map[string]any{"publication_id": "pub-r4", "content_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}},
{ID: "doc-r5", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-r5"}},
{ID: "doc-r6", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-r6"}},
{ID: "doc-r7", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-r7"}},
{ID: "doc-r8a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "dup-pub"}},
{ID: "doc-r8b", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "dup-pub"}},
}
store := &fakeReconciliationStore{
run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
ledger: ledger,
removal: []governance.ReconciliationLedgerRow{{PublicationID: "pub-r6"}},
}
// The ledger scan must be read-only over the wire, not merely against a fake
// that remembers it has no write methods. This server speaks the real client
// protocol and records every non-GET request.
var mu sync.Mutex
var writes []string
var pageSizes []int
listInFlight, maxInFlight := 0, 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
if r.Method != http.MethodGet {
writes = append(writes, r.Method+" "+r.URL.Path)
}
mu.Unlock()
path := r.URL.Path
switch {
case path == "/api/v1/knowledge-bases/kb-1":
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{"id": "kb-1", "tenant_id": 7}})
case path == "/api/v1/knowledge-bases/kb-1/knowledge":
size, _ := strconv.Atoi(r.URL.Query().Get("page_size"))
mu.Lock()
pageSizes = append(pageSizes, size)
listInFlight++
if listInFlight > maxInFlight {
maxInFlight = listInFlight
}
mu.Unlock()
defer func() {
mu.Lock()
listInFlight--
mu.Unlock()
}()
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": items, "total": len(items), "page": 1, "page_size": size})
case strings.HasPrefix(path, "/api/v1/knowledge/"):
id := strings.TrimPrefix(path, "/api/v1/knowledge/")
if id == "doc-r1" {
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "message": "not found"})
return
}
for _, item := range items {
if item.ID == id {
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": item})
return
}
}
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "message": "not found"})
default:
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
remote := &weknoraaccess.Client{
Resolver: readiness.Resolver{ResolveConnection: func(context.Context) (string, string, error) {
return server.URL, "test-key", nil
}},
Timeout: 5 * time.Second,
}
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now },
Grace: 30 * time.Minute, StallAfter: 2 * time.Hour, StaleAfter: 6 * time.Hour,
ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour,
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
if err != nil {
t.Fatal(err)
}
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
t.Fatal(err)
}
if store.completedRun == nil {
t.Fatalf("run was not completed: fail code %q", store.failCode)
}
mu.Lock()
defer mu.Unlock()
if len(writes) != 0 {
t.Fatalf("reconciliation wrote remotely over HTTP: %v", writes)
}
if len(pageSizes) == 0 || pageSizes[0] != scanPageSize {
t.Fatalf("page size = %v, want %d", pageSizes, scanPageSize)
}
if maxInFlight != 1 {
t.Fatalf("scan in-flight peak = %d, want 1", maxInFlight)
}
got := map[string]int{}
for _, finding := range store.findings {
got[finding.Type]++
}
for _, typ := range []string{"R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8"} {
if got[typ] != 1 {
t.Fatalf("%s count = %d, findings=%#v", typ, got[typ], store.findings)
}
}
if store.completedRun.Counts["R8"] != 1 || store.completedRun.LedgerCount != len(ledger) || store.completedRun.KBCount != len(items) {
t.Fatalf("run counts = %#v", store.completedRun)
}
// Every finding carries the WeKnora jump link built from the resolved test
// origin; an empty base would leave it empty, but a resolved one must not.
for _, finding := range store.findings {
if finding.WeKnoraURL != "https://test.example/platform/knowledge-bases/kb-1" {
t.Fatalf("%s weknora_url = %q", finding.Type, finding.WeKnoraURL)
}
}
}
// Two ledger publications may legitimately hold the same bytes in one test KB
// (adoption). R8 is keyed by publication_id, so that case must stay silent.
func TestR8DoesNotFlagAdoptedDuplicatesWithDistinctPublications(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
sha := strings.Repeat("a", 64)
md5 := strings.Repeat("b", 32)
row := func(pub, doc string) governance.ReconciliationLedgerRow {
return governance.ReconciliationLedgerRow{
PublicationID: pub, KnowledgeID: doc, ProcessingState: "completed", RetrievalState: "unpublished",
TargetScope: "internal", Title: doc, SHA256: sha, UploadMD5: md5, UpdatedAt: now.Add(-time.Hour),
}
}
ledger := []governance.ReconciliationLedgerRow{row("pub-a", "doc-a"), row("pub-b", "doc-b")}
items := []weknora.Knowledge{
{ID: "doc-a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: md5, Metadata: map[string]any{"publication_id": "pub-a", "content_sha256": sha}},
{ID: "doc-b", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: md5, Metadata: map[string]any{"publication_id": "pub-b", "content_sha256": sha}},
}
service, err := New(Config{Store: &fakeReconciliationStore{}, Remote: &fakeReconciliationRemote{}, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
run := governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", StartedAt: now}
findings, err := service.buildFindings(context.Background(), run, ledger, items, false)
if err != nil {
t.Fatal(err)
}
if len(findings) != 0 {
t.Fatalf("adopted duplicates produced findings: %#v", findings)
}
}
// The scan phase is serial, but confirmation may fan out up to the configured
// bound and never past it (acceptance #17).
func TestConfirmAllRespectsConfiguredConcurrency(t *testing.T) {
remote := &concurrencyRemote{}
service, err := New(Config{
Store: &fakeReconciliationStore{}, Remote: remote, ConfirmConcurrency: 2,
Now: time.Now,
})
if err != nil {
t.Fatal(err)
}
results := service.confirmAll(context.Background(), "kb-1", []string{"doc-1", "doc-2", "doc-3", "doc-4"})
if len(results) != 4 {
t.Fatalf("results = %d", len(results))
}
for id, result := range results {
if !result.notFound {
t.Fatalf("%s = %#v", id, result)
}
}
remote.mu.Lock()
peak := remote.maxInFlight
remote.mu.Unlock()
if peak != 2 {
t.Fatalf("confirm in-flight peak = %d, want 2", peak)
}
}
type concurrencyRemote struct {
fakeReconciliationRemote
mu sync.Mutex
inFlight int
maxInFlight int
}
func (r *concurrencyRemote) GetKnowledge(context.Context, string) (weknora.Knowledge, error) {
r.mu.Lock()
r.inFlight++
if r.inFlight > r.maxInFlight {
r.maxInFlight = r.inFlight
}
r.mu.Unlock()
time.Sleep(20 * time.Millisecond)
r.mu.Lock()
r.inFlight--
r.mu.Unlock()
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
}
func TestExecuteRunFailsWholeBatchWithoutFindings(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", StartedAt: now}}
remote := &fakeReconciliationRemote{listErr: errors.New("remote down")}
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
t.Fatal(err)
}
if store.completedRun != nil || len(store.findings) != 0 {
t.Fatal("partial findings were written on scan failure")
}
if store.failCode != "remote_scan_failed" {
t.Fatalf("fail code = %q", store.failCode)
}
}
func actionService(t *testing.T, store *fakeReconciliationStore, remote *fakeReconciliationRemote) *Service {
t.Helper()
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time {
return time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
}})
if err != nil {
t.Fatal(err)
}
return service
}
func TestWritebackHonorsMigrationTableAndCompletedDowngrade(t *testing.T) {
store := &fakeReconciliationStore{
actionView: governance.ReconciliationActionView{Finding: governance.ReconciliationFinding{
ID: "f1", Type: "R5", PublicationID: "pub-1", DocumentID: "doc-1",
LedgerState: "processing", NormalizedState: "completed", ActionState: "open",
}},
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
}
service := actionService(t, store, &fakeReconciliationRemote{})
if _, err := service.Writeback(context.Background(), "f1", "tester", "ok"); err != nil || !store.writebackHit {
t.Fatalf("allowed writeback err=%v hit=%t", err, store.writebackHit)
}
store.writebackHit = false
store.actionView.Finding.LedgerState = "completed"
store.actionView.Finding.NormalizedState = "pending"
if _, err := service.Writeback(context.Background(), "f1", "tester", "ok"); !errors.Is(err, ErrActionNotAllowed) || store.writebackHit {
t.Fatalf("completed downgrade err=%v hit=%t", err, store.writebackHit)
}
}
func TestRequeueR1AndR4UseTheSameSnapshotAndR4DeletesFirst(t *testing.T) {
store := &fakeReconciliationStore{
actionView: governance.ReconciliationActionView{TestKBID: "kb-1", Finding: governance.ReconciliationFinding{
ID: "f1", Type: "R1", PublicationID: "pub-1", DocumentID: "doc-1",
LedgerState: "completed", ActionState: "open",
}},
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
}
remote := &fakeReconciliationRemote{missing: map[string]bool{"doc-1": true}}
service := actionService(t, store, remote)
if _, err := service.Requeue(context.Background(), "f1", "tester", "ok"); err != nil || !store.requeueHit || store.requeueDoc != "doc-1" {
t.Fatalf("R1 requeue err=%v hit=%t doc=%q", err, store.requeueHit, store.requeueDoc)
}
store.requeueHit = false
store.actionView.Finding.Type = "R4"
item := weknora.Knowledge{ID: "doc-1", KnowledgeBaseID: "kb-1"}
remote.items = []weknora.Knowledge{item}
remote.missing = map[string]bool{}
if _, err := service.Requeue(context.Background(), "f1", "tester", "ok"); err != nil || remote.deleteCalls != 1 || !store.requeueHit {
t.Fatalf("R4 requeue err=%v deletes=%d hit=%t", err, remote.deleteCalls, store.requeueHit)
}
}
func TestRemoveR2RechecksOwnershipAndTreats404AsSuccess(t *testing.T) {
store := &fakeReconciliationStore{
orphan: true,
actionView: governance.ReconciliationActionView{TestKBID: "kb-1", Finding: governance.ReconciliationFinding{
ID: "f1", Type: "R2", DocumentID: "doc-1", ActionState: "open",
}},
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
}
remote := &fakeReconciliationRemote{missing: map[string]bool{"doc-1": true}}
service := actionService(t, store, remote)
if _, err := service.Remove(context.Background(), "f1", "tester", "ok"); err != nil || !store.removeHit {
t.Fatalf("404 removal err=%v hit=%t", err, store.removeHit)
}
store.removeHit = false
store.orphan = false
if _, err := service.Remove(context.Background(), "f1", "tester", "ok"); !errors.Is(err, ErrActionConflict) || store.removeHit {
t.Fatalf("owned removal err=%v hit=%t", err, store.removeHit)
}
}
// TestExecuteRunR6UsesRemovalCandidatesViewOnly freezes 陷阱 15: R6 and
// /monitor/overview must read one implementation. An upstream document still
// processing/finalizing, or a single read that misses the listing, must not
// remove a row from the R6 set — otherwise the two pages report different
// "需下架" numbers for the same instant.
func TestExecuteRunR6UsesRemovalCandidatesViewOnly(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
ledger := []governance.ReconciliationLedgerRow{
{PublicationID: "pub-a", KnowledgeID: "doc-a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
{PublicationID: "pub-b", KnowledgeID: "doc-b", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
{PublicationID: "pub-c", KnowledgeID: "doc-c", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)},
}
items := []weknora.Knowledge{
{ID: "doc-a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-a"}},
{ID: "doc-c", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-c"}},
}
store := &fakeReconciliationStore{
run: governance.ReconciliationRun{ID: "run-r6", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
ledger: ledger,
// The view is the authority: it lists three rows, including one whose
// upstream document is still processing and one absent from the scan.
removal: []governance.ReconciliationLedgerRow{
{PublicationID: "pub-a", KnowledgeID: "doc-a"},
{PublicationID: "pub-b", KnowledgeID: "doc-b"},
{PublicationID: "pub-c", KnowledgeID: "doc-c"},
},
}
remote := &fakeReconciliationRemote{items: items, missing: map[string]bool{"doc-b": true}}
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now },
Grace: 30 * time.Minute, StallAfter: 2 * time.Hour, StaleAfter: 6 * time.Hour,
ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour,
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
if err != nil {
t.Fatal(err)
}
if err := service.ExecuteRun(context.Background(), "run-r6"); err != nil {
t.Fatal(err)
}
r6 := map[string]governance.ReconciliationFinding{}
for _, finding := range store.findings {
if finding.Type == "R6" {
r6[finding.PublicationID] = finding
}
}
if len(r6) != len(store.removal) {
t.Fatalf("R6 count = %d, removal candidates = %d; findings=%#v", len(r6), len(store.removal), store.findings)
}
if processing, ok := r6["pub-a"]; !ok || processing.WeKnoraParseState != "processing" || processing.NormalizedState != "processing" {
t.Fatalf("R6 must keep an upstream-processing row: %#v", processing)
}
if missing, ok := r6["pub-b"]; !ok || missing.DocumentID != "doc-b" {
t.Fatalf("R6 must keep a row the scan could not list: %#v", missing)
}
if store.completedRun == nil || store.completedRun.Counts["R6"] != len(store.removal) {
t.Fatalf("run counts R6 = %#v", store.completedRun)
}
}
// TestCreateRunEnqueuesJobWithinJobIDLimit freezes the queue contract: jobs.id is
// VARCHAR(36), and the run id ("rec-" + 32 hex) already fills it. Deriving the job
// id from the run id overflowed the column, so every batch was created `failed`
// with queue_unavailable before a worker ever saw it.
func TestCreateRunEnqueuesJobWithinJobIDLimit(t *testing.T) {
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
store := &fakeReconciliationStore{
run: governance.ReconciliationRun{ID: "rec-unused", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
}
service, err := New(Config{Store: store, Queue: store, Remote: &fakeReconciliationRemote{},
Now: func() time.Time { return now }, Grace: 30 * time.Minute, StallAfter: 2 * time.Hour,
StaleAfter: 6 * time.Hour, ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour,
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
if err != nil {
t.Fatal(err)
}
run, err := service.CreateRun(context.Background(), "kb-1", "manual")
if err != nil {
t.Fatalf("CreateRun error = %v", err)
}
if len(store.enqueued) != 1 {
t.Fatalf("enqueued %d jobs", len(store.enqueued))
}
request := store.enqueued[0]
if len(request.ID) != 36 {
t.Fatalf("job id %q length = %d, want exactly 36 (VARCHAR(36))", request.ID, len(request.ID))
}
if request.Type != "reconciliation.run" || request.IdempotencyKey != "reconciliation-run:"+run.ID {
t.Fatalf("enqueue request = %#v", request)
}
if string(request.Payload) != `{"run_id":"`+run.ID+`"}` {
t.Fatalf("payload = %s", request.Payload)
}
}
@@ -274,7 +274,9 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
}
var bodies []json.RawMessage
for _, table := range pg.Tables {
bodies = append(bodies, table.Rows...)
if libraryResourceBodyTable(table.Name) {
bodies = append(bodies, table.Rows...)
}
}
references, err := libraryResourceHandles(bodies)
if err != nil {
@@ -35,7 +35,7 @@ func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identit
return PostgresSnapshot{}, err
}
rowsByTable[table] = rows
if table != "resource_bindings" && table != "knowledge_tag_relations" {
if libraryResourceBodyTable(table) {
bodies = append(bodies, rows...)
}
if table == "resource_bindings" {
@@ -0,0 +1,165 @@
package v071
import (
"context"
"errors"
"fmt"
"sort"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/libraryprofile"
)
// 漏表门禁:profile 只声明"必须存在什么",不声明"存在但没见过的表怎么办"。
// 于是 0.9.0 起 chunk_revisions / wiki_page_revisions 一直被静默跳过。这里用
// information_schema 反向扫描所有带知识列的表,按 profile 分类放行;未分类且
// 本次范围内有数据就拒绝,空表放行但留下警告。导出前(源库)与导入前(目标库)
// 各执行一次。
//
// 为什么错误不可重试:表没分类是契约缺口,重试不会让分类长出来;必须补 profile
// 或明确排除。错误里带表名与行数,运维不用再猜是哪张表。
const ReleaseUndeclaredKBTableCode = "release_undeclared_kb_table"
type UndeclaredKBTable struct {
Table string
Rows int64
}
type UndeclaredKBTableError struct {
Tables []UndeclaredKBTable
}
func (e *UndeclaredKBTableError) Error() string {
parts := make([]string, 0, len(e.Tables))
for _, table := range e.Tables {
if table.Rows < 0 {
parts = append(parts, table.Table+"(行数无法判定)")
continue
}
parts = append(parts, fmt.Sprintf("%s(%d 行)", table.Table, table.Rows))
}
return fmt.Sprintf("%s: 未声明的知识域表在本次发布范围内仍有数据:%v;先补 profile 关联表分类并接入整库搬运,或明确排除并写明理由。此错误不可重试。",
ReleaseUndeclaredKBTableCode, parts)
}
// knowledgeTableGateMarker 让测试夹具能区分"门禁探测"与"能力探测":两者都查
// information_schema.columns,但回答的列形状不同(表+列集合 vs 表+列)。
const knowledgeTableGateMarker = "/* knowledge-table-gate */"
const knowledgeScopedColumnsSQL = knowledgeTableGateMarker + `
SELECT c.table_name, array_agg(c.column_name ORDER BY c.column_name)
FROM information_schema.columns c
JOIN (
SELECT DISTINCT table_name
FROM information_schema.columns
WHERE table_schema='public' AND column_name IN ('knowledge_base_id','knowledge_id','kb_id')
) k ON k.table_name = c.table_name
WHERE c.table_schema='public'
GROUP BY c.table_name
ORDER BY c.table_name`
// verifyDeclaredKnowledgeTables 返回放行警告(未分类但为空的表);有未分类且
// 非空的表时返回 UndeclaredKBTableError。identity 是本知识库范围。
func verifyDeclaredKnowledgeTables(ctx context.Context, db schemaProbeDB, identity PostgresIdentity,
profile libraryprofile.Profile) ([]string, error) {
if identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) {
return nil, errors.New("漏表门禁缺少有效的知识库范围身份")
}
// 没有分类的 profile 不允许"静默跳过门禁":那等于把契约缺口藏起来。
if len(profile.RelatedTables) == 0 {
return nil, fmt.Errorf("profile %s 没有关联表分类,拒绝跳过漏表门禁", profile.Name)
}
rows, err := db.Query(ctx, knowledgeScopedColumnsSQL)
if err != nil {
return nil, fmt.Errorf("读取知识域表清单失败: %w", err)
}
defer rows.Close()
unclassified := make([]string, 0, 4)
columnsByTable := map[string]map[string]bool{}
for rows.Next() {
var table string
var columns []string
if err := rows.Scan(&table, &columns); err != nil {
return nil, fmt.Errorf("解析知识域表清单失败: %w", err)
}
if _, ok := profile.RelatedTableClass(table); ok {
continue
}
set := make(map[string]bool, len(columns))
for _, column := range columns {
set[column] = true
}
columnsByTable[table] = set
unclassified = append(unclassified, table)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("遍历知识域表清单失败: %w", err)
}
blocked := make([]UndeclaredKBTable, 0, len(unclassified))
warnings := make([]string, 0, len(unclassified))
for _, table := range unclassified {
count, ok := scopedKnowledgeTableCountSQL(table, columnsByTable[table], identity)
if !ok {
// 候选表却没有可用的范围列:无法证明"本次范围内有没有数据",
// 只能按有数据处理,避免把范围外的表误放行。
blocked = append(blocked, UndeclaredKBTable{Table: table, Rows: -1})
continue
}
var total int64
if err := db.QueryRow(ctx, count.sql, count.args...).Scan(&total); err != nil {
return nil, fmt.Errorf("统计未声明表 %s 失败: %w", table, err)
}
if total > 0 {
blocked = append(blocked, UndeclaredKBTable{Table: table, Rows: total})
continue
}
warnings = append(warnings, fmt.Sprintf(
"%s: 未分类表 %q 在本次范围内为空,已放行;请补 profile 关联表分类", ReleaseUndeclaredKBTableCode, table))
}
sort.Slice(blocked, func(i, j int) bool { return blocked[i].Table < blocked[j].Table })
sort.Strings(warnings)
if len(blocked) > 0 {
return nil, &UndeclaredKBTableError{Tables: blocked}
}
return warnings, nil
}
type scopedCount struct {
sql string
args []any
}
// scopedKnowledgeTableCountSQL 按"这张表实际有的范围列"构造计数:有
// knowledge_base_id 优先按 tenant+kb;有 kb_id 按 tenant+kb_id;只有
// knowledge_id 时走 knowledges 子查询。没有 tenant_id 的表(如 kb_shares)
// 只能按知识库身份过滤,不能硬塞一个不存在的列。
func scopedKnowledgeTableCountSQL(table string, columns map[string]bool,
identity PostgresIdentity) (scopedCount, bool) {
quoted := pgx.Identifier{"public", table}.Sanitize()
hasTenant := columns["tenant_id"]
var where string
var args []any
switch {
case columns["knowledge_base_id"]:
if hasTenant {
where, args = "tenant_id=$1 AND knowledge_base_id=$2", []any{identity.TenantID, identity.KnowledgeBaseID}
} else {
where, args = "knowledge_base_id=$1", []any{identity.KnowledgeBaseID}
}
case columns["kb_id"]:
if hasTenant {
where, args = "tenant_id=$1 AND kb_id=$2", []any{identity.TenantID, identity.KnowledgeBaseID}
} else {
where, args = "kb_id=$1", []any{identity.KnowledgeBaseID}
}
case columns["knowledge_id"]:
where = "knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)"
args = []any{identity.TenantID, identity.KnowledgeBaseID}
default:
return scopedCount{}, false
}
return scopedCount{sql: "/* knowledge-table-gate-count */ SELECT count(*) FROM " + quoted + " WHERE " + where, args: args}, true
}
@@ -0,0 +1,262 @@
package v071
import (
"context"
"errors"
"reflect"
"strings"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"knowledge-governance/internal/libraryprofile"
)
// gateRows 回答门禁的 information_schema 探测:table → 列集合。
type gateRows struct {
tables [][2]any
index int
}
func (r *gateRows) Close() {}
func (r *gateRows) Err() error { return nil }
func (r *gateRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} }
func (r *gateRows) FieldDescriptions() []pgconn.FieldDescription { return nil }
func (r *gateRows) RawValues() [][]byte { return nil }
func (r *gateRows) Conn() *pgx.Conn { return nil }
func (r *gateRows) Next() bool {
if r.index >= len(r.tables) {
return false
}
r.index++
return true
}
func (r *gateRows) Scan(dest ...any) error {
*dest[0].(*string) = r.tables[r.index-1][0].(string)
*dest[1].(*[]string) = r.tables[r.index-1][1].([]string)
_ = dest
return nil
}
func (r *gateRows) Values() ([]any, error) { return nil, nil }
type gateCountRow struct{ value *int64 }
func (r gateCountRow) Scan(dest ...any) error { *dest[0].(*int64) = *r.value; return nil }
// gateDB 只实现门禁需要的两个入口:探测表/列 + 按表计数。
type gateDB struct {
candidates []struct {
table string
columns []string
}
counts map[string]int64
}
func (d gateDB) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {
if !strings.Contains(sql, "knowledge-table-gate") {
return nil, errors.New("unexpected query: " + sql)
}
rows := &gateRows{}
for _, candidate := range d.candidates {
rows.tables = append(rows.tables, [2]any{candidate.table, candidate.columns})
}
return rows, nil
}
func (d gateDB) QueryRow(_ context.Context, sql string, _ ...any) pgx.Row {
for table, count := range d.counts {
if strings.Contains(sql, `"public"."`+table+`"`) {
value := count
return gateCountRow{value: &value}
}
}
return gateCountRow{value: new(int64)}
}
func gateProfile(t *testing.T) libraryprofile.Profile {
t.Helper()
profile, err := libraryprofile.For(libraryprofile.V091Version)
if err != nil {
t.Fatal(err)
}
return profile
}
func TestDeclaredTableGateRejectsUnclassifiedTableWithRows(t *testing.T) {
profile := gateProfile(t)
db := gateDB{
candidates: []struct {
table string
columns []string
}{
{"mystery_kb_table", []string{"id", "knowledge_base_id", "tenant_id"}},
},
counts: map[string]int64{"mystery_kb_table": 7},
}
_, err := verifyDeclaredKnowledgeTables(context.Background(), db,
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
var blocked *UndeclaredKBTableError
if !errors.As(err, &blocked) {
t.Fatalf("unclassified table with rows must be refused, got %v", err)
}
if !strings.Contains(err.Error(), ReleaseUndeclaredKBTableCode) ||
!strings.Contains(err.Error(), "mystery_kb_table") || !strings.Contains(err.Error(), "7 行") {
t.Fatalf("error must name code/table/rows, got %v", err)
}
if !strings.Contains(err.Error(), "不可重试") {
t.Fatalf("error must state non-retryable, got %v", err)
}
}
func TestDeclaredTableGateAllowsEmptyUnclassifiedTableWithWarning(t *testing.T) {
profile := gateProfile(t)
db := gateDB{
candidates: []struct {
table string
columns []string
}{
{"mystery_kb_table", []string{"id", "knowledge_base_id", "tenant_id"}},
},
counts: map[string]int64{"mystery_kb_table": 0},
}
warnings, err := verifyDeclaredKnowledgeTables(context.Background(), db,
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
if err != nil {
t.Fatalf("empty unclassified table must pass: %v", err)
}
if len(warnings) != 1 || !strings.Contains(warnings[0], "mystery_kb_table") ||
!strings.Contains(warnings[0], ReleaseUndeclaredKBTableCode) {
t.Fatalf("expected one persisted warning naming the table, got %v", warnings)
}
}
func TestDeclaredTableGateAllowsClassifiedTables(t *testing.T) {
profile := gateProfile(t)
db := gateDB{
candidates: []struct {
table string
columns []string
}{
{"chunk_images", []string{"knowledge_base_id", "knowledge_id"}},
{"sessions", []string{"knowledge_base_id", "tenant_id"}},
{"messages", []string{"knowledge_id", "tenant_id"}},
{"data_sources", []string{"knowledge_base_id"}},
{"chunks", []string{"knowledge_base_id", "knowledge_id"}},
},
counts: map[string]int64{"sessions": 27, "messages": 90, "chunk_images": 3},
}
warnings, err := verifyDeclaredKnowledgeTables(context.Background(), db,
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
if err != nil || len(warnings) != 0 {
t.Fatalf("derived/excluded/copied tables must pass silently, got %v/%v", warnings, err)
}
}
func TestDeclaredTableGateRefusesProfileWithoutClassification(t *testing.T) {
_, err := verifyDeclaredKnowledgeTables(context.Background(), gateDB{},
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, libraryprofile.Profile{Name: "bare"})
if err == nil || !strings.Contains(err.Error(), "分类") {
t.Fatalf("a profile without classification must not skip the gate, got %v", err)
}
}
func TestScopedKnowledgeTableCountSQLUsesExistingColumns(t *testing.T) {
identity := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}
cases := []struct {
name string
columns map[string]bool
wantSQL string
want []any
}{
{"kb+tenant", map[string]bool{"knowledge_base_id": true, "tenant_id": true},
`tenant_id=$1 AND knowledge_base_id=$2`, []any{uint64(10000), "kb-safe"}},
{"kb without tenant", map[string]bool{"knowledge_base_id": true},
`knowledge_base_id=$1`, []any{"kb-safe"}},
{"kb_id+tenant", map[string]bool{"kb_id": true, "tenant_id": true},
`tenant_id=$1 AND kb_id=$2`, []any{uint64(10000), "kb-safe"}},
{"kb_id without tenant", map[string]bool{"kb_id": true},
`kb_id=$1`, []any{"kb-safe"}},
{"knowledge only", map[string]bool{"knowledge_id": true},
`knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)`,
[]any{uint64(10000), "kb-safe"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
count, ok := scopedKnowledgeTableCountSQL("t", tc.columns, identity)
if !ok || !strings.Contains(count.sql, tc.wantSQL) {
t.Fatalf("sql=%q ok=%v, want fragment %q", count.sql, ok, tc.wantSQL)
}
if !reflect.DeepEqual(count.args, tc.want) {
t.Fatalf("args=%v, want %v", count.args, tc.want)
}
})
}
if _, ok := scopedKnowledgeTableCountSQL("t", map[string]bool{"id": true}, identity); ok {
t.Fatal("a table without any scope column must not be treated as countable")
}
}
// 导出路径必须真的执行门禁:候选表有数据时在封存前就失败。
type gateExportDB struct {
candidates []struct {
table string
columns []string
}
counts map[string]int64
}
func (d gateExportDB) BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error) {
return &gateExportTx{db: d}, nil
}
type gateExportTx struct {
pgx.Tx
db gateExportDB
}
func (tx *gateExportTx) Commit(context.Context) error { return nil }
func (tx *gateExportTx) Rollback(context.Context) error { return nil }
func (tx *gateExportTx) QueryRow(_ context.Context, sql string, _ ...any) pgx.Row {
if strings.Contains(sql, "schema_migrations") {
return gateSchemaRow{}
}
for table, count := range tx.db.counts {
if strings.Contains(sql, `"public"."`+table+`"`) {
value := count
return gateCountRow{value: &value}
}
}
return gateCountRow{value: new(int64)}
}
func (tx *gateExportTx) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {
if strings.Contains(sql, "knowledge-table-gate") {
rows := &gateRows{}
for _, candidate := range tx.db.candidates {
rows.tables = append(rows.tables, [2]any{candidate.table, candidate.columns})
}
return rows, nil
}
return legacySchemaProbeRows(), nil
}
type gateSchemaRow struct{}
func (gateSchemaRow) Scan(dest ...any) error {
*dest[0].(*int) = 74
*dest[1].(*bool) = false
return nil
}
func TestExportRunsDeclaredTableGateBeforeSealing(t *testing.T) {
db := gateExportDB{candidates: []struct {
table string
columns []string
}{{"mystery_kb_table", []string{"knowledge_base_id", "tenant_id"}}},
counts: map[string]int64{"mystery_kb_table": 2}}
_, err := ExportLibrary(context.Background(), db,
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"})
if err == nil || !strings.Contains(err.Error(), ReleaseUndeclaredKBTableCode) {
t.Fatalf("export must fail closed on undeclared table data, got %v", err)
}
}
+65 -1
View File
@@ -4,6 +4,10 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"github.com/jackc/pgx/v5"
)
@@ -34,6 +38,17 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
if err != nil {
return PostgresSnapshot{}, err
}
// 漏表门禁:在同一个只读快照事务里做,避免"检查完又长出未声明表"。
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, tx, identity, profile.Profile)
if err != nil {
return PostgresSnapshot{}, err
}
for _, warning := range gateWarnings {
log.Printf("library export declared-table gate: %s", warning)
}
if err := verifyRevisionParentClosure(ctx, tx, identity, profile); 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 {
return PostgresSnapshot{}, errors.New("source library unavailable")
@@ -85,7 +100,7 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
// The latter includes Wiki manual pages, which document bundles used to miss.
var bodies []json.RawMessage
for _, table := range snapshot.Tables {
if table.Name == "resource_bindings" || table.Name == "knowledge_tag_relations" {
if !libraryResourceBodyTable(table.Name) {
continue
}
bodies = append(bodies, table.Rows...)
@@ -147,13 +162,62 @@ const librarySettlementSQL = `SELECT
(SELECT count(*) FROM task_pending_ops WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)))),
(SELECT count(*) FROM task_dead_letters WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2))))`
// verifyRevisionParentClosure 只拒绝"父行完全不存在/父关系错乱"的修订行;
// 父行被软删的修订属于本次范围外(整库只发活跃内容),随父行一起不导出。
// 这与"历史日志按展示事实保留"不同:修订行的 chunk_id/page_id 是结构引用,
// 真缺失只可能是数据异常,不能静默跳过。
func verifyRevisionParentClosure(ctx context.Context, db schemaProbeDB, identity PostgresIdentity, profile SchemaProfile) error {
checks := make([]string, 0, 3)
labels := make([]string, 0, 3)
if profile.HasTable("chunk_revisions") {
checks = append(checks, `(SELECT count(*) FROM chunk_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
AND NOT EXISTS (SELECT 1 FROM chunks c WHERE c.id=r.chunk_id AND c.tenant_id=r.tenant_id))`)
labels = append(labels, "chunk_revisions 缺少 chunk 父行")
checks = append(checks, `(SELECT count(*) FROM chunk_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
AND EXISTS (SELECT 1 FROM chunks c WHERE c.id=r.chunk_id AND c.tenant_id=r.tenant_id AND (c.knowledge_id<>r.knowledge_id OR c.knowledge_base_id<>r.knowledge_base_id)))`)
labels = append(labels, "chunk_revisions 与父 chunk 的 knowledge_id/knowledge_base_id 不一致")
}
if profile.HasTable("wiki_page_revisions") {
checks = append(checks, `(SELECT count(*) FROM wiki_page_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
AND NOT EXISTS (SELECT 1 FROM wiki_pages p WHERE p.id=r.page_id AND p.tenant_id=r.tenant_id AND p.knowledge_base_id=r.knowledge_base_id))`)
labels = append(labels, "wiki_page_revisions 缺少 page 父行")
}
if len(checks) == 0 {
return nil
}
var counts = make([]int64, len(checks))
dest := make([]any, len(checks))
for index := range counts {
dest[index] = &counts[index]
}
if err := db.QueryRow(ctx, "/* library-revision-closure */ SELECT "+strings.Join(checks, ", "),
identity.TenantID, identity.KnowledgeBaseID).Scan(dest...); err != nil {
return fmt.Errorf("读取编辑历史父关系失败: %w", err)
}
problems := make([]string, 0, len(counts))
for index, count := range counts {
if count > 0 {
problems = append(problems, fmt.Sprintf("%s:%d 行", labels[index], count))
}
}
if len(problems) > 0 {
return fmt.Errorf("编辑历史存在无法解析的父引用,拒绝整库发布:%v", problems)
}
return nil
}
var libraryContentQueries = []struct{ name, sql string }{
{"knowledges", `SELECT to_jsonb(k) FROM knowledges k WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL ORDER BY k.id`},
{"chunks", `SELECT to_jsonb(c) 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 k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND c.deleted_at IS NULL ORDER BY c.id`},
// 编辑历史:只随活跃父行发布。父行被软删(不在本次范围)时不搬它的历史;
// 父行完全缺失属于数据异常,由 verifyRevisionParentClosure 拒绝,不静默跳过。
{"chunk_revisions", `SELECT to_jsonb(r) FROM chunk_revisions r JOIN chunks c ON c.id=r.chunk_id AND c.tenant_id=r.tenant_id AND c.knowledge_base_id=r.knowledge_base_id 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 r.tenant_id=$1 AND r.knowledge_base_id=$2 AND r.knowledge_id=c.knowledge_id AND c.deleted_at IS NULL AND k.deleted_at IS NULL ORDER BY r.id`},
{"knowledge_tags", `SELECT to_jsonb(t) FROM knowledge_tags t WHERE t.tenant_id=$1 AND t.knowledge_base_id=$2 AND t.deleted_at IS NULL ORDER BY t.id`},
{"knowledge_tag_relations", `SELECT to_jsonb(r) FROM knowledge_tag_relations r JOIN knowledges k ON k.id=r.knowledge_id JOIN knowledge_tags t ON t.id=r.tag_id AND t.tenant_id=k.tenant_id AND t.knowledge_base_id=k.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY r.knowledge_id,r.tag_id`},
{"resource_bindings", `SELECT to_jsonb(b) 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 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 b.id`},
{"wiki_pages", `SELECT to_jsonb(w) FROM wiki_pages w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
// 编辑历史:与 chunk_revisions 同一规则(活跃父行 + 真悬挂由守卫拒绝)。
{"wiki_page_revisions", `SELECT to_jsonb(r) FROM wiki_page_revisions r JOIN wiki_pages p ON p.id=r.page_id AND p.tenant_id=r.tenant_id AND p.knowledge_base_id=r.knowledge_base_id WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2 AND p.deleted_at IS NULL ORDER BY r.id`},
{"wiki_folders", `SELECT to_jsonb(w) FROM wiki_folders w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
{"wiki_page_issues", `SELECT to_jsonb(w) FROM wiki_page_issues w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
{"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`},
@@ -103,6 +103,11 @@ func (d *libraryFixtureTx) Query(_ context.Context, q string, _ ...any) (pgx.Row
if d.queryError {
return nil, errors.New("fixture failure")
}
// 漏表门禁也查 information_schema,但回答形状是(表,列集合);与能力探测分开打桩,
// 否则会被当成两列结果扫描。74 夹具没有任何未分类的知识域表。
if strings.Contains(q, "knowledge-table-gate") {
return &jsonRows{}, nil
}
// 能力探测走真实 SQL:假库按 0.7.1 profile 回答,避免"桩放行"。
if strings.Contains(q, "information_schema.columns") {
return legacySchemaProbeRows(), nil
@@ -31,7 +31,11 @@ var migrationIdentityContracts = map[string]rowIdentityContract{
"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"},
// 编辑历史:稳定字符串身份;id 是它自己的身份,chunk_id/page_id/knowledge_id
// 是引用(由 remapRow 显式映射)。两表都没有 deleted_at。
"chunk_revisions": {Columns: []string{"id"}, Kind: "stable-string"},
"wiki_page_revisions": {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 {
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
"log"
"net/http"
"sort"
"strings"
@@ -344,12 +345,16 @@ func (t *ProductionLibraryTarget) tableState(ctx context.Context, table string)
if name == "resources" {
continue
}
// 只需正文表与绑定表;修订历史按 Q2=B 不参与资源发现,不为它做整表扫描。
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
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" {
if name != "resource_bindings" && name != "knowledge_tag_relations" && libraryResourceBodyTable(name) {
bodies = append(bodies, items...)
}
if name == "resource_bindings" {
@@ -479,6 +484,16 @@ func (t *ProductionLibraryTarget) importRows(ctx context.Context, archive *libra
return errors.New("开启生产事务失败")
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
// 漏表门禁的最终判定:在写事务内、任何 DELETE 之前。放在事务外检查会留下
// "查完到写前"的窗口,未声明表的数据可能在这段时间被写进来。
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, tx,
PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, t.schema.Profile)
if err != nil {
return err
}
for _, warning := range gateWarnings {
log.Printf("library import declared-table gate: %s", warning)
}
for index := len(t.tables) - 1; index >= 0; index-- {
table := t.tables[index]
if _, ok := parts[table]; !ok {
@@ -104,7 +104,7 @@ func TestV090ProductionTargetPublishIsolated(t *testing.T) {
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)
call("PUT", "/"+index, `{"mappings":{"properties":{"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)
@@ -375,7 +375,7 @@ func v090PublishIndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA stri
t.Fatalf("decode chunk: %v", err)
}
source, err := json.Marshal(map[string]any{
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
"chunk_id": chunk.ID,
"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},
@@ -57,6 +57,10 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
t.Fatalf("unexpected fixture shape: chunks=%d knowledges=%d",
source.Table("chunks").RowCount, source.Table("knowledges").RowCount)
}
if source.Table("chunk_revisions").RowCount != 1 || source.Table("wiki_page_revisions").RowCount != 1 {
t.Fatalf("editing history must be exported: chunk_revisions=%d wiki_page_revisions=%d",
source.Table("chunk_revisions").RowCount, source.Table("wiki_page_revisions").RowCount)
}
es := v090IndexSnapshot(t, source, mappingSHA)
root := t.TempDir()
@@ -90,6 +94,13 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
t.Fatal("0.9.0 archive must not contain a wiki_log_entries part")
}
}
seenParts := map[string]bool{}
for _, part := range manifest.Parts {
seenParts[part.Kind+"/"+part.Name] = true
}
if !seenParts["database/chunk_revisions"] || !seenParts["wiki/wiki_page_revisions"] {
t.Fatalf("revision parts must be archived: %v", seenParts)
}
dst := v090Pool(t, "KG_V090_TARGET_DSN")
if err := seedV090Binding(t, ctx, dst); err != nil {
@@ -100,14 +111,21 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
t.Fatal(err)
}
document := PostgresIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: v090Knowledge}
if err := importer.Replace(ctx, document, source); err != nil {
// 文档级 Replace 只写单文档相关表;编辑历史走整库 Apply(0.9.0 发布目标用例覆盖)。
documentSource := withoutRevisionTables(source)
if err := importer.Replace(ctx, document, documentSource); 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)
compareSnapshotContent(t, documentSource, withoutRevisionTables(reloaded))
for _, table := range []string{"chunk_revisions", "wiki_page_revisions"} {
if reloaded.Table(table).RowCount != 0 {
t.Fatalf("document-level import must not invent %s rows", table)
}
}
// 0.9.0 新增的 NOT NULL 列在导入后必须仍是合法值,且 seq_id 由目标序列分配。
var defaults int
@@ -130,7 +148,7 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
}
// 跨版本必须拒绝:0.7.1 归档不能落到 0.9.0 目标。
crossVersion := source
crossVersion := documentSource
crossVersion.SchemaVersion = 74
crossVersion.Profile = "v071"
err = importer.Replace(ctx, document, crossVersion)
@@ -139,6 +157,18 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
}
}
func withoutRevisionTables(snapshot PostgresSnapshot) PostgresSnapshot {
tables := make([]TableSnapshot, 0, len(snapshot.Tables))
for _, table := range snapshot.Tables {
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
continue
}
tables = append(tables, table)
}
snapshot.Tables = tables
return snapshot
}
// compareSnapshotContent 逐表逐行比对"共有列"的规范化内容。
// chunks.seq_id 是库级序列值、不是文档内容,导入时由目标分配,故排除比对。
func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
@@ -147,6 +177,9 @@ func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
t.Fatalf("table set changed across round trip: %d -> %d", len(source.Tables), len(target.Tables))
}
for _, table := range source.Tables {
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
continue
}
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) {
@@ -9,13 +9,26 @@ import (
"knowledge-governance/internal/libraryrelease"
)
// libraryResourceBodyTable 报告该表是否参与"正文引用资源"的发现与作用域。
//
// 编辑历史按人类裁定(Q2=B)原样保留 resource:// 文本,不参与资源发现:历史版本
// 引用的对象可能早已删除,不能让它决定本次发布必须携带哪些对象。资源发现、目标
// 资源作用域、恢复保护三处必须用同一个判定,否则导出与校验会各算一套集合。
func libraryResourceBodyTable(table string) bool {
switch table {
case "resources", "resource_bindings", "knowledge_tag_relations", "chunk_revisions", "wiki_page_revisions":
return false
}
return true
}
// 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" {
if !libraryResourceBodyTable(table) {
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))
@@ -0,0 +1,187 @@
package v071
import (
"encoding/json"
"errors"
"strings"
"testing"
)
func revisionMapper() *targetIDMapper {
mapper := newTargetIDMapper(10001, "kb-target", nil)
for table, ids := range map[string][]string{
"knowledges": {"doc-src"},
"chunks": {"chunk-src"},
"wiki_pages": {"page-src"},
"chunk_revisions": {"crev-src"},
"wiki_page_revisions": {"wrev-src"},
} {
for _, id := range ids {
mapper.registerSourceID(table, id)
}
}
return mapper
}
func TestRevisionRowsUseTheSameScopeAndIdentityMapping(t *testing.T) {
mapper := revisionMapper()
chunkRevision := map[string]json.RawMessage{
"id": json.RawMessage(`"crev-src"`),
"knowledge_id": json.RawMessage(`"doc-src"`),
"chunk_id": json.RawMessage(`"chunk-src"`),
"revision": json.RawMessage(`3`),
"content": json.RawMessage(`"edit history text"`),
"editor_id": json.RawMessage(`"user-9"`),
"knowledge_base_id": json.RawMessage(`"kb-source"`),
}
if err := mapper.remapRow("chunk_revisions", chunkRevision); err != nil {
t.Fatalf("chunk revision mapping: %v", err)
}
if string(chunkRevision["id"]) != `"`+mapper.mapID("chunk_revisions", "crev-src")+`"` {
t.Fatal("revision id must be target-mapped")
}
if string(chunkRevision["chunk_id"]) != `"`+mapper.mapID("chunks", "chunk-src")+`"` {
t.Fatal("chunk_id must map to the target chunk identity")
}
if string(chunkRevision["knowledge_id"]) != `"`+mapper.mapID("knowledges", "doc-src")+`"` {
t.Fatal("knowledge_id must map to the target knowledge identity")
}
// editor_id 是用户身份,原样保留(目标查不到显示未知编辑者)。
if string(chunkRevision["editor_id"]) != `"user-9"` {
t.Fatal("editor_id must be preserved")
}
pageRevision := map[string]json.RawMessage{
"id": json.RawMessage(`"wrev-src"`),
"page_id": json.RawMessage(`"page-src"`),
"slug": json.RawMessage(`"legacy-slug"`),
"version": json.RawMessage(`2`),
"content": json.RawMessage(`"wiki history"`),
"knowledge_base_id": json.RawMessage(`"kb-source"`),
}
if err := mapper.remapRow("wiki_page_revisions", pageRevision); err != nil {
t.Fatalf("wiki page revision mapping: %v", err)
}
if string(pageRevision["page_id"]) != `"`+mapper.mapID("wiki_pages", "page-src")+`"` {
t.Fatal("page_id must map to the target page identity")
}
if string(pageRevision["slug"]) != `"legacy-slug"` {
t.Fatal("slug is content, not identity; it must be preserved")
}
}
func TestRevisionDanglingReferencesAreRefused(t *testing.T) {
mapper := revisionMapper()
cases := []struct {
name string
row map[string]json.RawMessage
}{
{"unknown chunk", map[string]json.RawMessage{
"id": json.RawMessage(`"crev-unknown"`), "knowledge_id": json.RawMessage(`"doc-src"`),
"chunk_id": json.RawMessage(`"chunk-other"`), "revision": json.RawMessage(`1`),
}},
{"unknown page", map[string]json.RawMessage{
"id": json.RawMessage(`"wrev-unknown"`), "page_id": json.RawMessage(`"page-other"`),
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
table := "chunk_revisions"
if tc.name == "unknown page" {
table = "wiki_page_revisions"
}
err := mapper.remapRow(table, tc.row)
if !errors.Is(err, errUnmappedTargetReference) || !strings.Contains(err.Error(), "unmapped") {
t.Fatalf("dangling reference must be refused, got %v", err)
}
})
}
}
func TestRevisionUniqueIndexKeysStayUniqueAfterMapping(t *testing.T) {
mapper := revisionMapper()
// 同一 chunk 的两个 revision:chunk_id 映射后仍相同,revision 仍是 1/2,
// 因此 (chunk_id, revision) 唯一性不会被映射破坏。
rows := []map[string]json.RawMessage{
{"id": json.RawMessage(`"crev-src"`), "knowledge_id": json.RawMessage(`"doc-src"`),
"chunk_id": json.RawMessage(`"chunk-src"`), "revision": json.RawMessage(`1`)},
{"id": json.RawMessage(`"crev-src2"`), "knowledge_id": json.RawMessage(`"doc-src"`),
"chunk_id": json.RawMessage(`"chunk-src"`), "revision": json.RawMessage(`2`)},
}
mapper.registerSourceID("chunk_revisions", "crev-src2")
mapped := map[string]bool{}
for _, row := range rows {
if err := mapper.remapRow("chunk_revisions", row); err != nil {
t.Fatal(err)
}
key := string(row["chunk_id"]) + "/" + string(row["revision"])
if mapped[key] {
t.Fatalf("mapped unique key collided: %s", key)
}
mapped[key] = true
}
if len(mapped) != 2 {
t.Fatal("both revision keys must remain distinct")
}
}
func TestRevisionTablesAreDeletedBeforeParents(t *testing.T) {
position := map[string]int{}
for index, table := range jobCreatedRowDeleteOrder {
position[table] = index
}
for _, child := range []string{"wiki_page_revisions", "chunk_revisions"} {
if _, ok := position[child]; !ok {
t.Fatalf("%s missing from recovery delete order", child)
}
}
if position["chunk_revisions"] > position["chunks"] {
t.Fatal("chunk_revisions must be deleted before chunks")
}
if position["wiki_page_revisions"] > position["wiki_pages"] {
t.Fatal("wiki_page_revisions must be deleted before wiki_pages")
}
}
func TestRevisionTablesAreNotResourceBodies(t *testing.T) {
for _, table := range []string{"chunk_revisions", "wiki_page_revisions"} {
if libraryResourceBodyTable(table) {
t.Fatalf("%s must not participate in resource discovery (Q2=B)", table)
}
}
sql := libraryResourceBodyReferenceSQL([]string{"chunks", "chunk_revisions", "wiki_page_revisions"}, "TRUE")
if strings.Contains(sql, "chunk_revisions") || strings.Contains(sql, "wiki_page_revisions") {
t.Fatalf("resource reference SQL must exclude revision tables: %s", sql)
}
if !strings.Contains(sql, "FROM chunks") {
t.Fatal("resource reference SQL must still scan live chunks")
}
}
func TestStructuredReferenceValidationCoversRevisions(t *testing.T) {
snapshot := PostgresSnapshot{Tables: []TableSnapshot{
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-1"}`)}),
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-1","knowledge_id":"doc-1"}`)}),
newTableSnapshot("chunk_revisions", []json.RawMessage{
json.RawMessage(`{"id":"crev-1","knowledge_id":"doc-1","chunk_id":"chunk-1"}`),
}),
newTableSnapshot("wiki_pages", []json.RawMessage{json.RawMessage(`{"id":"page-1"}`)}),
newTableSnapshot("wiki_page_revisions", []json.RawMessage{
json.RawMessage(`{"id":"wrev-1","page_id":"page-1"}`),
}),
}}
if err := validateLibraryStructuredReferences(snapshot); err != nil {
t.Fatalf("resolved revision references must pass: %v", err)
}
broken := snapshot
broken.Tables = []TableSnapshot{
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-1"}`)}),
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-1","knowledge_id":"doc-1"}`)}),
newTableSnapshot("chunk_revisions", []json.RawMessage{
json.RawMessage(`{"id":"crev-1","knowledge_id":"doc-1","chunk_id":"chunk-missing"}`),
}),
}
if err := validateLibraryStructuredReferences(broken); err == nil || !strings.Contains(err.Error(), "chunk_id") {
t.Fatalf("missing chunk parent must be refused, got %v", err)
}
}
@@ -25,6 +25,7 @@ import (
var tablesWithKB = map[string]bool{
"knowledges": true, "chunks": true, "knowledge_tags": true,
"wiki_folders": true, "wiki_pages": true, "wiki_page_issues": true, "wiki_log_entries": true,
"chunk_revisions": true, "wiki_page_revisions": true,
}
// tableHasTenant 报告这张表是否自带租户列。
@@ -90,6 +90,21 @@ func validateLibraryStructuredReferences(pg PostgresSnapshot) error {
}
}
}
// 编辑历史:chunk_id/page_id 是结构引用,不是展示事实。父行不在本快照里
// (软删父行按导出规则不出现)就拒绝;chunk 还必须与 revision.knowledge_id 同文档。
for _, r := range tables["chunk_revisions"] {
if e := ref(r, "knowledge_id", "knowledges", false); e != nil {
return e
}
if e := ref(r, "chunk_id", "chunks", true); e != nil {
return e
}
}
for _, r := range tables["wiki_page_revisions"] {
if e := ref(r, "page_id", "wiki_pages", false); e != nil {
return e
}
}
for _, r := range tables["wiki_folders"] {
if e := ref(r, "parent_id", "wiki_folders", false); e != nil {
return e
@@ -173,6 +173,26 @@ func (m *targetIDMapper) remapRow(table string, row map[string]json.RawMessage)
return err
}
}
case "chunk_revisions":
// 编辑历史与正文走同一套映射:自身身份 + 父文档/父分块引用。
// editor_id 是用户身份,原样保留(目标查不到就显示未知编辑者)。
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, "chunk_id", "chunks"); err != nil {
return err
}
case "wiki_page_revisions":
// 自身身份 + page 引用;slug/正文/版本号/aliases 原样保留。
if err := m.remapScalar(row, "id", table); err != nil {
return err
}
if err := m.remapScalar(row, "page_id", "wiki_pages"); err != nil {
return err
}
case "wiki_log_entries":
// id 是目标本地的 bigint,由既有 LocalIDs 分配;历史日志可能引用已删除文档,
// 这类引用只做"已知才换",不能当作悬挂拒绝(否则整库同步被历史日志卡死)。
@@ -80,12 +80,15 @@ func (t *ProductionLibraryTarget) productionTableContent(ctx context.Context, ta
if name == "resources" {
continue
}
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
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" {
if name != "resource_bindings" && name != "knowledge_tag_relations" && libraryResourceBodyTable(name) {
bodies = append(bodies, items...)
}
if name == "resource_bindings" {
@@ -122,6 +122,13 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
return libraryrelease.WriteSet{}, err
}
t.targetIDMode = libraryrelease.TargetIDModeScoped
// 漏表门禁:写第一笔之前的预检。导入事务里还会再查一次(写前最终判定),
// 这里负责尽早失败,并把"空表放行"的警告写进持久发布记录。
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, t.pool,
PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, t.schema.Profile)
if err != nil {
return libraryrelease.WriteSet{}, err
}
if err := validateArchivedLibraryClosure(archive, manifest); err != nil {
return libraryrelease.WriteSet{}, err
}
@@ -152,7 +159,8 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
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}
CreatedAt: t.now().UTC(), Universe: plan.Universe, Warnings: gateWarnings,
TargetIDMode: libraryrelease.TargetIDModeScoped}
for _, part := range manifest.Parts {
if part.Kind != "database" && part.Kind != "wiki" {
continue
@@ -350,6 +358,14 @@ func (t *ProductionLibraryTarget) assertWriteSetOwnership(table, id, owner strin
return nil
}
// jobCreatedRowDeleteOrder 是恢复清理的顺序契约:子表先删。编辑历史必须排在
// 父表 chunks/wiki_pages 之前;顺序写死在一处,并有单测防止新增表时漏改。
var jobCreatedRowDeleteOrder = []string{
"wiki_page_revisions", "chunk_revisions", "resource_bindings", "chunks", "knowledges",
"knowledge_tag_relations", "wiki_page_issues", "wiki_log_entries", "wiki_pages",
"wiki_folders", "knowledge_tags", "resources",
}
// clearJobCreatedRows 只删"写前不存在 ∧ 由本次写入 ∧ 不在恢复快照里"的精确身份,
// 并且对资源额外要求它仍然没有任何绑定/正文引用(作业失败期间被别的知识库接管
// 使用的资源不能删)。
@@ -365,9 +381,7 @@ func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set l
}
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"} {
for _, table := range jobCreatedRowDeleteOrder {
ids := make([]string, 0, 8)
for _, id := range set.CreatedIDs(table) {
if restored[table][id] {
@@ -84,6 +84,8 @@ const v090Folder = "wf-v090-1"
const v090Page = "wp-v090-1"
const v090Tag = "tg-v090-1"
const v090Resource = "rs-v090-1"
const v090ChunkRevision = "cr-v090-1"
const v090PageRevision = "wr-v090-1"
// seedV090 造 1 KB / 1 文档 / 2 分块 / 1 wiki 页 / 1 wiki 目录 / 1 资源。
// Wiki 必须非空:空表通过等于没有验证 wiki 部件。
@@ -99,6 +101,8 @@ func seedV090(t *testing.T, ctx context.Context, db *pgxpool.Pool) PostgresIdent
`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 chunk_revisions(id,tenant_id,knowledge_base_id,knowledge_id,chunk_id,revision,content,editor_id,edit_source) VALUES ('` + v090ChunkRevision + `',$1,'` + v090KB + `','` + v090Knowledge + `','` + v090ChunkOne + `',1,'第一段旧正文','editor-a','user')`,
`INSERT INTO wiki_page_revisions(id,tenant_id,knowledge_base_id,page_id,slug,version,title,content,edit_source,editor_id) VALUES ('` + v090PageRevision + `',$1,'` + v090KB + `','` + v090Page + `','fixture-page',1,'夹具页','旧 wiki 正文','pipeline','')`,
`INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES ('` + v090Knowledge + `','` + v090Tag + `')`,
}
for _, statement := range statements {
@@ -166,7 +170,7 @@ func v090IndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA string) Sea
t.Fatalf("decode chunk: %v", err)
}
source, err := json.Marshal(map[string]any{
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
"chunk_id": chunk.ID,
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
})

Some files were not shown because too many files have changed in this diff Show More