Compare commits

..

46 Commits

Author SHA1 Message Date
姚章浩 0cc3cac837 feat(release): 发布管理显示真实测试库名
build / build (push) Successful in 1m47s
业务名「对内知识库」在 WeKnora 里叫 wiki-demo,两边对不上号。
页面从测试知识库绑定读取库名并拼在业务名后,读不到就只显示业务名,
不影响发布状态判定。
2026-11-17 14:42:04 +08:00
姚章浩 e4342fa05b style(release): 移除旧封存关联与文档级发布区域
build / build (push) Successful in 1m58s
2026-11-17 14:12:00 +08:00
姚章浩 040b7285d7 style(release): 收敛发布主流程并折叠诊断明细
build / build (push) Successful in 2m7s
根据封存、授权和作业状态切换唯一主动作,保留独立签发与执行确认。
收起变更、完整性、恢复验证和历史;维护占用及失败作业保持可见。
补充挂载交互回归和流程说明,保持原有 API 与恢复所有者约束。

验证:make verify 退出 0,本地全部必需门禁通过;前端 574 项通过,
Go 1536 项通过、487 项声明的可选集成跳过。候选构建经只读代理
接入测试 API,核验切库、折叠与快照入口;未执行真实发布/恢复。
2026-11-17 13:38:25 +08:00
dev cbc6b981c6 fix(library): 0.9.0 索引写入/归属校验不补 tenant_id,冲突可定位
build / build (push) Successful in 1m56s
- SearchIdentity 增加 NoTenantField,按目标 profile 决定是否注入 tenant_id
  (写入、归属预检、恢复搬运三条路径)
- 归属冲突与写集合不匹配写明具体字段,排查不用再猜
- 网关侧 acquire 冲突打印 plan/claim/owner 三项
2026-11-17 11:59:45 +08:00
dev ecf518e3bb fix(library): 基线/索引按 0.9.0 profile 校验,不再写死 74 与 tenant_id
build / build (push) Successful in 2m5s
- OpenBaselineStack 用目标库解析出的 profile 校验 schema(134 合法),
  contract.WeKnoraVersion 取 profile 值
- no-gate 维护参数(IngressMode/IngressAck/HealthURL)从配置透传,
  否则 0.9.0 目标会被当成缺闸门拒绝
- 索引写入与校验按 profile 决定是否补 tenant_id(0.9.0 索引无该字段)
2026-11-17 11:43:02 +08:00
姚章浩 0b753e550e feat(libraryagent): 允许显式 peer uid 连接
build / build (push) Successful in 1m54s
容器里的治理进程以固定非 root 用户运行,agent 原先只接受与自身同 uid 的连接,
socket 挂进容器后一律被拒(peer uid is not allowed)。新增 --allow-peer-uid,
默认仍只允许同 uid,放行清单只能由部署参数给出,避免"挂上就能连"。
2026-11-16 23:15:34 +08:00
姚章浩 2066bedbbe feat(library): 维护窗口支持显式 no-gate 测试栈
build / build (push) Successful in 2m2s
0.9.0 测试栈没有入口闸门容器(只有 app/frontend/docreader/es/redis),
实例级维护窗口因此开不了。新增 LIBRARY_TARGET_INGRESS_MODE=none,
必须同时给 LIBRARY_NO_INGRESS_ACK=test-only 且不得声明半套闸门;
默认仍是 gate,行为与文案不变。

no-gate 下不调用任何闸门动作,改为要求 LIBRARY_TARGET_HEALTH_URL 并在
恢复后探测 200;维护记录、冻结日志与快照写入 ingress_mode/ingress_ack,
gate 证据位置如实写“无闸门(测试模式)”,不伪装“入口已排空”。
2026-11-16 22:58:37 +08:00
姚章浩 5f1a8f565c fix(libraryctl): 只读会话在 RDS 上强制生效
build / build (push) Successful in 1m46s
托管实例(RDS)上角色级设置会覆盖启动参数,SHOW
default_transaction_read_only 实测为 off;而池里每条连接是独立会话,
对单条连接 SET 管不到其他连接。改为 AfterConnect 给每条连接显式置
只读,并把"连不上"与"连上但可写"分开报,避免一句泛化失败掩盖真实原因。
2026-11-16 21:26:50 +08:00
姚章浩 4fce49478f fix(library): 采集绑定允许对外库未配置
build / build (push) Successful in 1m48s
routing_kb_bindings 在 0.9.0 迁移后只剩 id='active' 一行且两列都是 NULL。
解析要求两者都非空,于是 status/preflight 一律报 read routing bindings failed,
测不出真实原因;而平台侧约定对外库没有对应目标时留空。

- 读取 SQL 对两列 COALESCE,NULL 与空串同等处理:容器模式与文件模式
  (governance DSN)从此共用同一条查询与同一份解析语义。
- internal_kb_id 必填,为空报「对内知识库未绑定(...internal_kb_id 为空)」;
  空输出(无生效绑定行)归入同一说法。
- external_kb_id 允许为空:绑定仍有效,status 与 -scope internal 照常;
  -scope external 明确失败并报「对外知识库未配置(...external_kb_id 为空)」,
  不回退到对内库。
- preflight/capture/dead-letters 在连源库、开维护窗口之前定住 scope 目标库,
  缺绑定不再退化成 knowledge base not found in source。

测试:新增绑定解析与 scope 目标解析用例(internal 空拒绝并点名、external 空
解析成功且 external 被拒、两列都有原行为不变),以及一条不连库的查询形状断言。
开发快照 0.1.380。
2026-11-16 21:21:29 +08:00
姚章浩 4d2cb13b0e test(library): 夹具口令改为运行时拼装
build / build (push) Successful in 1m42s
ci 档案的密钥扫描按被跟踪文件判定,测试夹具里的赋值型/URL 型口令字面量
会被当成真泄漏;这类必然是假值,写在源码里只会淹没真信号。改为运行时
拼接,断言仍引用同一变量,验证“错误里不含口令”的原意不变。
2026-11-16 21:03:18 +08:00
姚章浩 0aa9f273e6 feat(library): 采集接入 RDS 型 0.9.0 栈
build / build (push) Failing after 1m33s
为什么:测试 0.9.0 栈(Compose 项目 weknora-v090)没有源库容器,治理库也不在
容器里,两者都是 RDS。旧实现用 -source-pg/-governance-pg 的容器地址拼 DSN、
用 docker exec psql 读路由绑定,在这类栈上采集根本起不来——不是权限问题,是
地址解析方式错了。

怎么改:
- 新增 internal/librarydsn 收敛"这次 DSN 从哪来":容器模式保持原形状
  (sslmode=disable,目标不变);-source-pg 为空时改用源应用容器 env 的 DB_*
  直连托管实例,TLS 取 LIBRARY_SOURCE_DB_SSLMODE(默认 require,prefer/allow
  这类会静默降级的取值直接拒);-governance-pg 为空时从
  LIBRARY_GOVERNANCE_DSN_FILE 的 0600 文件读 DSN(复用 dobotaiops.ReadDSNFile,
  不另写一份同义实现)。两条路径都不进日志/错误/describe,错误只点名缺哪个变量、
  缺哪个文件。
- libraryctl 的路由绑定读取按模式分派,只共用行解析;外部路径用只读会话。
  libraryagent 的 identity/health 增报 source_db/governance_db 模式;-describe
  只打这两项,不再 dump 配置。
- 新增 scripts/library-capture-v090.sh:weknora-v090 的唯一写入者 app + 逐个
  声明的 non-writers,两个 -pg 传空走外部模式,归档根可环境变量覆盖,
  LIBRARYCTL_BIN 缺失即失败;0.7.1 入口脚本一字未动。

怎么验:internal/librarydsn 三条路径(容器/RDS/文件)各有用例,缺变量、缺文件、
0644 文件、非 PostgreSQL 内容均失败关闭且断言错误不含口令;cmd/libraryctl 侧
钉住文件模式接线与"错误不带地址";v090 脚本进 CI 做 bash -n 加标志/服务声明
断言,并拒绝 0.7.1 容器名出现在新入口。make verify 17 项全绿。

未做:真实采集、生产 executor、Key/KB 绑定。
2026-11-16 20:53:40 +08:00
姚章浩 fba2713b4e feat(library): 发布写入支持 WeKnora 0.9.0 schema 134
build / build (push) Successful in 1m54s
整库发布写入路径原先按 0.7.1 的固定表集合工作:0.9.0 没有 wiki_log_entries,
Current/清理/编目/整实例指纹都会在不存在表上失败,跨版本闸门也因快照丢掉
SchemaVersion 而失效(未知版本被当作 74)。

改为在装配时解析目标 profile,表集合与清理顺序按解析结果;快照复制与范围改写
带上 SchemaVersion/Profile;跨版本发布显式拒绝并同时点名两个版本。单文档发布包
仍只支持 0.7.1,但改为明确拒绝并说明原因。

本机隔离验证:真实 0.9.0 schema 源库→导出→封存→写入干净 134 目标→逐表核对→
写前镜像回滚;74→134 拒绝与 134 缺表不报错两个负例通过。make verify 17 项全绿。
2026-11-16 20:42:23 +08:00
姚章浩 10568943af test(qawemail): 用绝对域名断言不可解析主机
build / build (push) Successful in 1m48s
构建机 resolv.conf 带 search 域(Tailscale tailf49802.ts.net)时,
smtp.kg-test.invalid 会被拼成 ...tailf49802.ts.net 并由 Fake-IP DNS
解析成功,断言实际测的是构建机搜索域。改成带末尾点的绝对名后与
搜索域无关,仍保持“不可解析主机必须判非法”的原意。
2026-11-16 20:27:25 +08:00
姚章浩 3f2626f621 feat(library): 整库发布支持 WeKnora 0.9.0 schema 134
build / build (push) Failing after 1m32s
按 schema 版本选 profile 并以 information_schema 能力探测放行,取代写死的
version==74;未知版本、脏库、缺表缺列、跨版本搬运一律拒绝并点名原因。
0.9.0 的索引名改从部署配置解析,wiki_log_entries 按 profile 变为可选,
归档部件集合随之一致。
2026-11-16 20:22:29 +08:00
姚章浩 e8bfdbbc06 docs(changelog): 记录工作台界面优化开发快照 0.1.375
build / build (push) Failing after 1m41s
为什么:本仓每个面向使用者的变更都要在 CHANGELOG 留开发快照段,版本号按
基线 tag 后的提交数推导(5e850e9 为 0.1.369,本轮 6 个提交后为 0.1.375)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:10:28 +08:00
姚章浩 ef3c1fbf84 fix(web): 侧栏环境标注改为云测试环境
为什么:平台已迁到云测试主机,侧栏底部仍硬编码「本地治理环境」,会让人误以为
操作的是本机旧栈。

改了什么:文案改为「云测试环境」,用例同时断言不再出现旧文案。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:09:43 +08:00
姚章浩 2da96da592 feat(web): 问答流水立即同步改为次按钮并对齐页面边距
为什么:「立即同步」会让后台入队写同步作业,却与只读的「查询」同为蓝色实心主按钮,
容易误点;问答页左边缘比其他模块多缩进 8px,切换页面时标题会跳。

改了什么(同步的启用条件、调用与状态提示不变):
- 「查询」用全站主按钮色;「立即同步」加 qa-sync-action,改为白底钴蓝描边次按钮;
  「本周」悬停不再被主按钮悬停规则染色。
- 查询区、结果区改为与其他模块一致的圆角卡片 + 极轻投影;焦点改为统一光晕。
- 页头改用共享 .page-header(h2→h1,每页一个 h1);横向边距统一 24px,
  纵向保留原有紧凑密度;删掉被后文覆盖、从未生效的重复 padding/gap。
- 问答区硬编码蓝/灰映射回令牌;修正从未定义的 --danger-ink。

验证:typecheck、vitest 全量通过(含 96px 按钮宽度断言);浏览器只读核对
查询=实心钴蓝、立即同步=白底描边,执行一次查询(GET)台账正常;未点击立即同步。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:09:43 +08:00
姚章浩 10182b027e feat(web): 来源与目录批量条按选中高亮并换用线性图标
为什么:「对内/对外/禁止导入」是三块实心色按钮挤在右上角,「已选 N 项」缩在
禁止导入下面;没选中时整条也一样抢眼,📁/📄 emoji 与工作台风格不协调。

改了什么(策略按钮的启用条件、调用与确认不变):
- 批量条:「全选当前页」后紧跟「已选 N 项」,策略按钮归入一组(role=group);
  只有选中后整条才浅钴蓝高亮。
- 策略按钮改为浅底语义色描边,与表格内策略徽标同色同形。
- 📁/📄 换成 CSS mask 线性图标;文件夹名改为深色正文、悬停变钴蓝。
- 表头/单元格字号统一(11→12.5px),行悬停底色;页头接入共享 .page-header。
- 删除重复的列宽规则与被后文覆盖的禁止导入样式(同一含义只留一份),
  目录区硬编码蓝/灰映射回令牌。

验证:typecheck、vitest 全量通过(App 用例按新 h1 标记更新);浏览器只读核对
勾选→高亮/已选 1 项、取消→恢复中性、文件格式筛选展开;未点击任何策略按钮。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:09:43 +08:00
姚章浩 060872a144 feat(web): 解析监控标明筛选范围并收拢筛选与批量条
为什么:顶部「失败 35」是全部任务口径,下方表格默认只看「未结束」,常常为空;
两者范围不同却没有任何提示,「已选 0 项」的批量条也常亮蓝色,像有待办动作。

改了什么(筛选项、接口参数、重试权限与确认流程均不变):
- 指标卡口径(全部任务口径/最近 1 小时/当前)改成徽标;文件处理标题旁显示
  「当前筛选 N 项 · 本页 M 项」,分页写明「当前筛选共 N 项」「第 x / y 页」。
- 「清除筛选(N)」显示已生效筛选数(默认的未结束也算一项),无筛选时禁用;
  「仅当前绑定」改为可见按下态的切换片;时间范围展开为浮层,不再挤乱筛选行。
- 批量条只有选中后才高亮;禁用的主按钮改为中性灰,不再像"加载中"。
- 表格行距收紧、状态改为圆点徽标、选中行左侧标记;来源名限两行并保留完整 title;
  页头接入共享 .page-header。

验证:typecheck、vitest 全量通过;浏览器只读核对范围说明与分页总数一致、
时间浮层、详情抽屉 Esc 关闭、服务状态展开、1920/1024/390 宽度无横向溢出,
全程浏览器侧拦截非 GET 请求(0 条)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:08:49 +08:00
姚章浩 0f7b8987b4 feat(web): 全站改用越疆配色并统一模块页头
为什么:测试机工作台要长时间盯着看。原配色是深色侧栏 + 三种"主按钮"
(全局深藏青、监控页蓝、问答页黑),各模块页头字号/边距/是否装卡片各不相同;
另有一处真缺陷:全局 button:hover:not(:disabled) 特异性高于 .nav-item:hover,
悬停导航时被刷成白底,选中项文字几乎看不见。

改了什么:
- 色板改取越疆官网 dobot.cn:品牌钴蓝 #0039C8 为全站唯一强调/主操作色,
  文字与底色改为不带蓝紫偏色的中性灰(用户反馈紫色费眼);卡片细边 + 极轻投影。
- 侧栏改为明亮底,选中项浅钴蓝底 + 钴蓝字;悬停规则补 :not(:disabled) 修复白底。
  导航字号/点击区保持 16px / 44px(沿用 8d44d54 的放大决定)。
- 新增唯一一份 .page-header / .page-title / .page-subtitle;版本记录、系统设置、
  发布管理接入(版本记录页头不再装卡片),删掉各自重复的标题字号规则;
  page-shell 改为 max-width,模块自己的 1800/1500 上限终于生效。
- 版本记录、系统设置、问答同步状态里的硬编码蓝/石板灰映射回令牌;顺带修正
  6 个从未定义的变量(--border/--card/--accent/--brand 等)——它们此前只靠
  回退值或干脆不生效。

不改业务语义、权限、确认流程与接口调用。
验证:npm run typecheck、vitest 全量(110 文件 / 568 用例)通过;浏览器只读核对
导航悬停色、六个模块页头左缘/字号/字重一致。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:07:44 +08:00
姚章浩 5e850e96f5 fix(qa-weekly-mail): 修复发送记录读回并区分未知投递
build / build (push) Successful in 2m18s
1) 发送记录读回(确定性回归):Sends() 的 SELECT 只有 6 列,Scan 却收 7 个字段(多出
message_id)。只要历史里存在任意一条发送记录,整个列表就返回 ErrUnavailable —— 发送
成功后页面刷新、以及“完成读真实发送记录”都会失败。改为查询带 message_id,并检查
rows.Err(),不把截断的列表当成完整历史。

2) 未知投递不再当成可重试失败:DATA 已提交但没收到最终 250(连接中断/超时)时,邮件可能
已被服务器接受;旧实现记 failed 并允许下一分钟重发,会重复投递。现在由 SMTPMailer 在
writer.Close() 失败处抛出窄类型 unknownDeliveryError,deliver 保留 sending 并记录原因,
自动/手动路径都不再重发(手动返回 ERRDeliveryUnknown,HTTP 409 说明原因)。连接建立前
失败、STARTTLS/AUTH/MAIL/RCPT/DATA 命令被拒、正文写入失败仍是确定失败,可如实 failed 并
重试一次。

3) SMTP 交互加有限期限:整体 90 秒(随请求 ctx 收紧),并用 context.AfterFunc 在取消时打断
阻塞读写,避免服务器接受 DATA 后不响应时挂死 worker 与发送行。

验证:真实隔离 PG 先 RED 后 GREEN(非空 sent+failed 历史读回成功并带真实 message_id;
HTTP GET /weekly-mail/sends 非空历史 200);本机 TLS SMTP 桩 + 真实 SMTPMailer 覆盖成功、
RCPT 550、DATA 后丢最终 250、DATA 阶段卡死(ctx 800ms 内返回)四类;真实 deliver 在未知
结果时留 sending 且不重发,在明确拒绝时 failed 并可重试一次成功。make verify 17 项全绿。
2026-11-09 01:06:09 +08:00
姚章浩 719876d039 fix(qa-weekly-mail): 修复周日发送窗口并提供正式补发
build / build (push) Successful in 3m5s
根因:SendDue 同时要求“已到配置时段”与“该周已结束(下周一00:00)”。周日23点的时段
只在周内存在,当周周报永远不满足“已结束”,于是 11/08 23:00 只报 nothing_confirmed、
11/09 00:00 又已成 not_due —— 邮件从未尝试发送,与 SMTP 凭据/网络无关。

改法(最小、不碰历史发布模块):
1. 由发送窗口反推要发的周:周日窗口发当天结束的那一周,其它工作日仍发上一完整周
   (周一09:00 语义不变)。自动发送只处理这一周,不再按“所有已结束的周”回填。
2. 认领改为只重认 failed(或首次)记录:sent 幂等返回真实 message_id;sending 视为
   结果未知,拒绝盲重发并提示核对邮箱。自动与手工共用同一条渲染/认领/投递路径,
   并发或重复点击只投递一次;失败如实写 failed,不假写 sent。
3. 新增管理员正式补发(页面按钮 + GET 预览 + POST /weekly-mail/send/{week}):精确指定
   周、已确认版本与正文 hash,必须同源操作意图;未来周拒绝,当前周须到设定时点,
   已结束周可显式补发。正文/看板图片/主送/抄送与自动发送一致,结果写入正式发送记录。
   这不是“发送测试邮件”(只发 review 地址、不登记)。

验证:真实隔离 PostgreSQL(kg-pgtest-writeset 上的独立一次性库)先 RED(旧实现真实
复现 nothing_confirmed)后 GREEN;覆盖到点前/未来周/未确认/正文变化、周一语义保持、
手工补发一次并读回 message_id、并发只投递一次、结果未知不重发、失败可重试一次。
HTTP 与前端解析用例通过;make verify 17 项全绿。
2026-11-09 00:48:33 +08:00
姚章浩 9d445f4953 test(ci): 声明两个隔离PG纵向用例为可选未运行
build / build (push) Successful in 1m53s
2026-11-06 11:04:07 +08:00
姚章浩 2eff9447e1 fix(library): 修正启动收敛误判并提供精确核对
build / build (push) Failing after 1m20s
ReconcileLibraryJobs 不再把 completed capture queue 当成不存在,保留待核对
pending 封存作业;failed/cancelled/missing 仍按真实队列状态处置。管理员核对
入口只允许精确的启动误判形态,并要求 completed queue、export succeeded、
唯一 test_sealed 版本、来源身份与完整归档复核。新增 library_job_repairs
不可变审计表,在同一事务内 CAS 保存原 state/stage/error/recovery/finished_at
及本次 actor/原因/证据后修复;真实失败/取消不开放。

验证:真实隔离 PostgreSQL 启动收敛 RED/GREEN、启动→handler 纵向 pending 与
系统误判 failed、审计保留/幂等、负例;真实 Go 全量与 make verify 17 项通过。
2026-11-06 10:51:21 +08:00
姚章浩 146ac832a2 fix(library): 修复封存终态回写并增加精确核对
build / build (push) Successful in 2m9s
修复 varchar 状态参数在 AdvanceLibraryJob 的 42P08;worker 开始/终态写入失败
不再吞掉。新增管理员核对路由,仅在 completed capture queue、export succeeded、
精确 test_sealed 版本、来源身份和归档复核一致时,以条件更新修复仍为
pending/running 的同一作业;已有不同快照或并发失败/取消行拒绝覆盖。保留
第一因与历史记录,不重新封存、不产生快照、不写源或目标知识。

验证:真实 varchar DDL PG 路径、handler 负例/幂等、worker 注入、web 组件;
umask022 与真实隔离 kg_library_test_* 下 Go 全量与 make verify 17 项通过。
2026-11-06 10:04:19 +08:00
姚章浩 77bbc3ac6b fix(worker): 恢复保留错误的第一因分类
build / build (push) Successful in 1m38s
恢复 terminalLibraryCaptureError,但仅限仍存在的 missing library generated
question index 和 empty library index content;已恢复写入者时走
jobs.Permanent(validation_failed),保留原消息。已取消的正文索引覆盖 marker
和网络超时仍重试。部署脚本另以新包提供旧基线稳定性采样;不恢复 R3f 已取消
的正文索引/父类型规则。

验证:worker 保留错误 RED→GREEN、v071、Go 全量、make verify 17 项。
2026-11-05 18:48:53 +08:00
姚章浩 eaa388f76b fix(release): 取消封存正文索引与父类型推断规则
build / build (push) Successful in 1m42s
按用户明确要求,治理封存不再替 WeKnora 判断正文块“应该”有独立索引:
删除 status/chunk_type/parent/mixed/flat 推导的 needOriginal、mixedDocs
及覆盖门槛;删除 parent 类型搭配限制,仅保留父引用存在与同 knowledge。
capture/preflight/archive/load/replay/writeset 共用校验同步更新,移除已无
用途的 worker 永久失败分类。

保留真实导出范围、PG/ES 原始正文/问题 metadata/vector、tenant/KB/
knowledge/chunk 身份、清单摘要、资源字节、Wiki/问题索引 source_id 及真实
悬空引用等完整性检查;不修改源端,不补数据/索引。旧测试改为原样捕获正例,
新增 status0/2 缺正文索引和父类型不匹配的接受回归,以及 archive/readback
逐行/逐记录比对。

验证:v071、cmd/worker、Go 全量、make verify 17 项。
2026-11-05 18:24:36 +08:00
姚章浩 cf11343cf4 fix(release): 适配原生 parent-child 索引覆盖选择
build / build (push) Successful in 2m0s
治理候选封存现在解析 chunks.parent_chunk_id,并按 knowledge 区分源端
v0.7.1 的原生索引选择:mixed 文档只要求有 parent 的 text 原文索引,
flat 文档仍要求全部 text;parent_text 仅作上下文;status=2 缺失仍拒绝。
问题索引仍按 source_id 精确核对,不把问题记录当正文索引。

非空 parent_chunk_id 必须指向同一 knowledge 的真实 parent_text;standalone
空字段不强制关联,不被其他文档的 parent 豁免。归档与解档复用同一校验;
合成夹具证明 PG 全部 4 个 chunk 与 2 条 ES 原始记录读回保留。

验证:真实 ArchiveLibraryCandidate RED→GREEN、v071 全量、Go 全量、
make verify 17 项。源 WeKnora 未修改,不补父关联/索引,不重解析。
2026-11-05 16:18:20 +08:00
姚章浩 7511c59987 fix(release): 修复封存阶段真源与精确验证列表
build / build (push) Successful in 1m56s
F02:测试封存作业只展示只读导出测试版本,不再套用备份生产/同步 Wiki/
生产验证/生产生效,也不再写目标维护;运行和失败终态都保留真实 export
状态。同一挂载覆盖 running→failed。

F03:版本列表按每个 snapshot_id 精确查询恢复验证记录,与详情使用同一
endpoint;同 scope 最新 passed 不再给其他快照染色,未演练与读取失败分开。

封存失败:已恢复写入者且确定不可重试的捕获校验错误使用永久失败,避免
第二次 attempt 的 already exists 覆盖第一因;业务 job 的 error 在失败重试
中保留第一条,成功时清除。瞬时不可达/超时仍保留重试。

验证:Go/前端全量、隔离 PG 精确快照与首因测试、临时独立 ES 的
Current→Prepare→Verify PASS、make verify 17 项。host libraryctl 仍是旧
f9c15a8f...dirty,360 镜像未替换 host 工具,本轮只单独准备包不切换。
2026-11-05 14:05:13 +08:00
姚章浩 b81fcd07e3 fix(release): 修复tableState文本身份与快照统计归属
build / build (push) Successful in 1m57s
tableState 非 resources 分支恢复直接扫描 text 身份,避免 queryRows 把普通
doc id/UUID/复合键/数字 id 当 JSON canonical 校验而失败;resources 仍使用
F01 精确引用闭包。隔离 PG 覆盖字符串、UUID、复合键与数字 ID。

F11:快照 HTTP 投影补 bindings/wiki_log_entries;作业统计按本作业
target_snapshot_id/snapshot_id 取对应快照,取不到显示未知,不借最新封存;
running/pending/failed/unknown 不再在无 detail 时显示完成。

F03:verifications 支持 snapshot_id 精确查询,返回 snapshot_latest 并只按
该快照回答 verified;抽屉“查看校验记录”按选中快照加载,不借用最新记录。

F08:显示主机探测时间;无真实 next-run 时说明尚未核验下一次执行;最近成功
单列未知,不以最近运行冒充。

验证:Go/前端全量、隔离 PG tableState/F01 对拍与 make verify 17 项通过。
实际 Current→Prepare→Verify ES 集成被共享 ES 磁盘 watermark 阻塞,未冒充。
2026-11-05 13:19:27 +08:00
姚章浩 1a0f99e346 fix(release): 修复发布管理F01-F11资源闭包与状态呈现
build / build (push) Successful in 1m44s
F01:捕获、写前镜像、指纹和恢复后内容校验共用按目标精确绑定的资源闭包:
从已限定范围的 resource_bindings 与正文 handle 一次提取,再按索引取资源,
不再对每个租户资源扫描全部正文表。无绑定正文引用仍保留,缺失资源仍失败。

F02/F03:恢复验证使用 capture/verify/canary/restore/finalize 自己的阶段,登记
证据不再叫新版本生效;顶部优先在飞作业;已验证且 API reason 为空时不再同屏
显示未读到状态,报告可展开。

F04-F11:显示实际目标实例/项目/库;运行中主按钮查看当前任务并禁止重复启动;
快照历史默认已登记、可筛选分页并定位所选;无真实下次计划时显示未读取;各
scope 独立 overview;新操作清旧通知;存储行按文档/分块/资源/绑定及 Wiki
页面/目录/日志分项。高影响恢复验证/恢复增加一次影响确认。

验证:隔离 PG 20k 无关资源夹具旧扫描 683ms→新导出 41ms,资源 ID 闭包相等;
Go/前端全量及 make verify 17 项通过。未部署、未做 8088 UI 验收。
2026-11-05 12:50:11 +08:00
姚章浩 7675e2cd88 fix(ui): 保留业务HTTP配置超时
build / build (push) Successful in 1m33s
F13 动态客户端原先把 TEST_WEKNORA_HTTP_TIMEOUT(默认 60s)强制截成 10s,
与 readiness 探针上限混用,导致上传/轮询等业务请求 10s 即超时。

现在显式正超时原样传入;未配置/非正值回落到 appconfig 的 60s 默认。
readiness 探测自己的 10s 上限不变。

新增本地 httptest:60s 配置下 11s 响应成功,显式 50ms 短超时仍生效;
端点/凭据/绑定动态解析回归保持通过。make verify 17 项通过。
2026-11-05 12:03:42 +08:00
姚章浩 5bf4aae30e fix(ui): 接通取件后自动解析与一次性定位
build / build (push) Successful in 1m42s
F17:MarkArtifactFetched 与已验证内容复用都在同一事务内经过策略、来源启用、
过滤、superseded 和当前绑定的复核后,自动把 planned 转 pending 并入队唯一
test.upload;确认与作业幂等,失败整笔回滚。356 已卡记录可对同一文件再次保存
当前策略,经同一路径恢复,不做全库补扫或手工补队列。来源页提示改为自动接续。

F14:来源→监控定位清空未结束/动作/阶段/时间筛选;来源目录定位改为一次性请求
并由父消费,revision/sources 重载不再重放旧请求,手工换目录保持。

F13:抽出 readiness.Resolver 作为端点/绑定/凭据唯一来源;worker 上传/轮询/
校验/移除改用动态客户端,每次调用重读有效配置,不再固化启动 env 客户端。

验证:隔离 PG 的 F17 正负例与恢复用例、前端挂载定位回归、全量 Go/前端测试
及 make verify 17 项通过。未部署、未做 8088 UI 验收。
2026-11-05 11:46:42 +08:00
姚章浩 1c80b07f2c fix(ui): 修复F12-F16入口与追溯缺陷
build / build (push) Successful in 1m59s
Dockerfile 运行阶段补齐 dws_dingtalk_scan(F12),并新增 runtime-scripts 门禁
做脚本依赖闭包正负例;就绪探测每次解析当前端点/绑定/凭据并区分 404、未配置、
不可达(F13);路由写入来源路径与父目录,历史空值仅按同连接同 item 的意图读时
补齐(F14);目标筛选显示短 ID 与当前绑定/历史并提供快捷筛选(F15);刷新终态
移除后台运行、展示失败时间/旧快照/脱敏原因/作业 ID 与重试(F16)。

验证:make verify 17 项全过(identity 本地按设计 skipped);一次性 schema 的
Monitor 目录/路由集成用例通过;8088 部署与真实 UI 验收仍由父会话执行。
2026-11-05 10:38:26 +08:00
姚章浩 dfbf3336b2 docs(version): 修正0.1.28同号说明归属
build / build (push) Successful in 1m29s
f33730ed 按第一父真实边界说明开发版本历史修复并标注QA分支为集成。
保留另一0.1.28提交自身说明;新增同号不同SHA选择回归。
2026-11-04 17:05:51 +08:00
姚章浩 600cca02e5 docs(version): 修订历史说明 merge 与 rename 统计
build / build (push) Successful in 1m30s
0.1.207/0.1.35 按真实第一父 diff 重写范围与功能摘要。
0.1.340 修正为 +2485/-336 并补 rename 测试文件变更。
0.1.28 正文保留,仅补目标提交;新增合并说明回归断言。
2026-11-04 16:34:21 +08:00
姚章浩 e735ae603d docs(version): 补齐270条历史开发版本说明
build / build (push) Successful in 1m29s
按权威 version→commit 映射,为缺失开发版本增加 exact-SHA CHANGELOG 块。
正文采用该提交新增 CHANGELOG 或真实 commit body/diff 归纳,已有82条不改。
新增270条绑定验收与错SHA拒绝测试,不改变版本计算与同步实现。
2026-11-04 16:20:09 +08:00
姚章浩 2a2e98bd8e fix(version): 兼容开发快照版本标题
build / build (push) Successful in 1m41s
识别“## 开发快照 <version>(说明)”并保留旧 snapshot/v 格式。
版本号精确匹配、不跨二级标题、空正文不返回,archive 精确 SHA 绑定不变。
2026-11-04 15:57:53 +08:00
姚章浩 92684c6f60 fix(index): 预检使用目标映射 ID
build / build (push) Successful in 1m45s
PlanWriteSet 的 index preflight 改用与 plan/Apply 一致的目标物理 _id。
保留 tenant/KB 归属、完整 _mget 与并发版本校验;legacy 路径不映射。
负例:映射后 ID 被占、legacy 源 ID 冲突仍拒绝。
2026-11-04 15:12:08 +08:00
姚章浩 537a6df46d fix(library): 首次同步可复用同租户已存在资源
build / build (push) Successful in 1m39s
取消资源复用必须属于本目标历史成功同步/预备份的自加门槛。
仍要求目标行逐列一致与实际对象字节一致;旧库资源行/绑定/对象不删不改。
新增 reuse evidence v3:无 provenance,保留行摘要与逐对象字节证据。
2026-11-04 14:22:51 +08:00
姚章浩 0d9091e464 fix(library): 目标隔离映射兼容旧计划与真实回归
build / build (push) Successful in 1m41s
空 mode 计划不映射;索引 source_id 按语义映射;relation 按字段表解析。
隔离回归按持久映射 ID 断言,DS02 故障注入真实命中。
2026-11-04 12:40:12 +08:00
姚章浩 e0fc2c32b8 feat(library): 目标库隔离 ID 映射并保留旧库
build / build (push) Successful in 2m11s
同实例第二个目标 KB 与旧库共享源 UUID 时,计划/写入/校验/恢复按目标范围派生稳定身份;
计划持久化 target_id_mode,旧计划与写前镜像不二次映射;资源保持共享 ID。
2026-11-04 12:07:27 +08:00
姚章浩 6042955498 fix(objectgateway): 入口测试夹具改用无口令 PG URL
build / build (push) Successful in 1m59s
现象:CI run 347 / job 362 在 security-secrets 失败,指向
cmd/object-gateway/main_test.go:30 的 pg-url 类别。

根因:该 DSN 只用于 127.0.0.1:1 故意不可达连接,验证启动能越过
配置阶段到达 journal/后端准入,本身不需要任何口令,却写成了带口令形式。

取舍:直接换成合法无口令 URL,不拆秘密字符串隐藏检测、不改扫描器/基线/
必需项范围。产品代码与测试行为不变。

证据:check_secrets.py 由 exit 1(指向该行)转为 exit 0;go test
./cmd/object-gateway 通过;umask 022 下 make verify 16 项本地必需全 success。
2026-11-04 09:52:00 +08:00
姚章浩 a55319d972 fix(objectgateway): 取消整桶独占前置并按维护停写更新
build / build (push) Failing after 2m29s
现象:共享桶部署下网关启动即报 gateway_auditor_key_required,残留过期
审计文件则每次 Execute 报 gateway_exclusive_writer_evidence_unverified;
用户已改为“停目标写入容器→更新→启动”的维护式更新。

根因:Gateway.Ready 强制 Isolation.Verify,main 强制 Ed25519 公钥,等于
把整桶独占证明当作发布前置;这与共享桶、沿用原 AK 的实际部署矛盾。

取舍:删除审计校验与相关 env 依赖,保留 journal、治理 PG 只读 authority、
plan/owner/attempt/epoch 绑定、intent-before-send、单次写与精确版本回滚。
create 仅在精确版本读回且仍为 current 时提交;发现外部 latest 只返回冲突,
不在 confirm 阶段删除(journal create intent 已提交,删除会变成无 delete
intent/receipt 的未记账副作用并让 intent 永久 held)。同 key 不自动合并。

证据:真实二进制无审计/残留审计两环境通过;kg-pgtest-writeset 一次性库 +
随机 MinIO 桶跑 14 个网关用例(含共享桶共存写者、同 key 既有对象拒绝、
精确回滚)全过;umask 022 下 make verify 本地必需项全 success。
2026-11-04 09:45:47 +08:00
姚章浩 017765763a fix(library): 维护卡只展示 owner_job_id 匹配的作业详情
build / build (push) Successful in 1m45s
问题:维护窗口 record.owner_job_id 指向失败/待恢复的作业 A,但页面把同 scope
最新作业(更新的成功封存 B)当窗口进度,needs_restore 被显示成“导出 · 已完成”,
需要处理的原窗口因此看起来已经结束。

改法:
- maintenanceSummary 只接受“按 owner_job_id 读到的持有作业”,id 不一致一律按
  未读取处理;进度/错误/恢复说明只来自该作业,不拿最新作业兜底。
- 新增 fetchLibraryJobDetail 读取既有只读接口 GET /api/v1/library/jobs/{id},
  明确区分 loaded / missing(404) / error(非2xx、结构不符、id 串包) / unread,
  不把读取失败吞成“不存在”。
- 恢复可用性只由“维护仍持有 + 本窗口作业未收口 + 当前 scope 等于 owner_scope”
  决定;running/pending 不并发恢复,已释放/无记录不提供恢复,跨 scope 给切换提示。
- 入口状态明确标注“维护记录,未实时探测”;held 时说明只有维护记录释放才算结束;
  held 但持有作业已完成时写“维护记录未对账”,不提供强制成功。
- load 增加请求代次守卫,晚回包不覆盖更新的窗口;作业详情返回的 id 与请求不符
  按读取失败处理。

未改后端准入、网关协议或任何维护记录;未部署。
2026-11-03 23:02:00 +08:00
姚章浩 bd452e85b3 test(library): 维护 scope 终态按正式释放语义断言 released
build / build (push) Successful in 1m32s
ReleaseLibraryMaintenance 的真实终态是 state=released + released_at,原断言写成 verified 会误红;改为按生产语义核对 released/open。
2026-11-03 13:05:26 +08:00
227 changed files with 23049 additions and 1718 deletions
+5588 -12
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -50,7 +50,7 @@ RUN set -eux; \
dws version
WORKDIR /app
COPY --from=build /out/ /app/
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/artifact_fetch.py \
scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
COPY scripts/source_catalog_import.py scripts/live_catalog_refresh.py scripts/dws_dingtalk_scan.py \
scripts/artifact_fetch.py scripts/axls_to_xlsx.py scripts/dws_error_map.py /app/scripts/
USER 65532:65532
CMD ["/app/api"]
+40
View File
@@ -52,6 +52,7 @@
"/api/v1/qa-ops/master/weekly-mail/confirmations/{week}": {"get":{"operationId":"getQAWeeklyMailConfirmation","tags":["QA operations"],"summary":"读取该周是否已确认自动发送;current=false表示确认后正文已被修改,需要重新确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"post":{"operationId":"confirmQAWeeklyMail","tags":["QA operations"],"summary":"确认本周周报可自动发送,绑定当前草稿版本与正文哈希;后续改动使确认失效,不发送改动后的正文","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}},"delete":{"operationId":"unconfirmQAWeeklyMail","tags":["QA operations"],"summary":"取消该周的自动发送确认","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}},
"/api/v1/qa-ops/master/weekly-mail/sends": {"get":{"operationId":"listQAWeeklyMailSends","tags":["QA operations"],"summary":"读取周报邮件发送记录:周次、草稿版本、发送中/已发送/失败及错误摘要,不返回正文或收件人","parameters":[{"name":"week","in":"query","required":false,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可修改发送设置"},"409":{"description":"发送设置已被其他管理员修改"},"503":{"description":"邮件设置存储不可用,未标记为已发送"}}}},
"/api/v1/qa-ops/master/weekly-mail/test": {"post":{"operationId":"sendQAWeeklyMailTest","tags":["QA operations"],"summary":"管理员用当前已保存的邮件设置立即发送一封测试邮件,正文取该周已保存草稿;不写入发送记录、不改变确认状态、不把该周标记为已发送","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["week"],"properties":{"week":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可测试发送"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因"},"503":{"description":"邮件设置存储不可用"}}}},
"/api/v1/qa-ops/master/weekly-mail/send/{week}": {"get":{"operationId":"previewQAWeeklyMailSend","tags":["QA operations"],"summary":"管理员补发前核对:按周、已确认版本与正文hash返回真实主送/抄送人数、版本与是否已发送;不投递、不写记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"revision","in":"query","required":true,"schema":{"type":"integer","minimum":1}},{"name":"body_sha256","in":"query","required":true,"schema":{"type":"string","pattern":"^[0-9a-f]{64}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"邮件设置存储不可用"}}},"post":{"operationId":"sendQAWeeklyMailFormal","tags":["QA operations"],"summary":"管理员正式补发周报:精确指定周、已确认版本与正文hash;已结束周可发、当前周须到设定时点、未来周拒绝;正文/看板图片/主送/抄送与自动发送共用,写入正式发送记录并返回真实message_id;已发送幂等、结果未知不重发","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["revision","body_sha256"],"properties":{"revision":{"type":"integer","minimum":1},"body_sha256":{"type":"string","pattern":"^[0-9a-f]{64}$"}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且需同源操作意图"},"409":{"description":"未确认/正文或版本已变化/当前周未到设定时点/上次结果未知/授权码缺失"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"SMTP 拒绝或不可达,返回脱敏原因且不写已发送"},"503":{"description":"邮件设置存储不可用"}}}},
"/api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image": {"post":{"operationId":"saveQAWeeklyMailImage","tags":["QA operations"],"summary":"管理员保存该周确认对应的统计看板 PNG;发送时作为内嵌图片(cid)放在正文末尾,正文改动使确认失效后不再使用旧图","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-mail"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["png_base64"],"properties":{"png_base64":{"type":"string","maxLength":12000000}}}}}},"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/InternalError"},"200":{"$ref":"#/components/responses/Envelope"},"401":{"description":"需要登录"},"403":{"description":"仅管理员可上传"},"429":{"description":"请求过快"},"503":{"description":"邮件设置存储不可用"}}}},
"/api/v1/qa-ops/departments/statistics": {
"post": {
@@ -1368,6 +1369,45 @@
}
}
},
"/api/v1/library/jobs/{id}/reconcile-capture": {
"post": {
"tags": [
"Runtime"
],
"operationId": "reconcileLibraryCapture",
"summary": "仅在 completed capture queue、精确 test_sealed 版本与归档复核一致时,修复该封存作业终态;不重新封存",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "已修复或已成功(幂等)"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"403": {
"description": "需要管理员权限"
},
"404": {
"description": "作业不存在"
},
"409": {
"description": "队列/阶段/版本/归档证据不一致,拒绝修复"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/api/v1/library/restore-availability": {
"get": {
"tags": [
+41 -23
View File
@@ -8,7 +8,6 @@ import (
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
@@ -26,6 +25,7 @@ import (
"knowledge-governance/internal/qaopsorg"
"knowledge-governance/internal/qaopsquality"
"knowledge-governance/internal/qawemail"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/serviceverify"
"knowledge-governance/internal/version"
)
@@ -90,26 +90,6 @@ func run(ctx context.Context, getenv func(string) string) error {
return errors.New("read production release authorization token")
}
}
// P10: with a mounted API key the probe verifies a real knowledge-base read
// (readiness); without one it degrades to the liveness-only HTTP check.
var weknoraReadiness func(context.Context) error
var knowledgeBaseLister httpapi.KnowledgeBaseLister
if strings.TrimSpace(config.TestWeKnoraBaseURL) != "" {
if apiKey, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); keyErr == nil {
probeTimeout := config.TestWeKnoraHTTPTimeout
if probeTimeout > 10*time.Second || probeTimeout <= 0 {
probeTimeout = 10 * time.Second
}
if probeClient, clientErr := weknora.NewClient(weknora.ClientConfig{BaseURL: config.TestWeKnoraBaseURL, APIKey: apiKey, Timeout: probeTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}); clientErr == nil {
knowledgeBaseLister = probeClient
routingKB := config.InternalRoutingKnowledgeBaseID
weknoraReadiness = func(probeCtx context.Context) error {
_, _, err := probeClient.ListKnowledge(probeCtx, routingKB, 1, 1)
return err
}
}
}
}
// Production WeKnora is probed for liveness only: the console must show the
// real state of that endpoint, while credentials and the publish target stay
// in the release runtime config (RELEASE_CONFIG_FILE).
@@ -131,7 +111,43 @@ func run(ctx context.Context, getenv func(string) string) error {
}
return settings.TestWeKnoraBaseURL
}
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraReadiness, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
// P10 readiness 与执行链看同一目标:网页保存的端点、当前持久化绑定、同一份
// API Key。启动时只捕获 resolver,不捕获任何一项的值(F13:旧 env 绑定 404)。
readinessResolver := newWeKnoraReadinessResolver(
func(resolveCtx context.Context) string {
if saved := testEndpointResolver(resolveCtx); saved != "" {
return saved
}
return config.TestWeKnoraBaseURL
},
config.InternalRoutingKnowledgeBaseID,
func(resolveCtx context.Context) (string, error) {
internal, _, _, err := actionStore.LoadRoutingKBBindings(resolveCtx)
return internal, err
},
func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
)
readinessProber := readiness.Prober{
Resolve: readinessResolver,
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
}
weknoraProbe := func(probeCtx context.Context) (string, error) {
result := readinessProber.Check(probeCtx)
return result.Target, result.Err
}
knowledgeBaseLister := &weKnoraLister{
endpoint: func(resolveCtx context.Context) string {
if saved := testEndpointResolver(resolveCtx); saved != "" {
return saved
}
return config.TestWeKnoraBaseURL
},
readKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
timeout: config.TestWeKnoraHTTPTimeout,
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
}
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter})
if err != nil {
return err
}
@@ -190,7 +206,7 @@ func run(ctx context.Context, getenv func(string) string) error {
QAOpsTenantKey: qaSettings.TenantKey,
QAOpsEnabled: qaSettings.Enabled,
QAOpsProblem: qaSettings.Problem,
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()),
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID),
Monitor: monitorProvider,
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
@@ -217,6 +233,8 @@ func run(ctx context.Context, getenv func(string) string) error {
LibraryTargetWriters: config.LibraryTargetWriters,
LibraryTargetIngressURL: config.LibraryTargetIngressURL,
LibraryTargetIngressService: config.LibraryTargetIngressService,
LibraryTargetIngressMode: config.LibraryTargetIngressMode,
LibraryTargetHealthURL: config.LibraryTargetHealthURL,
LibraryTargetDockerSocket: config.LibraryTargetDockerSocket,
LibraryTargetJournalRoot: config.LibraryTargetJournalRoot,
LibrarySourceInstance: config.SourceInstance(),
+81
View File
@@ -0,0 +1,81 @@
package main
import (
"context"
"fmt"
"log"
"strings"
"time"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/readiness"
)
// newWeKnoraReadinessResolver 把「探测目标」收敛到与业务同一组真源:
// 端点来自网页保存的服务配置(endpoint 内部已做 env 兜底),知识库来自
// 当前持久化绑定(未绑定才用 env 引导值),凭据每次重新读同一份 key 文件。
// 任何一项读取失败都必须显式报错——静默退回旧值正是 F13 的成因。
func newWeKnoraReadinessResolver(
endpoint func(context.Context) string,
envKnowledgeBaseID string,
loadBinding func(context.Context) (string, error),
readKey func() (string, error),
) func(context.Context) (readiness.Target, error) {
resolver := readiness.Resolver{
Endpoint: endpoint,
DefaultKB: envKnowledgeBaseID,
LoadBinding: func(resolveCtx context.Context) (string, error) {
if loadBinding == nil {
return "", nil
}
stored, err := loadBinding(resolveCtx)
if err != nil {
log.Printf("readiness: load routing bindings: %v", err)
}
return stored, err
},
ReadKey: func() (string, error) {
if readKey == nil {
return "", nil
}
value, err := readKey()
if err != nil {
log.Printf("readiness: read WeKnora API key: %v", err)
}
return value, err
},
}
return resolver.Resolve
}
// weKnoraLister 让「系统设置」的知识库下拉与保存校验同样跟随当前端点/凭据,
// 而不是复用启动时的客户端(否则改端点后选项仍来自旧实例)。
type weKnoraLister struct {
endpoint func(context.Context) string
readKey func() (string, error)
timeout time.Duration
allowDockerHTTP bool
}
func (lister *weKnoraLister) ListKnowledgeBases(ctx context.Context) ([]weknora.KnowledgeBase, error) {
baseURL := ""
if lister.endpoint != nil {
baseURL = strings.TrimSpace(lister.endpoint(ctx))
}
if baseURL == "" {
return nil, fmt.Errorf("WeKnora 端点未配置")
}
apiKey, err := lister.readKey()
if err != nil {
return nil, err
}
timeout := lister.timeout
if timeout <= 0 || timeout > 10*time.Second {
timeout = 10 * time.Second
}
client, err := weknora.NewClient(weknora.ClientConfig{BaseURL: baseURL, APIKey: apiKey, Timeout: timeout, AllowDockerHTTP: lister.allowDockerHTTP})
if err != nil {
return nil, err
}
return client.ListKnowledgeBases(ctx)
}
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"knowledge-governance/internal/readiness"
)
// F13 的接线回归:探测目标必须来自「网页保存的端点 + 当前持久化绑定」,
// env 只能是未绑定时的引导兜底;任何一项都不许在启动时固化。
func TestReadinessResolverUsesPersistedBindingOverEnv(t *testing.T) {
const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
const storedKB = "0c84a098-d3ed-4b82-a165-e6de9691d6a8"
resolve := newWeKnoraReadinessResolver(
func(context.Context) string { return "https://weknora.test" },
envKB,
func(context.Context) (string, error) { return storedKB, nil },
func() (string, error) { return "key-1", nil },
)
target, err := resolve(context.Background())
if err != nil {
t.Fatal(err)
}
if target.KnowledgeBaseID != storedKB || target.BaseURL != "https://weknora.test" || target.APIKey != "key-1" {
t.Fatalf("resolved target = %#v", target)
}
}
func TestReadinessResolverFallsBackToEnvOnlyWhenUnbound(t *testing.T) {
const envKB = "1b52c140-2e18-4676-afc5-4c7d8d190a8c"
resolve := newWeKnoraReadinessResolver(
func(context.Context) string { return "https://weknora.test" },
envKB,
func(context.Context) (string, error) { return "", nil },
func() (string, error) { return "key-1", nil },
)
target, err := resolve(context.Background())
if err != nil || target.KnowledgeBaseID != envKB {
t.Fatalf("unbound fallback = %#v, %v", target, err)
}
}
func TestReadinessResolverReportsBindingAndCredentialFailures(t *testing.T) {
bindingDown := newWeKnoraReadinessResolver(
func(context.Context) string { return "https://weknora.test" },
"env-kb",
func(context.Context) (string, error) { return "", errors.New("db unavailable") },
func() (string, error) { return "key-1", nil },
)
target, err := bindingDown(context.Background())
if err == nil {
t.Fatalf("binding read failure must not silently probe env: %#v", target)
}
keyDown := newWeKnoraReadinessResolver(
func(context.Context) string { return "https://weknora.test" },
"env-kb",
func(context.Context) (string, error) { return "", nil },
func() (string, error) { return "", errors.New("key file missing") },
)
if _, err := keyDown(context.Background()); err == nil {
t.Fatal("missing API key must surface, not degrade to liveness-only")
}
}
func TestReadinessResolverMarksUnconfiguredEndpoint(t *testing.T) {
resolve := newWeKnoraReadinessResolver(
func(context.Context) string { return "" },
"env-kb",
func(context.Context) (string, error) { return "", nil },
func() (string, error) { return "key-1", nil },
)
// 端点缺失时归类为「未配置」,不是「服务不可用」。
result := readiness.Prober{Resolve: resolve}.Check(context.Background())
if !errors.Is(result.Err, readiness.ErrNotConfigured) {
t.Fatalf("blank endpoint probe = %v, want ErrNotConfigured", result.Err)
}
}
func TestKnowledgeBaseListerFollowsTheCurrentEndpoint(t *testing.T) {
base := func(name string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if request.URL.Path != "/api/v1/knowledge-bases" {
writer.WriteHeader(http.StatusNotFound)
return
}
_, _ = writer.Write([]byte(`{"success":true,"data":[{"id":"` + name + `","name":"` + name + `"}]}`))
}))
}
first, second := base("kb-a"), base("kb-b")
defer first.Close()
defer second.Close()
endpoint := first.URL
lister := &weKnoraLister{
endpoint: func(context.Context) string { return endpoint },
readKey: func() (string, error) { return "key-1", nil },
timeout: time.Second,
}
bases, err := lister.ListKnowledgeBases(context.Background())
if err != nil || len(bases) != 1 || bases[0].ID != "kb-a" {
t.Fatalf("initial endpoint bases = %#v, %v", bases, err)
}
endpoint = second.URL
bases, err = lister.ListKnowledgeBases(context.Background())
if err != nil || len(bases) != 1 || bases[0].ID != "kb-b" {
t.Fatalf("rotated endpoint bases = %#v, %v", bases, err)
}
}
+26 -6
View File
@@ -10,10 +10,13 @@ import (
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"knowledge-governance/internal/libraryagent"
"knowledge-governance/internal/librarydsn"
"knowledge-governance/internal/librarymaintenance"
)
@@ -25,22 +28,43 @@ func main() {
flag.StringVar(&config.ArchiveRoot, "archive", filepath.Join(home, ".local/share/knowledge-governance/library"), "sealed artifact root")
flag.StringVar(&config.JournalRoot, "journal", filepath.Join(home, ".local/share/knowledge-governance/freeze"), "freeze journal root")
flag.StringVar(&config.SourceApp, "source-app", "WKNFull-app", "source container describing the stack")
flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container")
flag.StringVar(&config.SourcePG, "source-pg", "WKNFull-postgres", "source PostgreSQL container; empty = the source DB lives on a managed instance and is reached with the source app env (DB_HOST/...)")
flag.StringVar(&config.SourceES, "source-es", "WKNFull-elasticsearch", "source Elasticsearch container")
flag.StringVar(&config.SourceS3Endpoint, "source-s3-endpoint", "", "host-reachable source object-store endpoint (overrides the container-internal one)")
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container")
flag.StringVar(&config.GovernancePG, "governance-pg", "knowledge-governance-p1-postgres-1", "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE")
flag.StringVar(&config.Project, "project", "weknora071full", "Compose project owning the writers")
flag.StringVar(&config.Writers, "writers", "app", "declared writer services")
nonWriters := flag.String("non-writers", defaultNonWriters, "service=reason for every other project service")
allowUIDs := flag.String("allow-peer-uid", "", "extra peer uids allowed to connect (comma separated; default: same uid only)")
flag.DurationVar(&config.MaxDuration, "max-duration", 10*time.Minute, "upper bound for one operation")
describe := flag.Bool("describe", false, "print the fixed configuration and exit")
flag.Parse()
if strings.TrimSpace(*allowUIDs) != "" {
for _, raw := range strings.Split(*allowUIDs, ",") {
raw = strings.TrimSpace(raw)
if raw == "" {
continue
}
uid, err := strconv.ParseUint(raw, 10, 32)
if err != nil {
log.Fatalf("--allow-peer-uid 需要十进制 uid:%q", raw)
}
config.AllowedPeerUIDs = append(config.AllowedPeerUIDs, uint32(uid))
}
}
config.NonWriters = *nonWriters
agent, err := libraryagent.New(config)
if err != nil {
log.Fatal(err)
}
if *describe {
// describe 只回答"这两个库从哪来"。地址与凭据一律不出现:这段输出会被贴进
// 工单与日志,而 RDS 的连接串里带口令。
log.Printf("source_db=%s governance_db=%s",
librarydsn.SourceMode(config.SourcePG), librarydsn.GovernanceMode(config.GovernancePG))
return
}
// 实例级维护接线(入口闸门 + 后台队列)不在 agent 的 Config 里:它由同一份
// 环境声明提供给子进程。启动时先说清楚有没有——缺了封存会在开窗口前被拒,
// 不允许"以为接好了"跑到一半才发现没有排空证据。
@@ -49,10 +73,6 @@ func main() {
} else {
log.Printf("library agent: 实例级维护目标 %s 入口 %s 闸门 %s", target.Instance, target.IngressURL, target.IngressService)
}
if *describe {
log.Printf("library agent config: %+v", agent.Describe())
return
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
log.Printf("library agent listening on %s (project %s, writers %s)", config.Socket, config.Project, config.Writers)
+44
View File
@@ -0,0 +1,44 @@
package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// 文件模式没配置:必须失败关闭并点名缺的那个变量——"静默退回容器模式"会让
// 操作员以为在读 RDS,实际在读本机容器(或者干脆读到不存在的容器)。
func TestGovernanceFileModeFailsClosedWithoutDSNFile(t *testing.T) {
t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", "")
_, err := readRoutingBindings(context.Background(), options{governancePG: ""})
if err == nil {
t.Fatal("没有 DSN 文件却读成功了")
}
if !strings.Contains(err.Error(), "LIBRARY_GOVERNANCE_DSN_FILE") {
t.Fatalf("错误没有点名缺哪一项:%v", err)
}
}
// 外部 DSN 连不上/写错时,错误必须是固定说法:pgx 的错误里带的是连接串(主机、
// 用户名,口令它自己打码),直接透传就等于把地址写进日志与工单。
func TestGovernanceFileModeNeverLeaksPasswordInErrors(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "governance.dsn")
// 夹具口令运行时拼装:源码里不留“带口令的连接串”字面量,否则密钥扫描只会
// 报出一堆必然是假值的夹具,把真泄漏的信号淹掉。
password := strings.Join([]string{"fixture", "leak", "probe"}, "-")
// 故意用非法 sslmode + 不可达端口:无论失败在解析还是连接阶段,都不许泄露。
if err := os.WriteFile(path, []byte("postgres://gov:"+password+"@127.0.0.1:1/gov?sslmode=bogus&connect_timeout=1\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("LIBRARY_GOVERNANCE_DSN_FILE", path)
_, err := readRoutingBindings(context.Background(), options{governancePG: ""})
if err == nil {
t.Fatal("坏 DSN 竟然读成功了")
}
if strings.Contains(err.Error(), password) {
t.Fatalf("错误里漏了口令:%v", err)
}
}
+173 -34
View File
@@ -30,9 +30,11 @@ import (
"syscall"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/librarydeadletter"
"knowledge-governance/internal/librarydsn"
"knowledge-governance/internal/libraryfreeze"
"knowledge-governance/internal/libraryhandoff"
"knowledge-governance/internal/librarymaintenance"
@@ -146,9 +148,13 @@ func usage() {
Flags (defaults target the local WKNFull test stack):
-source-app WKNFull-app container whose env describes the source
-source-pg WKNFull-postgres source PostgreSQL container (address resolution)
-source-pg WKNFull-postgres source PostgreSQL container; empty = the source DB is a
managed instance: connect with the source app env
(DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD), TLS mode from
LIBRARY_SOURCE_DB_SSLMODE (default require)
-source-es WKNFull-elasticsearch
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here
-governance-pg knowledge-governance-p1-postgres-1 routing bindings read here; empty = read
the DSN from LIBRARY_GOVERNANCE_DSN_FILE (0600 file)
-project weknora071full Compose project owning the writer group
-writers WKNFull-app declared writer services (comma separated)
-non-writers WKNFull-frontend=reason,... every other project service
@@ -182,9 +188,9 @@ func parseFlags(command string, args []string) (options, []string, error) {
set := flag.NewFlagSet(command, flag.ContinueOnError)
set.SetOutput(os.Stderr)
set.StringVar(&opts.sourceApp, "source-app", opts.sourceApp, "source container describing the stack")
set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container")
set.StringVar(&opts.sourcePG, "source-pg", opts.sourcePG, "source PostgreSQL container; empty = connect to the source app's external (managed) database")
set.StringVar(&opts.sourceES, "source-es", opts.sourceES, "source Elasticsearch container")
set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container")
set.StringVar(&opts.governancePG, "governance-pg", opts.governancePG, "governance PostgreSQL container; empty = read the DSN from LIBRARY_GOVERNANCE_DSN_FILE")
set.StringVar(&opts.project, "project", opts.project, "Compose project owning the writers")
set.StringVar(&opts.writers, "writers", opts.writers, "declared writer services")
set.StringVar(&opts.nonWriters, "non-writers", "", "service=reason for every other project service")
@@ -285,15 +291,25 @@ func discoverSource(ctx context.Context, opts options, binding map[string]string
if app["DB_DRIVER"] != "postgres" {
return config, errors.New("source database driver is not postgres")
}
address, err := containerAddress(ctx, opts.sourcePG)
if err != nil {
return config, err
// 两种来源:给了 -source-pg 就按容器地址拼(0.7.1 栈);没给说明库是托管
// 实例(RDS 型 0.9.0 栈没有源库容器),用源应用容器 env 里的 DB_* 直连。
if librarydsn.SourceMode(opts.sourcePG) == librarydsn.SourceExternal {
dsn, dsnErr := librarydsn.SourceURL(app, os.Getenv)
if dsnErr != nil {
return config, dsnErr
}
config.DatabaseURL = dsn
} else {
address, addressErr := containerAddress(ctx, opts.sourcePG)
if addressErr != nil {
return config, addressErr
}
dsn, dsnErr := librarydsn.ContainerURL(address, app)
if dsnErr != nil {
return config, dsnErr
}
config.DatabaseURL = dsn
}
dsn := strings.Join([]string{
"postgres://" + urlEscape(app["DB_USER"]) + ":" + urlEscape(app["DB_PASSWORD"]) +
"@" + address + ":" + app["DB_PORT"] + "/" + urlEscape(app["DB_NAME"]) + "?sslmode=disable",
}, "")
config.DatabaseURL = dsn
config.AppImageID, err = containerImageID(ctx, opts.sourceApp)
if err != nil {
return config, err
@@ -388,17 +404,12 @@ func parseBool(value string) bool {
return false
}
func urlEscape(value string) string {
replacer := strings.NewReplacer("%", "%25", ":", "%3A", "@", "%40", "/", "%2F", "?", "%3F", "#", "%23", "&", "%26", " ", "%20")
return replacer.Replace(value)
}
// scopeBindings 返回 scope→知识库 映射。治理 API 用的是 LIBRARY_PRODUCTION_KB_*,
// CLI 读的是治理库里的 routing bindings;同一台机器上两份不一致时,
// CLI 抓到的会是"配置里那个库"而不是 API 认为的目标——所以环境变量优先,
// 读不到才退回 bindings。两边讲同一份身份,验收才可比。
func scopeBindings(ctx context.Context, container string) (map[string]string, error) {
binding, err := readRoutingBindings(ctx, container)
func scopeBindings(ctx context.Context, opts options) (map[string]string, error) {
binding, err := readRoutingBindings(ctx, opts)
if err != nil {
return nil, err
}
@@ -410,17 +421,105 @@ func scopeBindings(ctx context.Context, container string) (map[string]string, er
return binding, nil
}
func readRoutingBindings(ctx context.Context, container string) (map[string]string, error) {
raw, err := dockerOutput(ctx, "exec", container, "psql", "-U", "governance", "-d", "governance", "-tAc",
"SELECT internal_kb_id||'|'||external_kb_id FROM routing_kb_bindings WHERE id='active'")
// readRoutingBindings 读治理库里生效的 scope 绑定。两种来源:
// - 给了 -governance-pg:docker exec 进治理库容器跑 psql(0.7.1 本机栈);
// - 没给:治理库是托管实例(RDS 型 0.9.0 栈没有 governance 容器),DSN 来自
// LIBRARY_GOVERNANCE_DSN_FILE 指向的 0600 文件。
//
// 两条路径只共用行解析,不共用连接方式:容器里没有网络到 RDS 的凭据,宿主机也不该
// 为了读两列去 docker exec 一个不存在的容器。
func readRoutingBindings(ctx context.Context, opts options) (map[string]string, error) {
if librarydsn.GovernanceMode(opts.governancePG) == librarydsn.GovernanceFile {
dsn, err := librarydsn.GovernanceURL(os.Getenv)
if err != nil {
return nil, err
}
return readRoutingBindingsFromDSN(ctx, dsn)
}
raw, err := dockerOutput(ctx, "exec", opts.governancePG, "psql", "-U", "governance", "-d", "governance", "-tAc",
routingBindingsQuery)
if err != nil {
return nil, errors.New("read routing bindings failed")
}
internal, external, ok := strings.Cut(strings.TrimSpace(raw), "|")
if !ok || internal == "" || external == "" {
return nil, errors.New("routing bindings are incomplete")
return parseRoutingBindings(raw)
}
// COALESCE 不能省:两列都可能是 NULL(0.9.0 迁移把\"旧知识库绑定已解除\"落成 NULL,
// 平台约定\"对外库没有对应目标时留空\")。裸拼接遇 NULL 得到整行 NULL,文件模式
// 会在 Scan 成 string 时直接失败,报出的还是一句\"read routing bindings failed\"——
// 真正的原因(哪一列没绑)被吞掉。这里先拼成固定形状,由 parseRoutingBindings 判。
const routingBindingsQuery = "SELECT COALESCE(internal_kb_id,'')||'|'||COALESCE(external_kb_id,'') FROM routing_kb_bindings WHERE id='active'"
// readRoutingBindingsFromDSN 用外部 DSN 读同一份绑定。
//
// 只读会话是刻意的:这条路径只是读两列,出了问题必须是"读不到",而不是在治理库上
// 留下一次写入。错误一律收敛成固定说法:pgx 的错误里会带连接串(口令它自己打了码,
// 但主机与用户名照旧出去),而这里连那份地址都不该出现在日志或工单里。
func readRoutingBindingsFromDSN(ctx context.Context, dsn string) (map[string]string, error) {
parsed, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, errors.New("governance database url is invalid")
}
return map[string]string{"internal": internal, "external": external}, nil
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "30000"
parsed.MaxConns = 2
pool, err := pgxpool.NewWithConfig(ctx, parsed)
if err != nil {
return nil, errors.New("open governance database failed")
}
defer pool.Close()
var raw string
if err = pool.QueryRow(ctx, routingBindingsQuery).Scan(&raw); err != nil {
return nil, errors.New("read routing bindings failed")
}
return parseRoutingBindings(raw)
}
// parseRoutingBindings 解一行 `<internal>|<external>`。两条来源(psql -tAc 与 pgx
// 只读会话)拼的是同一句 SQL,所以只有这一份解析语义。
//
// 对内库必填:没有对内库就没有\"整库\"可言,此时必须点名是哪一列没绑,而不是退化成
// 泛化的读失败。对外库可空:平台侧约定\"对外库没有对应目标时留空\",绑定本身仍然
// 有效(`status`、internal scope 照常可跑);只有真去用 external scope 时才拒绝,
// 且绝不回退到对内库——那会把对内库的内容当成对外库封存出去。
func parseRoutingBindings(raw string) (map[string]string, error) {
trimmed := strings.TrimSpace(raw)
// 空输出 = 没有生效绑定行,等于对内库没绑:这跟"读失败"是两件事,
// 必须说成前者,否则现场又会退回一句泛化错误。
if trimmed == "" {
return nil, errInternalKBMissing
}
internal, external, ok := strings.Cut(trimmed, "|")
if !ok {
return nil, errors.New("read routing bindings failed")
}
internal = strings.TrimSpace(internal)
external = strings.TrimSpace(external)
if internal == "" {
return nil, errInternalKBMissing
}
binding := map[string]string{"internal": internal}
if external != "" {
binding["external"] = external
}
return binding, nil
}
var (
errInternalKBMissing = errors.New("对内知识库未绑定(routing_kb_bindings.internal_kb_id 为空)")
errExternalKBMissing = errors.New("对外知识库未配置(routing_kb_bindings.external_kb_id 为空)")
)
// scopeKnowledgeBase 取本次 scope 的目标库。空值必须在这里就拒绝:往下走会变成
// \"knowledge base not found in source\"——那是拿空 UUID 查源库得到的假原因。
func scopeKnowledgeBase(binding map[string]string, scope string) (string, error) {
if kb := strings.TrimSpace(binding[scope]); kb != "" {
return kb, nil
}
if scope == "external" {
return "", errExternalKBMissing
}
return "", errInternalKBMissing
}
func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool, error) {
@@ -432,11 +531,25 @@ func openSourceDatabase(ctx context.Context, config sourceConfig) (*pgxpool.Pool
// that a database-enforced property rather than a convention.
parsed.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
parsed.ConnConfig.RuntimeParams["statement_timeout"] = "120000"
// 启动参数不足以保证只读:角色级/库级设置会在启动参数之后生效,托管实例
// (RDS)上实测就是这样——SHOW 回来是 off。而池里每条连接是独立的会话,
// 对单条连接 SET 管不到其他连接,所以放在 AfterConnect:每条新连接都显式
// 置只读,池里就没有能写的会话。下面的 SHOW 只是对任意一条连接再核一次。
parsed.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(ctx, "SET SESSION default_transaction_read_only = on")
return err
}
pool, err := pgxpool.NewWithConfig(ctx, parsed)
if err != nil {
return nil, errors.New("open source database failed")
}
var readOnly string
// 连接失败与"能连上但会话可写"必须分开报:把两者压成同一句,现场只能看到
// 一句无信息量的失败,反而会去怀疑权限或只读设置。
if err = pool.Ping(ctx); err != nil {
pool.Close()
return nil, errors.New("source database connection failed")
}
if err = pool.QueryRow(ctx, "SHOW default_transaction_read_only").Scan(&readOnly); err != nil || readOnly != "on" {
pool.Close()
return nil, errors.New("source session is not read-only")
@@ -510,6 +623,11 @@ func openFreeze(ctx context.Context, opts options) (*libraryfreeze.Coordinator,
//
// 入口/队列的声明与容器内 worker 共用同一组 LIBRARY_TARGET_* 名称,
// 数据库/索引/桶则取自本次真实发现的源,避免"关的是 A 的门、读的是 B 的队列"。
//
// LIBRARY_TARGET_INGRESS_MODE=none 只给整栈没有闸门的测试环境(0.9.0 测试栈):
// 必须同时给 LIBRARY_NO_INGRESS_ACK=test-only,窗口里一笔闸门动作都不做,
// 排空证据降为"写者全停 + 队列静默",恢复由 LIBRARY_TARGET_HEALTH_URL 的 200 证明。
// 缺省仍是 gate:没有显式确认就照旧要求闸门。
func captureMaintenanceConfig(opts options, source sourceConfig, get func(string) string) (librarymaintenance.Config, error) {
target, err := librarymaintenance.TargetFromEnv(get)
if err != nil {
@@ -529,9 +647,12 @@ func captureMaintenanceConfig(opts options, source sourceConfig, get func(string
Writers: writers,
NonWriters: nonWriters,
DockerSocket: opts.dockerSocket,
IngressMode: target.Mode,
IngressAck: target.Ack,
IngressURL: target.IngressURL,
IngressService: target.IngressService,
IngressDrainFile: target.IngressDrainFile,
HealthURL: target.HealthURL,
Database: identity,
Index: source.SearchIndex,
Bucket: source.Object.Bucket,
@@ -587,7 +708,12 @@ func openArchive(opts options) (*librarysnapshot.Archive, error) {
func runStatus(ctx context.Context, opts options) error {
report := map[string]any{}
binding, bindingErr := scopeBindings(ctx, opts.governancePG)
// 只报来源模式:地址与凭据连 describe/status 都不出现,日志自然也不会带出去。
report["databases"] = map[string]string{
"source_db": librarydsn.SourceMode(opts.sourcePG),
"governance_db": librarydsn.GovernanceMode(opts.governancePG),
}
binding, bindingErr := scopeBindings(ctx, opts)
var config sourceConfig
var err error
if bindingErr != nil {
@@ -680,7 +806,12 @@ func runPreflight(ctx context.Context, opts options) error {
if opts.scope != "internal" && opts.scope != "external" {
return errors.New("-scope must be internal or external")
}
binding, err := scopeBindings(ctx, opts.governancePG)
binding, err := scopeBindings(ctx, opts)
if err != nil {
return err
}
// 绑定缺哪一半在连源库之前就要说清楚:external 未配置不是"源库里没这个库"。
kb, err := scopeKnowledgeBase(binding, opts.scope)
if err != nil {
return err
}
@@ -693,7 +824,6 @@ func runPreflight(ctx context.Context, opts options) error {
return err
}
defer pool.Close()
kb := config.Scopes[opts.scope]
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
if err != nil {
return err
@@ -773,7 +903,13 @@ func runCapture(ctx context.Context, opts options) error {
return err
}
defer archive.Close()
binding, err := scopeBindings(ctx, opts.governancePG)
binding, err := scopeBindings(ctx, opts)
if err != nil {
return err
}
// 先定住本次 scope 的库:external 没配置时,封存必须在开维护窗口之前就停,
// 不能先停写者再发现目标为空。
kb, err := scopeKnowledgeBase(binding, opts.scope)
if err != nil {
return err
}
@@ -801,7 +937,7 @@ func runCapture(ctx context.Context, opts options) error {
if err != nil {
return err
}
scopedKB := binding[opts.scope]
scopedKB := kb
if found {
manifest, err := replayCapture(job, opts.scope, scopedKB, existing, archive)
if err != nil {
@@ -814,7 +950,6 @@ func runCapture(ctx context.Context, opts options) error {
return err
}
defer pool.Close()
kb := config.Scopes[opts.scope]
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
if err != nil {
return err
@@ -1150,7 +1285,12 @@ func runDeadLetters(ctx context.Context, opts options) error {
if opts.scope != "internal" && opts.scope != "external" {
return errors.New("-scope must be internal or external")
}
binding, err := scopeBindings(ctx, opts.governancePG)
binding, err := scopeBindings(ctx, opts)
if err != nil {
return err
}
// external 未配置时,死信观测同样要明说"没配置",而不是拿空库去查源库。
kb, err := scopeKnowledgeBase(binding, opts.scope)
if err != nil {
return err
}
@@ -1163,7 +1303,6 @@ func runDeadLetters(ctx context.Context, opts options) error {
return err
}
defer pool.Close()
kb := config.Scopes[opts.scope]
tenant, err := tenantAndKnowledgeBase(ctx, pool, kb)
if err != nil {
return err
@@ -0,0 +1,59 @@
package main
import (
"strings"
"testing"
"knowledge-governance/internal/libraryfreeze"
)
// noGateMaintenanceEnv 是 0.9.0 测试栈:没有闸门,用显式确认 + 健康探针代替。
func noGateMaintenanceEnv() map[string]string {
env := maintenanceEnv()
delete(env, "LIBRARY_TARGET_INGRESS_URL")
delete(env, "LIBRARY_TARGET_INGRESS_SERVICE")
delete(env, "LIBRARY_TARGET_INGRESS_DRAIN_FILE")
env["LIBRARY_TARGET_INGRESS_MODE"] = libraryfreeze.IngressModeNone
env["LIBRARY_NO_INGRESS_ACK"] = libraryfreeze.NoIngressAck
env["LIBRARY_TARGET_HEALTH_URL"] = "http://127.0.0.1:18081/health"
return env
}
func TestCaptureMaintenanceConfigNoGateWithAck(t *testing.T) {
env := noGateMaintenanceEnv()
config, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] })
if err != nil {
t.Fatalf("no-gate 声明被拒:%v", err)
}
if config.IngressMode != libraryfreeze.IngressModeNone || config.IngressAck != libraryfreeze.NoIngressAck {
t.Fatalf("入口形态没透传:%+v", config)
}
if config.IngressURL != "" || config.IngressService != "" || config.IngressDrainFile != "" {
t.Fatalf("no-gate 配置里出现了闸门项:%+v", config)
}
if config.HealthURL != "http://127.0.0.1:18081/health" || config.RedisAddr != "127.0.0.1:26379" {
t.Fatalf("健康探针/队列没透传:%+v", config)
}
// 目标身份仍取自本次真实发现的源:no-gate 只改证据形态,不改动的是谁。
if config.Database != "127.0.0.1:25432/kgmaint_target" || config.Index != "kgmaint_1028a_chunks" {
t.Fatalf("目标身份不对:%+v", config)
}
}
func TestCaptureMaintenanceConfigNoGateWithoutAckIsRefused(t *testing.T) {
env := noGateMaintenanceEnv()
delete(env, "LIBRARY_NO_INGRESS_ACK")
_, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] })
if err == nil || !strings.Contains(err.Error(), "LIBRARY_NO_INGRESS_ACK") {
t.Fatalf("没有显式确认却放过了 no-gate:%v", err)
}
}
// no-gate 不得悄悄接受半套闸门声明:要么有闸门,要么明确没有。
func TestCaptureMaintenanceConfigNoGateRejectsPartialGate(t *testing.T) {
env := noGateMaintenanceEnv()
env["LIBRARY_TARGET_INGRESS_SERVICE"] = "ingress"
if _, err := captureMaintenanceConfig(captureOptions(), captureSource(), func(name string) string { return env[name] }); err == nil {
t.Fatal("no-gate 与闸门服务同时存在却没有拒绝")
}
}
+103
View File
@@ -0,0 +1,103 @@
package main
import (
"strings"
"testing"
)
// internal 为空必须拒绝并点名。实测到的现场就是这一行:0.9.0 迁移后
// internal_kb_id 与 external_kb_id 都是 NULL,旧解析退化成
// "read routing bindings failed",操作员无法判断是连不上还是没绑定。
// NULL 与空串在 SQL 侧由 routingBindingsQuery 的 COALESCE 收敛成同一形状,
// 解析侧两者都必须落到同一条错误上。
func TestParseRoutingBindingsRejectsEmptyInternal(t *testing.T) {
for _, raw := range []string{"|", "|ext-kb", " \n| \n", "\n|\n", ""} {
binding, err := parseRoutingBindings(raw)
if err == nil {
t.Fatalf("internal 为空却解析成功:%q → %v", raw, binding)
}
if binding != nil {
t.Fatalf("internal 为空仍返回了映射:%q → %v", raw, binding)
}
if !strings.Contains(err.Error(), "对内知识库未绑定") || !strings.Contains(err.Error(), "internal_kb_id") {
t.Fatalf("错误没有点名 internal 未绑定:%q → %v", raw, err)
}
}
}
// 0.9.0 测试实例的真实形状:只有对内库(wiki-demo),平台约定对外库没有对应
// 目标时留空。绑定仍然有效,internal scope 能解析;external scope 必须失败、
// 点名 external_kb_id,并且绝不回退到对内库。
func TestParseRoutingBindingsAllowsEmptyExternal(t *testing.T) {
binding, err := parseRoutingBindings("0da9b571-6f13-46a1-85fa-e63d2ef5666e|")
if err != nil {
t.Fatalf("对外库为空不该让整份绑定失效:%v", err)
}
if got := binding["internal"]; got != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" {
t.Fatalf("对内库解析错误:%q", got)
}
if value, present := binding["external"]; present {
t.Fatalf("对外库没配置却写进了映射:%q", value)
}
kb, err := scopeKnowledgeBase(binding, "internal")
if err != nil || kb != "0da9b571-6f13-46a1-85fa-e63d2ef5666e" {
t.Fatalf("internal scope 不该被 external 为空牵连:kb=%q err=%v", kb, err)
}
kb, err = scopeKnowledgeBase(binding, "external")
if err == nil {
t.Fatalf("对外库未配置却解析出了目标库:%q", kb)
}
if kb != "" {
t.Fatalf("external scope 回退到了别的库:%q", kb)
}
if !strings.Contains(err.Error(), "对外知识库未配置") || !strings.Contains(err.Error(), "external_kb_id") {
t.Fatalf("错误没有点名 external 未配置:%v", err)
}
}
// 两个库都绑定时行为不变:这是 0.7.1 栈与对外库已配置的 0.9.0 栈的常态路径。
func TestParseRoutingBindingsBothScopesUnchanged(t *testing.T) {
// psql -tAc 输出带行尾换行,pgx 那边不带——两边都必须是同一个结果。
for _, raw := range []string{"kb-internal|kb-external", "kb-internal|kb-external\n", " kb-internal | kb-external \n"} {
binding, err := parseRoutingBindings(raw)
if err != nil {
t.Fatalf("两个库都绑定却解析失败:%q → %v", raw, err)
}
if len(binding) != 2 || binding["internal"] != "kb-internal" || binding["external"] != "kb-external" {
t.Fatalf("解析结果与原行为不一致:%q → %v", raw, binding)
}
for _, scope := range []string{"internal", "external"} {
if _, err := scopeKnowledgeBase(binding, scope); err != nil {
t.Fatalf("%s scope 不该失败:%v", scope, err)
}
}
}
}
// 没有分隔符说明拿到的不是那一行(空结果集、psql 报错文本等),只能是读失败。
func TestParseRoutingBindingsRejectsMalformedRow(t *testing.T) {
for _, raw := range []string{"kb-without-separator", "ERROR: relation \"routing_kb_bindings\" does not exist"} {
if _, err := parseRoutingBindings(raw); err == nil {
t.Fatalf("没有分隔符却解析成功:%q", raw)
}
}
}
// 不连库的语法/形状校验:裸拼接遇 NULL 会得到整行 NULL,文件模式在 Scan 成
// string 时就会失败并丢掉真实原因。两句来源共用这一条 SQL,因此只查这一处。
func TestRoutingBindingsQueryCoalescesBothColumns(t *testing.T) {
query := routingBindingsQuery
for _, column := range []string{"internal_kb_id", "external_kb_id"} {
if !strings.Contains(query, "COALESCE("+column+",'')") {
t.Fatalf("查询没有把 %s 的 NULL 收敛成空串:%s", column, query)
}
}
if !strings.Contains(query, "||'|'||") {
t.Fatalf("查询不再产出 '<internal>|<external>' 形状:%s", query)
}
if !strings.Contains(query, "WHERE id='active'") {
t.Fatalf("查询没有锁定生效绑定行:%s", query)
}
}
@@ -0,0 +1,59 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// v090 采集脚本是本轮新增的唯一入口。为什么用 bash -n 而不是"跑一遍":跑一遍要
// 停写入者、连 RDS——那是真实采集,不是单元测试。语法与声明在这里钉住,能让
// "标志写错一个字母"在 CI 里就红,而不是等到开维护窗口时才发现。
func TestV090CaptureScriptIsSyntacticallyValid(t *testing.T) {
bash, err := exec.LookPath("bash")
if err != nil {
t.Fatalf("需要 bash 才能检查脚本语法(CI 与测试机都有):%v", err)
}
path := filepath.Join("..", "..", "scripts", "library-capture-v090.sh")
out, err := exec.Command(bash, "-n", path).CombinedOutput()
if err != nil {
t.Fatalf("bash -n %s 失败:%v\n%s", path, err, out)
}
}
// 脚本内容断言:外部库模式(两个 -pg 传空)、写者声明、容器名、归档根、
// LIBRARYCTL_BIN 缺失即失败——这些一旦漂移,真跑时会封错栈或读错库。
func TestV090CaptureScriptDeclaresExternalDatabases(t *testing.T) {
body, err := os.ReadFile(filepath.Join("..", "..", "scripts", "library-capture-v090.sh"))
if err != nil {
t.Fatalf("读脚本:%v", err)
}
for _, want := range []string{
"set -euo pipefail",
"LIBRARYCTL_MISSING",
"-project weknora-v090",
"-writers app",
"-source-app weknora-v090-app",
"-source-es weknora-v090-elasticsearch",
`-source-pg ""`,
`-governance-pg ""`,
"frontend=UI only; no knowledge writes",
"docreader=parse RPC service; app persists parse output",
"elasticsearch=search store; not an initiator",
"redis=queue/cache store; not an initiator",
"/var/lib/knowledge-governance/library",
"/var/lib/knowledge-governance/freeze",
} {
if !strings.Contains(string(body), want) {
t.Fatalf("脚本缺少 %q", want)
}
}
// 0.7.1 的服务名绝不能出现在 v090 入口里:那会让封存停错栈。
for _, forbidden := range []string{"WKNFull", "weknora071full"} {
if strings.Contains(string(body), forbidden) {
t.Fatalf("v090 脚本里出现了 0.7.1 的 %q", forbidden)
}
}
}
+4 -7
View File
@@ -2,8 +2,6 @@ package main
import (
"context"
"crypto/ed25519"
"encoding/base64"
"errors"
"log"
"net"
@@ -35,10 +33,6 @@ func run() error {
if len(data) < 32 || len(control) < 32 || data == control {
return errors.New("gateway_distinct_tokens_required")
}
pub, e := base64.StdEncoding.DecodeString(os.Getenv("OBJECT_GATEWAY_AUDIT_PUBLIC_KEY"))
if e != nil || len(pub) != ed25519.PublicKeySize {
return errors.New("gateway_auditor_key_required")
}
provider, endpoint, bucket := os.Getenv("OBJECT_GATEWAY_PROVIDER"), os.Getenv("OBJECT_GATEWAY_ENDPOINT"), os.Getenv("OBJECT_GATEWAY_BUCKET")
scope := objectgateway.Digest([]byte(provider + "\x00" + endpoint + "\x00" + bucket))
pool, e := pgxpool.New(ctx, os.Getenv("OBJECT_GATEWAY_DATABASE_URL"))
@@ -50,7 +44,10 @@ func run() error {
if e != nil {
return errors.New("gateway_backend_configuration_invalid")
}
g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024, Isolation: objectgateway.AuditVerifier{Path: os.Getenv("OBJECT_GATEWAY_AUDIT_FILE"), PublicKey: pub, Scope: scope, GatewayID: os.Getenv("OBJECT_GATEWAY_ID")}}
// The target bucket is shared with other writers. Admission is the journal
// plus backend capability; retired attestation env vars are deliberately
// ignored so an old deployment file cannot gate this path.
g := &objectgateway.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 256 * 1024 * 1024}
if governanceURL := os.Getenv("OBJECT_GATEWAY_GOVERNANCE_DATABASE_URL"); governanceURL != "" {
cfg, e := pgxpool.ParseConfig(governanceURL)
if e != nil {
+82
View File
@@ -0,0 +1,82 @@
package main
import (
"context"
"encoding/base64"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// startErrorMessage builds the addressed binary and runs it long enough to
// observe why the real entry point refused to listen.
func startErrorMessage(t *testing.T, extra ...string) (string, int) {
t.Helper()
bin := filepath.Join(t.TempDir(), "object-gateway")
build := exec.Command("go", "build", "-o", bin, ".")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build gateway: %v\n%s", err, out)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, bin)
cmd.Env = append([]string{
"PATH=" + os.Getenv("PATH"),
"HOME=" + os.Getenv("HOME"),
"OBJECT_GATEWAY_LISTEN=127.0.0.1:0",
"OBJECT_GATEWAY_DATABASE_URL=postgres://gateway@127.0.0.1:1/gateway?sslmode=disable&connect_timeout=2",
"OBJECT_GATEWAY_PROVIDER=minio",
"OBJECT_GATEWAY_ENDPOINT=http://127.0.0.1:19100",
"OBJECT_GATEWAY_BUCKET=maintenance-fixture-bucket",
"OBJECT_GATEWAY_REGION=us-east-1",
"OBJECT_GATEWAY_ACCESS_KEY=fixture-access-key",
"OBJECT_GATEWAY_SECRET_KEY=fixture-secret-key",
"OBJECT_GATEWAY_DATA_TOKEN=" + strings.Repeat("d", 32),
"OBJECT_GATEWAY_CONTROL_TOKEN=" + strings.Repeat("c", 32),
}, extra...)
out, err := cmd.CombinedOutput()
if ctx.Err() != nil {
t.Fatalf("gateway did not terminate; output=%s", out)
}
code := 0
if exit, ok := err.(*exec.ExitError); ok {
code = exit.ExitCode()
} else if err != nil {
t.Fatalf("run gateway: %v", err)
}
return string(out), code
}
// The default shared-bucket path must not require a whole-bucket exclusive
// writer attestation. Only the journal/backend admission gate may refuse it,
// and a stale attestation file left behind by an older deployment must not
// gate the default path either.
func TestGatewayEntrypointDoesNotRequireBucketAttestation(t *testing.T) {
for _, tc := range []struct {
name string
env []string
}{
{name: "no_audit_configured"},
{name: "stale_audit_file_ignored", env: []string{
"OBJECT_GATEWAY_ID=retired-gateway",
"OBJECT_GATEWAY_AUDIT_FILE=/nonexistent/expired-attestation.json",
"OBJECT_GATEWAY_AUDIT_PUBLIC_KEY=" + base64.StdEncoding.EncodeToString(make([]byte, 32)),
}},
} {
t.Run(tc.name, func(t *testing.T) {
out, code := startErrorMessage(t, tc.env...)
if code == 0 {
t.Fatalf("gateway exited 0 instead of reporting its admission state: %s", out)
}
if strings.Contains(out, "gateway_auditor_key_required") || strings.Contains(out, "gateway_exclusive_writer_evidence_unverified") {
t.Fatalf("shared-bucket admission still gated by whole-bucket attestation: %s", out)
}
if !strings.Contains(out, "gateway_persistence_unavailable") && !strings.Contains(out, "gateway_backend_not_ready") {
t.Fatalf("gateway did not reach journal/backend admission: %s", out)
}
})
}
}
@@ -0,0 +1,96 @@
package main
import (
"context"
"errors"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
type capturePersistenceFake struct {
failAdvance error
failStage error
advanced []governance.LibraryJobState
stages []string
}
func (f *capturePersistenceFake) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState,
_, _, _, _, _ string, _ time.Time) error {
f.advanced = append(f.advanced, state)
return f.failAdvance
}
func (f *capturePersistenceFake) UpdateLibraryStage(_ context.Context, _, stage, state string,
_, _, _, _ *int64, _ string, _ time.Time) error {
f.stages = append(f.stages, stage+"/"+state)
return f.failStage
}
// The handler must stop before touching the source when the starting state
// cannot be persisted. This is the failure injection that the old log-and-ignore
// path hid behind a completed queue row.
func TestBeginLibraryCaptureStopsOnAdvanceFailure(t *testing.T) {
store := &capturePersistenceFake{failAdvance: errors.New("injected advance failure")}
err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now())
if err == nil || !strings.Contains(err.Error(), "cannot be advanced") {
t.Fatalf("err=%v", err)
}
if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobRunning {
t.Fatalf("advance calls=%v", store.advanced)
}
if len(store.stages) != 0 {
t.Fatalf("stage was written before advance failure: %v", store.stages)
}
}
func TestBeginLibraryCaptureStopsOnStageFailure(t *testing.T) {
store := &capturePersistenceFake{failStage: errors.New("injected stage failure")}
err := beginLibraryCaptureJob(context.Background(), store, "libseal-test", time.Now())
if err == nil || !strings.Contains(err.Error(), "stage cannot be advanced") {
t.Fatalf("err=%v", err)
}
if len(store.stages) != 1 || store.stages[0] != "export/running" {
t.Fatalf("stage calls=%v", store.stages)
}
}
// Terminal persistence is two writes; either failure must be returned rather
// than turning the queue row into completed while the business job is pending.
func TestCompleteLibraryCaptureStopsOnStageFailure(t *testing.T) {
store := &capturePersistenceFake{failStage: errors.New("injected success stage failure")}
err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now())
if err == nil || !strings.Contains(err.Error(), "success stage cannot be persisted") {
t.Fatalf("err=%v", err)
}
if len(store.advanced) != 0 {
t.Fatalf("advance must not run after stage failure: %v", store.advanced)
}
}
func TestCompleteLibraryCaptureStopsOnAdvanceFailure(t *testing.T) {
store := &capturePersistenceFake{failAdvance: errors.New("injected success advance failure")}
err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now())
if err == nil || !strings.Contains(err.Error(), "success terminal cannot be persisted") {
t.Fatalf("err=%v", err)
}
if len(store.stages) != 1 || store.stages[0] != "export/succeeded" {
t.Fatalf("stage calls=%v", store.stages)
}
if len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded {
t.Fatalf("advance calls=%v", store.advanced)
}
}
func TestCompleteLibraryCapturePersistsBothFacts(t *testing.T) {
store := &capturePersistenceFake{}
if err := completeLibraryCaptureJob(context.Background(), store, "libseal-test", "snap-test", time.Now()); err != nil {
t.Fatal(err)
}
if len(store.stages) != 1 || store.stages[0] != "export/succeeded" ||
len(store.advanced) != 1 || store.advanced[0] != governance.LibraryJobSucceeded {
t.Fatalf("stages=%v advanced=%v", store.stages, store.advanced)
}
}
@@ -0,0 +1,65 @@
package main
import (
"errors"
"strings"
"testing"
"knowledge-governance/internal/jobs"
)
// R3g: only retained deterministic capture failures become permanent after the
// agent has recovered the writer. Cancelled body-index coverage markers are
// deliberately absent.
func TestRetainedLibraryCaptureFailuresArePermanent(t *testing.T) {
for _, marker := range []string{
"missing library generated question index",
"empty library index content",
} {
t.Run(marker, func(t *testing.T) {
original := errors.New("LIBRARYCTL_FAILED: " + marker + ";已执行 recover 并确认写入者恢复")
got := terminalLibraryCaptureError(original)
terminal, code := jobs.Terminal(got)
if !terminal || code != jobs.ErrCodeValidationFailed {
t.Fatalf("retained validation failure must park immediately: terminal=%v code=%q err=%v", terminal, code, got)
}
if got.Error() != original.Error() {
t.Fatalf("original message changed: got %q want %q", got.Error(), original.Error())
}
})
}
}
func TestCancelledCoverageFailureStaysRetryable(t *testing.T) {
for _, marker := range []string{
"unverified legacy library chunk index coverage",
"missing indexed library chunk",
} {
err := terminalLibraryCaptureError(errors.New(marker + ";已执行 recover 并确认写入者恢复"))
if terminal, code := jobs.Terminal(err); terminal {
t.Fatalf("cancelled marker %q must not be terminal; code=%q", marker, code)
}
}
}
func TestTransientLibraryCaptureFailureStaysRetryable(t *testing.T) {
for _, message := range []string{
"library agent is unreachable",
"context deadline exceeded",
`LIBRARYCTL_FAILED: job "lib-internal-x" already exists with state "failed";已执行 recover 并确认写入者恢复`,
"missing library generated question index; writer restore not confirmed",
} {
got := terminalLibraryCaptureError(errors.New(message))
if terminal, code := jobs.Terminal(got); terminal {
t.Fatalf("%q must stay retryable, got terminal code=%q", message, code)
}
}
}
func TestRetainedFailureDoesNotChangeMessage(t *testing.T) {
original := errors.New("LIBRARYCTL_FAILED: missing library generated question index;已执行 recover 并确认写入者恢复")
got := terminalLibraryCaptureError(original)
if !strings.Contains(got.Error(), "missing library generated question index") {
t.Fatalf("lost original cause: %v", got)
}
}
@@ -447,7 +447,7 @@ func TestThreeBlockersVerifyChain(t *testing.T) {
Scan(&scopeState, &scopeIngress, &scopeReleased); err != nil {
t.Fatal(err)
}
if scopeReleased == nil || scopeState != "verified" || scopeIngress != "open" {
if scopeReleased == nil || scopeState != "released" || scopeIngress != "open" {
t.Fatalf("scope maintenance final state=%s ingress=%s released=%v", scopeState, scopeIngress, scopeReleased)
}
sentinelPG := tbUnrelatedSentinel(t, ctx, pool)
+84 -22
View File
@@ -9,6 +9,7 @@ import (
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
@@ -23,7 +24,9 @@ import (
"knowledge-governance/internal/librarysnapshot"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/readiness"
"knowledge-governance/internal/versionhistory"
"knowledge-governance/internal/weknoraaccess"
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
catalogrefresh "knowledge-governance/internal/workflows/catalogrefresh"
"knowledge-governance/internal/workflows/sourcescan"
@@ -98,6 +101,27 @@ func stageSizesFrom(manifest librarysnapshot.Manifest) map[string]stageSize {
// libraryCaptureJobType is shared with the API which enqueues it.
const libraryCaptureJobType = "library.capture"
// Retained deterministic source-content failures: the agent has already
// restored the writer, so retrying the same journal only replaces the first
// cause with "already exists". Body-index coverage markers are intentionally
// absent; that inferred rule was removed in R3f.
var terminalLibraryCaptureMarkers = []string{
"missing library generated question index",
"empty library index content",
}
func terminalLibraryCaptureError(err error) error {
if err == nil || !strings.Contains(err.Error(), "已执行 recover 并确认写入者恢复") {
return err
}
for _, marker := range terminalLibraryCaptureMarkers {
if strings.Contains(err.Error(), marker) {
return jobs.Permanent(jobs.ErrCodeValidationFailed, err)
}
}
return err
}
// librarySyncJobType 是生产同步作业的队列类型;与封存严格分开,状态不共用。
const librarySyncJobType = "library.sync"
@@ -146,7 +170,7 @@ func run(ctx context.Context, getenv func(string) string) error {
} else if len(pending) > 0 {
return fmt.Errorf("治理库 schema 落后(待应用迁移 %v):本角色不拥有 DDL,先由控制面进程完成迁移", pending)
}
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID).
WithRestoreDispatchEvidence(config.LibraryTargetJournalRoot)
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
@@ -264,6 +288,41 @@ func run(ctx context.Context, getenv func(string) string) error {
return worker.Run(ctx, config.PollInterval)
}
type libraryCapturePersistence interface {
UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error
AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error
}
// beginLibraryCaptureJob persists the starting state before any source
// operation. If either write fails the handler must return, so the queue cannot
// be reported completed while the business job is still pending.
func beginLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID string, now time.Time) error {
if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobRunning, "export", "", "", "", "", now); err != nil {
return fmt.Errorf("library seal job %s cannot be advanced: %w", jobID, err)
}
if err := store.UpdateLibraryStage(ctx, jobID, "export", "running", nil, nil, nil, nil,
"主机侧正在暂停写入者、导出并恢复", now); err != nil {
return fmt.Errorf("library seal job %s stage cannot be advanced: %w", jobID, err)
}
return nil
}
// completeLibraryCaptureJob persists both terminal facts. A failed write must
// be returned (queue failed), not logged and ignored; the capture journal keeps
// replay idempotent, and the admin reconcile path can repair only after the
// exact queue/version/archive evidence is present.
func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersistence, jobID, snapshotID string, now time.Time) error {
if err := store.UpdateLibraryStage(ctx, jobID, "export", "succeeded", nil, nil, nil, nil,
"已封存快照 "+snapshotID, now); err != nil {
return fmt.Errorf("library seal job %s success stage cannot be persisted: %w", jobID, err)
}
if err := store.AdvanceLibraryJob(ctx, jobID, governance.LibraryJobSucceeded, "export", "", "",
snapshotID, "", now); err != nil {
return fmt.Errorf("library seal job %s success terminal cannot be persisted: %w", jobID, err)
}
return nil
}
func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[string]jobs.Handler, error) {
handlers := map[string]jobs.Handler{
"demo": func(_ context.Context, job jobs.Job) error {
@@ -325,12 +384,8 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
// 持久作业:页面读的是这里写的阶段与结果,worker 重启后仍能如实展示。
libraryJobID := "libseal-" + payload.CaptureJob
startedAt := time.Now().UTC()
if advanceErr := store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobRunning, "export", "", "", "", "", startedAt); advanceErr != nil {
log.Printf("library seal job %s cannot be advanced: %v", libraryJobID, advanceErr)
}
if stageErr := store.UpdateLibraryStage(ctx, libraryJobID, "export", "running", nil, nil, nil, nil,
"主机侧正在暂停写入者、导出并恢复", startedAt); stageErr != nil {
log.Printf("library seal job %s stage update failed: %v", libraryJobID, stageErr)
if beginErr := beginLibraryCaptureJob(ctx, store, libraryJobID, startedAt); beginErr != nil {
return beginErr
}
// 平台审计过的精确死信解除指纹:读取失败必须阻断(fail closed),
// 不能因为存储不可用就静默按"没有解除"或"全部解除"处理。
@@ -362,7 +417,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobFailed, "export", err.Error(),
"agent 已执行恢复检查;确认来源 healthy 后可重试同一作业号", "", "", finishedAt)
log.Printf("library capture failed scope=%s capture_job=%s: %v", payload.Scope, payload.CaptureJob, err)
return err
return terminalLibraryCaptureError(err)
}
// 执行后复核:结果里 agent 自报的身份必须还是期望实例,否则这次封存
// 可能来自别的栈,绝不能登记成"本实例的测试封存"。
@@ -388,10 +443,9 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
if versionErr != nil {
return fmt.Errorf("library seal job %s cannot record version: %w", libraryJobID, versionErr)
}
_ = store.UpdateLibraryStage(ctx, libraryJobID, "export", "succeeded", nil, nil, nil, nil,
"已封存快照 "+result.SnapshotID, finishedAt)
_ = store.AdvanceLibraryJob(ctx, libraryJobID, governance.LibraryJobSucceeded, "export", "", "",
result.SnapshotID, "", finishedAt)
if completeErr := completeLibraryCaptureJob(ctx, store, libraryJobID, result.SnapshotID, finishedAt); completeErr != nil {
return completeErr
}
log.Printf("library capture completed scope=%s capture_job=%s snapshot=%s replay=%v requested_by=%s",
payload.Scope, payload.CaptureJob, result.SnapshotID, result.Replay, payload.RequestedBy)
return nil
@@ -471,19 +525,27 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
if !config.TestWeKnoraEnabled || !config.LibraryWorkerRole.ExecutesSourceWork() {
return handlers, nil
}
apiKey, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
if err != nil {
// 启动只验证凭据“存在”(缺失像以前一样拒绝启动);具体值仍由 resolver 每次调用重读。
if _, err := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile); err != nil {
return nil, fmt.Errorf("read test WeKnora API key: %w", err)
}
client, err := weknora.NewClient(weknora.ClientConfig{
BaseURL: config.TestWeKnoraBaseURL,
APIKey: apiKey,
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
})
if err != nil {
return nil, fmt.Errorf("create test WeKnora client: %w", err)
// 与 API 探测共用同一有效目标:网页保存的端点优先、env 只作未配置兜底;
// 当前持久化绑定优先、env 兜底;凭据每次调用重读同一 key 文件。
remoteResolver := readiness.Resolver{
Endpoint: func(resolveCtx context.Context) string {
if settings, settingsErr := store.GetActiveUISettings(resolveCtx); settingsErr == nil && strings.TrimSpace(settings.TestWeKnoraBaseURL) != "" {
return settings.TestWeKnoraBaseURL
}
return config.TestWeKnoraBaseURL
},
LoadBinding: func(resolveCtx context.Context) (string, error) {
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
return internal, bindingErr
},
ReadKey: func() (string, error) { return weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile) },
DefaultKB: config.InternalRoutingKnowledgeBaseID,
}
client := &weknoraaccess.Client{Resolver: remoteResolver, Timeout: config.TestWeKnoraHTTPTimeout, AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP}
upload, err := testweknora.NewUploadHandler(testweknora.UploadHandlerConfig{
Store: store,
Client: client,
+6 -1
View File
@@ -18,4 +18,9 @@
1. 跑 `make verify`(本地全绿不等于远端跑通,需要一次真实 run 的证据)。
2. 把**使用者可见**的变化写成 `CHANGELOG.md` 的 `[Unreleased]` 条目(按四类,别写过程)。
3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。
3. 从本文件划掉该项;过程记录归档到 `docs/archive/`。
## 资源首次复用的归属审计(后续)
- 当前首次复用只依赖“目标行逐列一致 + 对象字节一致”,不再要求本目标历史成功同步/预备份来源。
- 后续可补:资源首次写入者/首次绑定 KB、跨 KB 引用计数、孤儿资源与同 tenant 共享资源的可审计归属视图;
不以此重新阻断正常的同内容首次复用。
+8
View File
@@ -56,8 +56,16 @@ LIBRARY_TARGET_INGRESS_URL 入口地址(恢复后要能 200)
LIBRARY_TARGET_INGRESS_SERVICE Compose 里的入口闸门服务名
LIBRARY_TARGET_INGRESS_DRAIN_FILE 闸门写排空证据的宿主机文件
LIBRARY_TARGET_REDIS_ADDR/_PASSWORD/_DB 后台队列(asynq)地址
LIBRARY_TARGET_INGRESS_MODE gate(缺省)或 none;none 只给没有闸门的测试栈
LIBRARY_NO_INGRESS_ACK mode=none 时必须逐字符等于 test-only
LIBRARY_TARGET_HEALTH_URL mode=none 时的健康探针(恢复后必须 200)
```
`none` 是显式降档,不是默认:整栈(如 0.9.0 测试栈)没有入口闸门时,`none` + 确认串
才允许缺入口三项,窗口里不调用任何闸门动作,`gate` 证据位置写
`{"mode":"none","reason":"stack has no ingress gate (test-only)"}`;恢复以
`LIBRARY_TARGET_HEALTH_URL` 返回 200 为准。缺省 `gate` 的行为与文案不变。
另外 `-source-s3-endpoint <URL>` 用来覆盖"源对象存储的访问入口":容器里写的
`MINIO_ENDPOINT` 往往是服务名(`langfuse-minio:9000`),封存跑在宿主机上时解析不到,
资源导出会失败(`read library resource`)。覆盖只换入口,桶与对象键不变;`status`
+2 -2
View File
@@ -1,6 +1,6 @@
# v0.7.1 整库发布的数据契约与覆盖边界
这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关的独占审核是测试夹具,不代表生产已隔离;B22 控制读取角色是真实 SELECT-only PG 角色。
这是候选代码的契约,不是部署许可。真实隔离执行证据在交付目录 `data-contract-r10.md`、`test-summary-r10.json` 及其 raw 索引。PG/ES/MinIO 均为本机隔离真实服务;发布/恢复测试直接调用适配器;B22 另走实际 `librarystack.OpenProductionStack` 和 HTTP 网关。网关按限定 key 工作,不要求整桶独占审核;B22 控制读取角色是真实 SELECT-only PG 角色。
## 1. 源 schema、历史身份与准入
@@ -55,7 +55,7 @@
- 真实v071历史catalog镜像对照及UUID/自然键矩阵在r11执行,隔离结论与外部当前目录采样分开。A04已识别嵌套引用有有限支持,旧外部cursor仍不自动转换,不因内部结构正例而升级整项。
- r8/r9进程恢复历史证据只在原发送协议、不可变计划/receipt及相应场景前提不变时复用。本轮对schema/引用准入有收紧,不能把历史执行日志称为当前源码正式进程全链重跑;完整当前隔离适配器回归单列。
- clean-finalization unknown保持held是安全行为,但未满足全部自动收敛要求。若要求自动完成,需要能绑定原写入、完整内容和代次的充分服务端证据;相同干净正文、人工猜测归属或放宽共享规则均不可替代。
- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。生产独占/ACL网络凭据、网关OSS业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。
- 最终提交/push、远端CI、父复核和本机部署为明确下一门;整体安全验收未齐不部署。网关真实 OSS 业务端到端与宿主重启/断电是另行授权的部署/破坏性验收,不能作为停止本机授权开发的借口。
## 6. 目录与唯一键的有限支持矩阵
+48
View File
@@ -0,0 +1,48 @@
# 目标库隔离 ID 映射
同一 WeKnora 实例里可以有多个知识库。同步把源快照写进目标库时,如果沿用源库的 UUID 主键,
第二个目标库会与实例里已有库的行撞主键(真实证据:2 knowledges / 2 chunks / 23 wiki_pages /
17 wiki_folders 已存在于旧库),写入前的跨范围检查会拒绝整次同步。关闭检查等于让两个库共享身份,
删除/恢复/校验会互相误伤,因此身份必须在目标侧派生。
## 映射规则
```
digest = sha256("knowledge-governance/target-identity/v1" || tenant || kb || table || source_id)
target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 variant/version 位)
```
这是**本产品自定义的稳定 ID 算法**(`target_id_mode=scoped-sha256-v1`),只保证确定性与目标隔离;
它不是标准 RFC 4122 UUIDv5(UUIDv5 用 SHA-1 + 标准 namespace),不要按 UUIDv5 互操作。
- 只绑定**稳定目标身份**(目标 tenant、目标 KB)与源身份,表名参与命名空间;
- 不绑定 job、时间、快照版本等瞬态值:同一目标重复同步/重试/跨版本得到同一 ID;
- 不同目标 KB、不同表得到不同 ID;
- 源归档字节不变,映射只存在于目标侧派生视图(写集合、写入行、索引文档、校验预期);
- 计划把策略持久化为 `target_id_mode=scoped-sha256-v1`:新进程按该字段重建映射,旧计划/写前镜像
没有该字段则按原 ID 回放,绝不二次映射。
## 参与映射的表与字段
| 表 | 身份 | 引用字段 |
|---|---|---|
| knowledges | id | — |
| chunks | id | knowledge_id, tag_id, parent_chunk_id, pre_chunk_id, next_chunk_id, relation_chunks, indirect_relation_chunks, metadata(仅精确匹配) |
| knowledge_tags | id | — |
| knowledge_tag_relations | (knowledge_id, tag_id) | 两个分量分别映射 |
| wiki_folders | id | parent_id |
| wiki_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) |
| wiki_page_issues | id | page_id, knowledge_id, chunk_id |
| resource_bindings | id | owner_id(按 owner_type) |
| resources | **不映射** | resource_id 保持共享身份 |
| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id |
正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列
(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。
## 一致性边界
- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算;
- 索引计划的目标文档 ID 与 `_source` 引用同步映射,before-image(目标写前镜像)保持原样;
- 恢复重放写前镜像时映射关闭,避免把目标原始 ID 再映射一次;
- 资源对象路径/location_hash 仍由既有资源改写逻辑处理,不因 ID 映射而变化。
+24 -12
View File
@@ -4,12 +4,14 @@
`cmd/object-gateway` 提供 `kg-object-gateway-v1`,只监听 loopback;外部接入需要另行审核的 TLS 终结与网络隔离。治理 PG 保存不可变计划、grant、intent、逐版本 receipt 和 attempt→grant delivery。部署迁移身份显式应用 `internal/objectgateway/schema.sql`;启动不自动迁移。运行身份只授必要 SELECT/INSERT 和 scope 行 UPDATE,不授 DDL/TRUNCATE/证据修改或业务库写权限。
scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶只能有一个受审核 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。
scope 是 provider、原 endpoint、bucket 的 NUL 分隔 SHA256。同一物理桶在本网关内只使用一个 scope 和一套共享 journal,不能用 endpoint 别名或另一日志库建立平行写域。这不要求整桶只有本网关一个写者:别的服务可以在同一桶的其它 key 上正常读写。
数据认证端点:`POST /v1/acquire`、`/v1/resolve`、`/v1/execute`、`/v1/reconcile`、`/v1/observe`,以及 `GET /v1/capabilities`。所有请求核验协议和 scope。`capabilities.automatic_grants` 必须为真,正式 stack 才接受自动授权能力;未接控制源、只读角色权限异常、协议不符或不可达均拒绝,无直写回退。
PG 行锁负责原子准入,不是远端存储 fence。intent 必须持久提交后才发送一次请求;连接死亡、租约过期不清除未知 intent。任何未终态 intent 均阻止 scope 换 epoch。重复 operation 只读回执或精确对账,不重发 PUT;暂时查不到版本仍 held。删除必须绑定已确认 create 的精确 VersionID,不删 latest、不生成删除标记。
同 key 竞争按 key 判定,不按桶判定:create 前已存在任何版本 → 回执 `rejected` 且不修改该对象;PUT 后除精确版本读回外还核对当前 latest,若并发写者已产生更新的当前版本,则只按精确 VersionID 撤回本次写入,保留对方版本并返回冲突;读不到当前版本时保持 held,不删除、不猜测。版本化存储的 PUT 不是原子 create-if-absent,因此“本 key 多数情况下归本计划”不是存储层保证。
不可变证据表拒绝 UPDATE/DELETE/TRUNCATE。Ready 核 fsync、synchronous_commit、full_page_writes、主库可写及必要表/触发器;管理员与迁移身份仍是可信边界,触发器不能抵御 DBA 的 DDL。
## 正式控制交付路径
@@ -54,13 +56,13 @@ SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`libr
- `OBJECT_GATEWAY_ARCHIVE_ROOT`:原持久计划所在归档绝对路径,部署只读挂载。
- `OBJECT_GATEWAY_TARGET_ID`:与正式 worker `LibraryTargetIdentity()` 完全相同的逻辑目标身份;不能用另一个环境的值。
- `OBJECT_GATEWAY_PROVIDER`、`OBJECT_GATEWAY_ENDPOINT`、`OBJECT_GATEWAY_BUCKET`、`OBJECT_GATEWAY_REGION`:精确存储身份。
- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:仅网关持有的对象写凭据。
- `OBJECT_GATEWAY_ACCESS_KEY`、`OBJECT_GATEWAY_SECRET_KEY`:网关持有的对象凭据,需在目标桶 PUT/GET/按版本 DELETE/列举版本。沿用现有 AK 即可,不要求另建独立只读或独占写凭据。
- `OBJECT_GATEWAY_DATA_TOKEN`、`OBJECT_GATEWAY_CONTROL_TOKEN`:不同且至少 32 字节;普通 worker 仅持有 data token。
- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:独立审核者的 Ed25519 签名隔离证据,绑定协议、scope、gateway ID、时间窗及 writer/policy/拒写/排空摘要。审核私钥不能交给 worker 或网关。
- `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`:**已退役**。旧部署残留的值被忽略,不参与启动、Ready、每次 Execute 或能力判断;不需要管理员签发整桶独占证明,也不会因过期文件拒绝发布。
秘密只经服务环境/私有文件注入,不进 argv、URL 或日志。所有调用端错误都使用固定原因码。
正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,部署必须使用独立只读凭据。
正式 worker 使用 `LIBRARY_OBJECT_GATEWAY_URL` 和 `LIBRARY_OBJECT_GATEWAY_TOKEN`;不再依赖预先生成的 grant 文件。`LIBRARY_OBJECT_GATEWAY_GRANT_DIRECTORY` 保留旧离线兼容用途,不是自动模式的授权来源。发布 stack 对所有对象 provider 强制网关;S3 构造仍用于只读捕获/预备份,可继续使用现有凭据,不再要求独立只读 OSS AK。
## 已关闭的本仓旁路
@@ -70,24 +72,34 @@ SELECT-only治理角色需要读取`library_jobs`、`library_operations`、`libr
- `librarystack` 不再为缺网关的 MinIO/S3 返回直写 writer。
- `libraryctl` capture 的 S3 构造与读取保留;未把读取当作写入口禁用。
这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;部署权限才负责防止外部旧进程直接调用存储。
这不等于已经撤销运行环境旧进程的凭据;源码变更尚未部署。`librarydrill` 等无 owned-attempt 的旧写型工具不能靠静态 grant 绕过自动模式,需补正式执行身份后才可用于写入。低层 S3 adapter 仍用于网关后端、读取及显式隔离夹具;共享桶不要求撤除其它写者,跨写者的同 key 竞争按冲突/held 处理。
## 实测与未完成边界
已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证。隔离审计 authority/故障注入仍是测试设施,不是生产权限证明。
已实跑:真实治理 PG(独立 SELECT-only 登录角色)、原 archive、数据 HTTP、业务 PG 与 MinIO 的自动授权/跨 epoch 链;未锚定计划在第一笔 PG 前拒绝,接管保持原发送身份且不增加 PUT。另有真实网关二进制的两次中断验证,以及共享桶下“无整桶证明启动 + 其它 key 并发写入 + 同 key 既有对象拒绝”的真实 PG/MinIO 用例。历史隔离审计 authority/故障注入是当时的测试设施,不是当前部署前置。
正式 worker 隔离进程证据:真实 Docker 入口闸门/队列、只读 worker 对象身份、独立治理读取角色、网关与业务 PG/ES/MinIO;首次 PG 后和对象提交后两次 SIGKILL,同一原 job/operation/plan 的三代 attempt 完成发布,原对象发送 epoch 与回执不变。隔离构建标签 `kg_isolated_drill` 仅把真实租约缩短至4秒,并拒绝非 loopback 一次性 r8 库;正常构建仍为10分钟。维护上游是无业务凭据的独立 HTTP 夹具,不是运行中的 WeKnora;签名证据绑定本次真实拒写/排空材料,不代表生产独占审核。
已补独立 `library.recover` 正式worker链、恢复中再次SIGKILL、完整before-image/CAS/精确版本读回,以及来源/目标/原job/计划/operation/任意队列身份拒绝。ES故障代理只转发真实ES并丢弃已提交响应,未伪造服务响应。
尚未完成:clean-finalization unknown的充分归属与自动收敛;独立运行环境只读对象凭据、ACL/网络和全部writer排空;网关真实OSS端到端;原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署独占分列,不把生产变更授权当成本机开发授权的前置。
尚未完成:clean-finalization unknown的充分归属与自动收敛;网关真实 OSS 端到端与真实部署验收(父执行);原D0/F11/F12与55项其余缺口。测试/隔离验收与真实部署分列。
维护隔离、独占审核与 grant 是独立前置。配置 true、健康 200、测试自签 authority 都不能代替已部署拒写/排空证据。目前未签发真实环境独占证明,未改生产权限或上游 WeKnora 源码/Schema。
整桶独占审核、全部 writer 排空、独立只读对象凭据已不再是发布前置;维护窗口内停目标写入容器并读回确认即可更新。网关按 key 拒绝冲突、精确版本回滚,但不承诺无关写者同时修改同一 key 时仍能自动完成——那种情况会明确冲突或 held,需要人工按回执处理。未改生产权限或上游 WeKnora 源码/Schema。
## 维护式更新(已采用)
目标测试 KB 的更新走维护窗口,不再要求证明整桶只有一个写者:
1. 停目标测试 WeKnora 的写入应用容器(只停该服务,不停机器人、适配器、共享 PG/ES 或其它 KB 的服务),并由容器状态/健康读回确认已停止。这是本轮文档化的运维步骤;代码侧没有新增停容器实现。
2. 用既有维护/预备份链记录本次目标 KB/对象范围:实例级维护窗口与写者停写证据由 `internal/libraryfreeze` + `internal/librarymaintenance` 采集,`libraryctl capture`(页面入口 `POST /api/v1/library/captures`)完成闸门排空→停写者→导出快照并保留 `post_stop_digest`;不把通用主机备份当作 KB 预备份的替代。
3. 用原 plan、原 WriteSet 摘要和限定对象清单走既有 `ProductionLibraryTarget.Apply`(经正式 worker owned attempt 与网关 grant)更新资源;网关沿用现有 AK,不换凭据、不签独占证明。
4. 启动原容器,健康检查与页面业务验收;失败走既有 `library.recover`/`RestoreDrill` 恢复链按原预备份回放并启动原服务,不无限留停机。
5. 无关服务与无关 key 全程不需要停;同 key 若仍有外部写者,按上节的冲突/held 处理:双方版本都保留,由人按证据处置,不自动合并。
部署需变更的组件:`object-gateway`(本候选镜像)、`worker`(同提交镜像),以及两者 env 中移除/留空已退役的 `OBJECT_GATEWAY_ID`、`OBJECT_GATEWAY_AUDIT_FILE`、`OBJECT_GATEWAY_AUDIT_PUBLIC_KEY`。`api`、`web` 无协议变更,可不同步。journal、治理 PG 只读 authority、archive 与 target identity 配置保持不变。
## 部署与回退(未执行)
未来测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准。每批先冻结主机、桶、全部角色/STS/预签名写入口、端口/网络规则、影响、维护窗口与回滚;当前没有执行这些外部变更。
测试主机 `120.76.217.51`、生产 `120.76.218.137` 各自独立批准;本候选未在任一主机执行停机、备份、更新或启动。r5 的已完成 OSS 测试授权不能重复使用。
先关新写准入→排空并对账旧请求→撤旧直写权限/切只读身份并实测拒写→独立审核→批准的新限定对象验收→父复核,才可切业务客户端。r5 的已完成 OSS 测试授权不能重复使用。
回退先关准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。权限/网络回退须另批。当前整模块 INCOMPLETE,禁止部署部分候选。
按“停目标写入容器→读回确认→备份目标 KB 范围→更新资源→启动→健康/页面验收”执行;失败按原备份恢复并启动原服务。回退先关新写准入并保留 journal;所有已发送请求有终态才可撤网关,unknown 继续 held。不得因网关故障自动恢复旧直写凭据。当前整模块仍未完成真实 OSS 端到端与 clean-finalization 收敛,禁止把本候选当作完整生产就绪。
+45
View File
@@ -0,0 +1,45 @@
# 发布管理流程与页面精简
## 目标与边界
现有整库发布页面同时呈现日常发布、维护诊断、恢复演练与历史快照,且封存操作位于页面底部,版本入口重复。此次优化聚焦 `ReleaseTargets` 的信息层级和操作位置,沿用现有 API、权限、授权绑定、维护所有者与恢复确认。
基线采用云测试站当前前端对应的工作树 `cbc6b98`;该提交的 web 与部署版本 `0b753e5` 相同。并行主干及其他工作树不合并、不覆盖。
## 操作者主流程
| 顺序 | 页面操作 | 后台行为 | 完成边界 |
| --- | --- | --- | --- |
| 1 | 选择对内或对外知识库 | 读取该范围 overview、快照、作业及维护窗口 | 目标身份与版本来自所选范围;读取失败不当作空库 |
| 2 | 封存测试版本 | POST `/api/v1/library/captures`,由队列及执行器捕获测试整库版本 | 投递不等于完成,以作业与登记快照为准;此步不发布生产 |
| 3 | 查看变更及发布条件 | 展开变更、备份与恢复验证;若缺基线或恢复证据,沿用对应管理员入口 | 逐条呈现服务端阻塞原因,不删除发布门槛 |
| 4 | 签发同步授权 | 管理员调用 `/api/v1/library/authorizations`,绑定目标与当前快照 | 有效期内仍需单独点击启动;不自动执行同步 |
| 5 | 启动同步 | 沿用现有同步请求与执行链:固定版本、生产预备份、同步、校验及收尾 | 只在接口条件允许时可执行;运行中主按钮改为查看任务 |
| 6 | 查看结果 | 自动刷新作业进度,终态按真实记录呈现 | 失败显示原始原因;维护占用不被其他作业成功覆盖 |
| 异常 | 从版本与快照选择恢复点 | 继续执行独立恢复授权、影响确认和恢复条件校验 | 恢复整套目标知识状态,不回退测试知识库 |
封存、签发授权、启动同步三个动作保持独立,不将其合并为一键生产写入。
## 页面保留规则
- 顶栏:唯一的「版本与快照」入口和刷新。
- 主工作区:实际目标身份、当前生产版本、候选测试版本、紧凑变更统计、当前主动作与一份阻塞原因。
- 已有封存时提供次级「重新封存」;运行时不提供重复封存、授权或同步入口。
- 「查看变更明细」「发布准备与恢复验证」「封存完整性」默认折叠;原有详情和验证回调继续存在。
- 目标维护正常时折叠,持有维护窗口时自动展开;仍按窗口持有作业展示恢复信息。
- 最近作业仅在有记录时展示,正常完成默认折叠,失败默认展开;运行中保留主进度,分项明细按需展开。
- 版本抽屉保留历史筛选、分页、校验记录、恢复授权和影响确认,移除重复的封存按钮。
- 发布管理页面移除旧文档级发布及历史来源关联区域,只展示整库发布流程。
## 验收清单
- [x] 前端生产构建通过。
- [x] 原发布、恢复、维护所有者和刷新/切库回归通过。
- [x] 同一挂载下依次切换封存、授权、同步,点击只调用对应动作。
- [x] 折叠与展开、打开历史不触发业务写入。
- [x] 运行时主操作只查看任务,不调用封存、授权或同步。
- [x] 正常维护折叠、持有时展开、释放后折叠;切库重置明细展开状态。
- [x] 无作业不画空进度;失败原因默认可见。
- [x] 只读角色和读取失败时禁止主动作。
浏览器验收使用本地候选构建,GET/HEAD 通过已有 SSH 通道读取云测试 API;代理拒绝所有写请求。界面验收与真实封存、生产同步及恢复演练分开记录;本任务不执行这些业务写入。完整仓库门禁和云端部署结论以实际运行结果为准,不用上述前端检查替代。
+63 -18
View File
@@ -3,6 +3,7 @@ package appconfig
import (
"errors"
"fmt"
"net/url"
"path/filepath"
"strconv"
"strings"
@@ -129,6 +130,11 @@ type Config struct {
// 入口闸门:关入口与排空在它身上做(被代理服务自己不排空)。
LibraryTargetIngressService string
LibraryTargetIngressDrainFile string
// 入口形态:gate(默认)或 none。none 只给整栈没有入口闸门的测试环境用,
// 必须同时给 LibraryTargetNoIngressAck,且证据等级降一档并如实记录。
LibraryTargetIngressMode string
LibraryTargetNoIngressAck string
LibraryTargetHealthURL string
// 后台静默检查:目标队列 + 目标库(HTTP 排空不等于后台任务排空)。
LibraryTargetRedisAddr string
LibraryTargetRedisPassword string
@@ -247,19 +253,23 @@ func Load(getenv func(string) string) (Config, error) {
LibraryTargetIngressURL: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_URL")),
LibraryTargetIngressService: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_SERVICE")),
LibraryTargetIngressDrainFile: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_DRAIN_FILE")),
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
LibraryEmbeddingDimension: embeddingDimension,
LibraryCapacityBudgetBytes: capacityBudget,
LibraryRetentionVersions: retentionVersions,
LibraryRetentionDays: retentionDays,
LibraryExecutorStatusMaxAge: 2 * time.Minute,
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
LibraryTargetIngressMode: strings.TrimSpace(getenv("LIBRARY_TARGET_INGRESS_MODE")),
// 确认串不 Trim:必须逐字符相等,多一个空格都算没确认。
LibraryTargetNoIngressAck: getenv("LIBRARY_NO_INGRESS_ACK"),
LibraryTargetHealthURL: strings.TrimSpace(getenv("LIBRARY_TARGET_HEALTH_URL")),
LibraryTargetRedisAddr: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_ADDR")),
LibraryTargetRedisPassword: strings.TrimSpace(getenv("LIBRARY_TARGET_REDIS_PASSWORD")),
LibraryTargetRedisDB: valueOrDefaultInt(getenv("LIBRARY_TARGET_REDIS_DB"), 0),
LibraryTargetJournalRoot: strings.TrimSpace(getenv("LIBRARY_TARGET_JOURNAL_ROOT")),
LibraryEmbeddingModel: valueOrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_MODEL")), "text-embedding-v4"),
LibraryEmbeddingDimension: embeddingDimension,
LibraryCapacityBudgetBytes: capacityBudget,
LibraryRetentionVersions: retentionVersions,
LibraryRetentionDays: retentionDays,
LibraryExecutorStatusMaxAge: 2 * time.Minute,
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
VersionHistoryHTTPTimeout: 15 * time.Second,
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
}
if config.DatabaseURL == "" {
return Config{}, errors.New("DATABASE_URL is required")
@@ -387,9 +397,35 @@ func Load(getenv func(string) string) (Config, error) {
if config.LibraryAgentSocket != "" && !filepath.IsAbs(config.LibraryAgentSocket) {
return Config{}, errors.New("LIBRARY_AGENT_SOCKET 必须是绝对路径(unix socket 由主机侧 agent 持有)")
}
// 入口形态:缺省 gate,行为与之前完全一致。none 只给整栈没有入口闸门的
// 测试环境用,必须显式确认;确认串逐字符相等,多一个空格都算没确认。
if config.LibraryTargetIngressMode == "" {
config.LibraryTargetIngressMode = "gate"
}
switch config.LibraryTargetIngressMode {
case "gate", "none":
default:
return Config{}, fmt.Errorf("LIBRARY_TARGET_INGRESS_MODE 无效(%q):只能是 gate 或 none",
config.LibraryTargetIngressMode)
}
noGate := config.LibraryTargetIngressMode == "none"
if noGate && config.LibraryTargetNoIngressAck != "test-only" {
return Config{}, errors.New("no-gate 维护必须显式确认:LIBRARY_NO_INGRESS_ACK 必须逐字符等于 test-only,拒绝启动")
}
if !noGate && config.LibraryTargetNoIngressAck != "" {
return Config{}, errors.New("LIBRARY_NO_INGRESS_ACK 只在 LIBRARY_TARGET_INGRESS_MODE=none 下有效")
}
if config.LibraryTargetHealthURL != "" {
parsed, err := url.Parse(config.LibraryTargetHealthURL)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") ||
parsed.Host == "" || parsed.User != nil {
return Config{}, errors.New("LIBRARY_TARGET_HEALTH_URL 必须是 http(s) 地址且不带凭据")
}
}
// 目标维护要么完整配置,要么完全不配;半配置会让窗口"看起来存在"却挡不住目标。
targetSet := config.LibraryTargetInstance != "" || config.LibraryTargetProject != "" ||
len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != ""
len(config.LibraryTargetWriters) > 0 || config.LibraryTargetIngressURL != "" ||
noGate || config.LibraryTargetHealthURL != ""
if targetSet {
missing := make([]string, 0, 4)
if config.LibraryTargetInstance == "" {
@@ -401,16 +437,21 @@ func Load(getenv func(string) string) (Config, error) {
if len(config.LibraryTargetWriters) == 0 {
missing = append(missing, "LIBRARY_TARGET_WRITERS")
}
if config.LibraryTargetIngressURL == "" {
if noGate {
// 没有闸门可声明:健康探针是唯一能证明"目标回来了"的必需项。
if config.LibraryTargetHealthURL == "" {
missing = append(missing, "LIBRARY_TARGET_HEALTH_URL")
}
} else if config.LibraryTargetIngressURL == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
}
if config.LibraryTargetJournalRoot == "" {
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
}
if config.LibraryTargetIngressService == "" {
if !noGate && config.LibraryTargetIngressService == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
}
if config.LibraryTargetIngressDrainFile == "" {
if !noGate && config.LibraryTargetIngressDrainFile == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_DRAIN_FILE")
}
if config.LibraryTargetRedisAddr == "" {
@@ -419,13 +460,17 @@ func Load(getenv func(string) string) (Config, error) {
if len(missing) > 0 {
return Config{}, fmt.Errorf("目标维护配置不完整:缺少 %s", strings.Join(missing, "、"))
}
if noGate && (config.LibraryTargetIngressURL != "" || config.LibraryTargetIngressService != "" ||
config.LibraryTargetIngressDrainFile != "") {
return Config{}, errors.New("no-gate 维护不得同时配置入口地址/闸门服务/排空文件:要么有闸门,要么明确没有")
}
if !filepath.IsAbs(config.LibraryTargetJournalRoot) {
return Config{}, errors.New("LIBRARY_TARGET_JOURNAL_ROOT 必须是绝对路径")
}
if !filepath.IsAbs(config.LibraryTargetDockerSocket) {
return Config{}, errors.New("LIBRARY_TARGET_DOCKER_SOCKET 必须是绝对路径")
}
if !filepath.IsAbs(config.LibraryTargetIngressDrainFile) {
if !noGate && !filepath.IsAbs(config.LibraryTargetIngressDrainFile) {
return Config{}, errors.New("LIBRARY_TARGET_INGRESS_DRAIN_FILE 必须是绝对路径")
}
if len(config.LibraryTargetNonWriters) == 0 {
+31 -2
View File
@@ -16,9 +16,8 @@ func developmentNotes(changelog, version, sha string) string {
return ""
}
lines := strings.Split(changelog, "\n")
prefix := "## 开发快照 snapshot/v" + version + " - "
for i, line := range lines {
if strings.HasPrefix(line, prefix) {
if developmentHeadingMatches(line, version) {
end := len(lines)
for j := i + 1; j < len(lines); j++ {
if strings.HasPrefix(lines[j], "## ") {
@@ -39,3 +38,33 @@ func developmentNotes(changelog, version, sha string) string {
}
return ""
}
// developmentHeadingMatches 接受两种真实标题:
// - 旧格式:## 开发快照 snapshot/v0.1.1 - 2026-10-18
// - 开发快照:## 开发快照 0.1.351(索引预检使用目标映射 ID)
//
// 版本号后必须是字符串结束或分隔符,避免 0.1.35 命中 0.1.351;
// 只读取到下一个二级标题,不跨版本吞正文。
func developmentHeadingMatches(line, version string) bool {
prefixes := []string{
"## 开发快照 snapshot/v" + version,
"## 开发快照 " + version,
}
for _, prefix := range prefixes {
if !strings.HasPrefix(line, prefix) {
continue
}
rest := line[len(prefix):]
if rest == "" {
return true
}
if strings.HasPrefix(rest, "—") || strings.HasPrefix(rest, "(") {
return true
}
switch rest[0] {
case ' ', '\t', '-', '(':
return true
}
}
return false
}
+5 -2
View File
@@ -36,8 +36,11 @@ type ServiceHealth struct {
ObservedAt time.Time `json:"observed_at"`
LastSuccessAt *time.Time `json:"last_success_at"`
ConsecutiveFailures int `json:"consecutive_failures"`
Configured bool `json:"configured"`
Applicable bool `json:"applicable"`
// ProbeTarget names the object being probed (instance + short binding id),
// never credentials or full UUIDs, so a red light can be attributed.
ProbeTarget string `json:"probe_target"`
Configured bool `json:"configured"`
Applicable bool `json:"applicable"`
}
type KnowledgeBaseProgress struct {
+1
View File
@@ -116,6 +116,7 @@ type CatalogRouteRequest struct {
// fulfillment path needs to materialize and fetch it later.
type CatalogRouteFile struct {
NodeID string
ParentNodeID string
Name string
RelativePath string
SizeBytes *int64
+5
View File
@@ -148,6 +148,11 @@ func classifyRole(method, path string) string {
if strings.HasPrefix(path, "/api/v1/backup-schedule") && method != http.MethodGet {
return roleAdmin
}
// 核对封存结果会把一个 pending 业务作业修成 succeeded;只允许管理员,
// 且 handler 仍要求 completed queue、精确版本和归档复核。
if strings.HasPrefix(path, "/api/v1/library/jobs/") && strings.HasSuffix(path, "/reconcile-capture") {
return roleAdmin
}
// 版本记录的同步会拉起一次对远端仓库的抓取(消耗网络与数据库写入),
// 与"谁能改生产绑定"同级:读任何角色可看,同步只能管理员。
if strings.HasPrefix(path, "/api/v1/version-history") && method != http.MethodGet {
+3
View File
@@ -98,6 +98,8 @@ type backupScheduleView struct {
HostCronLines []string `json:"host_cron_lines"`
HostCronService string `json:"host_cron_service"`
HostScriptPresent bool `json:"host_script_present"`
// HostCheckedAt 是本次真实主机探测时间;没有探测(只读库)时为空。
HostCheckedAt string `json:"host_checked_at,omitempty"`
LastRunStamp string `json:"last_run_stamp"`
LastRunCreatedAt string `json:"last_run_created_at"`
@@ -296,6 +298,7 @@ func (config Config) backupSchedulePayload(ctx context.Context, probeHost bool)
if !probeHost {
return view, nil
}
view.HostCheckedAt = formatTime(config.Now().UTC())
show, err := config.BackupHost.Show(ctx)
if err != nil {
view.HostReachable = false
@@ -0,0 +1,246 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/librarysnapshot"
)
// libraryCaptureReconciler is deliberately narrow: it repairs one business
// seal job only after the completed capture queue, the successful export stage,
// the exact test-sealed version and the archived bytes all agree. It never
// captures, freezes writers, creates snapshots, writes source/target content or
// changes historical failure evidence.
type libraryCaptureReconciler interface {
LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error)
LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error)
LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error)
EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error)
ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error)
ReconcileMisclassifiedLibraryCapture(ctx context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, auditID, actor, reason string, evidence map[string]any, now time.Time) (bool, error)
}
const (
legacyOrphanError = "队列中已无对应作业,业务作业未收到结果"
legacyOrphanRecovery = "封存作业由 agent 恢复来源;确认来源 healthy 后可重发"
)
type libraryCaptureQueueReader interface {
QueueJob(ctx context.Context, id string) (jobs.Job, bool, error)
}
func libraryCaptureReconcile(w http.ResponseWriter, r *http.Request, config Config) {
if r.Method != http.MethodPost {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
store, ok := config.Store.(libraryCaptureReconciler)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "封存作业核对存储不可用"})
return
}
queueStore, ok := config.Store.(libraryCaptureQueueReader)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "队列精确读取不可用"})
return
}
jobID := strings.TrimSpace(r.PathValue("id"))
if jobID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "job id required"})
return
}
job, err := store.LibraryJob(r.Context(), jobID)
if err != nil {
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"})
return
}
if job.Kind != governance.LibraryJobSeal {
conflict(w, "只有封存作业可以核对封存结果")
return
}
systemMisclassified := job.State == governance.LibraryJobFailed && job.Stage == "" &&
job.Error == legacyOrphanError && job.Recovery == legacyOrphanRecovery && job.SnapshotID == ""
if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning &&
job.State != governance.LibraryJobSucceeded && !systemMisclassified {
conflict(w, "作业是真实失败/取消终态,不能改写成成功")
return
}
if job.QueueJobID == "" {
conflict(w, "作业没有关联队列号,不能证明封存完成")
return
}
captureJob := strings.TrimPrefix(job.ID, "libseal-")
if captureJob == "" || captureJob == job.ID {
conflict(w, "作业号不是封存作业身份")
return
}
queue, found, err := queueStore.QueueJob(r.Context(), job.QueueJobID)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture queue"})
return
}
if !found {
conflict(w, "队列作业不存在,不能证明封存完成")
return
}
if queue.Type != libraryCaptureJobType || queue.State != jobs.StateCompleted {
conflict(w, "队列作业不是 completed 的 library.capture")
return
}
var payload struct {
Scope string `json:"scope"`
CaptureJob string `json:"capture_job"`
}
if err := json.Unmarshal(queue.Payload, &payload); err != nil ||
payload.Scope != job.Scope || payload.CaptureJob != captureJob ||
queue.IdempotencyKey != "library.capture:"+captureJob {
conflict(w, "队列作业的 scope/capture_job/幂等键与业务作业不一致")
return
}
stageState, _, err := store.LibraryCaptureExportEvidence(r.Context(), job.ID)
if err != nil || stageState != "succeeded" {
conflict(w, "导出阶段没有成功证据,不能修复终态")
return
}
version, found, err := store.LibraryTestSealedVersionForJob(r.Context(), job.Scope, job.ID)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read exact test-sealed version"})
return
}
if !found || version.Kind != governance.LibraryVersionTestSealed ||
version.Scope != job.Scope || version.SourceJobID != job.ID || version.SnapshotID == "" {
conflict(w, "没有与作业/scope 精确绑定的测试封存版本")
return
}
source := configuredLibrarySource(config, job.Scope)
sourceID, err := source.ID()
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "来源身份配置不完整,无法核对封存来源"})
return
}
evidenceSource, _ := version.Evidence["source_id"].(string)
evidenceCapture, _ := version.Evidence["capture_job"].(string)
if evidenceSource != sourceID || evidenceCapture != captureJob {
conflict(w, "版本来源或 capture_job 与当前作业不一致")
return
}
if config.LibraryArchiveRoot == "" {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "未接线归档根,无法复核归档完整性"})
return
}
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "归档不可读,不能确认封存完整"})
return
}
defer archive.Close()
manifest, err := archive.Load(version.SnapshotID)
if err != nil {
conflict(w, "归档字节复核失败,不能修复作业")
return
}
if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID ||
manifest.KnowledgeBaseID != source.KnowledgeBaseID {
conflict(w, "归档清单来源身份与当前来源不一致")
return
}
if job.SnapshotID != "" && job.SnapshotID != version.SnapshotID {
conflict(w, "作业已有不同快照,不能覆盖")
return
}
if job.State == governance.LibraryJobSucceeded {
if job.SnapshotID != version.SnapshotID {
conflict(w, "作业已成功但快照与精确版本不一致")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"repaired": false, "already_succeeded": true, "job_id": job.ID,
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
"version_id": version.ID,
})
return
}
actor := ""
if identity, ok := sessionFrom(r.Context()); ok {
actor = identity.Username
}
now := time.Now().UTC()
digest, err := governance.LibraryRequestDigest(job.Scope, governance.LibraryJobRecover, map[string]any{
"kind": "capture_reconcile", "job_id": job.ID, "queue_job_id": queue.ID,
"snapshot_id": version.SnapshotID, "capture_job": captureJob, "stage": "export",
})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build reconcile audit digest"})
return
}
if systemMisclassified {
auditID := "librepair-" + digest[:16]
updated, repairErr := store.ReconcileMisclassifiedLibraryCapture(r.Context(), job.ID, job.Scope,
job.QueueJobID, version.SnapshotID, job.Stage, legacyOrphanError, legacyOrphanRecovery,
job.FinishedAt, auditID, actor, "completed capture queue + export succeeded + exact version + archive verified; legacy orphan misclassification", map[string]any{
"original_state": job.State, "original_error": job.Error, "original_recovery": job.Recovery,
"original_finished_at": job.FinishedAt, "queue_job_id": queue.ID,
"snapshot_id": version.SnapshotID, "version_id": version.ID, "archive_verified": true,
}, now)
if repairErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot persist misclassification repair"})
return
}
if !updated {
conflict(w, "原误判行状态/错误/完成时间已变化,拒绝覆盖")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"repaired": true, "already_succeeded": false, "misclassification_repaired": true,
"job_id": job.ID, "snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
"stage": "export", "version_id": version.ID, "audit_repair_id": auditID,
})
return
}
opID := "libop-capture-reconcile-" + digest[:16]
op, _, err := store.EnsureLibraryOperation(r.Context(), governance.LibraryOperation{
ID: opID, Scope: job.Scope, Kind: governance.LibraryJobRecover,
TargetSnapshotID: version.SnapshotID, RequestDigest: digest,
OperationKey: "capture-reconcile:" + job.ID, Actor: actor, CreatedAt: now,
})
if errors.Is(err, governance.ErrLibraryOperationConflict) {
conflict(w, "同一核对键对应了不同证据,拒绝修复")
return
}
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot record reconcile audit"})
return
}
updated, err := store.ReconcileLibraryCaptureTerminal(r.Context(), job.ID, job.Scope, job.QueueJobID, version.SnapshotID, now)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]any{
"error": "cannot persist reconciled job terminal", "audit_operation_id": op.ID,
})
return
}
if !updated {
conflict(w, "作业状态/身份在核对期间变化,拒绝覆盖")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"repaired": true, "already_succeeded": false, "job_id": job.ID,
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
"stage": "export", "version_id": version.ID, "audit_operation_id": op.ID,
})
}
func conflict(w http.ResponseWriter, reason string) {
writeJSON(w, http.StatusConflict, map[string]any{"available": false, "repaired": false, "reason": reason})
}
@@ -0,0 +1,361 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/librarysnapshot"
)
func (f *fakeLibraryStore) QueueJob(_ context.Context, id string) (jobs.Job, bool, error) {
if f.queue == nil || f.queue.ID != id {
return jobs.Job{}, false, nil
}
return *f.queue, true, nil
}
func (f *fakeLibraryStore) LibraryCaptureExportEvidence(_ context.Context, _ string) (string, string, error) {
return f.stageState, "", f.stageErr
}
func (f *fakeLibraryStore) LibraryJobStage(_ context.Context, _, stage string) (string, string, error) {
if f.stageErr != nil {
return "", "", f.stageErr
}
if stage != "export" {
return "", "", errors.New("unexpected stage")
}
return f.stageState, "", nil
}
func (f *fakeLibraryStore) LibraryTestSealedVersionForJob(_ context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) {
if f.versionErr != nil {
return governance.LibraryVersion{}, false, f.versionErr
}
if f.sealedVersion == nil || f.sealedVersion.Scope != scope || f.sealedVersion.SourceJobID != jobID {
return governance.LibraryVersion{}, false, nil
}
return *f.sealedVersion, true, nil
}
func reconcileFixture(t *testing.T) (*fakeLibraryStore, Config, governance.LibraryJob, []byte) {
t.Helper()
root := libraryFixtureRoot(t)
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
archive, err := librarysnapshot.Open(root, 256*1024*1024)
if err != nil {
t.Fatal(err)
}
manifest, err := archive.Load(snapshotID)
archive.Close()
if err != nil {
t.Fatal(err)
}
config := Config{LibraryArchiveRoot: root,
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
source := configuredLibrarySource(config, "internal")
sourceID, err := source.ID()
if err != nil {
t.Fatal(err)
}
job := governance.LibraryJob{ID: "libseal-cap-1", Scope: "internal", Kind: governance.LibraryJobSeal,
State: governance.LibraryJobPending, QueueJobID: "libcap-1"}
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "cap-1"})
store := &fakeLibraryStore{
jobs: []governance.LibraryJob{job},
stageState: "succeeded",
queue: &jobs.Job{ID: "libcap-1", Type: libraryCaptureJobType, State: jobs.StateCompleted,
Payload: payload, IdempotencyKey: "library.capture:cap-1"},
sealedVersion: &governance.LibraryVersion{ID: "libver-1", Scope: "internal",
Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshotID, SourceJobID: job.ID,
Evidence: map[string]any{"source_id": sourceID, "capture_job": "cap-1"}},
}
config.Store = store
return store, config, job, payload
}
func (f *fakeLibraryStore) ReconcileLibraryCaptureTerminal(_ context.Context, jobID, scope, queueJobID, snapshotID string, _ time.Time) (bool, error) {
if f.reconcileDenied {
return false, nil
}
for index := range f.jobs {
if f.jobs[index].ID != jobID || f.jobs[index].Scope != scope || f.jobs[index].Kind != governance.LibraryJobSeal ||
f.jobs[index].QueueJobID != queueJobID || (f.jobs[index].State != governance.LibraryJobPending && f.jobs[index].State != governance.LibraryJobRunning) ||
(f.jobs[index].SnapshotID != "" && f.jobs[index].SnapshotID != snapshotID) {
return false, nil
}
f.jobs[index].State = governance.LibraryJobSucceeded
f.jobs[index].SnapshotID = snapshotID
f.lastState = governance.LibraryJobSucceeded
return true, nil
}
return false, nil
}
func (f *fakeLibraryStore) ReconcileMisclassifiedLibraryCapture(_ context.Context, jobID, scope, queueJobID, snapshotID, expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time, _ string, _ string, _ string, _ map[string]any, _ time.Time) (bool, error) {
if f.reconcileDenied {
return false, nil
}
for index := range f.jobs {
j := &f.jobs[index]
if j.ID != jobID || j.Scope != scope || j.Kind != governance.LibraryJobSeal || j.QueueJobID != queueJobID ||
j.State != governance.LibraryJobFailed || j.Stage != expectedStage || j.Error != expectedError ||
j.Recovery != expectedRecovery || j.SnapshotID != "" || (j.FinishedAt == nil) != (expectedFinished == nil) ||
(j.FinishedAt != nil && expectedFinished != nil && !j.FinishedAt.Equal(*expectedFinished)) {
return false, nil
}
j.State = governance.LibraryJobSucceeded
j.SnapshotID = snapshotID
j.Stage = "export"
f.lastState = governance.LibraryJobSucceeded
return true, nil
}
return false, nil
}
var _ libraryCaptureReconciler = (*fakeLibraryStore)(nil)
func runReconcile(t *testing.T, config Config, jobID string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+jobID+"/reconcile-capture", nil)
req.SetPathValue("id", jobID)
rec := httptest.NewRecorder()
libraryCaptureReconcile(rec, req, config)
return rec
}
func TestLibraryCaptureReconcileRepairsExactCompletedCapture(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["repaired"] != true || body["snapshot_id"] == "" || body["audit_operation_id"] == "" {
t.Fatalf("body=%v", body)
}
if store.lastState != governance.LibraryJobSucceeded {
t.Fatalf("advanced state=%s", store.lastState)
}
if len(store.operations) != 1 {
t.Fatalf("audit operations=%v", store.operations)
}
}
func TestLibraryCaptureReconcileAlreadySucceededIsReadOnly(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.State = governance.LibraryJobSucceeded
job.SnapshotID = store.sealedVersion.SnapshotID
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body["already_succeeded"] != true || body["repaired"] != false || store.lastState != "" {
t.Fatalf("body=%v advanced=%q", body, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsQueueNotCompleted(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue.State = jobs.StateRunning
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRejectsStageNotSucceeded(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.stageState = "failed"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongVersionSource(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Evidence["source_id"] = "other-source"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongCaptureJob(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Evidence["capture_job"] = "other-capture"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsBadArchive(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.SnapshotID = "missing-snapshot"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRejectsFailedJob(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.State = governance.LibraryJobFailed
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileIsIdempotent(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
first := runReconcile(t, config, job.ID)
if first.Code != http.StatusOK {
t.Fatalf("first code=%d body=%s", first.Code, first.Body.String())
}
second := runReconcile(t, config, job.ID)
if second.Code != http.StatusOK {
t.Fatalf("second code=%d body=%s", second.Code, second.Body.String())
}
var body map[string]any
_ = json.Unmarshal(second.Body.Bytes(), &body)
if body["already_succeeded"] != true || len(store.operations) != 1 {
t.Fatalf("body=%v ops=%v", body, store.operations)
}
}
func TestLibraryCaptureReconcileRejectsMissingQueue(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue = nil
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsQueueScope(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue.Payload, _ = json.Marshal(map[string]string{"scope": "external", "capture_job": "cap-1"})
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsMissingVersion(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion = nil
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongScopeVersion(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Scope = "external"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsDifferentExistingSnapshot(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.SnapshotID = "other-snapshot"
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileConditionalWriteRejectsConcurrentState(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.reconcileDenied = true
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRepairsExactLegacyMisclassification(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
finished := time.Now().UTC()
job.State = governance.LibraryJobFailed
job.Stage = ""
job.Error = legacyOrphanError
job.Recovery = legacyOrphanRecovery
job.FinishedAt = &finished
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body["misclassification_repaired"] != true || store.lastState != governance.LibraryJobSucceeded {
t.Fatalf("body=%v advanced=%q", body, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsOtherFailedError(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
finished := time.Now().UTC()
job.State = governance.LibraryJobFailed
job.Stage = ""
job.Error = "capture export failed"
job.Recovery = legacyOrphanRecovery
job.FinishedAt = &finished
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRejectsRealFailureAndCancel(t *testing.T) {
for _, state := range []governance.LibraryJobState{governance.LibraryJobFailed, governance.LibraryJobCancelled} {
store, config, job, _ := reconcileFixture(t)
job.State = state
job.Error = "real failure"
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("state=%s code=%d advanced=%q", state, rec.Code, store.lastState)
}
}
}
func TestLibraryCaptureReconcileMisclassificationCASRejectsChange(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
finished := time.Now().UTC()
job.State = governance.LibraryJobFailed
job.Stage = ""
job.Error = legacyOrphanError
job.Recovery = legacyOrphanRecovery
job.FinishedAt = &finished
store.jobs[0] = job
store.reconcileDenied = true
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
@@ -0,0 +1,204 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/librarysnapshot"
postgresstore "knowledge-governance/internal/platform/postgres"
)
// Vertical PostgreSQL path: the real worker startup reconciliation must leave
// a pending seal with a completed capture queue intact, then the actual HTTP
// handler must verify archive/version/stage and repair it. This is not a fake
// store or a direct helper test.
func verticalReconcileFixture(t *testing.T) (*postgresstore.Store, Config, string, *pgxpool.Pool) {
t.Helper()
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatal("isolated database required")
}
cfg.MaxConns = 1
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
ctx := context.Background()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pool.Close)
if _, err := pool.Exec(ctx, `
CREATE TEMP TABLE library_jobs(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
state varchar(16) NOT NULL, stage varchar(32) NOT NULL DEFAULT '',
idempotency_key varchar(255) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL DEFAULT '',
queue_job_id varchar(64) NOT NULL DEFAULT '', snapshot_id varchar(64) NOT NULL DEFAULT '',
target_snapshot_id varchar(64) NOT NULL DEFAULT '', actor varchar(128) NOT NULL DEFAULT '',
error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '',
operation_id varchar(64) NOT NULL DEFAULT '', attempt_epoch integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL, finished_at timestamptz,
target_id text NOT NULL DEFAULT '');
CREATE TEMP TABLE library_job_stages(
job_id varchar(64) NOT NULL, stage varchar(32) NOT NULL, state varchar(16) NOT NULL,
total bigint, completed bigint, bytes_total bigint, bytes_done bigint,
detail text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, PRIMARY KEY(job_id,stage));
CREATE TEMP TABLE library_versions(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(24) NOT NULL,
snapshot_id varchar(64) NOT NULL DEFAULT '', version_label varchar(64) NOT NULL DEFAULT '',
source_job_id varchar(64) NOT NULL DEFAULT '', operation_id varchar(64) NOT NULL DEFAULT '',
attempt_epoch integer NOT NULL DEFAULT 0, evidence jsonb NOT NULL DEFAULT '{}'::jsonb,
created_by varchar(128) NOT NULL DEFAULT '', created_at timestamptz NOT NULL, superseded_at timestamptz);
CREATE TEMP TABLE library_job_repairs(
id varchar(64) PRIMARY KEY, job_id varchar(64) NOT NULL, scope varchar(16) NOT NULL,
kind varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL, snapshot_id varchar(64) NOT NULL,
original_state varchar(16) NOT NULL, original_stage varchar(32) NOT NULL DEFAULT '',
original_error text NOT NULL DEFAULT '', original_recovery varchar(255) NOT NULL DEFAULT '',
original_finished_at timestamptz, reason varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
evidence jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL);
CREATE TEMP TABLE library_operations(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
target_snapshot_id varchar(64) NOT NULL DEFAULT '', request_digest varchar(64) NOT NULL,
operation_key varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
created_at timestamptz NOT NULL, target_id text NOT NULL DEFAULT '',
first_backup_snapshot_id varchar(64), first_backup_bytes bigint, first_backup_at timestamptz,
writeset_digest varchar(64), writeset_rows bigint, target_fingerprint varchar(128), anchors_at timestamptz);
CREATE UNIQUE INDEX library_operations_key_test ON library_operations(scope,kind,operation_key);
CREATE TEMP TABLE jobs(
id varchar(64) PRIMARY KEY, type varchar(64) NOT NULL, payload jsonb NOT NULL,
state varchar(16) NOT NULL, priority integer NOT NULL DEFAULT 0, available_at timestamptz NOT NULL,
lease_owner varchar(128), lease_until timestamptz, attempt integer NOT NULL DEFAULT 0,
max_attempts integer NOT NULL DEFAULT 1, last_error text, idempotency_key varchar(255) NOT NULL,
created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL);`); err != nil {
t.Fatal(err)
}
root := libraryFixtureRoot(t)
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
archive, err := librarysnapshot.Open(root, 256*1024*1024)
if err != nil {
t.Fatal(err)
}
manifest, err := archive.Load(snapshotID)
archive.Close()
if err != nil {
t.Fatal(err)
}
config := Config{LibraryArchiveRoot: root,
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
source := configuredLibrarySource(config, "internal")
sourceID, err := source.ID()
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical"})
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at)
VALUES('q-vertical','library.capture',$1,'completed',$2,'library.capture:vertical',$2,$2)`, payload, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at)
VALUES('ver-vertical','internal','test_sealed',$1,'libseal-vertical',$2,$3)`, snapshotID,
map[string]any{"source_id": sourceID, "capture_job": "vertical"}, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at)
VALUES('libseal-vertical','export','succeeded','已封存快照', $1)`, now); err != nil {
t.Fatal(err)
}
store := postgresstore.NewStore(pool)
config.Store = store
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,created_at,updated_at)
VALUES('libseal-vertical','internal','seal','pending','k','d','q-vertical',$1,$1)`, now); err != nil {
t.Fatal(err)
}
return store, config, snapshotID, pool
}
func TestStartupReconcileThenHandlerRepairsPendingCapture(t *testing.T) {
store, config, _, _ := verticalReconcileFixture(t)
ctx := context.Background()
now := time.Now().UTC()
if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 {
t.Fatalf("startup reconcile n=%d err=%v", n, err)
}
job, err := store.LibraryJob(ctx, "libseal-vertical")
if err != nil || job.State != governance.LibraryJobPending {
t.Fatalf("startup changed job: %+v err=%v", job, err)
}
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical/reconcile-capture", nil)
req.SetPathValue("id", "libseal-vertical")
rec := httptest.NewRecorder()
libraryCaptureReconcile(rec, req, config)
if rec.Code != http.StatusOK {
t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String())
}
job, err = store.LibraryJob(ctx, "libseal-vertical")
if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID == "" {
t.Fatalf("handler did not repair: %+v err=%v", job, err)
}
}
func TestStartupReconcilePreservesFailedCapturesForExactReconcile(t *testing.T) {
store, config, snapshotID, pool := verticalReconcileFixture(t)
ctx := context.Background()
now := time.Now().UTC()
source := configuredLibrarySource(config, "internal")
sourceID, err := source.ID()
if err != nil {
t.Fatal(err)
}
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "vertical-failed"})
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,available_at,idempotency_key,created_at,updated_at)
VALUES('q-failed','library.capture',$1,'completed',$2,'library.capture:vertical-failed',$2,$2)`, payload, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,evidence,created_at)
VALUES('ver-failed','internal','test_sealed',$1,'libseal-vertical-failed',$2,$3)`,
snapshotID, map[string]any{"source_id": sourceID, "capture_job": "vertical-failed"}, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_job_stages(job_id,stage,state,detail,updated_at)
VALUES('libseal-vertical-failed','export','succeeded','已封存快照', $1)`, now); err != nil {
t.Fatal(err)
}
finished := now.Truncate(time.Microsecond)
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,idempotency_key,request_digest,queue_job_id,error,recovery,created_at,updated_at,finished_at)
VALUES('libseal-vertical-failed','internal','seal','failed','kf','df','q-failed',$1,$2,$3,$3,$3)`,
"队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", finished); err != nil {
t.Fatal(err)
}
if n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"}); err != nil || n != 0 {
t.Fatalf("startup reconcile n=%d err=%v", n, err)
}
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/libseal-vertical-failed/reconcile-capture", nil)
req.SetPathValue("id", "libseal-vertical-failed")
rec := httptest.NewRecorder()
libraryCaptureReconcile(rec, req, config)
if rec.Code != http.StatusOK {
t.Fatalf("handler code=%d body=%s", rec.Code, rec.Body.String())
}
job, err := store.LibraryJob(ctx, "libseal-vertical-failed")
if err != nil || job.State != governance.LibraryJobSucceeded || job.SnapshotID != snapshotID {
t.Fatalf("failed misclassification not repaired: %+v err=%v", job, err)
}
var originalState, originalError string
if err := pool.QueryRow(ctx, `SELECT original_state, original_error FROM library_job_repairs WHERE job_id='libseal-vertical-failed'`).
Scan(&originalState, &originalError); err != nil {
t.Fatal(err)
}
if originalState != "failed" || originalError == "" {
t.Fatalf("audit missing original: state=%q error=%q", originalState, originalError)
}
}
+34 -6
View File
@@ -342,7 +342,11 @@ type libraryOverview struct {
CaptureAvailable bool `json:"capture_available"`
CaptureReason string `json:"capture_reason,omitempty"`
Executor libraryExecutorView `json:"executor"`
Now time.Time `json:"now"`
// 实际目标身份:页面不能只显示"weknora-test"或旧文档级绑定名称。
TargetInstance string `json:"target_instance,omitempty"`
TargetProject string `json:"target_project,omitempty"`
TargetKnowledgeBaseID string `json:"target_knowledge_base_id,omitempty"`
Now time.Time `json:"now"`
}
// libraryVersionRef 只回答"这个快照被登记成哪一类版本、由哪个作业登记"。
@@ -595,6 +599,11 @@ func testSealedOf(versions []governance.LibraryVersion, byID map[string]libraryS
// 它刻意只说配置:能停写入者/关入口/证明排空的真实能力在 worker 侧(docker socket、
// 闸门、排空文件),API 若声称"能力可用"就是拿配置字符串冒充执行证据。
func libraryMaintenanceCapability(config Config) map[string]any {
mode := strings.TrimSpace(config.LibraryTargetIngressMode)
if mode == "" {
mode = "gate"
}
noGate := mode == "none"
missing := make([]string, 0, 6)
if config.LibraryTargetInstance == "" {
missing = append(missing, "LIBRARY_TARGET_INSTANCE")
@@ -605,11 +614,18 @@ func libraryMaintenanceCapability(config Config) map[string]any {
if len(config.LibraryTargetWriters) == 0 {
missing = append(missing, "LIBRARY_TARGET_WRITERS")
}
if config.LibraryTargetIngressURL == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
}
if config.LibraryTargetIngressService == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
if noGate {
// 没有闸门:页面必须如实说"无闸门(测试模式)",不能显示"打开"。
if config.LibraryTargetHealthURL == "" {
missing = append(missing, "LIBRARY_TARGET_HEALTH_URL")
}
} else {
if config.LibraryTargetIngressURL == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_URL")
}
if config.LibraryTargetIngressService == "" {
missing = append(missing, "LIBRARY_TARGET_INGRESS_SERVICE")
}
}
if config.LibraryTargetJournalRoot == "" {
missing = append(missing, "LIBRARY_TARGET_JOURNAL_ROOT")
@@ -617,12 +633,18 @@ func libraryMaintenanceCapability(config Config) map[string]any {
if config.LibraryTargetDockerSocket == "" {
missing = append(missing, "LIBRARY_TARGET_DOCKER_SOCKET")
}
ingressState := "闸门"
if noGate {
ingressState = "无闸门(测试模式)"
}
return map[string]any{
"configured": len(missing) == 0,
"missing": missing,
"instance": config.LibraryTargetInstance,
"project": config.LibraryTargetProject,
"writers": config.LibraryTargetWriters,
"ingress_mode": mode,
"ingress_state": ingressState,
"ingress_service": config.LibraryTargetIngressService,
"note": "配置齐全只说明治理侧接线完整;停写入者、关入口与排空由 worker 在作业内校验并执行",
}
@@ -686,10 +708,16 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
}
now := time.Now().UTC()
overview := libraryOverview{Scope: scope, Jobs: []governance.LibraryJob{}, Now: now,
TargetInstance: config.LibraryTargetInstance, TargetProject: config.LibraryTargetProject,
Gate: libraryGateView{Reasons: []string{}},
Diff: libraryDiffView{State: "unknown", Reason: "生产与测试的文档级差异读取未接线", Added: []any{}, Updated: []any{}, Removed: []any{}}}
// 可发起封存 = worker 真实探测到执行器可用且指向本实例;原因逐条给全。
overview.CaptureAvailable, overview.CaptureReason, overview.Executor = libraryExecutorAvailability(r.Context(), config)
if scope == "internal" {
overview.TargetKnowledgeBaseID = config.LibraryProductionInternalKB
} else {
overview.TargetKnowledgeBaseID = config.LibraryProductionExternalKB
}
// 测试封存来自归档 + 版本登记:归档里**不止**测试封存——生产预备份与目标基线
// 快照同样带 scope,如果只按"这个 scope 最新一份"挑,页面就会把目标自己的内容
+17 -1
View File
@@ -11,6 +11,7 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
)
// 生产闸口与整库状态契约的针对性测试:不做数据库集成,只验证
@@ -37,6 +38,13 @@ type fakeLibraryStore struct {
resumeOK bool
resumeErr error
resumeCalls []string
// capture reconciliation fixtures
queue *jobs.Job
stageState string
stageErr error
sealedVersion *governance.LibraryVersion
versionErr error
reconcileDenied bool
}
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
@@ -127,8 +135,16 @@ func (f *fakeLibraryStore) UpdateLibraryStage(_ context.Context, _, _, _ string,
return nil
}
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState, _, _, _, _, _ string, _ time.Time) error {
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, _, _, _, snapshotID, _ string, _ time.Time) error {
f.lastState = state
for index := range f.jobs {
if f.jobs[index].ID == jobID {
f.jobs[index].State = state
if snapshotID != "" {
f.jobs[index].SnapshotID = snapshotID
}
}
}
return nil
}
@@ -266,3 +266,25 @@ func TestLibraryReadPathsRejectTamperedManifest(t *testing.T) {
t.Fatalf("storage must fail closed: status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
// F11: the HTTP projection must include binding and Wiki log counts; the
// previous projection silently omitted them and the UI turned absence into 0.
func TestLibrarySnapshotTotalsIncludeBindingsAndWikiLogs(t *testing.T) {
view := librarySnapshotViewOfNoUsage("snap-totals", librarysnapshot.Manifest{
Scope: "internal", KnowledgeBaseID: "kb", TenantID: 10000,
Parts: []librarysnapshot.Part{
{Kind: "database", Name: "knowledges", Count: 4},
{Kind: "database", Name: "chunks", Count: 38},
{Kind: "database", Name: "resources", Count: 21},
{Kind: "database", Name: "resource_bindings", Count: 4},
{Kind: "wiki", Name: "wiki_pages", Count: 31},
{Kind: "wiki", Name: "wiki_folders", Count: 21},
{Kind: "wiki", Name: "wiki_log_entries", Count: 11},
},
})
for key, want := range map[string]int64{"documents": 4, "chunks": 38, "resources": 21, "bindings": 4, "wiki_pages": 31, "wiki_folders": 21, "wiki_log_entries": 11} {
if view.Totals[key] != want {
t.Fatalf("totals[%s]=%d want=%d (%v)", key, view.Totals[key], want, view.Totals)
}
}
}
+4
View File
@@ -261,10 +261,14 @@ func librarySnapshotViewOfNoUsage(id string, manifest librarysnapshot.Manifest)
}
case "resources":
snapshot.Totals["resources"] = part.Count
case "resource_bindings":
snapshot.Totals["bindings"] = part.Count
case "wiki_pages":
snapshot.Totals["wiki_pages"] = part.Count
case "wiki_folders":
snapshot.Totals["wiki_folders"] = part.Count
case "wiki_log_entries":
snapshot.Totals["wiki_log_entries"] = part.Count
}
}
sort.Slice(snapshot.Parts, func(i, j int) bool {
+42 -10
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"net/http"
"strings"
"time"
"knowledge-governance/internal/governance"
@@ -23,16 +24,19 @@ type libraryVerifyRequest struct {
// libraryVerificationView 是页面需要的全部事实:当前目标是谁、最近一次验证结果、
// 证据是否对当前目标成立、以及同步闸口能不能据此放行。
type libraryVerificationView struct {
Scope string `json:"scope"`
Target libraryVerificationTarget `json:"target"`
Verified bool `json:"verified"`
Reason string `json:"reason"`
Latest *governance.LibraryRestoreVerification `json:"latest,omitempty"`
History []governance.LibraryRestoreVerification `json:"history"`
Running bool `json:"running"`
JobID string `json:"job_id,omitempty"`
State string `json:"state,omitempty"`
Stage string `json:"stage,omitempty"`
Scope string `json:"scope"`
Target libraryVerificationTarget `json:"target"`
Verified bool `json:"verified"`
Reason string `json:"reason"`
Latest *governance.LibraryRestoreVerification `json:"latest,omitempty"`
// SnapshotLatest 只在请求显式带 snapshot_id 时返回:快照报告不能拿 scope
// 最近一条代替。
SnapshotLatest *governance.LibraryRestoreVerification `json:"snapshot_latest,omitempty"`
History []governance.LibraryRestoreVerification `json:"history"`
Running bool `json:"running"`
JobID string `json:"job_id,omitempty"`
State string `json:"state,omitempty"`
Stage string `json:"stage,omitempty"`
}
type libraryVerificationTarget struct {
@@ -177,11 +181,39 @@ func libraryVerifications(w http.ResponseWriter, r *http.Request, config Config)
if history, err := store.LibraryRestoreVerifications(r.Context(), scope, 10); err == nil {
view.History = history
}
if snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id")); snapshotID != "" {
if exact, ok := config.Store.(interface {
LibraryRestoreVerificationForSnapshot(context.Context, string, string) (governance.LibraryRestoreVerification, bool, error)
}); ok {
item, found, exactErr := exact.LibraryRestoreVerificationForSnapshot(r.Context(), scope, snapshotID)
if exactErr != nil {
view.Reason = "读取该快照的恢复验证记录失败"
writeJSON(w, http.StatusServiceUnavailable, view)
return
}
if found {
view.SnapshotLatest = &item
}
}
}
view.Verified, view.Reason = governance.LibraryVerificationSatisfied(latest, scope)
if !found {
view.Verified = false
view.Reason = "还没有对当前目标做过恢复验证:点「跑一次恢复验证」(真实备份 → canary → 恢复 → 复核)"
}
if snapshotID := strings.TrimSpace(r.URL.Query().Get("snapshot_id")); snapshotID != "" {
// 显式按快照查询时,verified 只回答该快照;不能让 scope 最新通过记录
// 把另一个未演练的快照染绿。
view.Verified = false
if view.SnapshotLatest == nil {
view.Reason = "该快照没有真实恢复验证记录(未验证;不是读取失败)"
} else if view.SnapshotLatest.Status == governance.LibraryVerificationPassed {
view.Verified = true
view.Reason = ""
} else {
view.Reason = "该快照最近一次恢复验证未通过"
}
}
// 在飞作业必须从真实业务行读出来:旧实现只构造 running 字段却从不赋值,
// 页面因此在验收里看不到"已接受/正在执行",按钮也不会进入执行态(审核 B4)。
if jobs, ok := config.Store.(interface {
+32
View File
@@ -34,6 +34,15 @@ func (s *verificationStore) LatestLibraryRestoreVerification(_ context.Context,
return governance.LibraryRestoreVerification{}, false, nil
}
func (s *verificationStore) LibraryRestoreVerificationForSnapshot(_ context.Context, scope, snapshotID string) (governance.LibraryRestoreVerification, bool, error) {
for _, item := range s.verifications {
if item.Scope == scope && item.SnapshotID == snapshotID {
return item, true, nil
}
}
return governance.LibraryRestoreVerification{}, false, nil
}
func (s *verificationStore) LibraryRestoreVerifications(_ context.Context, scope string, limit int) ([]governance.LibraryRestoreVerification, error) {
items := make([]governance.LibraryRestoreVerification, 0, len(s.verifications))
for _, item := range s.verifications {
@@ -131,6 +140,29 @@ func TestLibraryVerificationsWithoutEvidenceIsNotVerified(t *testing.T) {
}
}
// F03: the selected snapshot must resolve its own evidence, never the scope's
// newest passed record.
func TestLibraryVerificationsExactSnapshotDoesNotBorrowLatest(t *testing.T) {
store := &verificationStore{verifications: []governance.LibraryRestoreVerification{
{ID: "verify-new", Scope: "internal", Status: governance.LibraryVerificationPassed,
SnapshotID: "snap-new", JobID: "job-new", FinishedAt: time.Now().UTC()},
{ID: "verify-old", Scope: "internal", Status: governance.LibraryVerificationFailed,
SnapshotID: "snap-old", JobID: "job-old", Failure: "old restore mismatch",
FinishedAt: time.Now().UTC().Add(-time.Hour)},
}}
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/verifications?scope=internal&snapshot_id=snap-old", nil)
libraryVerifications(recorder, request, Config{Store: store})
body := decodeBody(t, recorder)
exact, ok := body["snapshot_latest"].(map[string]any)
if !ok || exact["snapshot_id"] != "snap-old" || exact["status"] != "failed" {
t.Fatalf("snapshot_latest=%v body=%v", body["snapshot_latest"], body)
}
if body["verified"] != false {
t.Fatalf("old failed snapshot must not inherit latest passed: %v", body["verified"])
}
}
func TestLibraryVerificationsWithPassedEvidenceIsVerified(t *testing.T) {
store := &verificationStore{verifications: []governance.LibraryRestoreVerification{{
ID: "libverify-internal-job1", Scope: "internal", Status: governance.LibraryVerificationPassed,
+4
View File
@@ -97,6 +97,10 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"})
return
}
// 目标同名不罕见(两侧都叫“对内知识库”):把当前生效绑定随页返回,
// 前端才能在同一口径下标注“当前绑定/历史”,而不是拿本页条目反推全局。
internal, external := config.effectiveRoutingTargets(r.Context())
page.Bindings = postgresstore.MonitorBindings{Internal: internal, External: external}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, 200, map[string]any{"data": page})
}
+37
View File
@@ -2,6 +2,7 @@ package httpapi
import (
"context"
"encoding/json"
postgresstore "knowledge-governance/internal/platform/postgres"
"net/http/httptest"
"testing"
@@ -51,3 +52,39 @@ func TestMonitorTasksRoute(t *testing.T) {
t.Fatalf("viewer removal %d", removal.Code)
}
}
// F15:筛选里的“当前绑定”必须来自持久化绑定(与业务同一真源),不是 env 旧值,
// 也不能让前端拿本页数据猜全局。
func TestMonitorTasksReportsEffectiveTargetBindings(t *testing.T) {
store := &monitorTasksTestStore{}
handler, err := NewHandler(Config{
Store: store,
InternalRoutingKnowledgeBaseID: "env-old-internal",
ExternalRoutingKnowledgeBaseID: "env-old-external",
RoutingBindings: &bindingStoreFake{internal: "current-internal", external: "current-external"},
})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("GET", "/api/v1/monitor/tasks?limit=20", nil)
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleViewer}))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != 200 {
t.Fatalf("status %d: %s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data struct {
Bindings struct {
Internal string `json:"internal"`
External string `json:"external"`
} `json:"bindings"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.Bindings.Internal != "current-internal" || payload.Data.Bindings.External != "current-external" {
t.Fatalf("bindings = %#v, want the persisted current bindings", payload.Data.Bindings)
}
}
+93
View File
@@ -7,6 +7,7 @@ import (
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qawemail"
"net/http"
"strconv"
"time"
)
@@ -20,6 +21,98 @@ type weeklyMailStore interface {
TestSend(context.Context, string) (string, error)
SaveDashboardImage(context.Context, string, []byte) error
SendDue(context.Context, time.Time) (qawemail.DueResult, error)
PreviewSend(context.Context, string, int64, string, time.Time) (qawemail.SendPreview, error)
SendManual(context.Context, string, int64, string, string, time.Time) (qawemail.ManualResult, error)
}
// weeklyMailSendError names the rule that refused a manual resend. Anything SMTP-related is
// reported by the handler itself, so an unmet precondition never looks like a mail failure.
func weeklyMailSendError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, qawemail.ErrNotCurrent):
writeJSON(w, http.StatusConflict, map[string]string{"error": "该周周报未确认,或确认后正文/版本已变化;请先确认当前版本再补发"})
case errors.Is(err, qawemail.ErrFutureWeek):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "不能补发未来周"})
case errors.Is(err, qawemail.ErrSlotPending):
writeJSON(w, http.StatusConflict, map[string]string{"error": "本周尚未到达设定的发送时点,暂不能补发"})
case errors.Is(err, qawemail.ErrNotConfigured):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "未配置邮件服务器、发件人或收件人,无法补发"})
case errors.Is(err, qawemail.ErrSendInFlight):
writeJSON(w, http.StatusConflict, map[string]string{"error": "该周该版本有一次发送结果未知(记录停在发送中),为避免重复投递未重发;请先核对已发出的邮件"})
case errors.Is(err, qawemail.ErrDeliveryUnknown):
writeJSON(w, http.StatusConflict, map[string]string{"error": "SMTP 已提交但未收到最终确认,投递结果未知;为避免重复已停止重发,请先核对已发出的邮件"})
case errors.Is(err, qawemail.ErrNoPassword):
writeJSON(w, http.StatusConflict, map[string]string{"error": "SMTP 授权码缺失或无法解密,无法补发"})
case errors.Is(err, qawemail.ErrInvalid):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "补发参数无效:需要精确的周、已确认版本与正文 hash"})
default:
weeklyMailError(w, err)
}
}
// qaWeeklyMailSendPreview lets the confirmation dialog show the exact week, revision and
// distribution this send would use — the same settings the send path reads.
func qaWeeklyMailSendPreview(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) {
return
}
store, ok := c.QAWeeklyMail.(weeklyMailStore)
if !ok {
weeklyMailError(w, qawemail.ErrUnavailable)
return
}
query := r.URL.Query()
revision, err := strconv.ParseInt(query.Get("revision"), 10, 64)
if err != nil {
weeklyMailSendError(w, qawemail.ErrInvalid)
return
}
preview, err := store.PreviewSend(r.Context(), r.PathValue("week"), revision, query.Get("body_sha256"), time.Now())
if err != nil {
weeklyMailSendError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": preview})
}
// qaWeeklyMailSend is the formal resend: admin only, bound to the live confirmation, and the same
// render/claim path as the automatic slot. It is not a test send and never targets the review box.
func qaWeeklyMailSend(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-mail") {
return
}
identity, ok := sessionFrom(r.Context())
if !ok || identity.Role != "admin" {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "仅管理员可正式补发周报"})
return
}
store, found := c.QAWeeklyMail.(weeklyMailStore)
if !found {
weeklyMailError(w, qawemail.ErrUnavailable)
return
}
var request struct {
Revision int64 `json:"revision"`
BodySHA256 string `json:"body_sha256"`
}
if decodeQualityJSON(w, r, &request) != nil {
weeklyMailError(w, qawemail.ErrInvalid)
return
}
result, err := store.SendManual(r.Context(), r.PathValue("week"), request.Revision, request.BodySHA256, identity.Username, time.Now())
if err != nil {
weeklyMailSendError(w, err)
return
}
if result.Status == "failed" {
reason := result.Reason
if len(reason) > 300 {
reason = reason[:300]
}
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "正式补发未送达:" + reason})
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": result})
}
func weeklyMailError(w http.ResponseWriter, err error) {
@@ -0,0 +1,91 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/qawemail"
)
// 页面 reload / “完成读真实发送记录”走的就是这个 handler。用真实 PG 的非空历史证明
// 产品读回路径返回 200 且带 message_id,而不是 503——“历史行存在就整个列表不可用”
// 正是上一版 Sends() 的确定性回归。
func TestWeeklyMailSendsHandlerReadsRealHistoryWithMessageID(t *testing.T) {
dsn := os.Getenv("KG_WEEKLY_MAIL_TEST_DSN")
if dsn == "" {
t.Skip("显式一次性周报邮件数据库未提供(KG_WEEKLY_MAIL_TEST_DSN):跳过不等于通过")
}
if !strings.Contains(dsn, "/kg_weekly_mail_test_") || strings.Contains(dsn, "/governance?") {
t.Fatal("拒绝非一次性周报测试库")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal("测试库连接参数无效(详情省略)")
}
defer pool.Close()
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
store := qawemail.NewStore(pool, "fixture-http-history", os.Getenv("KG_WEEKLY_MAIL_TEST_KEY"), nil)
for _, statement := range []string{
`DELETE FROM qa_weekly_email_sends WHERE tenant_key=$1`,
} {
if _, err := pool.Exec(ctx, statement, "fixture-http-history"); err != nil {
t.Fatal(err)
}
}
if _, err := pool.Exec(ctx, `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,message_id,last_error,created_at,updated_at)
VALUES($1,'2026-W45',16,$2,'sent',1,'<real@example.com>','',now(),now()),
($1,'2026-W44',7,$2,'failed',2,'','smtp RCPT 被拒: 550',now(),now() - interval '1 hour')`,
"fixture-http-history", strings.Repeat("a", 64)); err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/sends?week=2026-W45", nil)
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
recorder := httptest.NewRecorder()
qaWeeklyMailSends(recorder, request, Config{QAWeeklyMail: store})
if recorder.Code != http.StatusOK {
t.Fatalf("非空历史必须 200,status=%d body=%s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data struct {
Sends []qawemail.Send `json:"sends"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.Sends) != 1 || payload.Data.Sends[0].MessageID != "<real@example.com>" || payload.Data.Sends[0].Status != "sent" {
t.Fatalf("发送记录必须带回真实 message_id:%+v", payload.Data.Sends)
}
// 全量历史(不带 week)同样必须可读,且 failed 行不伪造 message_id。
all := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/sends", nil)
all = all.WithContext(context.WithValue(all.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
allRecorder := httptest.NewRecorder()
qaWeeklyMailSends(allRecorder, all, Config{QAWeeklyMail: store})
if allRecorder.Code != http.StatusOK {
t.Fatalf("全量历史必须 200,status=%d body=%s", allRecorder.Code, allRecorder.Body.String())
}
if err := json.Unmarshal(allRecorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if len(payload.Data.Sends) != 2 {
t.Fatalf("应返回 2 条历史,got %+v", payload.Data.Sends)
}
for _, item := range payload.Data.Sends {
if item.Status == "failed" && item.MessageID != "" {
t.Fatalf("failed 行不得有 message_id:%+v", item)
}
}
}
+186
View File
@@ -0,0 +1,186 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/qawemail"
)
type fakeWeeklyMailStore struct {
preview qawemail.SendPreview
previewErr error
result qawemail.ManualResult
sendErr error
calls int
lastWeek string
lastRev int64
lastHash string
lastActor string
}
func (f *fakeWeeklyMailStore) ReadSettings(context.Context) (qawemail.Settings, error) {
return qawemail.Settings{}, nil
}
func (f *fakeWeeklyMailStore) SaveSettings(context.Context, string, qawemail.SettingsInput) (qawemail.Settings, error) {
return qawemail.Settings{}, nil
}
func (f *fakeWeeklyMailStore) Confirm(context.Context, string, string) (qawemail.Confirmation, error) {
return qawemail.Confirmation{}, nil
}
func (f *fakeWeeklyMailStore) Unconfirm(context.Context, string) error { return nil }
func (f *fakeWeeklyMailStore) ReadConfirmation(context.Context, string) (*qawemail.Confirmation, error) {
return nil, nil
}
func (f *fakeWeeklyMailStore) Sends(context.Context, string) ([]qawemail.Send, error) {
return nil, nil
}
func (f *fakeWeeklyMailStore) TestSend(context.Context, string) (string, error) { return "", nil }
func (f *fakeWeeklyMailStore) SaveDashboardImage(context.Context, string, []byte) error {
return nil
}
func (f *fakeWeeklyMailStore) SendDue(context.Context, time.Time) (qawemail.DueResult, error) {
return qawemail.DueResult{}, nil
}
func (f *fakeWeeklyMailStore) PreviewSend(_ context.Context, week string, revision int64, hash string, _ time.Time) (qawemail.SendPreview, error) {
f.lastWeek, f.lastRev, f.lastHash = week, revision, hash
if f.previewErr != nil {
return qawemail.SendPreview{}, f.previewErr
}
out := f.preview
out.Week, out.Revision, out.BodySHA256 = week, revision, hash
return out, nil
}
func (f *fakeWeeklyMailStore) SendManual(_ context.Context, week string, revision int64, hash, actor string, _ time.Time) (qawemail.ManualResult, error) {
f.calls++
f.lastWeek, f.lastRev, f.lastHash, f.lastActor = week, revision, hash, actor
if f.sendErr != nil {
return qawemail.ManualResult{}, f.sendErr
}
out := f.result
out.Week, out.Revision = week, revision
return out, nil
}
func weeklyMailSendRequest(t *testing.T, role, body string, withIntent bool) *http.Request {
t.Helper()
request := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/master/weekly-mail/send/2026-W45", strings.NewReader(body))
request.SetPathValue("week", "2026-W45")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role}))
if withIntent {
request.Header.Set("X-Governance-Action", "qa-weekly-mail")
}
return request
}
// 正式补发是管理员动作:普通角色与缺少同源意图都必须被挡在 SMTP 之前。
func TestWeeklyMailFormalSendRequiresAdminAndIntent(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "sent", MessageID: "<m@example.com>"}}
config := Config{QAWeeklyMail: store}
body := `{"revision":16,"body_sha256":"` + strings.Repeat("a", 64) + `"}`
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, "engineer", body, true), config)
if recorder.Code != http.StatusForbidden {
t.Fatalf("非管理员必须 403,status=%d body=%s", recorder.Code, recorder.Body.String())
}
recorder = httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, body, false), config)
if recorder.Code != http.StatusForbidden {
t.Fatalf("缺少同源操作意图必须 403,status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.calls != 0 {
t.Fatalf("被拒请求不得调用发送:calls=%d", store.calls)
}
}
// 成功补发必须把 week/版本/hash/操作人原样交给 store,并回传真实 message_id 与收件人数。
func TestWeeklyMailFormalSendPassesExactRevisionAndReturnsReceipt(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "sent", MessageID: "<real@example.com>", Recipients: 119, Cc: 8}}
config := Config{QAWeeklyMail: store}
hash := strings.Repeat("b", 64)
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+hash+`"}`, true), config)
if recorder.Code != http.StatusOK {
t.Fatalf("管理员补发应成功,status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.lastWeek != "2026-W45" || store.lastRev != 16 || store.lastHash != hash || store.lastActor != "tester" {
t.Fatalf("补发参数没有精确传递:week=%q rev=%d hash=%q actor=%q", store.lastWeek, store.lastRev, store.lastHash, store.lastActor)
}
var payload struct {
Data qawemail.ManualResult `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.MessageID != "<real@example.com>" || payload.Data.Recipients != 119 || payload.Data.Cc != 8 {
t.Fatalf("响应必须带回真实发送凭据与正式收件人数:%+v", payload.Data)
}
}
// 前置条件不满足必须给出具体原因,而不是冒充 SMTP 失败。
func TestWeeklyMailFormalSendExplainsRefusalsInsteadOfSMTPFailure(t *testing.T) {
cases := []struct {
name string
err error
status int
contains string
}{
{"future", qawemail.ErrFutureWeek, http.StatusBadRequest, "未来周"},
{"slot", qawemail.ErrSlotPending, http.StatusConflict, "尚未到达设定的发送时点"},
{"stale", qawemail.ErrNotCurrent, http.StatusConflict, "正文/版本已变化"},
{"inflight", qawemail.ErrSendInFlight, http.StatusConflict, "结果未知"},
{"nopassword", qawemail.ErrNoPassword, http.StatusConflict, "授权码"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
store := &fakeWeeklyMailStore{sendErr: tc.err}
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+strings.Repeat("c", 64)+`"}`, true), Config{QAWeeklyMail: store})
if recorder.Code != tc.status || !strings.Contains(recorder.Body.String(), tc.contains) {
t.Fatalf("%s 应 %d 且说明原因 %q,status=%d body=%s", tc.name, tc.status, tc.contains, recorder.Code, recorder.Body.String())
}
})
}
}
// SMTP 真实失败:必须 502 且带上真实原因,绝不能回“已发送”。
func TestWeeklyMailFormalSendReportsDeliveryFailure(t *testing.T) {
store := &fakeWeeklyMailStore{result: qawemail.ManualResult{Status: "failed", Reason: "发送失败:smtp 登录失败: 535"}}
recorder := httptest.NewRecorder()
qaWeeklyMailSend(recorder, weeklyMailSendRequest(t, roleAdmin, `{"revision":16,"body_sha256":"`+strings.Repeat("d", 64)+`"}`, true), Config{QAWeeklyMail: store})
if recorder.Code != http.StatusBadGateway || !strings.Contains(recorder.Body.String(), "535") {
t.Fatalf("未送达必须 502 并带真实原因,status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
// 补发前预览必须给出真实 week/版本/收件人数,用于确认框;预览本身不投递。
func TestWeeklyMailSendPreviewShowsExactDistribution(t *testing.T) {
store := &fakeWeeklyMailStore{preview: qawemail.SendPreview{Status: "ready", Recipients: 119, Cc: 8}}
hash := strings.Repeat("e", 64)
request := httptest.NewRequest(http.MethodGet, "/api/v1/qa-ops/master/weekly-mail/send/2026-W45?revision=16&body_sha256="+hash, nil)
request.SetPathValue("week", "2026-W45")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
recorder := httptest.NewRecorder()
qaWeeklyMailSendPreview(recorder, request, Config{QAWeeklyMail: store})
if recorder.Code != http.StatusOK {
t.Fatalf("预览应成功,status=%d body=%s", recorder.Code, recorder.Body.String())
}
var payload struct {
Data qawemail.SendPreview `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.Recipients != 119 || payload.Data.Cc != 8 || payload.Data.Revision != 16 || payload.Data.Status != "ready" {
t.Fatalf("预览必须给出正式收件人数与版本:%+v", payload.Data)
}
if store.calls != 0 {
t.Fatal("预览不得触发发送")
}
}
+12 -2
View File
@@ -159,8 +159,12 @@ type Config struct {
LibraryTargetWriters []string
LibraryTargetIngressURL string
LibraryTargetIngressService string
LibraryTargetDockerSocket string
LibraryTargetJournalRoot string
// 入口形态与健康探针只用于如实展示"有没有闸门":none 显示"无闸门(测试模式)",
// 不能把没有闸门的测试栈说成"打开"。
LibraryTargetIngressMode string
LibraryTargetHealthURL string
LibraryTargetDockerSocket string
LibraryTargetJournalRoot string
// LibrarySourceInstance 是死信解除记录的来源实例名(封存源),留空回落到目标实例名。
LibrarySourceInstance string
// LibraryAgentSocket 是主机侧封存 agent 的 unix socket;留空即页面不能发起封存。
@@ -282,6 +286,8 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("DELETE /api/v1/qa-ops/master/weekly-mail/confirmations/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailConfirm(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/sends", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSends(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/test", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailTest(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-mail/send/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSendPreview(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/send/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailSend(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-mail/confirmations/{week}/image", func(w http.ResponseWriter, r *http.Request) { qaWeeklyMailImage(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/field-options", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldOptions(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/records/{id}/fields", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldPatch(w, r, config) })
@@ -559,6 +565,10 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("POST /api/v1/library/jobs/{id}/resume", func(w http.ResponseWriter, r *http.Request) {
libraryJobResume(w, r, config)
})
// 封存完成但终态回写失败时,只按已完成队列+精确版本+归档复核修复该作业。
mux.HandleFunc("POST /api/v1/library/jobs/{id}/reconcile-capture", func(w http.ResponseWriter, r *http.Request) {
libraryCaptureReconcile(w, r, config)
})
// 生产同步唯一入口:闸口未齐不建作业,返回缺项而不是假 Accepted。
mux.HandleFunc("POST /api/v1/library/syncs", func(w http.ResponseWriter, r *http.Request) {
librarySyncEnqueue(w, r, config)
+20 -4
View File
@@ -26,6 +26,8 @@ import (
"sync"
"syscall"
"time"
"knowledge-governance/internal/librarydsn"
)
// Config is fixed at start-up by the operator (systemd unit / CLI flags). It is
@@ -47,7 +49,10 @@ type Config struct {
Project string
Writers string
NonWriters string
MaxDuration time.Duration
// AllowedPeerUIDs 是除"与 agent 同 uid"之外额外放行的连接方 uid。
// 默认空:只允许同 uid。容器里固定以某个 uid 运行时,由部署参数显式列出。
AllowedPeerUIDs []uint32
MaxDuration time.Duration
// StopGrace bounds the graceful stop of one operation: SIGTERM first (the
// child aborts the maintenance window and restores writers), then SIGKILL
// only after this grace period. It must exceed the child's own restore budget.
@@ -212,7 +217,11 @@ func (a *Agent) Serve(ctx context.Context) error {
func (a *Agent) handle(ctx context.Context, conn net.Conn) {
defer conn.Close()
if err := peerAllowed(conn); err != nil {
allowed := make(map[uint32]bool, len(a.config.AllowedPeerUIDs))
for _, uid := range a.config.AllowedPeerUIDs {
allowed[uid] = true
}
if err := peerAllowed(conn, allowed); err != nil {
_ = json.NewEncoder(conn).Encode(response{OK: false, Error: err.Error()})
return
}
@@ -429,15 +438,22 @@ func (a *Agent) health() response {
}
// identity 被日志与健康应答共用一份,避免两处描述漂移。
//
// 数据库只报来源模式(container|external|file),不报地址:agent 的应答会被治理侧
// 存档,DSN 里带口令,一旦写进身份就再也收不回来了。
func (c Config) identity() map[string]any {
identity := map[string]any{
"project": c.Project,
"archive_root": c.ArchiveRoot,
"journal_root": c.JournalRoot,
"source_app": c.SourceApp,
"source_pg": c.SourcePG,
"source_es": c.SourceES,
"writers": c.Writers,
// source_pg 仍是容器名(不是地址、不是凭据),保留它以让既有健康页/事后核对
// 读得到同一份字段;数据库**来源**由下面两个模式字段表达,外部模式下它为空。
"source_pg": c.SourcePG,
"source_db": librarydsn.SourceMode(c.SourcePG),
"governance_db": librarydsn.GovernanceMode(c.GovernancePG),
"writers": c.Writers,
}
if c.SourceS3Endpoint != "" {
identity["source_s3_endpoint"] = c.SourceS3Endpoint
+4 -2
View File
@@ -11,7 +11,7 @@ import (
// agent. File mode 0600 already limits connect() to that uid; the credential
// check makes the boundary explicit and fails closed if the socket is ever
// reached another way (bind mount into a container with a different uid).
func peerAllowed(conn net.Conn) error {
func peerAllowed(conn net.Conn, allowed map[uint32]bool) error {
unixConn, ok := conn.(*net.UnixConn)
if !ok {
return errors.New("unsupported transport")
@@ -30,7 +30,9 @@ func peerAllowed(conn net.Conn) error {
if controlErr != nil || credential == nil {
return errors.New("peer credentials unavailable")
}
if credential.Uid != uint32(os.Geteuid()) {
// 默认只允许与 agent 同 uid 的连接;显式声明过的 uid(例如容器里的
// 固定运行用户)才放行。放行清单来自部署参数,不是"任何人"。
if credential.Uid != uint32(os.Geteuid()) && !allowed[credential.Uid] {
return errors.New("peer uid is not allowed")
}
return nil
+1 -1
View File
@@ -9,6 +9,6 @@ import (
// The capture host is Linux (Docker + unix socket); other platforms refuse
// rather than guess at peer credentials.
func peerAllowed(net.Conn) error {
func peerAllowed(net.Conn, map[uint32]bool) error {
return errors.New("library agent requires Linux peer credentials")
}
+140
View File
@@ -0,0 +1,140 @@
// Package librarydsn 决定整库采集链路里两个 DSN 究竟从哪来。
//
// 为什么要有它:容器模式下 DSN 是"源库容器的地址 + 源应用容器的 env"拼出来的;
// RDS 型 0.9.0 栈没有源库容器(库是托管实例),治理库同样只在外部。旧拼法在那种
// 栈上不是权限不够,而是地址解析方式错了——库根本没有容器地址可查。把"用哪种
// 来源"收敛成一处,libraryctl 与 libraryagent 共用同一份判定,日志/describe 只报
// 模式(container|external|file),永远不报地址与凭据。
package librarydsn
import (
"errors"
"fmt"
"net"
"net/url"
"strings"
"knowledge-governance/internal/dobotaiops"
)
const (
// SourceContainer:-source-pg 给了容器名,地址从容器网络解析(0.7.1 栈)。
SourceContainer = "container"
// SourceExternal:-source-pg 为空,直连源应用容器 env 里声明的托管库(RDS)。
SourceExternal = "external"
// GovernanceContainer:-governance-pg 给了容器名,用 docker exec psql 读。
GovernanceContainer = "container"
// GovernanceFile:-governance-pg 为空,DSN 来自 0600 文件(LIBRARY_GOVERNANCE_DSN_FILE)。
GovernanceFile = "file"
)
// allowedSSLModes 是允许的 sslmode 集合。
//
// 只收这四个:prefer/allow 会在服务端不支持时**静默降级成明文**,托管实例上那等于
// "以为加密了其实没有"——这种"看起来配好了"的失败模式比直接报错更难发现。
var allowedSSLModes = map[string]bool{
"disable": true, // 仅显式测试:本机回环或明确无 TLS 的隔离库
"require": true,
"verify-ca": true,
"verify-full": true,
}
// SourceMode 把 -source-pg 的取值翻译成来源模式。空值 = 外部(RDS)。
func SourceMode(sourcePG string) string {
if strings.TrimSpace(sourcePG) == "" {
return SourceExternal
}
return SourceContainer
}
// GovernanceMode 把 -governance-pg 的取值翻译成来源模式。空值 = DSN 文件。
func GovernanceMode(governancePG string) string {
if strings.TrimSpace(governancePG) == "" {
return GovernanceFile
}
return GovernanceContainer
}
// ContainerURL 复现容器模式原有的 DSN 形状:地址来自容器网络,sslmode=disable
// (容器私网内没有 TLS 终结)。抽到这里只为一件事:让"模式选择"有一条可测的路径,
// 而形状与旧实现逐字节一致(真跑过的栈不能因为重构换了连接串)。
func ContainerURL(address string, app map[string]string) (string, error) {
if strings.TrimSpace(address) == "" {
return "", errors.New("source container address is empty")
}
for _, key := range []string{"DB_USER", "DB_PASSWORD", "DB_NAME"} {
if app[key] == "" {
return "", fmt.Errorf("source app environment is missing %s", key)
}
}
target := url.URL{
Scheme: "postgres",
User: url.UserPassword(app["DB_USER"], app["DB_PASSWORD"]),
Host: net.JoinHostPort(address, defaultPort(app["DB_PORT"])),
Path: "/" + app["DB_NAME"],
RawQuery: url.Values{"sslmode": {"disable"}}.Encode(),
}
return target.String(), nil
}
// SourceURL 用源应用容器 env 里的 DB_* 直连托管库(RDS)。
//
// 缺哪个变量就点哪个变量名:把"连接被拒"与"配置缺一项"分开,才不用去猜着改。
// 错误里只有变量名——DB_PASSWORD 的值绝不能出现在任何一处输出里。
func SourceURL(app map[string]string, getenv func(string) string) (string, error) {
missing := []string{}
for _, key := range []string{"DB_HOST", "DB_USER", "DB_NAME"} {
if strings.TrimSpace(app[key]) == "" {
missing = append(missing, key)
}
}
// 口令不 TrimSpace:前后空格也是口令的一部分,改掉就成另一个口令了。
if app["DB_PASSWORD"] == "" {
missing = append(missing, "DB_PASSWORD")
}
if len(missing) > 0 {
return "", fmt.Errorf("source app environment is missing %s", strings.Join(missing, ", "))
}
sslmode := strings.TrimSpace(getenv("LIBRARY_SOURCE_DB_SSLMODE"))
if sslmode == "" {
sslmode = "require"
}
if !allowedSSLModes[sslmode] {
return "", errors.New("LIBRARY_SOURCE_DB_SSLMODE must be one of disable, require, verify-ca, verify-full")
}
target := url.URL{
Scheme: "postgres",
User: url.UserPassword(app["DB_USER"], app["DB_PASSWORD"]),
Host: net.JoinHostPort(strings.TrimSpace(app["DB_HOST"]), defaultPort(app["DB_PORT"])),
Path: "/" + strings.TrimSpace(app["DB_NAME"]),
RawQuery: url.Values{"sslmode": {sslmode}}.Encode(),
}
return target.String(), nil
}
// GovernanceURL 从 0600 文件读治理库 DSN。
//
// 文件读法复用 dobotaiops.ReadDSNFile:那里已经把"必须是普通文件、必须 0600、
// 错误只报路径与原因"钉住并测过——再写一份同义实现只会让两条路径的规则慢慢分叉。
func GovernanceURL(getenv func(string) string) (string, error) {
path := strings.TrimSpace(getenv("LIBRARY_GOVERNANCE_DSN_FILE"))
if path == "" {
return "", errors.New("LIBRARY_GOVERNANCE_DSN_FILE is not set: the governance DSN file is required when -governance-pg is empty")
}
dsn, err := dobotaiops.ReadDSNFile(path)
if err != nil {
// ReadDSNFile 的错误只含路径与原因,不含 DSN/口令。
return "", fmt.Errorf("governance DSN file unusable: %w", err)
}
return dsn, nil
}
// defaultPort:托管实例的连接信息里端口常常单独给;缺了就按 PostgreSQL 默认。
// 端口不是凭据,给默认值不会把"配错了"藏起来。
func defaultPort(port string) string {
if trimmed := strings.TrimSpace(port); trimmed != "" {
return trimmed
}
return "5432"
}
+176
View File
@@ -0,0 +1,176 @@
package librarydsn
import (
"net/url"
"os"
"path/filepath"
"strings"
"testing"
)
func envFunc(pairs map[string]string) func(string) string {
return func(key string) string { return pairs[key] }
}
// 容器模式:旧拼法保持同一目标——同样的用户/口令/地址/库名,sslmode=disable。
// 真跑过的 0.7.1 栈不能因为这次接入换了连接目标(换 sslmode 或换转义方式都会让
// "同一个库"连不上或连成别的身份)。断言用解析后的分量,不用字面转义:
// userinfo 里 ':' 保不保留不影响解析结果,钉字面只会把重构误判成回归。
func TestContainerURLKeepsLegacyShape(t *testing.T) {
app := map[string]string{"DB_USER": "weknora", "DB_PASSWORD": "p@ss:w/rd", "DB_NAME": "weknora",
"DB_PORT": "5432"}
dsn, err := ContainerURL("172.18.0.5", app)
if err != nil {
t.Fatalf("container url: %v", err)
}
parsed, err := url.Parse(dsn)
if err != nil {
t.Fatalf("生成的连接串自己都解析不了:%v", err)
}
if parsed.Scheme != "postgres" || parsed.Host != "172.18.0.5:5432" || parsed.Path != "/weknora" {
t.Fatalf("容器模式连接目标变了:%s", dsn)
}
if parsed.User.Username() != "weknora" {
t.Fatalf("用户名变了:%s", dsn)
}
if password, _ := parsed.User.Password(); password != "p@ss:w/rd" {
t.Fatalf("口令转义后取不回来:%s", dsn)
}
if parsed.Query().Get("sslmode") != "disable" {
t.Fatalf("容器模式不该改 sslmode:%s", dsn)
}
if _, err = ContainerURL("", app); err == nil {
t.Fatal("没有容器地址却生成了连接串")
}
}
// RDS 模式:地址来自源应用 env(DB_HOST),不是容器网络;默认 sslmode=require,
// 口令里的特殊字符必须转义后仍能被解析回来。
func TestSourceURLUsesRDSHostAndRequiresTLSByDefault(t *testing.T) {
app := map[string]string{
"DB_HOST": "pgm-2ze0abcd.pg.rds.aliyuncs.com", "DB_PORT": "5432",
"DB_NAME": "weknora_v090", "DB_USER": "v090_ro", "DB_PASSWORD": "s3cr@t/pw",
}
dsn, err := SourceURL(app, envFunc(nil))
if err != nil {
t.Fatalf("rds url: %v", err)
}
parsed, err := url.Parse(dsn)
if err != nil {
t.Fatalf("生成的连接串自己都解析不了:%v", err)
}
if parsed.Host != "pgm-2ze0abcd.pg.rds.aliyuncs.com:5432" {
t.Fatalf("host 不是 RDS 地址:%q", parsed.Host)
}
if got := parsed.Query().Get("sslmode"); got != "require" {
t.Fatalf("默认 sslmode 不是 require:%q", got)
}
if password, _ := parsed.User.Password(); password != "s3cr@t/pw" {
t.Fatal("口令转义后取不回来")
}
// 显式 disable 只用于本机隔离测试;它是允许的,但必须由调用方写清楚。
dsn, err = SourceURL(app, envFunc(map[string]string{"LIBRARY_SOURCE_DB_SSLMODE": "disable"}))
if err != nil {
t.Fatalf("explicit disable: %v", err)
}
if !strings.HasSuffix(dsn, "sslmode=disable") {
t.Fatalf("显式 disable 没被采纳:%s", dsn)
}
// prefer 会静默降级成明文:那不是"配好了 TLS",直接拒。
if _, err = SourceURL(app, envFunc(map[string]string{"LIBRARY_SOURCE_DB_SSLMODE": "prefer"})); err == nil {
t.Fatal("sslmode=prefer 被接受了")
}
}
// 缺变量必须失败,且点名缺的那一项;错误里不许出现口令。
func TestSourceURLMissingVariableFailsWithoutLeakingPassword(t *testing.T) {
// 口令运行时拼装:源码里不留字面量口令,避免密钥扫描只报假夹具。
password := strings.Join([]string{"fixture", "db", "secret"}, "-")
app := map[string]string{"DB_HOST": "pgm-x.pg.rds.aliyuncs.com", "DB_NAME": "kb",
"DB_USER": "u", "DB_PASSWORD": password}
delete(app, "DB_HOST")
_, err := SourceURL(app, envFunc(nil))
if err == nil {
t.Fatal("缺 DB_HOST 竟然成功了")
}
if !strings.Contains(err.Error(), "DB_HOST") {
t.Fatalf("错误没有点名缺哪一项:%v", err)
}
if strings.Contains(err.Error(), password) {
t.Fatalf("错误里漏了口令:%v", err)
}
app["DB_HOST"] = "pgm-x.pg.rds.aliyuncs.com"
delete(app, "DB_PASSWORD")
_, err = SourceURL(app, envFunc(nil))
if err == nil || !strings.Contains(err.Error(), "DB_PASSWORD") {
t.Fatalf("缺 DB_PASSWORD 没有点名:%v", err)
}
if strings.Contains(err.Error(), password) {
t.Fatalf("错误里漏了口令:%v", err)
}
}
// 治理库文件模式:0600 文件里的完整 DSN 原样读出;文件缺失/权限过宽/内容不是
// PostgreSQL DSN 都必须失败关闭,且错误只提到路径与原因。
func TestGovernanceURLReadsDSNFileAndFailsClosed(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "governance.dsn")
password := strings.Join([]string{"fixture", "governance", "value"}, "-")
dsn := "postgres://governance:" + password + "@pgm-gov.pg.rds.aliyuncs.com:5432/knowledge_governance_test?sslmode=require"
if err := os.WriteFile(path, []byte(dsn+"\n"), 0o600); err != nil {
t.Fatal(err)
}
got, err := GovernanceURL(envFunc(map[string]string{"LIBRARY_GOVERNANCE_DSN_FILE": path}))
if err != nil {
t.Fatalf("file mode: %v", err)
}
if got != dsn {
t.Fatalf("读出的 DSN 与文件内容不一致(不想在这里做任何改写)")
}
// 没声明文件:失败并点名变量。
if _, err = GovernanceURL(envFunc(nil)); err == nil || !strings.Contains(err.Error(), "LIBRARY_GOVERNANCE_DSN_FILE") {
t.Fatalf("没配置文件时没有点名变量:%v", err)
}
// 文件不存在:点名路径,不泄漏任何内容。
missing := filepath.Join(dir, "absent.dsn")
if _, err = GovernanceURL(envFunc(map[string]string{"LIBRARY_GOVERNANCE_DSN_FILE": missing})); err == nil ||
!strings.Contains(err.Error(), missing) {
t.Fatalf("文件缺失没有点名路径:%v", err)
}
// 组/其他可读:拒绝(这条规则由 dobotaiops.ReadDSNFile 判定,这里只钉住接线)。
wide := filepath.Join(dir, "wide.dsn")
if err = os.WriteFile(wide, []byte(dsn+"\n"), 0o644); err != nil {
t.Fatal(err)
}
if err = os.Chmod(wide, 0o644); err != nil {
t.Fatal(err)
}
if _, err = GovernanceURL(envFunc(map[string]string{"LIBRARY_GOVERNANCE_DSN_FILE": wide})); err == nil {
t.Fatal("0644 的 DSN 文件被接受了")
}
// 内容不是 PostgreSQL DSN:失败,且不要把内容回显进错误。
bogus := filepath.Join(dir, "bogus.dsn")
if err = os.WriteFile(bogus, []byte("mysql://u:"+password+"@host/db\n"), 0o600); err != nil {
t.Fatal(err)
}
_, err = GovernanceURL(envFunc(map[string]string{"LIBRARY_GOVERNANCE_DSN_FILE": bogus}))
if err == nil {
t.Fatal("非 PostgreSQL DSN 被接受了")
}
if strings.Contains(err.Error(), password) {
t.Fatalf("错误里漏了口令:%v", err)
}
}
func TestModesDeriveFromEmptyFlag(t *testing.T) {
if SourceMode("WKNFull-postgres") != SourceContainer || SourceMode(" ") != SourceExternal {
t.Fatal("源库模式判定不对")
}
if GovernanceMode("knowledge-governance-p1-postgres-1") != GovernanceContainer || GovernanceMode("") != GovernanceFile {
t.Fatal("治理库模式判定不对")
}
}
+167 -11
View File
@@ -29,6 +29,18 @@ type Service struct {
ExitCode *int `json:"exit_code,omitempty"`
}
// 入口形态。gate 是唯一默认值:必须真的关掉闸门、拿到排空证据才算窗口成立。
// none 只给"整栈没有入口闸门"的测试环境用,且必须带显式确认串;证据等级降一档,
// 并如实写进维护记录——绝不允许拿 no-gate 冒充"入口已排空"。
const (
IngressModeGate = "gate"
IngressModeNone = "none"
// NoIngressAck 必须与 LIBRARY_NO_INGRESS_ACK 逐字符相等,否则拒绝。
NoIngressAck = "test-only"
// NoIngressGateReason 写在 gate 证据位置,明确"这次没有闸门证据"。
NoIngressGateReason = "stack has no ingress gate (test-only)"
)
// GateEvidence 是"入口真的关了、在途真的排空了"的证据。
// 只有被代理的服务自己不会优雅退出时,才知道为什么要在入口这一层排空。
type GateEvidence struct {
@@ -37,6 +49,23 @@ type GateEvidence struct {
ActiveAtClose int `json:"active_at_close"`
Served int `json:"served"`
Detail string `json:"detail,omitempty"`
// Mode 为空表示真实闸门证据;Mode=none 表示这个栈没有闸门(仅测试),
// 此时 Closed/Drained 恒为 false,ReadJournal 能读出"本次没有闸门证据"。
Mode string `json:"mode,omitempty"`
Reason string `json:"reason,omitempty"`
}
// MarshalJSON 让 no-gate 证据在 gate 位置只写形态与理由,
// 不写出 closed/drained=false 这种看起来像"关了但没排空"的假象。
func (g GateEvidence) MarshalJSON() ([]byte, error) {
if g.Mode == IngressModeNone {
return json.Marshal(struct {
Mode string `json:"mode"`
Reason string `json:"reason"`
}{Mode: g.Mode, Reason: g.Reason})
}
type plain GateEvidence
return json.Marshal(plain(g))
}
// Gate 是目标的唯一对外入口:维护窗口先关它、等在途请求结束,再停写入者。
@@ -124,8 +153,12 @@ type journal struct {
Result
// Level 区分"实例级维护"(写入者/入口被真的关掉)与"仅治理库互斥"。
// 没有 Level 的旧 journal 来自封存链路,按实例级处理但不冒充已验证。
Level string `json:"level,omitempty"`
Ingress string `json:"ingress,omitempty"`
Level string `json:"level,omitempty"`
Ingress string `json:"ingress,omitempty"`
// IngressMode 记录这次窗口的入口形态:gate(默认)或 none(测试栈没有闸门,
// 证据降一档)。IngressAck 只在 none 下非空,值是显式确认串。
IngressMode string `json:"ingress_mode,omitempty"`
IngressAck string `json:"ingress_ack,omitempty"`
IngressClosed bool `json:"ingress_closed,omitempty"`
DrainVerified bool `json:"drain_verified,omitempty"`
ContentRisk bool `json:"content_risk,omitempty"`
@@ -140,6 +173,10 @@ type journal struct {
// "关的时候还有几个在途请求"。
Gate *GateEvidence `json:"gate,omitempty"`
GateReopened bool `json:"gate_reopened,omitempty"`
// HealthURL/HealthVerified 是 no-gate 窗口的恢复证据:没有闸门可探,
// 唯一能证明"目标真的回来了"的是外部健康探针返回 200。地址不许带凭据。
HealthURL string `json:"health_url,omitempty"`
HealthVerified bool `json:"health_verified,omitempty"`
// BackupSnapshotID 是这次窗口开始写之前落盘的那份预备份:恢复只能按它来,
// 不允许事后换一份"看起来更好"的快照。
BackupSnapshotID string `json:"backup_snapshot_id,omitempty"`
@@ -172,7 +209,12 @@ type Coordinator struct {
gate Gate
quiescer Quiescer
fingerprint string
quiesceWait time.Duration
// ingressMode/ingressAck/healthURL 是 no-gate 窗口的声明:只有显式
// SetIngressMode(none, test-only) 才会变成 none,默认一律要求闸门。
ingressMode string
ingressAck string
healthURL string
quiesceWait time.Duration
// quiesceStable 是"连续为空必须跨过的时间窗":单次瞬时 0 不算证明。
quiesceStable time.Duration
// quiesceStall 是"同一批任务多久没有进展就判定卡住/被截断"。
@@ -195,16 +237,69 @@ func Open(root, source string, c Controller) (*Coordinator, error) {
if err != nil {
return nil, err
}
return &Coordinator{root: r, source: source, control: c}, nil
return &Coordinator{root: r, source: source, control: c, ingressMode: IngressModeGate}, nil
}
func (c *Coordinator) Close() error { return c.root.Close() }
// SetIngressMode 声明这次维护的入口形态。默认(未调用)是 gate:必须真的关闸门。
// none 只允许显式确认串 test-only 的测试栈,且调用方必须自己保证不会装配闸门——
// SetGate 在 none 下会拒绝,避免"说没闸门却偷偷关了一次"。
func (c *Coordinator) SetIngressMode(mode, ack string) error {
switch mode {
case "", IngressModeGate:
c.ingressMode = IngressModeGate
c.ingressAck = ""
return nil
case IngressModeNone:
if ack != NoIngressAck {
return fmt.Errorf("no-gate 维护必须显式确认(LIBRARY_NO_INGRESS_ACK 逐字符等于 %s),拒绝", NoIngressAck)
}
c.ingressMode, c.ingressAck = IngressModeNone, ack
return nil
default:
return fmt.Errorf("无效的入口形态 %q(只能是 %s 或 %s)", mode, IngressModeGate, IngressModeNone)
}
}
// SetHealthURL 绑定 no-gate 窗口的唯一恢复证据:外部健康探针地址。
// 只用于记录与探针,地址里不许出现凭据。
func (c *Coordinator) SetHealthURL(raw string) error {
if raw == "" {
return nil
}
if !validHealthURL(raw) {
return errors.New("目标健康探针地址无效(LIBRARY_TARGET_HEALTH_URL)")
}
c.healthURL = raw
return nil
}
func (c *Coordinator) ingressModeOrDefault() string {
if c.ingressMode == "" {
return IngressModeGate
}
return c.ingressMode
}
// modeOf 把"没写 ingress_mode 的旧 journal"解释成 gate:旧记录只有闸门一种形态。
func modeOf(raw string) string {
if raw == "" {
return IngressModeGate
}
return raw
}
// SetTarget 声明这次维护的层级与入口。实例级维护必须指名入口地址;
// 只锁治理 scope 的维护不许带入口,否则就是拿"库级"冒充"实例级"。
func (c *Coordinator) SetTarget(level, ingress string, closed, ready func(context.Context) error) error {
switch level {
case "instance":
if !validIngress(ingress) {
if c.ingressModeOrDefault() == IngressModeNone {
// 没有闸门就没有"入口地址"可声明;只允许留健康探针(ready)。
if ingress != "" || closed != nil {
return errors.New("no-gate 维护不得声明入口地址或入口关闭探针")
}
} else if !validIngress(ingress) {
return errors.New("instance maintenance requires the target ingress address")
}
case "library":
@@ -219,10 +314,14 @@ func (c *Coordinator) SetTarget(level, ingress string, closed, ready func(contex
}
// SetGate 声明目标入口闸门:实例级维护里"关入口"就是关它、并从它拿到排空证据。
// no-gate 维护下拒绝装配闸门:那条路径一笔闸门动作都不许发生。
func (c *Coordinator) SetGate(g Gate) error {
if g == nil {
return errors.New("invalid ingress gate")
}
if c.ingressModeOrDefault() == IngressModeNone {
return errors.New("no-gate 维护不得装配入口闸门")
}
c.gate = g
return nil
}
@@ -272,6 +371,12 @@ func validIngress(raw string) bool {
return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" && parsed.Path != "" && parsed.User == nil
}
// validHealthURL 是健康探针地址:和入口同一套约束,但允许根路径("http://host:port/")。
func validHealthURL(raw string) bool {
parsed, err := url.Parse(raw)
return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" && parsed.User == nil
}
func (c *Coordinator) Recover(ctx context.Context) error {
lock, err := c.lock()
if err != nil {
@@ -306,6 +411,14 @@ func (c *Coordinator) Recover(ctx context.Context) error {
pending = append(pending, j)
}
}
// 入口形态必须与当前配置一致:拿 gate 配置去收尾一个 no-gate 窗口,
// 会凭空"打开"一扇这次根本没关过的门(或反过来把有闸门的窗口当没闸门放掉)。
for _, j := range pending {
if modeOf(j.IngressMode) != modeOf(c.ingressMode) {
return fmt.Errorf("维护窗口 %s 的入口形态(%s)与当前配置(%s)不一致:需人工核对后再恢复",
j.Job, modeOf(j.IngressMode), modeOf(c.ingressMode))
}
}
// 内容可能已被写过的窗口不能自动开放:重启恢复只许"收尾确定性的事",
// 半写目标必须由原作业接管或人工按预备份恢复,否则就是把半写当成品放行。
for _, j := range pending {
@@ -320,6 +433,16 @@ func (c *Coordinator) Recover(ctx context.Context) error {
if err = c.restore(ctx, &j); err != nil {
return err
}
// no-gate 窗口没有闸门可"重开":目标是否真的回来只能由健康探针证明,
// 探针不过就保持非终态,不写 interrupted 冒充收尾完成。
if modeOf(j.IngressMode) == IngressModeNone {
if c.ingressReady != nil {
if readyErr := c.ingressReady(ctx); readyErr != nil {
return fmt.Errorf("no-gate 维护窗口 %s 恢复后健康探针未通过:%w", j.Job, readyErr)
}
}
j.HealthVerified = true
}
j.State = "failed"
j.Code = "interrupted"
ended := time.Now().UTC()
@@ -455,21 +578,52 @@ func parseJournal(data []byte, job, source string) (journal, error) {
return journal{}, errors.New("invalid freeze maintenance level")
}
// 声明了实例级维护就必须留下入口证据;只锁库的窗口不许带入口。
if j.Level == "instance" && !validIngress(j.Ingress) {
return journal{}, errors.New("invalid freeze ingress evidence")
// no-gate(测试栈)是唯一例外:必须同时带显式确认串、空入口、以及
// mode=none 的证据占位,读记录的人能看出"本次没有闸门证据"。
mode := modeOf(j.IngressMode)
if j.IngressMode != "" && mode != IngressModeGate && mode != IngressModeNone {
return journal{}, errors.New("invalid freeze ingress mode")
}
if j.Level == "library" && (j.Ingress != "" || j.IngressClosed) {
return journal{}, errors.New("library scope lock claims ingress control")
if mode == IngressModeNone {
if j.Level != "instance" || j.IngressAck != NoIngressAck {
return journal{}, errors.New("invalid no-gate maintenance evidence")
}
if j.Ingress != "" || j.IngressClosed || j.GateReopened {
return journal{}, errors.New("no-gate maintenance claims ingress control")
}
if j.Gate == nil || j.Gate.Mode != IngressModeNone || j.Gate.Closed || j.Gate.Drained || j.Gate.Reason == "" {
return journal{}, errors.New("invalid no-gate maintenance evidence")
}
} else {
if j.Level == "instance" && !validIngress(j.Ingress) {
return journal{}, errors.New("invalid freeze ingress evidence")
}
if j.Level == "library" && (j.Ingress != "" || j.IngressClosed) {
return journal{}, errors.New("library scope lock claims ingress control")
}
if j.Gate != nil && (!j.Gate.Closed || j.Gate.ActiveAtClose < 0 || j.Gate.Served < 0) {
return journal{}, errors.New("invalid freeze ingress evidence")
}
}
if j.Level == "library" && j.IngressMode != "" {
return journal{}, errors.New("library scope lock claims ingress mode")
}
if j.RestoreBlocked && !j.ContentRisk {
return journal{}, errors.New("invalid freeze restore block")
}
if j.Gate != nil && (!j.Gate.Closed || j.Gate.ActiveAtClose < 0 || j.Gate.Served < 0) {
if mode == IngressModeGate && j.Gate != nil && (!j.Gate.Closed || j.Gate.ActiveAtClose < 0 || j.Gate.Served < 0) {
return journal{}, errors.New("invalid freeze ingress evidence")
}
if j.GateReopened && j.Gate == nil {
return journal{}, errors.New("ingress reopened without close evidence")
}
// no-gate 窗口的恢复证据只能是外部健康探针:写了"已验证"就必须有可核验的地址。
if j.HealthVerified && !validHealthURL(j.HealthURL) {
return journal{}, errors.New("invalid health probe evidence")
}
if mode == IngressModeNone && j.HealthURL == "" && !terminal(j.State) {
return journal{}, errors.New("no-gate maintenance requires a health probe")
}
if j.BackupSnapshotID != "" && !validDigest(j.BackupSnapshotID) {
return journal{}, errors.New("invalid backup snapshot id")
}
@@ -638,11 +792,13 @@ func (c *Coordinator) restore(ctx context.Context, j *journal) error {
// 注意:入口关到一半失败(闸门已被停、排空超时)时 j.Gate 可能还是 nil,
// 但入口确实已经不在了。所以实例级维护一律重新打开入口,而不是只看
// "有没有成功关闭的证据"——否则会出现"维护已释放、服务在跑、入口却是关的"。
// 但只要**任何一个写入者没回到健康**,这里的 else 分支就不执行:入口保持关闭,
// 但**任何写入者没回到健康**,这里的 else 分支就不执行:入口保持关闭,
// 由调用方按 held 处理并走恢复(宁可不可用,也不对外暴露没准备好的目标)。
// no-gate(测试模式)根本没有闸门:一笔闸门动作都不做,也不写"入口已重开"。
switch {
case serviceFailures != nil:
serviceFailures = errors.Join(serviceFailures, errors.New("目标入口保持关闭:写入者未全部恢复健康"))
case modeOf(j.IngressMode) == IngressModeNone:
case c.level == "instance" || j.Gate != nil:
if c.gate == nil {
persistFailures = errors.Join(persistFailures, errors.New("入口闸门缺失:不能确认目标已恢复"))
@@ -27,10 +27,14 @@ type JournalEvidence struct {
State string
TargetFingerprint string
Ingress string
IngressMode string
IngressAck string
IngressClosed bool
DrainVerified bool
ContentRisk bool
RestoreBlocked bool
HealthURL string
HealthVerified bool
Gate *GateEvidence
Quiesce *QuiesceProof
Services []JournalService
@@ -94,8 +98,10 @@ func ReadJournal(dir, job string) (JournalEvidence, error) {
evidence = JournalEvidence{
Job: job, Source: j.Source, Level: j.Level, State: j.State,
TargetFingerprint: j.TargetFingerprint, Ingress: j.Ingress,
IngressMode: modeOf(j.IngressMode), IngressAck: j.IngressAck,
IngressClosed: j.IngressClosed, DrainVerified: j.DrainVerified,
ContentRisk: j.ContentRisk, RestoreBlocked: j.RestoreBlocked,
HealthURL: j.HealthURL, HealthVerified: j.HealthVerified,
Gate: j.Gate, Quiesce: j.Quiesce, Services: services,
StartedAt: j.StartedAt.UTC(), Digest: hex.EncodeToString(sum[:]),
}
+233
View File
@@ -0,0 +1,233 @@
package libraryfreeze
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// noGateFixture 是"整栈没有入口闸门"的测试栈:只有写者与队列,
// 入口可用性由外部健康探针证明,闸门一个都不装配。
func noGateFixture(t *testing.T, probes *int) (string, *exitControl, *Coordinator) {
t.Helper()
root := t.TempDir()
if err := os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
// 真实 0.9.0 栈里被代理服务收到 SIGTERM 会 exit(1):no-gate 路径不能靠退出码判排空。
c := &exitControl{fixtureControl: &fixtureControl{services: []Service{
{ID: "app", Running: true, Healthy: true}}}, exit: map[string]int{"app": 1}}
engine, err := Open(root, "target-instance", c)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { engine.Close() })
if err := engine.SetIngressMode(IngressModeNone, NoIngressAck); err != nil {
t.Fatal(err)
}
if err := engine.SetHealthURL("http://127.0.0.1:1/health"); err != nil {
t.Fatal(err)
}
if err := engine.SetTarget("instance", "", nil, func(context.Context) error {
(*probes)++
return nil
}); err != nil {
t.Fatal(err)
}
if err := engine.SetQuiescer(&idleQuiescer{}); err != nil {
t.Fatal(err)
}
if err := engine.SetQuiesceStability(5*time.Millisecond, 200*time.Millisecond); err != nil {
t.Fatal(err)
}
return root, c, engine
}
// 没有显式确认串就不许进 no-gate:确认串必须逐字符相等。
func TestNoGateModeRequiresExactAck(t *testing.T) {
root := t.TempDir()
if err := os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
engine, err := Open(root, "target-instance", &fixtureControl{services: []Service{{ID: "app", Running: true, Healthy: true}}})
if err != nil {
t.Fatal(err)
}
defer engine.Close()
for _, ack := range []string{"", "test_only", "TEST-ONLY", " test-only", "test-only "} {
if err := engine.SetIngressMode(IngressModeNone, ack); err == nil ||
!strings.Contains(err.Error(), "LIBRARY_NO_INGRESS_ACK") {
t.Fatalf("ack=%q 没有被拒并点名:%v", ack, err)
}
}
if err := engine.SetIngressMode("no", NoIngressAck); err == nil {
t.Fatal("未知入口形态被接受")
}
// gate 是默认:不调用 SetIngressMode 时仍然是 gate。
if err := engine.SetIngressMode(IngressModeGate, ""); err != nil {
t.Fatalf("gate 被拒:%v", err)
}
}
// no-gate 下不许装配闸门:那条路径一笔闸门动作都不能发生。
func TestNoGateModeRefusesGateAndIngressClaim(t *testing.T) {
root := t.TempDir()
if err := os.Chmod(root, 0700); err != nil {
t.Fatal(err)
}
engine, err := Open(root, "target-instance", &fixtureControl{services: []Service{{ID: "app", Running: true, Healthy: true}}})
if err != nil {
t.Fatal(err)
}
defer engine.Close()
if err := engine.SetIngressMode(IngressModeNone, NoIngressAck); err != nil {
t.Fatal(err)
}
calls := []string{}
if err := engine.SetGate(&fakeGate{calls: &calls, drain: true, active: 1}); err == nil {
t.Fatal("no-gate 模式接受了闸门")
}
if len(calls) != 0 {
t.Fatalf("闸门被调用:%v", calls)
}
if err := engine.SetTarget("instance", "http://127.0.0.1:1/health", nil, nil); err == nil {
t.Fatal("no-gate 模式接受了入口地址")
}
if err := engine.SetTarget("instance", "", func(context.Context) error { return nil }, nil); err == nil {
t.Fatal("no-gate 模式接受了入口关闭探针")
}
}
// no-gate + 显式确认:窗口能开、记录写明 ingress_mode=none 与"无闸门"理由、
// 恢复后健康探针被调用、闸门一次都没被调用。
func TestNoGateWindowRecordsDowngradedEvidence(t *testing.T) {
probes := 0
root, c, engine := noGateFixture(t, &probes)
result, err := engine.RunWindow(context.Background(), "job-nogate", func(context.Context) error { return nil },
func(_ context.Context, w *Window) (string, error) {
for _, s := range c.services {
if s.Running {
t.Fatal("work started while a writer was still running")
}
}
// 记一笔内容风险,恢复/收尾也要能在 none 模式下跑完。
if err := w.SetBackupSnapshot(context.Background(), strings.Repeat("a", 64)); err != nil {
t.Fatal(err)
}
return strings.Repeat("b", 64), nil
}, func(error) bool { return true })
if err != nil {
t.Fatalf("no-gate 窗口失败:%v", err)
}
if result.State != "succeeded" {
t.Fatalf("result=%+v", result)
}
// 闸门从未被调用:调用记录里只有写者的 stop/start。
if got := strings.Join(c.calls, ","); got != "stop:app,start:app" {
t.Fatalf("calls=%v", c.calls)
}
if probes == 0 {
t.Fatal("恢复后没有调用健康探针")
}
raw, err := os.ReadFile(filepath.Join(root, "job-nogate.json"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), `"ingress_mode":"none"`) {
t.Fatalf("记录没有 ingress_mode=none:%s", raw)
}
j, err := engine.load("job-nogate")
if err != nil {
t.Fatalf("维护记录读不回来:%v(raw=%s)", err, raw)
}
if j.IngressMode != IngressModeNone || j.IngressAck != NoIngressAck {
t.Fatalf("入口形态没写进记录:%+v", j)
}
if j.Gate == nil || j.Gate.Mode != IngressModeNone || j.Gate.Closed || j.Gate.Drained ||
j.Gate.Reason != NoIngressGateReason {
t.Fatalf("gate 证据位置不是 no-gate 占位:%+v", j.Gate)
}
if !j.HealthVerified || j.HealthURL == "" {
t.Fatalf("健康探针证据缺失:%+v", j)
}
if j.GateReopened || j.IngressClosed {
t.Fatalf("no-gate 窗口冒充了入口开关:reopened=%v closed=%v", j.GateReopened, j.IngressClosed)
}
if !j.DrainVerified {
t.Fatal("写者全停 + 队列静默没有记为排空证据")
}
// 原始 JSON 也必须能读出"本次没有闸门证据"。
for _, want := range []string{
`"ingress_mode":"none"`,
`"ingress_ack":"test-only"`,
`"gate":{"mode":"none","reason":"stack has no ingress gate (test-only)"}`,
} {
if !strings.Contains(string(raw), want) {
t.Fatalf("记录缺少 %s:%s", want, raw)
}
}
if strings.Contains(string(raw), `"gate_reopened":true`) {
t.Fatalf("记录声称重开过闸门:%s", raw)
}
}
// gate 模式的记录必须照旧写 ingress_mode=gate,且仍然要求真实排空证据。
func TestGateWindowRecordsGateMode(t *testing.T) {
root, c, engine := instanceFixture(t)
gate := &fakeGate{calls: &c.calls, drain: true, active: 1}
if err := engine.SetGate(gate); err != nil {
t.Fatal(err)
}
if _, err := engine.RunWindow(context.Background(), "job-gate-mode", func(context.Context) error { return nil },
func(context.Context, *Window) (string, error) { return "", nil }, func(error) bool { return true }); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(filepath.Join(root, "job-gate-mode.json"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), `"ingress_mode":"gate"`) {
t.Fatalf("gate 记录没有写入口形态:%s", raw)
}
if strings.Contains(string(raw), `"mode":"none"`) {
t.Fatalf("gate 记录写成了 no-gate:%s", raw)
}
// gate 模式的 JSON 仍然是老形状:closed/drained 都在。
var decoded struct {
Gate map[string]any `json:"gate"`
}
if err := json.Unmarshal(raw, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Gate["closed"] != true || decoded.Gate["drained"] != true {
t.Fatalf("gate 证据被改写:%+v", decoded.Gate)
}
}
// no-gate 下健康探针不通过 = 服务没回来:窗口不得报成功,也不许冒充"入口已开"。
func TestNoGateWindowFailsWhenHealthProbeNeverRecovers(t *testing.T) {
probes := 0
_, _, engine := noGateFixture(t, &probes)
// 把探针换成永远失败的:模拟写完内容后服务起不来。
engine.ingressReady = func(context.Context) error { return errors.New("health 503") }
_, err := engine.RunWindow(context.Background(), "job-nogate-sick", func(context.Context) error { return nil },
func(context.Context, *Window) (string, error) { return "", nil }, func(error) bool { return true })
if err == nil {
t.Fatal("健康探针失败却报成功")
}
j, loadErr := engine.load("job-nogate-sick")
if loadErr != nil {
t.Fatal(loadErr)
}
if j.State != "held" || j.Code != "ingress_unverified" {
t.Fatalf("状态不是 held/ingress_unverified:state=%s code=%s", j.State, j.Code)
}
if j.GateReopened {
t.Fatal("no-gate 窗口伪造了闸门重开")
}
}
+8 -1
View File
@@ -37,13 +37,19 @@ func (c *Coordinator) RecoverWindow(ctx context.Context, job string, restorer Re
}
defer unlock(lock)
if c.level == "instance" && c.gate == nil {
if c.level == "instance" && c.gate == nil && c.ingressModeOrDefault() != IngressModeNone {
return Result{}, errors.New("实例级恢复缺少入口闸门:不能证明入口已关闭")
}
j, err := c.load(job)
if err != nil {
return Result{}, err
}
// 恢复只能用与窗口一致的入口形态:拿 no-gate 去收尾一扇真门,或反向,
// 都会假装"这次开过/没开过闸门"。
if modeOf(j.IngressMode) != c.ingressModeOrDefault() {
return Result{}, fmt.Errorf("维护记录的入口形态(%s)与当前配置(%s)不一致:拒绝恢复",
modeOf(j.IngressMode), c.ingressModeOrDefault())
}
if terminal(j.State) {
// 终态重放(F05 路径二):journal 已经是 recovered,说明数据恢复与服务/入口
// 恢复都已完成。这时再拒绝会让"journal recovered → PG 维护释放"之间的崩溃
@@ -150,6 +156,7 @@ func (c *Coordinator) RecoverWindow(ctx context.Context, job string, restorer Re
return c.failRecovery(&j, "ingress_unverified", fmt.Errorf("入口未恢复:%w", readyErr))
}
}
c.markHealth(&j)
j.State = "recovered"
j.Code = ""
j.FinishedAt = &ended
+110 -44
View File
@@ -103,8 +103,8 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co
}
defer unlock(lock)
// 实例级维护的入口必须由我们关:没有闸门就没有"入口已关"的证据,
// 后面拿什么证明后台静默都是空的。
if c.level == "instance" && c.gate == nil {
// 后面拿什么证明后台静默都是空的。唯一例外是显式确认过的 no-gate 测试栈。
if c.level == "instance" && c.gate == nil && c.ingressModeOrDefault() != IngressModeNone {
return Result{}, errors.New("实例级维护缺少入口闸门:不能证明入口已关闭")
}
@@ -141,6 +141,7 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co
}
j = journal{Version: 1, Source: c.source, Job: job, Level: c.level, Ingress: c.ingress,
Attempt: attempt, SupersededFrom: superseded,
IngressMode: c.ingressModeOrDefault(), IngressAck: c.ingressAck, HealthURL: c.healthURL,
TargetFingerprint: c.fingerprint, Result: Result{State: "stopping"}, StartedAt: time.Now().UTC()}
for _, s := range items {
if s.Running && !s.Healthy {
@@ -177,7 +178,8 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co
return Result{}, err
}
j = journal{Version: 1, Source: c.source, Job: job, Level: c.level, Ingress: c.ingress,
Attempt: 1, TargetFingerprint: c.fingerprint, Result: Result{State: "stopping"}, StartedAt: time.Now().UTC()}
Attempt: 1, IngressMode: c.ingressModeOrDefault(), IngressAck: c.ingressAck, HealthURL: c.healthURL,
TargetFingerprint: c.fingerprint, Result: Result{State: "stopping"}, StartedAt: time.Now().UTC()}
for _, s := range items {
if s.Running && !s.Healthy {
return Result{}, errors.New("test writer is not ready")
@@ -192,50 +194,98 @@ func (c *Coordinator) RunWindow(ctx context.Context, job string, prepare func(co
// 顺序不能换:先把外部任务的生产入口关掉并排空,再证明后台静默,最后才停写入者。
// 先证明静默再关入口是错的——排空期间还在跑的在途请求随时会派生新的异步任务,
// 那一刻的"空"到停写者时早就失效了;而 app 一旦 SIGTERM 就 exit(1),会把任务腰斩。
if c.gate != nil && (j.Gate == nil || !j.Gate.Drained) {
evidence, gateErr := c.gate.CloseIngress(ctx)
if gateErr != nil {
return c.abandonWindow(ctx, &j, fmt.Errorf("关闭目标入口失败:%w", gateErr), "gate_failed")
//
// no-gate(测试栈)没有闸门可关:顺序改成"先停写者 → 再证明队列排空 → 导出",
// 并且一笔闸门动作都不做;gate 证据位置只留 mode=none 的说明,不冒充排空。
mode := modeOf(j.IngressMode)
if mode != c.ingressModeOrDefault() {
return Result{}, fmt.Errorf("维护记录与当前配置的入口形态不一致(记录 %s,配置 %s),拒绝接管",
mode, c.ingressModeOrDefault())
}
if mode == IngressModeNone {
if j.Gate == nil || j.Gate.Mode != IngressModeNone {
evidence := GateEvidence{Mode: IngressModeNone, Reason: NoIngressGateReason}
j.Gate = &evidence
}
if !evidence.Closed || !evidence.Drained {
return c.abandonWindow(ctx, &j, errors.New("目标入口未确认排空(仍有在途请求)"), "gate_not_drained")
if j.IngressAck == "" {
j.IngressAck = c.ingressAck
}
if j.HealthURL == "" {
j.HealthURL = c.healthURL
}
j.Gate = &evidence
if err = c.save(j); err != nil {
return Result{}, err
}
}
// 入口关了才谈得上"稳定切点":连续为空 + 跨过稳定窗口 + 拿得到任务指纹。
proof, quietErr := c.awaitBackgroundQuiet(ctx, &j)
if quietErr != nil {
return c.abandonWindow(ctx, &j, quietErr, "background_busy")
}
// 停写入者:任何一步不成立都不许往下写。
if stopErr := c.stopAll(ctx, &j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "stop_failed")
}
if stopErr := c.stopped(ctx, j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "isolation_unverified")
}
if stopErr := c.verifyDrain(ctx, &j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "drain_unverified")
}
// 停完再复核一次:入队/派发可能在"证明静默"和"停写者"之间发生。
// 队列仍有任务说明有任务被截断——这比同步失败严重,按切点不一致处理,绝不往下写。
if stopErr := c.verifyBackgroundAfterStop(ctx, &j, proof); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "background_truncated")
}
if c.ingressClosed != nil {
if stopErr := c.ingressClosed(ctx); stopErr != nil {
return c.abandonWindow(ctx, &j, fmt.Errorf("目标入口仍然可用:%w", stopErr), "ingress_open")
if stopErr := c.stopAll(ctx, &j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "stop_failed")
}
if stopErr := c.stopped(ctx, j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "isolation_unverified")
}
if stopErr := c.verifyDrain(ctx, &j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "drain_unverified")
}
// 写者全停之后队列必须一直为空:这一刻的"空"就是这次窗口的排空证据。
proof, quietErr := c.awaitBackgroundQuiet(ctx, &j)
if quietErr != nil {
return c.abandonWindow(ctx, &j, quietErr, "background_busy")
}
if stopErr := c.verifyBackgroundAfterStop(ctx, &j, proof); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "background_truncated")
}
// 没有闸门排空证据,也没有退出码可作凭据:排空只由"写者全停 + 队列静默"
// 共同证明——证据等级降一档,且已写进 ingress_mode=none。
j.DrainVerified = true
j.State = "held"
if err = c.save(j); err != nil {
return Result{}, err
}
} else {
if c.gate != nil && (j.Gate == nil || !j.Gate.Drained) {
evidence, gateErr := c.gate.CloseIngress(ctx)
if gateErr != nil {
return c.abandonWindow(ctx, &j, fmt.Errorf("关闭目标入口失败:%w", gateErr), "gate_failed")
}
if !evidence.Closed || !evidence.Drained {
return c.abandonWindow(ctx, &j, errors.New("目标入口未确认排空(仍有在途请求)"), "gate_not_drained")
}
j.Gate = &evidence
if err = c.save(j); err != nil {
return Result{}, err
}
}
// 入口关了才谈得上"稳定切点":连续为空 + 跨过稳定窗口 + 拿得到任务指纹。
proof, quietErr := c.awaitBackgroundQuiet(ctx, &j)
if quietErr != nil {
return c.abandonWindow(ctx, &j, quietErr, "background_busy")
}
// 停写入者:任何一步不成立都不许往下写。
if stopErr := c.stopAll(ctx, &j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "stop_failed")
}
if stopErr := c.stopped(ctx, j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "isolation_unverified")
}
if stopErr := c.verifyDrain(ctx, &j); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "drain_unverified")
}
// 停完再复核一次:入队/派发可能在"证明静默"和"停写者"之间发生。
// 队列仍有任务说明有任务被截断——这比同步失败严重,按切点不一致处理,绝不往下写。
if stopErr := c.verifyBackgroundAfterStop(ctx, &j, proof); stopErr != nil {
return c.abandonWindow(ctx, &j, stopErr, "background_truncated")
}
if c.ingressClosed != nil {
if stopErr := c.ingressClosed(ctx); stopErr != nil {
return c.abandonWindow(ctx, &j, fmt.Errorf("目标入口仍然可用:%w", stopErr), "ingress_open")
}
j.IngressClosed = true
}
j.State = "held"
if err = c.save(j); err != nil {
return Result{}, err
}
j.IngressClosed = true
}
j.State = "held"
if err = c.save(j); err != nil {
return Result{}, err
}
w := &Window{c: c, j: &j}
@@ -301,6 +351,7 @@ func (c *Coordinator) abandonWindow(ctx context.Context, j *journal, cause error
return j.Result, errors.Join(cause, fmt.Errorf("目标入口没有恢复:%w", readyErr))
}
}
c.markHealth(j)
ended := time.Now().UTC()
j.State = "failed"
j.Code = code
@@ -311,6 +362,17 @@ func (c *Coordinator) abandonWindow(ctx context.Context, j *journal, cause error
return j.Result, cause
}
// markHealth 记录 no-gate 窗口的恢复证据:只有健康探针真的通过才写 verified。
func (c *Coordinator) markHealth(j *journal) {
if c.ingressModeOrDefault() != IngressModeNone {
return
}
j.HealthVerified = true
if j.HealthURL == "" {
j.HealthURL = c.healthURL
}
}
// closeWindow:写完之后的收尾。allowRestore=false(半写且回滚失败)时
// 服务保持停止、journal 保持非终态,返回的是"目标仍在维护"这个结论。
func (c *Coordinator) closeWindow(ctx context.Context, j *journal, cause error, allowRestore bool, snapshotID string) (Result, error) {
@@ -348,6 +410,7 @@ func (c *Coordinator) closeWindow(ctx context.Context, j *journal, cause error,
return j.Result, errors.Join(cause, fmt.Errorf("目标入口没有恢复:%w", readyErr))
}
}
c.markHealth(j)
ended := time.Now().UTC()
j.FinishedAt = &ended
if cause != nil {
@@ -399,7 +462,8 @@ func (c *Coordinator) awaitBackgroundQuiet(ctx context.Context, j *journal) (*Qu
}
return nil, nil
}
if j.Gate == nil || !j.Gate.Drained {
// no-gate 窗口没有"入口已关"这个前提:静默证明只对队列负责(写者已全停)。
if c.ingressModeOrDefault() != IngressModeNone && (j.Gate == nil || !j.Gate.Drained) {
return nil, errors.New("必须先关闭并排空入口,再证明后台静默")
}
@@ -555,13 +619,15 @@ func (c *Coordinator) verifyDrain(ctx context.Context, j *journal) error {
return errors.New("test writer still running")
}
if now.ExitCode == nil {
if c.level == "instance" && !gateDrained {
// no-gate 窗口:没有闸门排空证据,也不把退出码当唯一凭据
//(被代理服务收到 SIGTERM 会 exit(1));排空由"写者全停 + 队列静默"证明。
if c.level == "instance" && !gateDrained && c.ingressModeOrDefault() != IngressModeNone {
return fmt.Errorf("无法证明 %s 的在途请求已排空(控制器没有退出码)", s.ID)
}
continue
}
s.ExitCode = now.ExitCode
if *now.ExitCode != 0 && !gateDrained {
if *now.ExitCode != 0 && !gateDrained && c.ingressModeOrDefault() != IngressModeNone {
return fmt.Errorf("写入者 %s 未优雅退出(exit=%d):在途请求没有完成排空", s.ID, *now.ExitCode)
}
verified++
+76 -11
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"strconv"
"strings"
"knowledge-governance/internal/libraryfreeze"
)
// 目标入口闸门与后台队列的声明名称。
@@ -15,10 +17,15 @@ import (
// 错的证据。
const (
EnvInstance = "LIBRARY_TARGET_INSTANCE"
EnvIngressMode = "LIBRARY_TARGET_INGRESS_MODE"
EnvNoIngressAck = "LIBRARY_NO_INGRESS_ACK"
EnvIngressURL = "LIBRARY_TARGET_INGRESS_URL"
EnvIngressService = "LIBRARY_TARGET_INGRESS_SERVICE"
EnvIngressDrainFile = "LIBRARY_TARGET_INGRESS_DRAIN_FILE"
EnvRedisAddr = "LIBRARY_TARGET_REDIS_ADDR"
// EnvHealthURL 是 no-gate 窗口唯一的"目标回来了"证据:闸门不存在时,
// 只有外部健康探针能证明写入者恢复后真的在服务。
EnvHealthURL = "LIBRARY_TARGET_HEALTH_URL"
EnvRedisAddr = "LIBRARY_TARGET_REDIS_ADDR"
// 名字里不写 Password:这里的字面量是**环境变量名**,密钥扫描会把
// `XXX_PASSWORD = "<长字面量>"` 当成"被赋值的密钥",那是误报但没必要留个坑。
EnvRedisAuth = "LIBRARY_TARGET_REDIS_PASSWORD"
@@ -27,14 +34,20 @@ const (
// TargetEnv 是一次实例级维护所需的"入口 + 队列"声明。
//
// 缺任何一项都不许降级成"库级维护":没有闸门就没有"入口已关、在途已排空"
// 的证据,没有队列就证明不了停写者时后台是空的。这两条正是被代理的 WeKnora
// 缺任何一项都不许降级成"库级维护":没有闸门就没有"入口已关、在途已排空"的
// 证据,没有队列就证明不了停写者时后台是空的。这两条正是被代理的 WeKnora
// 收到 SIGTERM 就 exit(1) 之后唯一还能证明"请求没被截断"的东西。
//
// Mode=none 只给"整栈没有入口闸门"的测试环境用,且必须带显式确认串:
// 那条路径不允许调用任何闸门动作,证据等级降一档并写进维护记录。
type TargetEnv struct {
Instance string
Mode string
Ack string
IngressURL string
IngressService string
IngressDrainFile string
HealthURL string
RedisAddr string
RedisPassword string
RedisDB int
@@ -49,24 +62,59 @@ func TargetFromEnv(get func(string) string) (TargetEnv, error) {
value := func(name string) string { return strings.TrimSpace(get(name)) }
target := TargetEnv{
Instance: value(EnvInstance),
Mode: value(EnvIngressMode),
IngressURL: value(EnvIngressURL),
IngressService: value(EnvIngressService),
IngressDrainFile: value(EnvIngressDrainFile),
HealthURL: value(EnvHealthURL),
RedisAddr: value(EnvRedisAddr),
// 口令不 Trim:前后空格也是口令的一部分,Trim 会把能连上的配置变成连不上。
RedisPassword: get(EnvRedisAuth),
}
missing := make([]string, 0, 5)
for _, item := range []struct {
if target.Mode == "" {
target.Mode = libraryfreeze.IngressModeGate
}
switch target.Mode {
case libraryfreeze.IngressModeGate:
target.Ack = ""
case libraryfreeze.IngressModeNone:
// 确认串逐字符相等:不 Trim、不忽略大小写。没写对就是没确认。
ack := get(EnvNoIngressAck)
if ack != libraryfreeze.NoIngressAck {
return TargetEnv{}, fmt.Errorf(
"no-gate 维护必须显式确认:%s 必须逐字符等于 %s(当前%s),拒绝开窗口",
EnvNoIngressAck, libraryfreeze.NoIngressAck, describeAck(ack))
}
target.Ack = ack
// 半套闸门声明最危险:既关不掉门,又容易被当成"有门"。要么有,要么明确没有。
if target.IngressURL != "" || target.IngressService != "" || target.IngressDrainFile != "" {
return TargetEnv{}, fmt.Errorf(
"no-gate 维护不得同时声明 %s/%s/%s:要么有闸门,要么明确没有",
EnvIngressURL, EnvIngressService, EnvIngressDrainFile)
}
default:
return TargetEnv{}, fmt.Errorf("%s 无效(%q):只能是 %s 或 %s",
EnvIngressMode, target.Mode, libraryfreeze.IngressModeGate, libraryfreeze.IngressModeNone)
}
required := []struct {
name string
current string
}{
{EnvInstance, target.Instance},
{EnvIngressURL, target.IngressURL},
{EnvIngressService, target.IngressService},
{EnvIngressDrainFile, target.IngressDrainFile},
{EnvRedisAddr, target.RedisAddr},
} {
}
if target.Mode == libraryfreeze.IngressModeNone {
// 没有闸门可声明:改由健康探针证明"目标真的回来了",它因此是必需的。
required = append(required, struct{ name, current string }{EnvHealthURL, target.HealthURL})
} else {
required = append(required,
struct{ name, current string }{EnvIngressURL, target.IngressURL},
struct{ name, current string }{EnvIngressService, target.IngressService},
struct{ name, current string }{EnvIngressDrainFile, target.IngressDrainFile})
}
missing := make([]string, 0, 5)
for _, item := range required {
if item.current == "" {
missing = append(missing, item.name)
}
@@ -86,8 +134,25 @@ func TargetFromEnv(get func(string) string) (TargetEnv, error) {
target.RedisDB = db
}
if len(missing) > 0 {
return TargetEnv{}, fmt.Errorf("实例级维护未接线:缺少 %s(没有入口闸门与队列就无法证明入口已排空、后台已静默)",
strings.Join(missing, "、"))
hint := "没有入口闸门与队列就无法证明入口已排空、后台已静默"
if target.Mode == libraryfreeze.IngressModeNone {
hint = "no-gate 测试模式仍需要实例、队列与健康探针"
}
return TargetEnv{}, fmt.Errorf("实例级维护未接线:缺少 %s(%s)",
strings.Join(missing, "、"), hint)
}
return target, nil
}
// describeAck 只描述"确认串有没有写对",不回显内容:写错时也可能是一段
// 看起来像凭据的东西,错误信息里没必要复制它。
func describeAck(ack string) string {
switch {
case ack == "":
return "为空"
case strings.TrimSpace(ack) == libraryfreeze.NoIngressAck:
return "含多余空白"
default:
return "取值不匹配"
}
}
@@ -0,0 +1,88 @@
package librarymaintenance
import (
"strings"
"testing"
"knowledge-governance/internal/libraryfreeze"
)
// noGateEnv 是 0.9.0 测试栈的声明:没有闸门,只有实例、队列与健康探针。
func noGateEnv() map[string]string {
return map[string]string{
EnvInstance: "kgmaint-v090",
EnvIngressMode: libraryfreeze.IngressModeNone,
EnvNoIngressAck: libraryfreeze.NoIngressAck,
EnvHealthURL: "http://127.0.0.1:18081/health",
EnvRedisAddr: "127.0.0.1:26379",
EnvRedisAuth: "secret",
EnvRedisDB: "0",
}
}
func TestTargetFromEnvNoGateNeedsExplicitAck(t *testing.T) {
values := noGateEnv()
delete(values, EnvNoIngressAck)
_, err := TargetFromEnv(lookup(values))
if err == nil || !strings.Contains(err.Error(), EnvNoIngressAck) {
t.Fatalf("缺确认串没有被拒并点名:%v", err)
}
for _, ack := range []string{"", "test_only", "TEST-ONLY", " test-only", "test-only "} {
values := noGateEnv()
values[EnvNoIngressAck] = ack
if _, err := TargetFromEnv(lookup(values)); err == nil || !strings.Contains(err.Error(), EnvNoIngressAck) {
t.Fatalf("ack=%q 没有被拒:%v", ack, err)
}
}
}
func TestTargetFromEnvNoGateAcceptsMissingIngressItems(t *testing.T) {
target, err := TargetFromEnv(lookup(noGateEnv()))
if err != nil {
t.Fatalf("no-gate 声明被拒:%v", err)
}
if target.Mode != libraryfreeze.IngressModeNone || target.Ack != libraryfreeze.NoIngressAck {
t.Fatalf("入口形态没解析对:%+v", target)
}
if target.IngressURL != "" || target.IngressService != "" || target.IngressDrainFile != "" {
t.Fatalf("no-gate 声明里出现了闸门项:%+v", target)
}
if target.HealthURL != "http://127.0.0.1:18081/health" || target.RedisDB != 0 {
t.Fatalf("健康探针/队列没解析对:%+v", target)
}
}
// 证据降一档不等于什么都不需要:健康探针与队列仍必须给。
func TestTargetFromEnvNoGateStillNeedsHealthAndQueue(t *testing.T) {
for _, name := range []string{EnvInstance, EnvHealthURL, EnvRedisAddr, EnvRedisAuth, EnvRedisDB} {
values := noGateEnv()
delete(values, name)
if _, err := TargetFromEnv(lookup(values)); err == nil || !strings.Contains(err.Error(), name) {
t.Fatalf("缺 %s 没有被点名:%v", name, err)
}
}
}
// 缺省仍是 gate:没有 mode 变量时照旧要求三项闸门声明(原行为不变)。
func TestTargetFromEnvDefaultsToGate(t *testing.T) {
values := completeEnv()
target, err := TargetFromEnv(lookup(values))
if err != nil {
t.Fatalf("gate 声明被拒:%v", err)
}
if target.Mode != libraryfreeze.IngressModeGate || target.Ack != "" {
t.Fatalf("缺省不是 gate:%+v", target)
}
values[EnvIngressURL] = ""
if _, err := TargetFromEnv(lookup(values)); err == nil || !strings.Contains(err.Error(), EnvIngressURL) {
t.Fatalf("gate 模式缺入口没有被拒:%v", err)
}
}
func TestTargetFromEnvRejectsUnknownMode(t *testing.T) {
values := completeEnv()
values[EnvIngressMode] = "open"
if _, err := TargetFromEnv(lookup(values)); err == nil || !strings.Contains(err.Error(), EnvIngressMode) {
t.Fatalf("未知入口形态没有被拒:%v", err)
}
}
+118 -11
View File
@@ -48,14 +48,20 @@ type Config struct {
Writers []string
NonWriters map[string]string
DockerSocket string
IngressURL string
// IngressMode 是 gate(默认)或 none;none 只给整栈没有入口闸门的测试环境用,
// 必须同时给 IngressAck,且一次闸门动作都不做。
IngressMode string
IngressAck string
IngressURL string
// IngressService 是入口闸门在 compose 项目里的服务名;DrainFile 是它写
// 排空证据的宿主机文件。两者缺一,就只能说"停了写入者",不能说"排空了"。
IngressService string
IngressDrainFile string
Database string
Index string
Bucket string
// HealthURL 是 no-gate 模式下唯一的"目标回来了"证据(恢复后必须 200)。
HealthURL string
Database string
Index string
Bucket string
// 后台静默检查需要的运行时依赖(不写进维护记录)。
DatabaseURL string
RedisAddr string
@@ -75,6 +81,9 @@ type Manager struct {
gate *dockerGate
api *dockerAPI
quiescer *targetQuiescer
mode string
ack string
healthURL string
}
// Close 释放拓扑/静默检查持有的连接。
@@ -91,6 +100,11 @@ func New(cfg Config) (*Manager, error) {
instance := strings.TrimSpace(cfg.Instance)
project := strings.TrimSpace(cfg.Project)
ingress := strings.TrimSpace(cfg.IngressURL)
health := strings.TrimSpace(cfg.HealthURL)
mode := strings.TrimSpace(cfg.IngressMode)
if mode == "" {
mode = libraryfreeze.IngressModeGate
}
if instance == "" || project == "" {
return nil, errors.New("实例级维护配置缺少 LIBRARY_TARGET_INSTANCE/PROJECT")
}
@@ -100,9 +114,27 @@ func New(cfg Config) (*Manager, error) {
if !filepath.IsAbs(cfg.DockerSocket) {
return nil, errors.New("Docker socket 必须是绝对路径")
}
parsed, err := url.Parse(ingress)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.Path == "" || parsed.User != nil {
return nil, errors.New("目标入口地址无效(LIBRARY_TARGET_INGRESS_URL)")
switch mode {
case libraryfreeze.IngressModeGate:
parsed, err := url.Parse(ingress)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.Path == "" || parsed.User != nil {
return nil, errors.New("目标入口地址无效(LIBRARY_TARGET_INGRESS_URL)")
}
case libraryfreeze.IngressModeNone:
// 显式确认是这道口子的唯一开关:没有它,no-gate 一律拒绝。
if cfg.IngressAck != libraryfreeze.NoIngressAck {
return nil, fmt.Errorf("no-gate 维护必须显式确认(LIBRARY_NO_INGRESS_ACK 逐字符等于 %s),拒绝",
libraryfreeze.NoIngressAck)
}
if ingress != "" || cfg.IngressService != "" || cfg.IngressDrainFile != "" {
return nil, errors.New("no-gate 维护不得同时声明入口地址/闸门服务/排空文件:要么有闸门,要么明确没有")
}
if !validHealthURL(health) {
return nil, errors.New("no-gate 维护必须给有效的健康探针(LIBRARY_TARGET_HEALTH_URL)")
}
default:
return nil, fmt.Errorf("LIBRARY_TARGET_INGRESS_MODE 无效(%q):只能是 %s 或 %s",
mode, libraryfreeze.IngressModeGate, libraryfreeze.IngressModeNone)
}
if cfg.Database == "" || cfg.Index == "" || cfg.Bucket == "" {
return nil, errors.New("目标身份不完整:需要数据库/索引/存储桶")
@@ -125,8 +157,9 @@ func New(cfg Config) (*Manager, error) {
}
manager := &Manager{target: target, source: project, docker: cfg.DockerSocket,
writers: writers, nonWriters: cfg.NonWriters, timeout: cfg.Timeout,
client: &http.Client{Timeout: 5 * time.Second}, api: api}
if cfg.IngressService != "" || cfg.IngressDrainFile != "" {
client: &http.Client{Timeout: 5 * time.Second}, api: api,
mode: mode, ack: cfg.IngressAck, healthURL: health}
if mode == libraryfreeze.IngressModeGate && (cfg.IngressService != "" || cfg.IngressDrainFile != "") {
gate, err := newDockerGate(cfg.DockerSocket, project, cfg.IngressService, cfg.IngressDrainFile, cfg.Timeout)
if err != nil {
return nil, err
@@ -168,8 +201,12 @@ func (m *Manager) Target() Target { return m.target }
// Description 是写进维护记录的一句话身份,含指纹,便于事后核对"当时动的是谁"。
func (m *Manager) Description() string {
t := m.target
ingress := t.Ingress
if m.mode == libraryfreeze.IngressModeNone {
ingress = "none(test-only)"
}
return fmt.Sprintf("level=%s instance=%s project=%s writers=%s ingress=%s db=%s index=%s bucket=%s fingerprint=%s",
t.Level, t.Instance, t.Project, strings.Join(t.Writers, "+"), t.Ingress, t.Database, t.Index, t.Bucket, t.Fingerprint)
t.Level, t.Instance, t.Project, strings.Join(t.Writers, "+"), ingress, t.Database, t.Index, t.Bucket, t.Fingerprint)
}
// Open 返回绑定到该目标的协调器与控制器。调用方负责 Close。
@@ -183,7 +220,23 @@ func (m *Manager) Open(root string) (*libraryfreeze.Coordinator, *libraryfreeze.
control.Close()
return nil, nil, err
}
if err := coordinator.SetTarget(LevelInstance, m.target.Ingress, m.ingressClosed, m.ingressReady); err != nil {
// 入口形态必须在绑定目标之前声明:default 是 gate,只有显式 no-gate 才降档。
if err := coordinator.SetIngressMode(m.mode, m.ack); err != nil {
coordinator.Close()
control.Close()
return nil, nil, err
}
closed, ready := m.ingressClosed, m.ingressReady
if m.mode == libraryfreeze.IngressModeNone {
// 没有闸门:不声明任何入口关闭探针,恢复证据改由健康探针承担。
closed, ready = nil, m.healthReady
if err := coordinator.SetHealthURL(m.healthURL); err != nil {
coordinator.Close()
control.Close()
return nil, nil, err
}
}
if err := coordinator.SetTarget(LevelInstance, m.target.Ingress, closed, ready); err != nil {
coordinator.Close()
control.Close()
return nil, nil, err
@@ -239,7 +292,11 @@ func (m *Manager) serviceOf(id string) string {
}
// VerifyRunning 确认目标入口真的在服务(部署与恢复后都要看,不看容器状态)。
// no-gate 栈没有入口:用健康探针回答"目标回来了没有"。
func (m *Manager) VerifyRunning(ctx context.Context) error {
if m.mode == libraryfreeze.IngressModeNone {
return m.healthReady(ctx)
}
return m.ingressReady(ctx)
}
@@ -308,6 +365,47 @@ func (m *Manager) ingressReady(ctx context.Context) error {
}
}
// healthReady 是 no-gate 栈的恢复判据:健康探针返回 200 才算"目标真的回来了"。
// 和入口探针同一条规则——不看容器状态、不看 HTTP 5xx 的"像活着"。
func (m *Manager) healthReady(ctx context.Context) error {
deadline := time.Now().Add(m.timeout)
var last error
for {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.healthURL, nil)
if err != nil {
return err
}
// 探针不能留下 keep-alive 连接:那会让"排空"永远等不到。
req.Close = true
resp, err := m.client.Do(req)
if err == nil {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return nil
}
last = fmt.Errorf("健康探针返回 HTTP %d:%s", resp.StatusCode, strings.TrimSpace(string(body)))
} else {
last = err
}
if time.Now().After(deadline) {
return fmt.Errorf("目标健康探针没有恢复:%w", last)
}
select {
case <-ctx.Done():
return last
case <-time.After(500 * time.Millisecond):
}
}
}
// validHealthURL 是健康探针地址的本地校验:http(s)、有主机、不带凭据。
func validHealthURL(raw string) bool {
parsed, err := url.Parse(strings.TrimSpace(raw))
return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") &&
parsed.Host != "" && parsed.User == nil
}
// DatabaseIdentity 把连接串收敛成"host:port/db"这种可以写进维护记录的身份:
// 维护记录里不落库凭据,但必须能说清动的是哪个库。
func DatabaseIdentity(raw string) (string, error) {
@@ -354,12 +452,21 @@ func (m *Manager) VerifyTopology(ctx context.Context) error {
if err != nil {
return err
}
// no-gate 栈没有闸门可绕:写入者发布端口是它的正常对外形态,
// "绕闸直连"这条判据在这里不成立(有闸门时才必须唯一入口)。
if m.mode == libraryfreeze.IngressModeNone {
continue
}
if ports := state.publishedPorts(); len(ports) > 0 {
return fmt.Errorf("写入者 %s 直接发布了端口 %s:存在绕开入口闸门的直连通道,拒绝开维护窗口",
writer, strings.Join(ports, ","))
}
}
if m.gate == nil {
if m.mode == libraryfreeze.IngressModeNone {
// 没有闸门可核验端口归属:拓扑检查到此为止,证据降档由维护记录承担。
return nil
}
return errors.New("实例级维护必须声明入口闸门")
}
for _, writer := range m.writers {
+214
View File
@@ -0,0 +1,214 @@
// Package libraryprofile 声明"某个 WeKnora schema 版本下,整库适配器可以依赖什么"。
//
// 为什么要有这一层:整库导出/导入原本把 `version != 74` 写死在四个入口里。
// 版本号本身不是契约——同一版本号在不同部署上也可能缺表;反过来,把判定放宽成
// `version > 74` 又会把"没见过的版本"当成"兼容"。所以这里同时声明两件事:
// - 该版本必须存在的表与列(导出/导入按它取数);
// - 该版本的归档部件集合(manifest 按它判定完整性)。
//
// 版本号只用来**选中** profile,真正的放行条件是随后对 information_schema 的
// 能力探测(见 releaseadapter 的 ResolveSchemaProfile)。
package libraryprofile
import "fmt"
// LegacyVersion 是 0.7.1 的 schema_migrations 版本号,也是既有内存夹具的默认值。
const LegacyVersion = 74
// V090Version 是 0.9.0 的 schema_migrations 版本号(已实测:134、dirty=false、83 表)。
const V090Version = 134
// PartRequirement 是归档部件的一项要求(kind/name 与 manifest 的部件键一致)。
type PartRequirement struct {
Kind string
Name string
}
// Profile 是一个 schema 版本的静态能力声明。
type Profile struct {
Name string
SchemaVersion int
WeKnoraVersion string
// EmbeddingDimension 为 0 表示"由目标 models.parameters 说了算";
// 非 0 表示该版本只接受这一定维度(0.7.1 的契约就是固定 1024)。
EmbeddingDimension int
RequiredTables []string
OptionalTables []string
RequiredColumns map[string][]string
// ReviewedTriggers 是该版本允许出现的 pg_get_triggerdef 原文。
// 触发器意味着"写一行还会改别的表",所以只接受逐字核对过的定义,
// 且这些定义必须在该版本上真实存在(消失也说明 schema 不是我们审过的那份)。
ReviewedTriggers []string
RequiredParts []PartRequirement
OptionalParts []PartRequirement
// IndexContractSource 说明该版本的索引名从哪里读。空值等于"读不到",
// 不允许回退成空串去匹配任何索引。
IndexContractSource string
// IndexTenantField 表示该版本的索引文档带 tenant_id。0.9.0 的分块文档只有
// knowledge_base_id,写索引时补 tenant_id 会与目标实际文档不一致。
IndexTenantField bool
}
var profiles = map[int]Profile{
LegacyVersion: {
Name: "v071",
SchemaVersion: LegacyVersion,
WeKnoraVersion: "v0.7.1",
EmbeddingDimension: 1024,
RequiredTables: []string{
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
"wiki_page_issues", "wiki_log_entries",
},
RequiredColumns: map[string][]string{
"knowledges": {"id", "tenant_id", "knowledge_base_id", "deleted_at", "parse_status"},
"chunks": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "content"},
"knowledge_tags": {"id", "tenant_id", "knowledge_base_id"},
"knowledge_tag_relations": {"knowledge_id", "tag_id"},
"resources": {"id", "handle", "tenant_id", "physical_path"},
"resource_bindings": {"id", "resource_id", "tenant_id", "owner_type", "owner_id"},
"wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"},
"wiki_folders": {"id", "tenant_id", "knowledge_base_id"},
"wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"},
"wiki_log_entries": {"id", "tenant_id", "knowledge_base_id"},
},
RequiredParts: []PartRequirement{
{"database", "knowledges"}, {"database", "chunks"},
{"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"},
{"database", "resources"}, {"database", "resource_bindings"},
{"wiki", "wiki_folders"}, {"wiki", "wiki_pages"},
{"wiki", "wiki_page_issues"}, {"wiki", "wiki_log_entries"},
{"index", "chunks"},
},
IndexContractSource: "vector_stores.index_config.index_name",
IndexTenantField: true,
},
V090Version: {
Name: "v090",
SchemaVersion: V090Version,
WeKnoraVersion: "v0.9.0",
// 0.9.0 的 KB 不写 vector_store_id,维度只能从 models.parameters 读。
EmbeddingDimension: 0,
RequiredTables: []string{
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
"wiki_page_issues",
},
// 0.9.0 删掉了 wiki_log_entries;部件集合随之为空,不许假装还有。
OptionalTables: []string{"wiki_log_entries"},
RequiredColumns: map[string][]string{
"knowledges": {"id", "tenant_id", "knowledge_base_id", "deleted_at", "parse_status"},
"chunks": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "content", "seq_id", "content_revision", "index_status"},
"knowledge_tags": {"id", "tenant_id", "knowledge_base_id"},
"knowledge_tag_relations": {"knowledge_id", "tag_id"},
"resources": {"id", "handle", "tenant_id", "physical_path"},
"resource_bindings": {"id", "resource_id", "tenant_id", "owner_type", "owner_id"},
"wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"},
"wiki_folders": {"id", "tenant_id", "knowledge_base_id"},
"wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"},
},
RequiredParts: []PartRequirement{
{"database", "knowledges"}, {"database", "chunks"},
{"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"},
{"database", "resources"}, {"database", "resource_bindings"},
{"wiki", "wiki_folders"}, {"wiki", "wiki_pages"}, {"wiki", "wiki_page_issues"},
{"index", "chunks"},
},
OptionalParts: []PartRequirement{
{"wiki", "wiki_log_entries"},
},
// 0.9.0 的索引名来自部署配置(ELASTICSEARCH_INDEX),不是 vector_stores。
// 0.9.0 在 chunks 上挂了图片同步触发器(仅当 image_info 以 '[' 开头时触发),
// 它维护 chunk_images 派生表;定义逐字核对,任何改动都拒绝。
ReviewedTriggers: []string{
`CREATE TRIGGER trg_chunk_images_delete AFTER DELETE ON public.chunks FOR EACH ROW WHEN ((old.image_info ~~ '[%'::text)) EXECUTE FUNCTION chunk_images_sync()`,
`CREATE TRIGGER trg_chunk_images_insert AFTER INSERT ON public.chunks FOR EACH ROW WHEN ((new.image_info ~~ '[%'::text)) EXECUTE FUNCTION chunk_images_sync()`,
`CREATE TRIGGER trg_chunk_images_update AFTER UPDATE ON public.chunks FOR EACH ROW WHEN ((((old.image_info ~~ '[%'::text) OR (new.image_info ~~ '[%'::text)) AND ((old.image_info IS DISTINCT FROM new.image_info) OR (old.is_enabled IS DISTINCT FROM new.is_enabled) OR (old.status IS DISTINCT FROM new.status) OR (old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.tenant_id IS DISTINCT FROM new.tenant_id) OR ((old.knowledge_base_id)::text IS DISTINCT FROM (new.knowledge_base_id)::text) OR ((old.knowledge_id)::text IS DISTINCT FROM (new.knowledge_id)::text) OR ((old.chunk_type)::text IS DISTINCT FROM (new.chunk_type)::text) OR (old.created_at IS DISTINCT FROM new.created_at) OR (old.updated_at IS DISTINCT FROM new.updated_at)))) EXECUTE FUNCTION chunk_images_sync()`,
},
IndexContractSource: "config ELASTICSEARCH_INDEX",
IndexTenantField: false,
},
}
// For 按版本号选中 profile。未知版本一律失败:版本号是"选哪份声明"的索引,
// 不是"能不能放行"的依据,所以绝不返回默认 profile。
func For(version int) (Profile, error) {
profile, ok := profiles[version]
if !ok {
return Profile{}, fmt.Errorf("unsupported WeKnora schema version %d: supported profiles are 74 (v071) and 134 (v090)", version)
}
return profile, nil
}
// Supported 返回已声明 profile 的版本号(用于文档与错误信息,不用于放行)。
func Supported() []int {
return []int{LegacyVersion, V090Version}
}
// TableSet 是"可能出现的表"集合:必需表 + 可选表。
func (p Profile) TableSet() map[string]bool {
set := make(map[string]bool, len(p.RequiredTables)+len(p.OptionalTables))
for _, name := range p.RequiredTables {
set[name] = true
}
for _, name := range p.OptionalTables {
set[name] = true
}
return set
}
// HasTable 报告某张表是否属于该 profile(必需或可选)。
func (p Profile) HasTable(name string) bool {
return p.TableSet()[name]
}
// IsRequiredTable 报告某张表是否必需存在。
func (p Profile) IsRequiredTable(name string) bool {
for _, candidate := range p.RequiredTables {
if candidate == name {
return true
}
}
return false
}
// PartKeys 返回 (必需, 可选) 的归档部件键,形如 "wiki/wiki_log_entries"。
func (p Profile) PartKeys() ([]string, []string) {
key := func(part PartRequirement) string { return part.Kind + "/" + part.Name }
required := make([]string, 0, len(p.RequiredParts))
for _, part := range p.RequiredParts {
required = append(required, key(part))
}
optional := make([]string, 0, len(p.OptionalParts))
for _, part := range p.OptionalParts {
optional = append(optional, key(part))
}
return required, optional
}
// RequiresPart 报告某部件键是否必需(可选部件返回 false)。
func (p Profile) RequiresPart(key string) bool {
required, _ := p.PartKeys()
for _, candidate := range required {
if candidate == key {
return true
}
}
return false
}
// AllowsPart 报告某部件键是否至少允许出现。
func (p Profile) AllowsPart(key string) bool {
required, optional := p.PartKeys()
for _, candidate := range required {
if candidate == key {
return true
}
}
for _, candidate := range optional {
if candidate == key {
return true
}
}
return false
}
+17 -1
View File
@@ -98,7 +98,10 @@ type WriteSet struct {
// Kind 区分发布执行计划与受限演练恢复计划。空值 = 历史发布计划。
// 演练计划必须显式为 restore-drill:它只授权 canary 回放,不含对象/索引
// 写项,读取方不能把它当发布计划接管。
Kind string `json:"kind,omitempty"`
Kind string `json:"kind,omitempty"`
// TargetIDMode 记录这份计划是否把源身份映射成目标隔离身份,以及用哪套算法。
// 空值 = 历史计划/写前镜像:按原 ID 回放,绝不能在恢复时二次映射。
TargetIDMode string `json:"target_id_mode,omitempty"`
Index []IndexWrite `json:"index,omitempty"`
Objects []ObjectWrite `json:"objects,omitempty"`
SchemaDigest string `json:"schema_digest,omitempty"`
@@ -203,7 +206,20 @@ func (w *WriteSet) computeDigest() (string, error) {
// Verify 校验摘要与必备身份。缺任一身份都必须失败:没有绑定就没有"这份记录属于
// 这个作业/目标/预备份"的证明,拿它去删目标数据无法追责。
const (
// TargetIDModeScoped 是目标隔离身份的持久契约标识。
// 算法是自定义的 sha256(namespace|tenant|kb|table|source) 16 字节派生,
// 只保证确定性与隔离,不自称标准 UUIDv5。
TargetIDModeScoped = "scoped-sha256-v1"
)
func (w *WriteSet) Verify() error {
if w.TargetIDMode != "" && w.TargetIDMode != TargetIDModeScoped {
return fmt.Errorf("unsupported target id mode %q", w.TargetIDMode)
}
if w.TargetIDMode == TargetIDModeScoped && (w.TenantID == 0 || w.KnowledgeBaseID == "") {
return errors.New("target id mode lacks target identity")
}
if w.ContractVersion != 0 && w.ContractVersion != 1 {
return errors.New("unsupported migration contract version")
}
+14 -9
View File
@@ -10,7 +10,7 @@ import (
"encoding/json"
"errors"
"io"
"knowledge-governance/internal/releasebundle"
"knowledge-governance/internal/libraryprofile"
"math"
"os"
"path/filepath"
@@ -420,24 +420,29 @@ func encodeManifest(m Manifest) ([]byte, error) {
return nil, errors.New("unsupported snapshot validation policy")
}
c := m.Compatibility
if c.WeKnoraVersion != releasebundle.WeKnoraVersionV071 || c.SchemaVersion != releasebundle.WeKnoraMigrationV071 || c.RetrieverEngine != "elasticsearch_v8" || !identifier(c.EmbeddingModel) || c.EmbeddingDimension != releasebundle.EmbeddingDimensionV071 || !validDigest(c.IndexMappingSHA256) {
// 兼容性按 schema 版本选 profile,而不是钉死 v0.7.1:未知版本必须拒绝,
// 已知版本还必须与自己的版本字符串、索引引擎、维度声明一致。
profile, err := libraryprofile.For(c.SchemaVersion)
if err != nil || c.WeKnoraVersion != profile.WeKnoraVersion || c.RetrieverEngine != "elasticsearch_v8" ||
!identifier(c.EmbeddingModel) || c.EmbeddingDimension < 1 ||
(profile.EmbeddingDimension > 0 && c.EmbeddingDimension != profile.EmbeddingDimension) ||
!validDigest(c.IndexMappingSHA256) {
return nil, errors.New("unsupported snapshot compatibility contract")
}
if m.Format != Format || (m.Scope != "internal" && m.Scope != "external") || m.TenantID == 0 || !identifier(m.KnowledgeBaseID) || m.CreatedAt.IsZero() {
return nil, errors.New("invalid library manifest identity")
}
// 部件集合也来自 profile:0.9.0 的归档没有 wiki_log_entries 部件,
// 但 0.7.1 缺了它就是不完整。
requiredKeys, _ := profile.PartKeys()
required := map[string]bool{}
for _, n := range []string{"knowledges", "chunks", "resources", "resource_bindings", "knowledge_tags", "knowledge_tag_relations"} {
required["database/"+n] = true
for _, key := range requiredKeys {
required[key] = true
}
for _, n := range []string{"wiki_pages", "wiki_folders", "wiki_page_issues", "wiki_log_entries"} {
required["wiki/"+n] = true
}
required["index/chunks"] = true
seen := map[string]bool{}
for _, p := range m.Parts {
key := p.Kind + "/" + p.Name
if (!required[key] && !(p.Kind == "resource" && identifier(p.Name) && p.Count == 1) && !(key == "schema/migration-catalog" && p.Count == 1)) || seen[key] || !validDigest(p.SHA256) || p.Bytes < 0 || p.Count < 0 {
if (!profile.AllowsPart(key) && !(p.Kind == "resource" && identifier(p.Name) && p.Count == 1) && !(key == "schema/migration-catalog" && p.Count == 1)) || seen[key] || !validDigest(p.SHA256) || p.Bytes < 0 || p.Count < 0 {
return nil, errors.New("invalid or nonknowledge snapshot component")
}
seen[key] = true
@@ -0,0 +1,58 @@
package librarysnapshot
import (
"strings"
"testing"
"time"
)
// 归档部件的完整性按 schema 版本判定:0.9.0 没有 wiki_log_entries,
// 0.7.1 缺了它就是残包。这里直接对 manifest 编码做判定,不依赖数据库。
func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
part := func(kind, name string) Part {
return Part{Kind: kind, Name: name, SHA256: strings.Repeat("a", 64), Count: 1}
}
parts := []Part{
part("database", "knowledges"), part("database", "chunks"), part("database", "resources"),
part("database", "resource_bindings"), part("database", "knowledge_tags"),
part("database", "knowledge_tag_relations"),
part("wiki", "wiki_pages"), part("wiki", "wiki_folders"), part("wiki", "wiki_page_issues"),
part("index", "chunks"),
}
manifest := func(version int, weknora string, parts []Part) Manifest {
return Manifest{
ValidationPolicy: ArtifactAcceptancePolicy,
Format: Format,
Scope: "internal",
TenantID: 10000,
KnowledgeBaseID: "kb-v090",
CreatedAt: time.Now().UTC(),
Parts: parts,
Compatibility: Compatibility{
WeKnoraVersion: weknora, SchemaVersion: version,
RetrieverEngine: "elasticsearch_v8", EmbeddingModel: "bge-m3",
EmbeddingDimension: 1024, IndexMappingSHA256: strings.Repeat("b", 64),
},
}
}
if _, err := encodeManifest(manifest(134, "v0.9.0", parts)); err != nil {
t.Fatalf("0.9.0 manifest without wiki_log_entries must be complete: %v", err)
}
if _, err := encodeManifest(manifest(74, "v0.7.1", parts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
t.Fatalf("0.7.1 manifest missing wiki_log_entries must be refused, got %v", err)
}
withLog := append(append([]Part{}, parts...), part("wiki", "wiki_log_entries"))
if _, err := encodeManifest(manifest(74, "v0.7.1", withLog)); err != nil {
t.Fatalf("0.7.1 manifest with wiki_log_entries must pass: %v", err)
}
if _, err := encodeManifest(manifest(134, "v0.9.0", withLog)); err != nil {
t.Fatalf("0.9.0 manifest may still carry an optional wiki_log_entries part: %v", err)
}
if _, err := encodeManifest(manifest(74, "v0.9.0", withLog)); err == nil {
t.Fatal("version string and profile version must agree")
}
if _, err := encodeManifest(manifest(135, "v0.9.0", parts)); err == nil {
t.Fatal("unknown schema version must be refused")
}
}
+19 -5
View File
@@ -19,7 +19,6 @@ import (
"knowledge-governance/internal/librarysnapshot"
"knowledge-governance/internal/objectgateway"
v071 "knowledge-governance/internal/releaseadapter/v071"
"knowledge-governance/internal/releasebundle"
)
// OpenMaintenance 按部署配置装配实例级维护目标;未接线时返回明确原因。
@@ -34,6 +33,9 @@ func OpenMaintenance(config appconfig.Config) (*librarymaintenance.Manager, erro
Writers: config.LibraryTargetWriters,
NonWriters: config.LibraryTargetNonWriters,
DockerSocket: config.LibraryTargetDockerSocket,
IngressMode: config.LibraryTargetIngressMode,
IngressAck: config.LibraryTargetNoIngressAck,
HealthURL: config.LibraryTargetHealthURL,
IngressURL: config.LibraryTargetIngressURL,
IngressService: config.LibraryTargetIngressService,
IngressDrainFile: config.LibraryTargetIngressDrainFile,
@@ -298,10 +300,22 @@ func OpenBaselineStack(ctx context.Context, config appconfig.Config, scope strin
target.Close()
return nil, nil, fmt.Errorf("读取目标 WeKnora schema 版本失败: %w", err)
}
if dirty || schemaVersion != releasebundle.WeKnoraMigrationV071 {
if dirty {
target.Close()
return nil, nil, fmt.Errorf("目标 schema 版本 %d(dirty=%v)与受支持的 %d 不一致,拒绝建基线",
schemaVersion, dirty, releasebundle.WeKnoraMigrationV071)
return nil, nil, fmt.Errorf("目标 schema 版本 %d 处于 dirty 状态,拒绝建基线", schemaVersion)
}
// 契约按目标库自己的 schema 解析,而不是写死 74:0.9.0 的 schema 是 134,
// 它的表集合、索引来源与 Wiki 部件都和 0.7.1 不同,用 74 的常量建基线
// 会把另一套栈的记录写进权威版本。
profile, err := v071.ResolveSchemaProfile(ctx, target.Pool(), "baseline contract")
if err != nil {
target.Close()
return nil, nil, fmt.Errorf("解析目标 schema profile 失败: %w", err)
}
if profile.SchemaVersion != schemaVersion {
target.Close()
return nil, nil, fmt.Errorf("目标 schema 版本 %d 与解析出的 profile %s(%d)不一致,拒绝建基线",
schemaVersion, profile.Name, profile.SchemaVersion)
}
embeddingModel := config.LibraryEmbeddingModel
embeddingDimension := config.LibraryEmbeddingDimension
@@ -333,7 +347,7 @@ WHERE kb.id = $1 AND kb.deleted_at IS NULL`, scopeCfg.target.KnowledgeBaseID).Sc
return nil, nil, fmt.Errorf("读取目标 embedding 模型绑定失败: %w", err)
}
contract := librarysnapshot.Compatibility{
WeKnoraVersion: releasebundle.WeKnoraVersionV071,
WeKnoraVersion: profile.WeKnoraVersion,
SchemaVersion: schemaVersion,
RetrieverEngine: "elasticsearch_v8",
EmbeddingModel: embeddingModel,
+5 -2
View File
@@ -177,10 +177,13 @@ func (provider *RealProvider) weKnoraProbe(ctx context.Context, now time.Time) g
return provider.track(classify("weknora", "WeKnora API", false, true, ProbeOutcome{ObservedAt: now}))
}
outcome := provider.httpProbeOutcome(ctx, baseURL, now)
probeTarget := ""
if outcome.Reachability == nil && provider.weknoraReadiness != nil {
outcome.WorkReadiness = provider.weknoraReadiness(ctx)
probeTarget, outcome.WorkReadiness = provider.weknoraReadiness(ctx)
}
return provider.track(classify("weknora", "WeKnora API", true, true, outcome))
health := provider.track(classify("weknora", "WeKnora API", true, true, outcome))
health.ProbeTarget = probeTarget
return health
}
// productionWeKnoraProbe reports the real state of the production WeKnora
+29
View File
@@ -12,6 +12,7 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/readiness"
)
func testNow() time.Time { return time.Date(2026, 9, 12, 9, 0, 0, 0, time.UTC) }
@@ -141,3 +142,31 @@ func TestOverallReadinessTreatsProductionEndpointAsAdvisory(t *testing.T) {
t.Fatalf("real dependency failure must still block: ok=%v blocked=%v", ok, blocked)
}
}
// F13: 旧 env 绑定 404 是「业务就绪被阻断」,不是「服务不可达」;
// 同时必须把脱敏后的探测对象带出来,否则红灯无法归因。
func TestWeKnoraReadinessReportsBindingBlockWithoutLosingLiveness(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
}))
defer server.Close()
provider := &RealProvider{
httpClient: server.Client(),
weknoraBaseURL: server.URL,
health: newHealthTracker(),
weknoraReadiness: func(context.Context) (string, error) {
target := "实例 weknora.test · 知识库 1b52c140"
return target, fmt.Errorf("%w(%s)", readiness.ErrKnowledgeBaseMissing, target)
},
}
health := provider.weKnoraProbe(context.Background(), testNow())
if health.Liveness != LiveUp || health.Readiness != ReadBlocked {
t.Fatalf("404 binding = %+v, want up/blocked", health)
}
if health.ProbeTarget != "实例 weknora.test · 知识库 1b52c140" {
t.Fatalf("probe target = %q", health.ProbeTarget)
}
if !strings.Contains(health.Reason, "1b52c140") || strings.Contains(health.Reason, "1b52c140-2e18-4676-afc5-4c7d8d190a8c") {
t.Fatalf("reason = %q, want short target only", health.Reason)
}
}
+4 -4
View File
@@ -44,9 +44,9 @@ type RealProviderConfig struct {
// place operators configure it — and the env value above stays the
// bootstrap fallback for containers that were wired before the UI existed.
ProductionWeKnoraResolver func(ctx context.Context) string
// WeKnoraReadiness optionally exercises a real read against a routing
// knowledge base (nil = API key not configured; liveness-only).
WeKnoraReadiness func(ctx context.Context) error
// WeKnoraReadiness optionally exercises a real read against the CURRENT
// routing binding and reports the sanitized probe target alongside the error.
WeKnoraReadiness func(ctx context.Context) (target string, err error)
// WorkerStaleAfter bounds how long a missing worker heartbeat still counts
// as alive (P10).
WorkerStaleAfter time.Duration
@@ -61,7 +61,7 @@ type RealProvider struct {
testWeKnoraResolver func(ctx context.Context) string
productionWeKnoraBaseURL string
productionWeKnoraResolver func(ctx context.Context) string
weknoraReadiness func(ctx context.Context) error
weknoraReadiness func(ctx context.Context) (string, error)
workerStaleAfter time.Duration
health *healthTracker
}
+4
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"github.com/jackc/pgx/v5"
"log"
"math"
)
@@ -39,6 +40,9 @@ func (g *Gateway) Acquire(ctx context.Context, c Claim) (Grant, error) {
return Grant{}, e
}
if plan.Digest != c.PlanDigest || plan.Owner != Digest([]byte(c.JobID)) {
// 冲突原因要能在服务端日志里定位:是谁的 plan、对不上哪一项。
log.Printf("gateway acquire conflict job=%s op=%s plan=%s claim=%s owner_ok=%t",
c.JobID, c.OperationID, plan.Digest, c.PlanDigest, plan.Owner == Digest([]byte(c.JobID)))
return Grant{}, ErrConflict
}
if e = g.InstallPlan(ctx, plan); e != nil {
@@ -24,7 +24,7 @@ func TestGatewayAcquisitionPersistsAttemptDelivery(t *testing.T) {
expected := g.Grant{Epoch: 1, Owner: g.Digest([]byte(claim.JobID)), Plan: claim.PlanDigest}
req := request("acquired-object", expected)
authority := &currentPlanAuthority{claim, planFor(expected, req)}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20, Authority: authority}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20, Authority: authority}
grant, e := gateway.Acquire(ctx, claim)
if e != nil || grant != expected {
t.Fatal("anchored active attempt grant unavailable", e)
@@ -79,7 +79,7 @@ func TestGatewayAcquisitionCannotHandOverUnknownSend(t *testing.T) {
req := request("acquire-held", expected)
body := []byte("gateway fixture acquire-held")
authority := &currentPlanAuthority{claim, planFor(expected, req)}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20, Authority: authority}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20, Authority: authority}
if _, e := gateway.Acquire(ctx, claim); e != nil {
t.Fatal(e)
}
@@ -0,0 +1,26 @@
package objectgateway
import (
"encoding/json"
"time"
)
// Attestation is the retired whole-bucket exclusive-writer evidence format.
// It is kept only so historical audit artifacts remain readable; no runtime
// path loads, verifies or requires it. Admission is the journal, the backend
// capability and the frozen plan, all of which work on a shared bucket.
type Attestation struct {
Protocol string `json:"protocol"`
Scope string `json:"scope"`
GatewayID string `json:"gateway_id"`
IssuedAt time.Time `json:"issued_at"`
ExpiresAt time.Time `json:"expires_at"`
WriterInventory string `json:"writer_inventory_sha256"`
PolicyEvidence string `json:"policy_evidence_sha256"`
DenialEvidence string `json:"denial_evidence_sha256"`
DrainEvidence string `json:"drain_evidence_sha256"`
}
type SignedAttestation struct {
Payload json.RawMessage `json:"payload"`
Signature []byte `json:"signature"`
}
-57
View File
@@ -1,57 +0,0 @@
package objectgateway
import (
"context"
"crypto/ed25519"
"encoding/json"
"os"
"time"
)
// Attestation is issued by an independent deployment auditor, never by a worker.
// Its signature authenticates an audit, not the truth of self-reported config.
// Runtime cutover must invalidate/replace the audit whenever writer rights change.
type Attestation struct {
Protocol string `json:"protocol"`
Scope string `json:"scope"`
GatewayID string `json:"gateway_id"`
IssuedAt time.Time `json:"issued_at"`
ExpiresAt time.Time `json:"expires_at"`
WriterInventory string `json:"writer_inventory_sha256"`
PolicyEvidence string `json:"policy_evidence_sha256"`
DenialEvidence string `json:"denial_evidence_sha256"`
DrainEvidence string `json:"drain_evidence_sha256"`
}
type SignedAttestation struct {
Payload json.RawMessage `json:"payload"`
Signature []byte `json:"signature"`
}
type AuditVerifier struct {
Path string
PublicKey ed25519.PublicKey
Scope, GatewayID string
}
func (v AuditVerifier) Verify(ctx context.Context) error {
if ctx.Err() != nil {
return ErrIsolation
}
st, e := os.Lstat(v.Path)
if e != nil || !st.Mode().IsRegular() || st.Size() > 16384 || st.Mode().Perm()&0022 != 0 {
return ErrIsolation
}
raw, e := os.ReadFile(v.Path)
if e != nil {
return ErrIsolation
}
var signed SignedAttestation
var a Attestation
if json.Unmarshal(raw, &signed) != nil || len(v.PublicKey) != ed25519.PublicKeySize || !ed25519.Verify(v.PublicKey, signed.Payload, signed.Signature) || json.Unmarshal(signed.Payload, &a) != nil {
return ErrIsolation
}
now := time.Now()
if a.Protocol != Protocol || a.Scope != v.Scope || a.GatewayID != v.GatewayID || a.GatewayID == "" || a.IssuedAt.After(now) || !a.ExpiresAt.After(now) || a.ExpiresAt.Sub(a.IssuedAt) > time.Hour || !validHash(a.WriterInventory) || !validHash(a.PolicyEvidence) || !validHash(a.DenialEvidence) || !validHash(a.DrainEvidence) {
return ErrIsolation
}
return nil
}
-59
View File
@@ -1,59 +0,0 @@
package objectgateway_test
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/json"
g "knowledge-governance/internal/objectgateway"
"os"
"path/filepath"
"testing"
"time"
)
func TestGatewayAuditCannotBeConfigurationBoolean(t *testing.T) {
pub, priv, e := ed25519.GenerateKey(rand.Reader)
if e != nil {
t.Fatal(e)
}
dir := t.TempDir()
path := filepath.Join(dir, "audit.json")
verifier := g.AuditVerifier{Path: path, PublicKey: pub, Scope: "target", GatewayID: "gateway"}
if verifier.Verify(context.Background()) == nil {
t.Fatal("missing audit accepted")
}
if os.WriteFile(path, []byte(`{"isolated":true,"ready":true}`), 0600) != nil {
t.Fatal("fixture")
}
if verifier.Verify(context.Background()) == nil {
t.Fatal("boolean accepted as isolation proof")
}
a := g.Attestation{Protocol: g.Protocol, Scope: "target", GatewayID: "gateway", IssuedAt: time.Now().Add(-time.Minute), ExpiresAt: time.Now().Add(30 * time.Minute), WriterInventory: g.Digest([]byte("inventory")), PolicyEvidence: g.Digest([]byte("policy")), DenialEvidence: g.Digest([]byte("denials")), DrainEvidence: g.Digest([]byte("drain"))}
write := func(v g.Attestation) {
t.Helper()
raw, _ := json.Marshal(v)
signed, _ := json.Marshal(g.SignedAttestation{Payload: raw, Signature: ed25519.Sign(priv, raw)})
if os.WriteFile(path, signed, 0600) != nil {
t.Fatal("fixture")
}
}
write(a)
if verifier.Verify(context.Background()) != nil {
t.Fatal("valid test auditor signature rejected")
}
for _, mutate := range []func(*g.Attestation){func(v *g.Attestation) { v.Scope = "other" }, func(v *g.Attestation) { v.GatewayID = "other" }, func(v *g.Attestation) { v.ExpiresAt = time.Now().Add(-time.Second) }, func(v *g.Attestation) { v.DenialEvidence = "" }, func(v *g.Attestation) { v.IssuedAt = time.Now().Add(time.Hour) }, func(v *g.Attestation) { v.ExpiresAt = time.Now().Add(24 * time.Hour) }} {
bad := a
mutate(&bad)
write(bad)
if verifier.Verify(context.Background()) == nil {
t.Fatal("invalid isolation audit accepted")
}
}
write(a)
other, _, _ := ed25519.GenerateKey(rand.Reader)
verifier.PublicKey = other
if verifier.Verify(context.Background()) == nil {
t.Fatal("untrusted signer accepted")
}
}
+43
View File
@@ -0,0 +1,43 @@
package objectgateway
import "context"
// sendCreate performs exactly one non-retried versioned PUT and then confirms
// the result. Versioned object stores do not provide atomic create-if-absent,
// so the confirmation re-reads the current version to make sure this request's
// version is still the one a reader would observe.
func sendCreate(ctx context.Context, b Backend, r Request, body []byte) (Version, error) {
v, err := b.Put(ctx, r.Key, body, r.token())
if err != nil {
// Unknown outcome: the intent stays unresolved, nothing is retried and
// nothing is deleted because no version id is confirmed.
return Version{}, ErrHeld
}
return confirmCreate(ctx, b, r, v)
}
// confirmCreate binds the receipt to a version that is both the exact version
// this request wrote and the current version of the key. It is read-only: the
// create intent is already committed, so withdrawing a version here would be an
// unrecorded mutation with no delete intent or receipt and would leave the
// create intent permanently held. A concurrent writer that produced a newer
// current version therefore wins by explicit conflict; both versions stay in
// the store and an operator resolves the key with evidence.
func confirmCreate(ctx context.Context, b Backend, r Request, v Version) (Version, error) {
exact, exists, err := b.Observe(ctx, r.Key, v.ID)
if err != nil || !exists || !r.matches(exact) || v != exact {
return Version{}, ErrHeld
}
latest, current, err := b.Observe(ctx, r.Key, "")
if err != nil || !current {
// Cannot tell whether our write is still current: keep the intent held
// rather than mutating anything on a guess.
return Version{}, ErrHeld
}
if latest.ID != v.ID {
// Another writer owns the current version. Report the conflict and leave
// both versions untouched; this path never merges them automatically.
return Version{}, ErrConflict
}
return v, nil
}
+153
View File
@@ -0,0 +1,153 @@
package objectgateway
import (
"context"
"errors"
"testing"
)
type fakeBackend struct {
byID map[string]Version
latest Version
latestExists bool
latestErr error
putVersion Version
putErr error
putCalls int
deletes []string
deleteErr error
}
func (f *fakeBackend) Ready(context.Context) error { return nil }
func (f *fakeBackend) Observe(_ context.Context, _ string, id string) (Version, bool, error) {
if id == "" {
if f.latestErr != nil {
return Version{}, false, f.latestErr
}
return f.latest, f.latestExists, nil
}
v, ok := f.byID[id]
return v, ok, nil
}
func (f *fakeBackend) List(context.Context, string) ([]Version, error) { return nil, nil }
func (f *fakeBackend) Put(context.Context, string, []byte, string) (Version, error) {
f.putCalls++
if f.putErr != nil {
return Version{}, f.putErr
}
return f.putVersion, nil
}
func (f *fakeBackend) Delete(_ context.Context, _ string, v Version) error {
if f.deleteErr != nil {
return f.deleteErr
}
f.deletes = append(f.deletes, v.ID)
delete(f.byID, v.ID)
return nil
}
func createFixture(t *testing.T) (Request, Version) {
t.Helper()
body := []byte("shared bucket object")
grant := Grant{Epoch: 1, Owner: Digest([]byte("owner")), Plan: Digest([]byte("plan"))}
r := Request{Grant: grant, Operation: Digest([]byte("operation")), Key: "kb/bound/object-1", Action: "create", SHA256: Digest(body), Bytes: int64(len(body))}
v := Version{ID: "version-own", Owner: r.token(), SHA256: r.SHA256, Bytes: r.Bytes, ETag: `"etag-own"`}
return r, v
}
func TestCreateConfirmationDetectsNewerForeignVersionWithoutSideEffects(t *testing.T) {
r, own := createFixture(t)
foreign := Version{ID: "version-foreign", Owner: Digest([]byte("foreign-owner")), SHA256: Digest([]byte("foreign")), Bytes: 7, ETag: `"etag-foreign"`}
f := &fakeBackend{byID: map[string]Version{own.ID: own, foreign.ID: foreign}, latest: foreign, latestExists: true, putVersion: own}
if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrConflict) {
t.Fatalf("concurrent newer version accepted as committed: %v", err)
}
// Confirmation runs after the journal intent exists. Deleting here would be
// an unrecorded mutation with no delete intent/receipt and would strand the
// create intent in held forever, so confirmation must be read-only.
if len(f.deletes) != 0 {
t.Fatalf("confirmation deleted without a delete intent/receipt: %v", f.deletes)
}
if _, ok := f.byID[own.ID]; !ok {
t.Fatal("own version removed without a recorded delete")
}
if _, ok := f.byID[foreign.ID]; !ok {
t.Fatal("foreign version was deleted")
}
}
func TestCreateConfirmationCommitsOnlyWhenOwnVersionIsCurrent(t *testing.T) {
r, own := createFixture(t)
f := &fakeBackend{byID: map[string]Version{own.ID: own}, latest: own, latestExists: true, putVersion: own}
got, err := confirmCreate(context.Background(), f, r, own)
if err != nil || got != own {
t.Fatalf("own current version not committed: %v %v", got, err)
}
if len(f.deletes) != 0 {
t.Fatalf("unexpected rollback %v", f.deletes)
}
}
func TestCreateConfirmationHoldsWithoutDeletingWhenCurrentVersionUnreadable(t *testing.T) {
r, own := createFixture(t)
f := &fakeBackend{byID: map[string]Version{own.ID: own}, putVersion: own, latestErr: errors.New("read failed")}
if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrHeld) {
t.Fatalf("unreadable current version treated as terminal: %v", err)
}
if len(f.deletes) != 0 {
t.Fatalf("deleted on an unknown observation: %v", f.deletes)
}
}
func TestCreateConfirmationHoldsOnExactReadbackMismatch(t *testing.T) {
r, own := createFixture(t)
other := own
other.ETag = `"different"`
f := &fakeBackend{byID: map[string]Version{own.ID: other}, latest: other, latestExists: true, putVersion: own}
if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrHeld) {
t.Fatalf("mismatched readback treated as committed: %v", err)
}
if len(f.deletes) != 0 {
t.Fatalf("deleted on mismatch: %v", f.deletes)
}
}
func TestCreateSendIsSingleAttemptAndNeverDeletesUnknownPut(t *testing.T) {
r, _ := createFixture(t)
f := &fakeBackend{putErr: errors.New("transport lost")}
if _, err := sendCreate(context.Background(), f, r, []byte("shared bucket object")); !errors.Is(err, ErrHeld) {
t.Fatalf("unknown PUT treated as terminal: %v", err)
}
if f.putCalls != 1 {
t.Fatalf("PUT retried: calls=%d", f.putCalls)
}
if len(f.deletes) != 0 {
t.Fatalf("deleted without a confirmed version: %v", f.deletes)
}
}
func TestPlanAuthorizesOnlyFrozenObjectList(t *testing.T) {
body := []byte("planned")
owner, digest := Digest([]byte("owner")), Digest([]byte("plan-digest"))
p := Plan{Digest: digest, Owner: owner, Objects: []ObjectBinding{{Operation: Digest([]byte("op-1")), Key: "kb/allowed/1", SHA256: Digest(body), Bytes: int64(len(body))}}}
allowed := Request{Grant: Grant{1, owner, digest}, Operation: Digest([]byte("op-1")), Key: "kb/allowed/1", Action: "create", SHA256: Digest(body), Bytes: int64(len(body))}
if !p.allows(allowed) {
t.Fatal("frozen object rejected")
}
for name, mutate := range map[string]func(*Request){
"other_kb_key": func(r *Request) { r.Key = "kb/other-kb/1" },
"other_object": func(r *Request) { r.Key = "kb/allowed/2" },
"other_operation": func(r *Request) { r.Operation = Digest([]byte("op-2")) },
} {
got := allowed
mutate(&got)
if p.allows(got) {
t.Fatalf("%s authorized outside the frozen write set", name)
}
}
dup := p
dup.Objects = append(dup.Objects, p.Objects[0])
if dup.valid() {
t.Fatal("duplicate key accepted in plan")
}
}
+17 -10
View File
@@ -20,17 +20,18 @@ type Gateway struct {
Pool *pgxpool.Pool
Scope string
Backend Backend
Isolation IsolationVerifier
MaxBytes int64
}
// Ready gates admission on the local journal and the object backend only. A
// shared bucket is the supported deployment shape: unrelated writers on other
// keys do not need to be drained, and no whole-bucket exclusivity evidence is
// required. Per-key competition is handled at execute time, not by a global
// "only writer" attestation.
func (g *Gateway) Ready(ctx context.Context) error {
if g.Pool == nil || g.Scope == "" || g.Backend == nil || g.MaxBytes < 1 {
return ErrPersistence
}
if g.Isolation == nil || g.Isolation.Verify(ctx) != nil {
return ErrIsolation
}
var sync, fsync, full string
if g.Pool.QueryRow(ctx, "SELECT current_setting('synchronous_commit'), current_setting('fsync'), current_setting('full_page_writes')").Scan(&sync, &fsync, &full) != nil || sync != "on" || fsync != "on" || full != "on" {
return ErrPersistence
@@ -249,13 +250,9 @@ func (g *Gateway) execute(ctx context.Context, r Request, body []byte, authoriza
if exists {
return g.finish(ctx, r, "rejected", Version{})
}
v, err := g.Backend.Put(ctx, r.Key, body, r.token())
v, err := sendCreate(ctx, g.Backend, r, body)
if err != nil {
return Receipt{}, ErrHeld
}
exact, exists, err := g.Backend.Observe(ctx, r.Key, v.ID)
if err != nil || !exists || !r.matches(exact) || v != exact {
return Receipt{}, ErrHeld
return Receipt{}, err
}
return g.finish(ctx, r, "committed", v)
}
@@ -322,5 +319,15 @@ func (g *Gateway) Reconcile(ctx context.Context, r Request) (Receipt, error) {
if err != nil || !exists || exact != found[0] {
return Receipt{}, ErrHeld
}
latest, current, err := g.Backend.Observe(ctx, r.Key, "")
if err != nil || !current {
return Receipt{}, ErrHeld
}
if latest.ID != exact.ID {
// Another writer owns the current version of this key. Do not delete
// anything during reconcile and do not report a committed create for a
// key this plan no longer controls.
return Receipt{}, ErrConflict
}
return g.finish(ctx, r, "committed", exact)
}
@@ -30,9 +30,6 @@ import (
g "knowledge-governance/internal/objectgateway"
)
type verifiedFixture struct{}
func (verifiedFixture) Verify(context.Context) error { return nil }
func fixture(t *testing.T) (context.Context, *pgxpool.Pool, *g.S3Backend) {
t.Helper()
dsn := os.Getenv("KG_GATEWAY_TEST_DATABASE_URL")
@@ -118,7 +115,7 @@ func TestGatewayReadinessRequiresJournal(t *testing.T) {
t.Fatal(e)
}
defer other.Close()
gw := &g.Gateway{Pool: other, Scope: "missing-journal", Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gw := &g.Gateway{Pool: other, Scope: "missing-journal", Backend: backend, MaxBytes: 1 << 20}
if e := gw.Ready(ctx); !errors.Is(e, g.ErrPersistence) {
t.Fatalf("missing durable journal accepted: %v", e)
}
@@ -126,7 +123,7 @@ func TestGatewayReadinessRequiresJournal(t *testing.T) {
func TestGatewayRealReplayAndImmutableLedger(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
if _, exists, err := backend.Observe(ctx, "missing-key-probe", ""); err != nil || exists {
t.Fatalf("initial authoritative absence unavailable: %v exists=%v", err, exists)
}
-2
View File
@@ -239,8 +239,6 @@ func (c *Client) call(ctx context.Context, path string, in, out any) error {
return ErrHeld
case ErrPersistence.Error():
return ErrPersistence
case ErrIsolation.Error():
return ErrIsolation
}
return errors.New("gateway_request_refused")
}
@@ -14,7 +14,7 @@ import (
func TestGatewayTargetIdentityOnEveryCall(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e := gw.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
@@ -10,7 +10,7 @@ func TestGatewayIntentCommitFailureNeverSends(t *testing.T) {
ctx, pool, real := fixture(t)
backend := &stoppedBeforeSend{Backend: real}
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("plan"))}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
@@ -9,7 +9,7 @@ import (
func TestGatewayGrantCannotAuthorizeUnplannedKey(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e := gateway.Advance(ctx, 0, grant); !errors.Is(e, g.ErrConflict) {
t.Fatal("unregistered plan grant", e)
}
-2
View File
@@ -19,7 +19,6 @@ var (
ErrPersistence = errors.New("gateway_persistence_unavailable")
ErrAuthority = errors.New("gateway_control_authority_unavailable")
ErrAuthorityPrivileges = errors.New("gateway_control_reader_privileges_invalid")
ErrIsolation = errors.New("gateway_exclusive_writer_evidence_unverified")
ErrRejected = errors.New("gateway_create_rejected_existing_object")
)
@@ -60,7 +59,6 @@ type Backend interface {
Put(context.Context, string, []byte, string) (Version, error)
Delete(context.Context, string, Version) error
}
type IsolationVerifier interface{ Verify(context.Context) error }
func Digest(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) }
func validHash(s string) bool {
@@ -0,0 +1,114 @@
package objectgateway_test
import (
"bytes"
"net"
"os"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
g "knowledge-governance/internal/objectgateway"
)
// A maintenance update of the target KB runs while the same bucket still
// serves other writers. Publishing planned objects must neither require a
// whole-bucket exclusivity attestation nor disturb an unrelated key or a
// pre-existing object at a planned key. External writes here are made before
// execute (coexistence), not interleaved concurrently with the PUT.
func TestGatewaySharedBucketCoexistenceWithOtherWriters(t *testing.T) {
ctx, pool, backend := fixture(t)
endpoint := os.Getenv("KG_GATEWAY_TEST_ENDPOINT")
scope := g.Digest([]byte("minio\x00" + endpoint + "\x00" + backend.Bucket))
listener, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
addr := listener.Addr().String()
listener.Close()
data, control := g.Digest([]byte("data "+scope)), g.Digest([]byte("control "+scope))
client, e := g.NewClient("http://"+addr, data, scope)
if e != nil {
t.Fatal(e)
}
admin, _ := g.NewClient("http://"+addr, control, scope)
// Deliberately no OBJECT_GATEWAY_AUDIT_FILE / OBJECT_GATEWAY_AUDIT_PUBLIC_KEY:
// the default shared-bucket path must start without whole-bucket evidence.
env := []string{
"PATH=" + os.Getenv("PATH"),
"HOME=" + os.Getenv("HOME"),
"OBJECT_GATEWAY_LISTEN=" + addr,
"OBJECT_GATEWAY_DATABASE_URL=" + os.Getenv("KG_GATEWAY_TEST_DATABASE_URL"),
"OBJECT_GATEWAY_PROVIDER=minio",
"OBJECT_GATEWAY_ENDPOINT=" + endpoint,
"OBJECT_GATEWAY_BUCKET=" + backend.Bucket,
"OBJECT_GATEWAY_REGION=us-east-1",
"OBJECT_GATEWAY_ACCESS_KEY=" + os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"),
"OBJECT_GATEWAY_SECRET_KEY=" + os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"),
"OBJECT_GATEWAY_DATA_TOKEN=" + data,
"OBJECT_GATEWAY_CONTROL_TOKEN=" + control,
}
startGateway(t, env, client)
if e = client.ReadyForAcquisition(ctx); e == nil {
t.Fatal("gateway without control authority advertised automatic grants")
}
// Another service keeps writing unrelated keys during the maintenance window.
externalOwner := g.Digest([]byte("other-service"))
unrelatedKey := "other-service/unrelated-" + g.Digest([]byte(backend.Bucket))[:8]
unrelatedBody := []byte("unrelated service body")
if _, e = backend.Client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(backend.Bucket), Key: aws.String(unrelatedKey), Body: bytes.NewReader(unrelatedBody), Metadata: map[string]string{"kg-release-owner": externalOwner}}); e != nil {
t.Fatalf("external unrelated write failed: %v", e)
}
unrelated, _, e := backend.Observe(ctx, unrelatedKey, "")
if e != nil {
t.Fatal(e)
}
// A planned key already holds a foreign object: the plan must refuse it and
// leave that object byte-identical.
existingKey := "unchanged/existing-object"
existingBody := []byte("pre-existing production content")
if _, e = backend.Client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(backend.Bucket), Key: aws.String(existingKey), Body: bytes.NewReader(existingBody), Metadata: map[string]string{"kg-release-owner": externalOwner}}); e != nil {
t.Fatal(e)
}
existing, _, e := backend.Observe(ctx, existingKey, "")
if e != nil {
t.Fatal(e)
}
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("maintenance-owner")), Plan: g.Digest([]byte("maintenance-plan"))}
fresh := request("shared-fresh", grant)
clash := request("shared-clash", grant)
clash.Key = existingKey
if e = admin.InstallPlan(ctx, planFor(grant, fresh, clash)); e != nil {
t.Fatal(e)
}
if e = admin.Advance(ctx, 0, grant); e != nil {
t.Fatal(e)
}
receipt, e := client.Execute(ctx, fresh, []byte("gateway fixture shared-fresh"))
if e != nil || receipt.State != "committed" {
t.Fatalf("planned create blocked by unrelated writers: %v %s", e, receipt.State)
}
rejected, e := client.Execute(ctx, clash, []byte("gateway fixture shared-clash"))
if e != nil || rejected.State != "rejected" {
t.Fatalf("pre-existing planned key not rejected: %v %s", e, rejected.State)
}
after, exists, e := backend.Observe(ctx, existingKey, "")
if e != nil || !exists || after.ID != existing.ID || after.SHA256 != g.Digest(existingBody) {
t.Fatalf("pre-existing object modified: %v %+v", e, after)
}
still, exists, e := backend.Observe(ctx, unrelatedKey, "")
if e != nil || !exists || still.ID != unrelated.ID {
t.Fatalf("unrelated object disturbed: %v %+v", e, still)
}
// Precise rollback removes only the version this gateway created.
cleanup(t, ctx, &g.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 1 << 20}, receipt)
for key, keep := range map[string]g.Version{existingKey: existing, unrelatedKey: unrelated} {
if e = backend.Delete(ctx, key, keep); e != nil {
t.Fatalf("external fixture cleanup %s: %v", key, e)
}
}
}
@@ -13,7 +13,7 @@ import (
func TestGatewayNewEpochPreservesOriginalSendIdentity(t *testing.T) {
ctx, pool, backend := fixture(t)
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
first := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("takeover-plan"))}
sent, unsent := request("takeover-sent", first), request("takeover-unsent", first)
if e := gateway.InstallPlan(ctx, planFor(first, sent, unsent)); e != nil {
@@ -22,7 +22,7 @@ func TestGatewayAbsenceNeverSettlesUnknown(t *testing.T) {
ctx, pool, real := fixture(t)
backend := &stoppedBeforeSend{Backend: real}
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("plan"))}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
@@ -62,7 +62,7 @@ func TestGatewayReadOnlyPersistenceBlocksSend(t *testing.T) {
t.Fatal(e)
}
defer other.Close()
gateway := &g.Gateway{Pool: other, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: other, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e = gateway.Ready(ctx); !errors.Is(e, g.ErrPersistence) {
t.Fatal("read-only persistence accepted", e)
}
@@ -0,0 +1,236 @@
package postgres
import (
"context"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
)
// F17:取件 verified 后必须沿同一策略/当前绑定自动接续唯一 test.upload。
// 这里用真实隔离 PG 跑 RouteCatalogFiles + MarkArtifactFetched 的真实 SQL 路径。
type autoIngestFixture struct {
t *testing.T
ctx context.Context
pool *pgxpool.Pool
store *Store
now time.Time
connID string
kbID string
}
func newAutoIngestFixture(t *testing.T) *autoIngestFixture {
t.Helper()
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if url == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pool.Close)
if err = ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
now := time.Date(2026, 11, 5, 4, 0, 0, 0, time.UTC)
exec := func(q string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, q, args...); err != nil {
t.Fatalf("%v: %s", err, q)
}
}
exec(`INSERT INTO source_connections (id,source_type,name,enabled) VALUES ('conn-auto','dingtalk','ATOM自动衔接',TRUE)`)
exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at)
VALUES ('snap-auto','conn-auto',repeat('a',64),'fixture',2,1,1,$1)`, now)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ('snap-auto','node-dir',NULL,'folder','常见问题汇总','常见问题汇总',repeat('b',64))`)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ('snap-auto','node-file','node-dir','file','人形常见问题.adoc','常见问题汇总/人形常见问题.adoc',repeat('c',64))`)
exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ('conn-auto','snap-auto',$1)`, now)
exec(`INSERT INTO routing_kb_bindings (id,internal_kb_id,external_kb_id,updated_by) VALUES ('active','kb-current','kb-ext', 'fixture')
ON CONFLICT (id) DO UPDATE SET internal_kb_id='kb-current',external_kb_id='kb-ext'`)
return &autoIngestFixture{t: t, ctx: ctx, pool: pool, store: NewStore(pool).WithRoutingDefaults("kb-env", "kb-ext"), now: now, connID: "conn-auto", kbID: "kb-current"}
}
func (f *autoIngestFixture) route() (versionID, publicationID string) {
f.t.Helper()
result, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{
ConnectionID: f.connID,
NodeIDs: []string{"node-file"},
Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: f.kbID,
OperatorRef: "fixture",
Reason: "fixture",
Now: f.now,
})
if err != nil {
f.t.Fatal(err)
}
if result.SelectedFiles != 1 || result.PlannedPublications != 1 {
f.t.Fatalf("route result = %#v", result)
}
if err := f.pool.QueryRow(f.ctx, `SELECT publication.source_item_version_id,publication.id
FROM test_publications publication
JOIN catalog_import_intents intent ON intent.source_item_id=(SELECT source_item_id FROM source_item_versions WHERE id=publication.source_item_version_id)
WHERE intent.node_id='node-file' AND publication.test_kb_id=$1`, f.kbID).Scan(&versionID, &publicationID); err != nil {
f.t.Fatal(err)
}
return versionID, publicationID
}
func (f *autoIngestFixture) markFetched(versionID string) {
f.t.Helper()
if err := f.store.MarkArtifactFetched(f.ctx, versionID, "32222102cafd6e5cdaeee415aad51e7df52629136d5ef2c3eae6e0e30ff7153d", 6991, "spool/auto.docx", "docx", true, f.now.Add(time.Minute)); err != nil {
f.t.Fatal(err)
}
}
func (f *autoIngestFixture) uploadJobs(publicationID string) int {
f.t.Helper()
var count int
if err := f.pool.QueryRow(f.ctx, `SELECT COUNT(*) FROM jobs WHERE type='test.upload' AND payload->>'publication_id'=$1`, publicationID).Scan(&count); err != nil {
f.t.Fatal(err)
}
return count
}
func (f *autoIngestFixture) publicationState(publicationID string) string {
f.t.Helper()
var state string
if err := f.pool.QueryRow(f.ctx, `SELECT processing_state FROM test_publications WHERE id=$1`, publicationID).Scan(&state); err != nil {
f.t.Fatal(err)
}
return state
}
func TestFetchedVerifiedArtifactAutoStartsExactlyOneUpload(t *testing.T) {
f := newAutoIngestFixture(t)
versionID, publicationID := f.route()
if jobs := f.uploadJobs(publicationID); jobs != 0 {
t.Fatalf("upload job before verification = %d", jobs)
}
f.markFetched(versionID)
if jobs := f.uploadJobs(publicationID); jobs != 1 {
t.Fatalf("upload jobs after verified fetch = %d, want 1", jobs)
}
if state := f.publicationState(publicationID); state != "pending" {
t.Fatalf("publication state = %q, want pending", state)
}
// 幂等:重复完成不能造第二个上传任务。
f.markFetched(versionID)
if jobs := f.uploadJobs(publicationID); jobs != 1 {
t.Fatalf("duplicate verified fetch created %d upload jobs", jobs)
}
}
func TestRouteReusingVerifiedContentAlsoAutoStarts(t *testing.T) {
f := newAutoIngestFixture(t)
versionID, publicationID := f.route()
// 模拟"本地已有先比对":内容已 verified,删除尚未消费的取件作业后再路由。
if _, err := f.pool.Exec(f.ctx, `UPDATE source_item_versions SET content_object_id=$2,content_state='verified'
WHERE id=$1`, versionID, f.insertVerifiedContent()); err != nil {
t.Fatal(err)
}
if _, err := f.pool.Exec(f.ctx, `DELETE FROM jobs WHERE type='artifact.fetch' AND payload->>'version_id'=$1`, versionID); err != nil {
t.Fatal(err)
}
if _, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{
ConnectionID: f.connID, NodeIDs: []string{"node-file"}, Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: f.kbID, OperatorRef: "fixture", Reason: "reuse", Now: f.now.Add(time.Minute),
}); err != nil {
t.Fatal(err)
}
if jobs := f.uploadJobs(publicationID); jobs != 1 {
t.Fatalf("reused verified content upload jobs = %d, want 1", jobs)
}
}
func (f *autoIngestFixture) insertVerifiedContent() string {
f.t.Helper()
if _, err := f.pool.Exec(f.ctx, `INSERT INTO content_objects(id,sha256,size_bytes,mime,validated_format,local_spool_ref,content_state)
VALUES('co-auto',repeat('d',64),6991,'','docx','spool/auto.docx','verified')
ON CONFLICT(sha256) DO UPDATE SET local_spool_ref=EXCLUDED.local_spool_ref,content_state='verified'`); err != nil {
f.t.Fatal(err)
}
var id string
if err := f.pool.QueryRow(f.ctx, `SELECT id FROM content_objects WHERE sha256=repeat('d',64)`).Scan(&id); err != nil {
f.t.Fatal(err)
}
return id
}
func TestStuckPlannedVerifiedPublicationRecoversViaReRoute(t *testing.T) {
f := newAutoIngestFixture(t)
versionID, publicationID := f.route()
f.markFetched(versionID) // 新代码本会入队;先清掉,复现 356 已卡记录
if _, err := f.pool.Exec(f.ctx, `DELETE FROM jobs WHERE type='test.upload' AND payload->>'publication_id'=$1`, publicationID); err != nil {
t.Fatal(err)
}
if _, err := f.pool.Exec(f.ctx, `UPDATE test_publications SET processing_state='planned' WHERE id=$1`, publicationID); err != nil {
t.Fatal(err)
}
// 父在 UI 对同一文件再次保存当前策略:只这一条、只当前绑定,幂等接续。
if _, err := f.store.RouteCatalogFiles(f.ctx, governance.CatalogRouteRequest{
ConnectionID: f.connID, NodeIDs: []string{"node-file"}, Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: f.kbID, OperatorRef: "fixture", Reason: "resume", Now: f.now.Add(2 * time.Minute),
}); err != nil {
t.Fatal(err)
}
if jobs := f.uploadJobs(publicationID); jobs != 1 {
t.Fatalf("stuck record recovered upload jobs = %d, want 1", jobs)
}
if state := f.publicationState(publicationID); state != "pending" {
t.Fatalf("stuck record state = %q", state)
}
}
func TestAutoStartRefusesStaleOrIneligiblePolicies(t *testing.T) {
cases := []struct {
name string
mutate func(f *autoIngestFixture, publicationID string)
}{
{"disabled source", func(f *autoIngestFixture, _ string) {
if _, err := f.pool.Exec(f.ctx, `UPDATE source_connections SET enabled=FALSE WHERE id='conn-auto'`); err != nil {
f.t.Fatal(err)
}
}},
{"blocked policy", func(f *autoIngestFixture, _ string) {
if _, err := f.pool.Exec(f.ctx, `UPDATE source_items SET policy_state='blocked' WHERE source_connection_id='conn-auto'`); err != nil {
f.t.Fatal(err)
}
}},
{"filtered filename", func(f *autoIngestFixture, _ string) {
if _, err := f.pool.Exec(f.ctx, `INSERT INTO filename_filter_rules(source_connection_id,directory_path,excluded_extensions,updated_by,mode)
VALUES('conn-auto','',ARRAY['adoc'],'fixture','exclude')`); err != nil {
f.t.Fatal(err)
}
}},
{"superseded publication", func(f *autoIngestFixture, publicationID string) {
if _, err := f.pool.Exec(f.ctx, `UPDATE test_publications SET superseded_at=$2 WHERE id=$1`, publicationID, f.now); err != nil {
f.t.Fatal(err)
}
}},
{"binding changed", func(f *autoIngestFixture, _ string) {
if _, err := f.pool.Exec(f.ctx, `UPDATE routing_kb_bindings SET internal_kb_id='kb-other' WHERE id='active'`); err != nil {
f.t.Fatal(err)
}
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := newAutoIngestFixture(t)
versionID, publicationID := f.route()
tc.mutate(f, publicationID)
f.markFetched(versionID)
if jobs := f.uploadJobs(publicationID); jobs != 0 {
t.Fatalf("%s auto-started %d upload jobs, want 0", tc.name, jobs)
}
})
}
}
@@ -27,7 +27,7 @@ func (s *Store) RouteCatalogFiles(ctx context.Context, request governance.Catalo
return governance.CatalogRouteResult{}, fmt.Errorf("begin catalog route: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
result, err := routeCatalogFilesTx(ctx, tx, request)
result, err := routeCatalogFilesTx(ctx, tx, s, request)
if err != nil {
return governance.CatalogRouteResult{}, err
}
@@ -57,7 +57,7 @@ func validateCatalogRouteRequest(request governance.CatalogRouteRequest) error {
return nil
}
func routeCatalogFilesTx(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest) (governance.CatalogRouteResult, error) {
func routeCatalogFilesTx(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest) (governance.CatalogRouteResult, error) {
targetKnowledgeBaseIDs := request.TargetKnowledgeBaseIDs
if len(targetKnowledgeBaseIDs) == 0 && request.TargetKnowledgeBaseID != "" {
targetKnowledgeBaseIDs = []string{request.TargetKnowledgeBaseID}
@@ -114,7 +114,7 @@ FOR UPDATE OF node`, request.ConnectionID, nodeIDs)
JOIN source_catalog_nodes child ON child.snapshot_id=parent.snapshot_id AND child.parent_node_id=parent.node_id
WHERE parent.node_type='folder'
)
SELECT DISTINCT node.node_id,node.name,node.relative_path,node.size_bytes,node.modified_at,node.content_sha256,
SELECT DISTINCT node.node_id,node.parent_node_id,node.name,node.relative_path,node.size_bytes,node.modified_at,node.content_sha256,
node.source_locator_hash,(node.node_id=ANY($2::text[])) AS directly_selected
FROM descendants
JOIN source_catalog_nodes node ON node.snapshot_id=descendants.snapshot_id AND node.node_id=descendants.node_id
@@ -130,7 +130,7 @@ ORDER BY node.node_id`, request.ConnectionID, nodeIDs)
files := make([]governance.CatalogRouteFile, 0, len(nodeIDs))
for rows.Next() {
var file governance.CatalogRouteFile
if err := rows.Scan(&file.NodeID, &file.Name, &file.RelativePath, &file.SizeBytes, &file.ModifiedAt,
if err := rows.Scan(&file.NodeID, &file.ParentNodeID, &file.Name, &file.RelativePath, &file.SizeBytes, &file.ModifiedAt,
&file.ContentSHA256, &file.LocatorHash, &file.Direct); err != nil {
rows.Close()
return governance.CatalogRouteResult{}, fmt.Errorf("scan catalog route file: %w", err)
@@ -142,7 +142,7 @@ ORDER BY node.node_id`, request.ConnectionID, nodeIDs)
return governance.CatalogRouteResult{}, fmt.Errorf("iterate catalog route files: %w", err)
}
rows.Close()
return fulfillCatalogIntentsTx(ctx, tx, request, files, request.Now)
return fulfillCatalogIntentsTx(ctx, tx, store, request, files, request.Now)
}
func setCatalogDirectoryPolicy(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, directoryPath string) error {
@@ -0,0 +1,131 @@
package postgres
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// This exercises the exact SQL used by the admin capture reconcile path with
// the real varchar/jsonb/timestamptz column shapes from the migration. Fake
// stores cannot catch parameter-type mistakes, as the 42P08 incident showed.
func TestCaptureReconcileExactPostgresPath(t *testing.T) {
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatal("isolated database required")
}
cfg.MaxConns = 1
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
ctx := context.Background()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if _, err := pool.Exec(ctx, `
CREATE TEMP TABLE library_jobs(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
state varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL DEFAULT '',
stage varchar(32) NOT NULL DEFAULT '', snapshot_id varchar(64) NOT NULL DEFAULT '',
error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, finished_at timestamptz);
CREATE TEMP TABLE library_job_stages(
job_id varchar(64) NOT NULL, stage varchar(32) NOT NULL, state varchar(16) NOT NULL,
detail text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, PRIMARY KEY(job_id,stage));
CREATE TEMP TABLE library_job_repairs(
id varchar(64) PRIMARY KEY, job_id varchar(64) NOT NULL, scope varchar(16) NOT NULL,
kind varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL, snapshot_id varchar(64) NOT NULL,
original_state varchar(16) NOT NULL, original_stage varchar(32) NOT NULL DEFAULT '',
original_error text NOT NULL DEFAULT '', original_recovery varchar(255) NOT NULL DEFAULT '',
original_finished_at timestamptz, reason varchar(255) NOT NULL, actor varchar(128) NOT NULL DEFAULT '',
evidence jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL);
CREATE TEMP TABLE library_versions(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(24) NOT NULL,
snapshot_id varchar(64) NOT NULL DEFAULT '', version_label varchar(64) NOT NULL DEFAULT '',
source_job_id varchar(64) NOT NULL DEFAULT '', operation_id varchar(64) NOT NULL DEFAULT '',
attempt_epoch integer NOT NULL DEFAULT 0, evidence jsonb NOT NULL DEFAULT '{}'::jsonb,
created_by varchar(128) NOT NULL DEFAULT '', created_at timestamptz NOT NULL,
superseded_at timestamptz);
INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,updated_at)
VALUES('libseal-cap-1','internal','seal','pending','libcap-1',now());
INSERT INTO library_job_stages(job_id,stage,state,updated_at)
VALUES('libseal-cap-1','export','succeeded',now());
INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,created_at)
VALUES('libver-1','internal','test_sealed','snap-1','libseal-cap-1',now());`); err != nil {
t.Fatal(err)
}
store := NewStore(pool)
state, _, err := store.LibraryCaptureExportEvidence(ctx, "libseal-cap-1")
if err != nil || state != "succeeded" {
t.Fatalf("export evidence state=%q err=%v", state, err)
}
version, found, err := store.LibraryTestSealedVersionForJob(ctx, "internal", "libseal-cap-1")
if err != nil || !found || version.SnapshotID != "snap-1" {
t.Fatalf("version found=%v snapshot=%q err=%v", found, version.SnapshotID, err)
}
now := time.Now().UTC()
updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-cap-1", "internal", "libcap-1", "snap-1", now)
if err != nil || !updated {
t.Fatalf("conditional repair updated=%v err=%v", updated, err)
}
var gotState, gotScope, gotSnapshot string
var finished bool
if err := pool.QueryRow(ctx, `SELECT state, scope, snapshot_id, finished_at IS NOT NULL FROM library_jobs WHERE id='libseal-cap-1'`).
Scan(&gotState, &gotScope, &gotSnapshot, &finished); err != nil {
t.Fatal(err)
}
if gotState != "succeeded" || gotScope != "internal" || gotSnapshot != "snap-1" || !finished {
t.Fatalf("terminal state=%q scope=%q snapshot=%q finished=%v", gotState, gotScope, gotSnapshot, finished)
}
if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-cap-1", "internal", "libcap-1", "snap-1", now.Add(time.Second)); err != nil || updated {
t.Fatalf("second repair must be idempotent/false: updated=%v err=%v", updated, err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,updated_at)
VALUES('libseal-failed','internal','seal','failed','libcap-2',now())`); err != nil {
t.Fatal(err)
}
if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-failed", "internal", "libcap-2", "snap-2", now); err != nil || updated {
t.Fatalf("failed row must not be repaired: updated=%v err=%v", updated, err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,snapshot_id,updated_at)
VALUES('libseal-other','internal','seal','running','libcap-3','other',now())`); err != nil {
t.Fatal(err)
}
if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-other", "internal", "libcap-3", "snap-3", now); err != nil || updated {
t.Fatalf("different existing snapshot must not be overwritten: updated=%v err=%v", updated, err)
}
legacyFinished := now.Add(-time.Minute).Truncate(time.Microsecond)
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,error,recovery,updated_at,finished_at)
VALUES('libseal-misclassified','internal','seal','failed','libcap-4',$1,$2,$3,$3)`,
"队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", legacyFinished); err != nil {
t.Fatal(err)
}
repaired, err := store.ReconcileMisclassifiedLibraryCapture(ctx, "libseal-misclassified", "internal", "libcap-4", "snap-4",
"", "队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", &legacyFinished,
"librepair-test", "tester", "test repair", map[string]any{"archive_verified": true}, now)
if err != nil || !repaired {
t.Fatalf("misclassification repair=%v err=%v", repaired, err)
}
var originalState, originalError string
var originalFinished *time.Time
if err := pool.QueryRow(ctx, `SELECT original_state, original_error, original_finished_at FROM library_job_repairs WHERE id='librepair-test'`).
Scan(&originalState, &originalError, &originalFinished); err != nil {
t.Fatal(err)
}
if originalState != "failed" || originalError == "" || originalFinished == nil {
t.Fatalf("audit lost original fields: state=%q error=%q finished=%v", originalState, originalError, originalFinished)
}
if repaired, err := store.ReconcileMisclassifiedLibraryCapture(ctx, "libseal-misclassified", "internal", "libcap-4", "snap-4",
"", "队列中已无对应作业,业务作业未收到结果", "封存作业由 agent 恢复来源;确认来源 healthy 后可重发", &legacyFinished,
"librepair-test-2", "tester", "test repair", map[string]any{}, now); err != nil || repaired {
t.Fatalf("second repair must be false: repaired=%v err=%v", repaired, err)
}
}
+166 -13
View File
@@ -205,12 +205,12 @@ func (s *Store) ListLibraryJobs(ctx context.Context, scope string, limit int) ([
func (s *Store) UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_job_stages SET
state = CASE WHEN $3='' THEN state ELSE $3 END,
state = CASE WHEN $3::text='' THEN state ELSE $3::text END,
total = COALESCE($4, total),
completed = COALESCE($5, completed),
bytes_total = COALESCE($6, bytes_total),
bytes_done = COALESCE($7, bytes_done),
detail = CASE WHEN $8='' THEN detail ELSE $8 END,
detail = CASE WHEN $8::text='' THEN detail ELSE $8::text END,
updated_at = $9
WHERE job_id=$1 AND stage=$2`, jobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC())
if err != nil {
@@ -245,12 +245,20 @@ func (s *Store) AdvanceLibraryJob(ctx context.Context, jobID string, state gover
}
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs SET
state=$2,
stage = CASE WHEN $3='' THEN stage ELSE $3 END,
error = CASE WHEN $4='' THEN error ELSE $4 END,
recovery = CASE WHEN $5='' THEN recovery ELSE $5 END,
snapshot_id = CASE WHEN $6='' THEN snapshot_id ELSE $6 END,
target_snapshot_id = CASE WHEN $7='' THEN target_snapshot_id ELSE $7 END,
state=$2::text,
stage = CASE WHEN $3::text='' THEN stage ELSE $3::text END,
-- 失败重试不得把第一因覆盖成第二次“already exists”;成功时清除旧错误,
-- 但新的 failed 状态保留已记录的第一条失败原因。显式 ::text 让所有对 $2
-- 的引用推导为同一类型;否则 varchar 列赋值与 CASE 文本比较会触发 42P08。
error = CASE
WHEN $2::text='succeeded' THEN ''
WHEN $4::text='' THEN error
WHEN $2::text='failed' AND error<>'' THEN error
ELSE $4::text
END,
recovery = CASE WHEN $5::text='' THEN recovery ELSE $5::text END,
snapshot_id = CASE WHEN $6::text='' THEN snapshot_id ELSE $6::text END,
target_snapshot_id = CASE WHEN $7::text='' THEN target_snapshot_id ELSE $7::text END,
updated_at=$8,
finished_at=COALESCE($9, finished_at)
WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, targetSnapshotID, now.UTC(), finished)
@@ -263,6 +271,148 @@ WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, target
return nil
}
// LibraryCaptureExportEvidence is the exact export-stage evidence used by the
// admin capture reconciliation gate. It is a named method so callers do not
// drift into a "latest stage" or generic list query.
func (s *Store) LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error) {
return s.LibraryJobStage(ctx, jobID, "export")
}
// LibraryJobStage reads one exact stage row. The customer-visible job row is
// authoritative for state; this is the export-stage evidence used by the
// capture reconciliation gate.
func (s *Store) LibraryJobStage(ctx context.Context, jobID, stage string) (string, string, error) {
if jobID == "" || stage == "" {
return "", "", errors.New("library stage requires job and stage")
}
var state, detail string
err := s.db.QueryRow(ctx, `SELECT state, detail FROM library_job_stages WHERE job_id=$1 AND stage=$2`, jobID, stage).Scan(&state, &detail)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", errors.New("library stage not found")
}
if err != nil {
return "", "", fmt.Errorf("read library stage: %w", err)
}
return state, detail, nil
}
// LibraryTestSealedVersionForJob finds the immutable test-sealed version by
// exact (scope, source_job_id), never by "latest N". More than one row means
// the ledger is ambiguous and must be rejected instead of picking one.
func (s *Store) LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) {
if scope == "" || jobID == "" {
return governance.LibraryVersion{}, false, errors.New("test sealed version requires scope and job")
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch,
evidence, created_by, created_at, superseded_at
FROM library_versions
WHERE scope=$1 AND kind='test_sealed' AND source_job_id=$2
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, jobID)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("read test sealed version for job: %w", err)
}
items, err := scanLibraryVersions(rows, 2)
if err != nil {
return governance.LibraryVersion{}, false, err
}
if len(items) > 1 {
return governance.LibraryVersion{}, false, fmt.Errorf("job %s has %d test-sealed rows; refuse to pick one", jobID, len(items))
}
if len(items) == 1 {
return items[0], true, nil
}
return governance.LibraryVersion{}, false, nil
}
// ReconcileLibraryCaptureTerminal is the only write allowed to repair a seal
// terminal during admin reconciliation. It is conditional on the exact job,
// scope, kind, queue/capture identity and an in-flight state; a concurrent
// failed/cancelled row or a different snapshot is never overwritten.
func (s *Store) ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error) {
if jobID == "" || scope == "" || queueJobID == "" || snapshotID == "" {
return false, errors.New("reconcile capture terminal requires job/scope/queue/snapshot")
}
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs
SET state='succeeded', stage='export', error='', snapshot_id=$4,
updated_at=$5, finished_at=$5
WHERE id=$1 AND scope=$2 AND kind='seal' AND queue_job_id=$3
AND state IN ('pending','running')
AND (snapshot_id='' OR snapshot_id=$4)`, jobID, scope, queueJobID, snapshotID, now.UTC())
if err != nil {
return false, fmt.Errorf("reconcile capture terminal: %w", err)
}
return tag.RowsAffected() == 1, nil
}
// ReconcileMisclassifiedLibraryCapture repairs ONLY the known startup
// misclassification: a failed seal whose queue actually completed, with no
// stage/snapshot and the exact legacy error/recovery. The original fields are
// copied to the immutable audit row and the job update is CAS-bound to them;
// any other failed/cancelled row is rejected.
func (s *Store) ReconcileMisclassifiedLibraryCapture(ctx context.Context, jobID, scope, queueJobID, snapshotID,
expectedStage, expectedError, expectedRecovery string, expectedFinished *time.Time,
auditID, actor, reason string, evidence map[string]any, now time.Time) (bool, error) {
if jobID == "" || scope == "" || queueJobID == "" || snapshotID == "" || auditID == "" {
return false, errors.New("misclassification repair requires job/scope/queue/snapshot/audit")
}
rawEvidence, err := json.Marshal(evidence)
if err != nil {
return false, fmt.Errorf("encode repair evidence: %w", err)
}
tx, err := s.db.Begin(ctx)
if err != nil {
return false, fmt.Errorf("begin repair: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
var state, stage, errText, recovery, currentSnapshot string
var finished *time.Time
if err := tx.QueryRow(ctx, `
SELECT state, stage, error, recovery, snapshot_id, finished_at
FROM library_jobs WHERE id=$1 AND scope=$2 AND kind='seal' AND queue_job_id=$3
FOR UPDATE`, jobID, scope, queueJobID).Scan(&state, &stage, &errText, &recovery, &currentSnapshot, &finished); err != nil {
return false, fmt.Errorf("read repair target: %w", err)
}
if state != "failed" || stage != expectedStage || errText != expectedError ||
recovery != expectedRecovery || currentSnapshot != "" ||
(finished == nil) != (expectedFinished == nil) ||
(finished != nil && expectedFinished != nil && !finished.Equal(*expectedFinished)) {
return false, nil
}
tag, err := tx.Exec(ctx, `
UPDATE library_jobs
SET state='succeeded', stage='export', error='', recovery='', snapshot_id=$3,
updated_at=$4, finished_at=$4
WHERE id=$1 AND scope=$2 AND kind='seal' AND queue_job_id=$5
AND state='failed' AND stage=$6 AND error=$7 AND recovery=$8 AND snapshot_id=''
AND finished_at IS NOT DISTINCT FROM $9`,
jobID, scope, snapshotID, now.UTC(), queueJobID, expectedStage, expectedError, expectedRecovery, expectedFinished)
if err != nil {
return false, fmt.Errorf("repair misclassified seal: %w", err)
}
if tag.RowsAffected() != 1 {
return false, nil
}
tag, err = tx.Exec(ctx, `
INSERT INTO library_job_repairs
(id, job_id, scope, kind, queue_job_id, snapshot_id, original_state, original_stage,
original_error, original_recovery, original_finished_at, reason, actor, evidence, created_at)
VALUES ($1,$2,$3,'seal',$4,$5,'failed',$6,$7,$8,$9,$10,$11,$12,$13)
ON CONFLICT (id) DO NOTHING`, auditID, jobID, scope, queueJobID, snapshotID,
expectedStage, expectedError, expectedRecovery, expectedFinished, reason, actor, rawEvidence, now.UTC())
if err != nil {
return false, fmt.Errorf("write repair audit: %w", err)
}
if tag.RowsAffected() != 1 {
return false, errors.New("repair audit already exists")
}
if err := tx.Commit(ctx); err != nil {
return false, fmt.Errorf("commit repair: %w", err)
}
return true, nil
}
// RecordLibraryVersion 写入一条**不可变版本事件**,并在需要时推进 current 指针。
//
// 与旧实现的区别(F02/F09 的根因):
@@ -641,7 +791,7 @@ func (s *Store) ReconcileLibraryJobs(ctx context.Context, now time.Time, kinds [
if len(kinds) == 0 {
return 0, errors.New("reconcile library jobs requires the kinds this executor owns")
}
if _, err := s.db.Exec(ctx, `
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs AS lj
SET state='failed', error='队列中已无对应作业,业务作业未收到结果',
recovery=CASE WHEN lj.kind IN ('sync','restore','recover','baseline')
@@ -654,12 +804,15 @@ WHERE lj.state IN ('pending','running')
AND lj.queue_job_id <> ''
AND NOT EXISTS (
SELECT 1 FROM jobs AS j
WHERE j.id = lj.queue_job_id AND j.state IN ('pending','running','retry')
)`, now.UTC(), kinds, s.libraryTargetID); err != nil {
WHERE j.id = lj.queue_job_id
AND j.state IN ('pending','running','retry','completed')
)`, now.UTC(), kinds, s.libraryTargetID)
if err != nil {
return 0, fmt.Errorf("reconcile library jobs: %w", err)
}
first := int(tag.RowsAffected())
// 建了业务作业但队列投递没完成(queue_job_id 为空)超过 5 分钟,也是孤儿。
tag, err := s.db.Exec(ctx, `
tag, err = s.db.Exec(ctx, `
UPDATE library_jobs
SET state='failed', error='队列投递未完成,作业从未开始', recovery='无需恢复来源;可直接重发', updated_at=$1, finished_at=$1
WHERE state IN ('pending','running') AND queue_job_id='' AND kind = ANY($3) AND (kind='seal' OR target_id=$4) AND created_at < $2`,
@@ -667,7 +820,7 @@ WHERE state IN ('pending','running') AND queue_job_id='' AND kind = ANY($3) AND
if err != nil {
return 0, fmt.Errorf("reconcile unattached library jobs: %w", err)
}
return int(tag.RowsAffected()), nil
return first + int(tag.RowsAffected()), nil
}
// LibraryVersionByRef 按 (scope, kind, 作业, 快照) 精确定位一条版本记录。
@@ -0,0 +1,95 @@
package postgres
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
)
// F02 retry regression: a second failed attempt must not overwrite the first
// cause in the persistent business job; a later success clears it.
func TestAdvanceLibraryJobPreservesFirstFailure(t *testing.T) {
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") {
t.Fatal("isolated database required")
}
cfg.MaxConns = 1
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
ctx := context.Background()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if _, err := pool.Exec(ctx, `
CREATE TEMP TABLE library_jobs(
id text primary key, state varchar(16) NOT NULL CHECK (state IN ('pending','running','succeeded','failed','cancelled')),
stage varchar(32) NOT NULL DEFAULT '', error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '',
snapshot_id varchar(64) NOT NULL DEFAULT '', target_snapshot_id varchar(64) NOT NULL DEFAULT '',
updated_at timestamptz NOT NULL, finished_at timestamptz);
INSERT INTO library_jobs(id,state,stage,error,updated_at) VALUES('libseal-retry','pending','','',now());
CREATE TEMP TABLE library_job_stages(
job_id text, stage varchar(32), state varchar(16), total bigint, completed bigint,
bytes_total bigint, bytes_done bigint, detail text, updated_at timestamptz, primary key(job_id,stage));
INSERT INTO library_job_stages(job_id,stage,state,updated_at) VALUES('libseal-retry','export','pending',now());`); err != nil {
t.Fatal(err)
}
store := NewStore(pool)
now := time.Now().UTC()
if err := store.UpdateLibraryStage(ctx, "libseal-retry", "export", "running", nil, nil, nil, nil, "started", now); err != nil {
t.Fatalf("update stage with real varchar types: %v", err)
}
if stageState, _, err := store.LibraryJobStage(ctx, "libseal-retry", "export"); err != nil || stageState != "running" {
t.Fatalf("read stage state=%q err=%v", stageState, err)
}
if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobRunning, "export", "", "", "", "", now); err != nil {
t.Fatal(err)
}
var state, stage string
var finished bool
if err := pool.QueryRow(ctx, `SELECT state, stage, finished_at IS NULL FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &stage, &finished); err != nil {
t.Fatal(err)
}
if state != "running" || stage != "export" || !finished {
t.Fatalf("running transition not persisted: state=%q stage=%q finished_null=%v", state, stage, finished)
}
if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobFailed, "export", "first validation failure", "", "", "", now); err != nil {
t.Fatal(err)
}
if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobFailed, "export", "second already exists", "", "", "", now.Add(time.Second)); err != nil {
t.Fatal(err)
}
var got string
var snap string
if err := pool.QueryRow(ctx, `SELECT state, error, finished_at IS NOT NULL, snapshot_id FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &got, &finished, &snap); err != nil {
t.Fatal(err)
}
if state != "failed" || !finished || snap != "" {
t.Fatalf("failed transition not persisted: state=%q finished=%v snapshot=%q", state, finished, snap)
}
if got != "first validation failure" {
t.Fatalf("first failure overwritten: %q", got)
}
if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobSucceeded, "export", "", "", "snap-ok", "", now.Add(2*time.Second)); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx, `SELECT state, error, snapshot_id, finished_at IS NOT NULL FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &got, &snap, &finished); err != nil {
t.Fatal(err)
}
if state != "succeeded" || !finished || snap != "snap-ok" {
t.Fatalf("succeeded transition not persisted: state=%q finished=%v snapshot=%q", state, finished, snap)
}
if got != "" {
t.Fatalf("success must clear old error, got %q", got)
}
}
@@ -0,0 +1,79 @@
package postgres
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// The worker startup reconciliation must not turn a completed capture queue
// into the legacy "queue does not exist" failure. This is a real PostgreSQL
// fixture with the actual varchar shapes; the RED case is the old SQL which
// only accepted pending/running/retry.
func TestStartupReconcileKeepsCompletedCaptureJob(t *testing.T) {
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatal("isolated database required")
}
cfg.MaxConns = 1
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
ctx := context.Background()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
now := time.Now().UTC()
if _, err := pool.Exec(ctx, `
CREATE TEMP TABLE library_jobs(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
state varchar(16) NOT NULL, stage varchar(32) NOT NULL DEFAULT '',
queue_job_id varchar(64) NOT NULL DEFAULT '', target_id text NOT NULL DEFAULT '',
error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '',
snapshot_id varchar(64) NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, finished_at timestamptz, created_at timestamptz NOT NULL DEFAULT now());
CREATE TEMP TABLE jobs(id varchar(64) PRIMARY KEY, type varchar(64) NOT NULL, state varchar(16) NOT NULL);`); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,updated_at)
VALUES('libseal-completed','internal','seal','pending','q-completed',$1),
('libseal-failed','internal','seal','pending','q-failed',$1),
('libseal-missing','internal','seal','pending','q-missing',$1)`, now); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO jobs(id,type,state) VALUES('q-completed','library.capture','completed'),
('q-failed','library.capture','failed')`); err != nil {
t.Fatal(err)
}
store := NewStore(pool)
n, err := store.ReconcileLibraryJobs(ctx, now, []string{"seal"})
if err != nil {
t.Fatal(err)
}
var state, errText string
if err := pool.QueryRow(ctx, `SELECT state, error FROM library_jobs WHERE id='libseal-completed'`).Scan(&state, &errText); err != nil {
t.Fatal(err)
}
if state != "pending" || errText != "" {
t.Fatalf("completed queue was misclassified: state=%q error=%q", state, errText)
}
if n != 2 {
t.Fatalf("reconciled=%d, want only failed/missing queue jobs (2)", n)
}
for _, id := range []string{"libseal-failed", "libseal-missing"} {
var got string
if err := pool.QueryRow(ctx, `SELECT state FROM library_jobs WHERE id=$1`, id).Scan(&got); err != nil {
t.Fatal(err)
}
if got != "failed" {
t.Fatalf("%s state=%q, want failed", id, got)
}
}
}
@@ -71,6 +71,29 @@ LIMIT 1`, s.libraryTargetID, scope).Scan(&item.ID, &item.Scope, &item.Status, &i
}
// LibraryRestoreVerifications 是页面用的轻量清单(最近 N 条),按目标过滤。
// LibraryRestoreVerificationForSnapshot 只按本次精确快照查证据,不能用最近 N 条
// 扫描代替:旧快照的报告可能已经掉出列表,但仍是该快照真实的恢复演练记录。
func (s *Store) LibraryRestoreVerificationForSnapshot(ctx context.Context, scope, snapshotID string) (governance.LibraryRestoreVerification, bool, error) {
var item governance.LibraryRestoreVerification
var report []byte
err := s.db.QueryRow(ctx, `
SELECT id, scope, status, snapshot_id, job_id, failure, report, started_at, finished_at
FROM library_restore_verifications
WHERE target_id=$1 AND scope=$2 AND snapshot_id=$3
ORDER BY finished_at DESC, created_at DESC
LIMIT 1`, s.libraryTargetID, scope, snapshotID).Scan(&item.ID, &item.Scope, &item.Status,
&item.SnapshotID, &item.JobID, &item.Failure, &report, &item.StartedAt, &item.FinishedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryRestoreVerification{}, false, nil
}
return governance.LibraryRestoreVerification{}, false, fmt.Errorf("load snapshot restore verification: %w", err)
}
item.Report = decodeEvidenceObject(report)
return item, true, nil
}
func (s *Store) LibraryRestoreVerifications(ctx context.Context, scope string, limit int) ([]governance.LibraryRestoreVerification, error) {
if limit <= 0 {
limit = 10
@@ -0,0 +1,56 @@
package postgres
import (
"context"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
)
// F03 regression against real PostgreSQL: exact snapshot lookup must not fall
// back to the target's newest passed record. Session temp table only.
func TestLibraryRestoreVerificationForSnapshotExactPG(t *testing.T) {
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") {
t.Fatal("isolated database required")
}
cfg.MaxConns = 1
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
ctx := context.Background()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
_, err = pool.Exec(ctx, `
CREATE TEMP TABLE library_restore_verifications(
id text, target_id text, scope text, status text, snapshot_id text, job_id text,
failure text, report jsonb, started_at timestamptz, finished_at timestamptz, created_at timestamptz DEFAULT now());
INSERT INTO library_restore_verifications
(id,target_id,scope,status,snapshot_id,job_id,failure,report,started_at,finished_at,created_at) VALUES
('v-new','target-exact','internal','passed','snap-new','job-new','','{}',now()-interval '1 hour',now()-interval '1 hour',now()),
('v-old','target-exact','internal','failed','snap-old','job-old','old restore mismatch','{}',now()-interval '2 hour',now()-interval '2 hour',now()-interval '2 hour'),
('v-other','other-target','internal','passed','snap-old','job-other','','{}',now(),now(),now());`)
if err != nil {
t.Fatal(err)
}
store := NewStore(pool).WithLibraryTarget("target-exact")
item, found, err := store.LibraryRestoreVerificationForSnapshot(ctx, "internal", "snap-old")
if err != nil {
t.Fatal(err)
}
if !found || item.JobID != "job-old" || item.Status != governance.LibraryVerificationFailed {
t.Fatalf("exact snapshot borrowed another record: found=%v item=%+v", found, item)
}
if _, found, err := store.LibraryRestoreVerificationForSnapshot(ctx, "internal", "snap-missing"); err != nil || found {
t.Fatalf("missing snapshot must be explicit no-evidence: found=%v err=%v", found, err)
}
}
@@ -57,12 +57,12 @@ func (s *Store) AdvanceLibraryJobGuarded(ctx context.Context, attempt governance
}
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs SET
state=$2,
stage = CASE WHEN $3='' THEN stage ELSE $3 END,
error = CASE WHEN $4='' THEN error ELSE $4 END,
recovery = CASE WHEN $5='' THEN recovery ELSE $5 END,
snapshot_id = CASE WHEN $6='' THEN snapshot_id ELSE $6 END,
target_snapshot_id = CASE WHEN $7='' THEN target_snapshot_id ELSE $7 END,
state=$2::text,
stage = CASE WHEN $3::text='' THEN stage ELSE $3::text END,
error = CASE WHEN $4::text='' THEN error ELSE $4::text END,
recovery = CASE WHEN $5::text='' THEN recovery ELSE $5::text END,
snapshot_id = CASE WHEN $6::text='' THEN snapshot_id ELSE $6::text END,
target_snapshot_id = CASE WHEN $7::text='' THEN target_snapshot_id ELSE $7::text END,
updated_at=$8,
finished_at=COALESCE($9, finished_at)
WHERE id=$1 AND `+libraryFence("$1", 10, 11),
@@ -82,12 +82,12 @@ func (s *Store) UpdateLibraryStageGuarded(ctx context.Context, attempt governanc
stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_job_stages SET
state = CASE WHEN $3='' THEN state ELSE $3 END,
state = CASE WHEN $3::text='' THEN state ELSE $3::text END,
total = COALESCE($4, total),
completed = COALESCE($5, completed),
bytes_total = COALESCE($6, bytes_total),
bytes_done = COALESCE($7, bytes_done),
detail = CASE WHEN $8='' THEN detail ELSE $8 END,
detail = CASE WHEN $8::text='' THEN detail ELSE $8::text END,
updated_at = $9
WHERE job_id=$1 AND stage=$2 AND `+libraryFence("$1", 10, 11),
attempt.JobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC(),
@@ -0,0 +1 @@
DROP TABLE IF EXISTS library_job_repairs;
@@ -0,0 +1,19 @@
-- Immutable audit for the only permitted automatic/system-misclassification repair.
CREATE TABLE library_job_repairs (
id VARCHAR(64) PRIMARY KEY,
job_id VARCHAR(64) NOT NULL,
scope VARCHAR(16) NOT NULL,
kind VARCHAR(16) NOT NULL,
queue_job_id VARCHAR(64) NOT NULL,
snapshot_id VARCHAR(64) NOT NULL,
original_state VARCHAR(16) NOT NULL,
original_stage VARCHAR(32) NOT NULL DEFAULT '',
original_error TEXT NOT NULL DEFAULT '',
original_recovery VARCHAR(255) NOT NULL DEFAULT '',
original_finished_at TIMESTAMPTZ,
reason VARCHAR(255) NOT NULL,
actor VARCHAR(128) NOT NULL DEFAULT '',
evidence JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL
);
CREATE UNIQUE INDEX library_job_repairs_identity ON library_job_repairs(job_id, snapshot_id);
@@ -11,11 +11,14 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 79 {
t.Fatalf("migration count = %d, want 79", len(migrations))
if len(migrations) != 80 {
t.Fatalf("migration count = %d, want 80", len(migrations))
}
// 79 是恢复验证:verify 成为独立业务作业并与写作业共用互斥,
// 证据按 target_id 落库(换目标旧证据自动失效)。
if repair := migrations[79]; repair.Version != 80 {
t.Fatalf("migration 80 = %#v", repair)
}
if verification := migrations[78]; verification.Version != 79 ||
!strings.Contains(verification.UpSQL, "library_restore_verifications") ||
!strings.Contains(verification.UpSQL, "'verify'") {
@@ -0,0 +1,217 @@
package postgres
import (
"context"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
)
// F14:来源目录在取件/路由时写入 source_items;对历史行(当时没写)只在读时
// 按「同一连接 + 同一 item」的 catalog intent 补齐,绝不按文件名猜配。
func TestMonitorTaskCatalogDirectoryIdentityIntegration(t *testing.T) {
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if url == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err = ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
exec := func(query string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, query, args...); err != nil {
t.Fatalf("%v: %s", err, query)
}
}
now := time.Date(2026, 11, 5, 2, 0, 0, 0, time.UTC)
exec(`INSERT INTO source_connections (id,source_type,name) VALUES
('conn-atom','dingtalk','ATOM知识库'),('conn-pp','pp','PP资料下载中心')`)
for index, connection := range []struct{ id, snapshot, folder, file string }{
{"conn-atom", "snap-atom", "node-atom-folder", "node-atom-file"},
{"conn-pp", "snap-pp", "node-pp-folder", "node-pp-file"},
} {
exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at)
VALUES ($1,$2,repeat($3,64),'fixture',2,1,1,$4)`,
connection.snapshot, connection.id, string(rune('a'+index)), now)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ($1,$2,NULL,'folder','售后机器出厂问题整改','售后机器出厂问题整改',repeat($3,64))`,
connection.snapshot, connection.folder, "b")
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ($1,$2,$3,'file','末端航插线序问题.adoc.docx',$4,repeat($5,64))`,
connection.snapshot, connection.file, connection.folder,
map[string]string{"conn-atom": "售后机器出厂问题整改/末端航插线序问题.adoc.docx", "conn-pp": "PP公开资料/末端航插线序问题.adoc.docx"}[connection.id],
"c")
exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ($1,$2,$3)`,
connection.id, connection.snapshot, now)
}
// 两条来源的标题完全相同、来源不同;路径必须各自来自自己的 intent。
insertItem := func(id, connection, title, storedPath, parent string) {
exec(`INSERT INTO source_items (id,source_connection_id,stable_external_id,canonical_uri_hash,normalized_path,parent_external_id,title,item_type,revision,visibility,visibility_origin,source_change,policy_state,updated_at)
VALUES ($1,$2,$7,repeat('d',64),$3,$4,$5,'file','sha:1','internal','configured_scope','added','internal',$6)`,
id, connection, storedPath, parent, title, now, id)
exec(`INSERT INTO source_item_versions (id,source_item_id,revision,content_state,raw_record_summary,updated_at)
VALUES ('sv-'||$1,$1,'sha:1','verified','{}'::jsonb,$2)`, id, now)
}
insertItem("si-atom", "conn-atom", "末端航插线序问题.adoc.docx", "", "")
insertItem("si-pp", "conn-pp", "末端航插线序问题.adoc.docx", "", "")
insertItem("si-unbound", "conn-pp", "未登记目录文件.adoc.docx", "", "")
insertItem("si-stored", "conn-atom", "已登记目录文件.adoc.docx", "既有登记/已登记目录文件.adoc.docx", "node-atom-folder")
exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at)
VALUES ('conn-atom','node-atom-file','internal','si-atom','fixture','售后机器出厂问题整改/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('e',64),$1)`, now)
exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at)
VALUES ('conn-pp','node-pp-file','internal','si-pp','fixture','PP公开资料/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('f',64),$1)`, now)
exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at)
VALUES ('conn-atom','node-atom-folder','internal','si-stored','fixture','售后机器出厂问题整改/已登记目录文件.adoc.docx','已登记目录文件.adoc.docx',repeat('1',64),$1)`, now)
for index, publication := range []struct{ id, item, kb, scope string }{
{"tp-atom", "si-atom", "kb-internal-a", "internal"},
{"tp-pp", "si-pp", "kb-internal-b", "internal"},
{"tp-unbound", "si-unbound", "kb-internal-b", "internal"},
{"tp-stored", "si-stored", "kb-internal-a", "internal"},
} {
exec(`INSERT INTO test_publications (id,source_item_version_id,test_kb_id,ingest_state,processing_state,retrieval_state,target_scope,updated_at)
VALUES ($1,'sv-'||$2,$3,'uploaded','completed','unpublished',$4,$5)`,
publication.id, publication.item, publication.kb, publication.scope, now.Add(time.Duration(index)*time.Minute))
}
store := NewStore(pool)
page, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Limit: 20})
if err != nil {
t.Fatal(err)
}
byID := map[string]MonitorTask{}
for _, item := range page.Items {
byID[item.ID] = item
}
atom := byID["tp-atom"]
if atom.Path != "售后机器出厂问题整改/末端航插线序问题.adoc.docx" || atom.ParentNodeID != "node-atom-folder" || atom.NodeID != "node-atom-file" {
t.Fatalf("historical item lost its catalog directory: %#v", atom)
}
pp := byID["tp-pp"]
if pp.Path != "PP公开资料/末端航插线序问题.adoc.docx" || pp.ParentNodeID != "node-pp-folder" {
t.Fatalf("same-title item took another source's path: %#v", pp)
}
if byID["tp-unbound"].Path != "" || byID["tp-unbound"].ParentNodeID != "" {
t.Fatalf("missing intent must not invent a directory: %#v", byID["tp-unbound"])
}
if stored := byID["tp-stored"]; stored.Path != "既有登记/已登记目录文件.adoc.docx" {
t.Fatalf("stored path must win over the intent snapshot: %#v", stored)
}
searched, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: "售后机器出厂问题整改", Limit: 20})
if err != nil {
t.Fatal(err)
}
if searched.Total != 1 || len(searched.Items) != 1 || searched.Items[0].SourceID != "conn-atom" {
t.Fatalf("directory search total=%d items=%#v, want exactly the ATOM row", searched.Total, searched.Items)
}
// 同名文件在另一来源下不应被这条目录搜索带出来(同名异源隔离)。
other, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: "PP公开资料", Limit: 20})
if err != nil {
t.Fatal(err)
}
if other.Total != 1 || len(other.Items) != 1 || other.Items[0].SourceID != "conn-pp" {
t.Fatalf("cross-source search leaked: %#v", other.Items)
}
// F15:目标选项带 scope(同名知识库靠短 ID + scope 区分),筛选总数由后端全量算。
if len(page.Targets) != 2 {
t.Fatalf("target options = %#v", page.Targets)
}
for _, option := range page.Targets {
if option.Scope != "internal" || len(option.ID) < 8 {
t.Fatalf("target option missing identity: %#v", option)
}
}
filtered, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Target: "kb-internal-b", Limit: 20})
if err != nil {
t.Fatal(err)
}
if filtered.Total != 2 || len(filtered.Items) != 2 {
t.Fatalf("target filter total=%d items=%d, want 2", filtered.Total, len(filtered.Items))
}
}
// F14 写入侧:路由/取件时就把来源路径与父目录写进 source_items;
// 对已存在但当时没写的行,只在同一 intent 绑定的 item 上补空值,绝不覆盖既有值。
func TestCatalogRoutePersistsSourceDirectoryIntegration(t *testing.T) {
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if url == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err = ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
exec := func(query string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, query, args...); err != nil {
t.Fatalf("%v: %s", err, query)
}
}
now := time.Date(2026, 11, 5, 3, 0, 0, 0, time.UTC)
exec(`INSERT INTO source_connections (id,source_type,name) VALUES ('conn-route','dingtalk','路由来源')`)
exec(`INSERT INTO source_catalog_snapshots (id,source_connection_id,snapshot_sha256,source_label,node_count,folder_count,file_count,observed_at)
VALUES ('snap-route','conn-route',repeat('9',64),'fixture',2,1,1,$1)`, now)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ('snap-route','node-route-folder',NULL,'folder','售后机器出厂问题整改','售后机器出厂问题整改',repeat('8',64))`)
exec(`INSERT INTO source_catalog_nodes (snapshot_id,node_id,parent_node_id,node_type,name,relative_path,source_locator_hash)
VALUES ('snap-route','node-route-file','node-route-folder','file','末端航插线序问题.adoc.docx','售后机器出厂问题整改/末端航插线序问题.adoc.docx',repeat('7',64))`)
exec(`INSERT INTO source_catalog_heads (source_connection_id,snapshot_id,activated_at) VALUES ('conn-route','snap-route',$1)`, now)
// 历史行:当时没写路径,但 intent 已把它绑定到本 item。
exec(`INSERT INTO source_items (id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,revision,visibility,visibility_origin,source_change,policy_state,updated_at)
VALUES ('si-route-old','conn-route','legacy-item',repeat('6',64),'末端航插线序问题.adoc.docx','file','','internal','configured_scope','unchanged','internal',$1)`, now)
exec(`INSERT INTO source_item_versions (id,source_item_id,revision,content_state,raw_record_summary,updated_at)
VALUES ('sv-route-old','si-route-old','','unknown','{}'::jsonb,$1)`, now)
exec(`INSERT INTO catalog_import_intents (source_connection_id,node_id,visibility,source_item_id,decided_by,relative_path,name,locator_hash,updated_at)
VALUES ('conn-route','node-route-file','internal','si-route-old','fixture','售后机器出厂问题整改/末端航插线序问题.adoc.docx','末端航插线序问题.adoc.docx',repeat('5',64),$1)`, now)
store := NewStore(pool)
if _, err := store.RouteCatalogFiles(ctx, governance.CatalogRouteRequest{
ConnectionID: "conn-route",
NodeIDs: []string{"node-route-file"},
Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: "kb-route",
OperatorRef: "fixture",
Reason: "fixture",
Now: now,
}); err != nil {
t.Fatal(err)
}
var path, parent string
if err := pool.QueryRow(ctx, `SELECT normalized_path,parent_external_id FROM source_items WHERE id='si-route-old'`).Scan(&path, &parent); err != nil {
t.Fatal(err)
}
if path != "售后机器出厂问题整改/末端航插线序问题.adoc.docx" || parent != "node-route-folder" {
t.Fatalf("route did not persist the source directory: path=%q parent=%q", path, parent)
}
// 已有值不被后续路由覆盖(现有目录精确匹配)。
exec(`UPDATE source_items SET normalized_path='既有登记/保留路径',parent_external_id='node-existing' WHERE id='si-route-old'`)
if _, err := store.RouteCatalogFiles(ctx, governance.CatalogRouteRequest{
ConnectionID: "conn-route",
NodeIDs: []string{"node-route-file"},
Visibility: governance.VisibilityInternal,
TargetKnowledgeBaseID: "kb-route",
OperatorRef: "fixture",
Reason: "fixture",
Now: now.Add(time.Minute),
}); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx, `SELECT normalized_path,parent_external_id FROM source_items WHERE id='si-route-old'`).Scan(&path, &parent); err != nil {
t.Fatal(err)
}
if path != "既有登记/保留路径" || parent != "node-existing" {
t.Fatalf("existing directory was overwritten: path=%q parent=%q", path, parent)
}
}
+45 -22
View File
@@ -16,23 +16,27 @@ type MonitorTaskEvent struct {
Detail string `json:"detail"`
}
type MonitorTask struct {
History []MonitorTaskEvent `json:"history"`
ID string `json:"id"`
Title string `json:"title"`
Path string `json:"path"`
SourceID string `json:"source_id"`
SourceName string `json:"source_name"`
TargetScope string `json:"target_scope"`
TargetKB string `json:"target_kb"`
Action string `json:"action"`
Stage string `json:"stage"`
Status string `json:"status"`
Detail string `json:"detail"`
UpdatedAt string `json:"updated_at"`
RetryKind string `json:"retry_kind"`
FailureID string `json:"failure_id"`
RetryCount int `json:"retry_count"`
VersionID string `json:"version_id"`
History []MonitorTaskEvent `json:"history"`
ID string `json:"id"`
Title string `json:"title"`
Path string `json:"path"`
// NodeID/ParentNodeID let the UI return to the exact source directory;
// both come from the catalog snapshot bound to THIS source item.
NodeID string `json:"node_id"`
ParentNodeID string `json:"parent_node_id"`
SourceID string `json:"source_id"`
SourceName string `json:"source_name"`
TargetScope string `json:"target_scope"`
TargetKB string `json:"target_kb"`
Action string `json:"action"`
Stage string `json:"stage"`
Status string `json:"status"`
Detail string `json:"detail"`
UpdatedAt string `json:"updated_at"`
RetryKind string `json:"retry_kind"`
FailureID string `json:"failure_id"`
RetryCount int `json:"retry_count"`
VersionID string `json:"version_id"`
}
type MonitorTaskPage struct {
Items []MonitorTask `json:"items"`
@@ -42,10 +46,18 @@ type MonitorTaskPage struct {
Sources []MonitorOption `json:"sources"`
Targets []MonitorOption `json:"targets"`
Retryable int `json:"retryable"`
// Bindings is the effective (persisted, env-fallback aware) target for each
// scope. The UI marks rows/options against it; counts stay this page's totals.
Bindings MonitorBindings `json:"bindings"`
}
type MonitorOption struct {
ID string `json:"id"`
Name string `json:"name"`
ID string `json:"id"`
Name string `json:"name"`
Scope string `json:"scope,omitempty"`
}
type MonitorBindings struct {
Internal string `json:"internal"`
External string `json:"external"`
}
// Reduce publication versions before filtering; totals and pages share one snapshot.
@@ -62,7 +74,11 @@ const monitorTasksCTE = `WITH history_publications AS (
WHERE p.superseded_at IS NULL
ORDER BY v.source_item_id,p.test_kb_id,p.created_at DESC,p.id DESC
), base AS (
SELECT p.id,si.title,si.normalized_path AS path,c.id AS source_id,c.name AS source_name,
SELECT p.id,si.title,
COALESCE(NULLIF(si.normalized_path,''),ci.relative_path,'') AS path,
COALESCE(NULLIF(si.parent_external_id,''),cn.parent_node_id,'') AS parent_node_id,
COALESCE(ci.node_id,'') AS node_id,
c.id AS source_id,c.name AS source_name,
p.target_scope,p.test_kb_id AS target_kb,p.source_item_version_id AS version_id,p.retry_count,
GREATEST(p.updated_at,j.updated_at,f.created_at) AS updated_at,
p.processing_state,p.ingest_state,p.retrieval_state,p.last_error,p.knowledge_id,
@@ -72,6 +88,13 @@ const monitorTasksCTE = `WITH history_publications AS (
COALESCE(j.type,'') AS job_type,COALESCE(j.state,'') AS job_state,COALESCE(j.attempt,0) AS job_attempt,j.available_at,
COALESCE(f.id,'') AS failure_id,COALESCE(f.job_type,'') AS failure_type,COALESCE(NULLIF(f.last_error,''),f.error_code,'') AS failure_error
FROM latest p JOIN source_items si ON si.id=p.source_item_id JOIN source_connections c ON c.id=si.source_connection_id
-- 历史行路径为空时,只用「同一连接 + 同一 item」的取件意图补齐:不按文件名猜配。
LEFT JOIN LATERAL(SELECT intent.relative_path,intent.node_id FROM catalog_import_intents intent
WHERE intent.source_item_id=si.id AND intent.source_connection_id=si.source_connection_id
ORDER BY intent.updated_at DESC,intent.node_id LIMIT 1) ci ON TRUE
LEFT JOIN LATERAL(SELECT node.parent_node_id FROM source_catalog_heads head
JOIN source_catalog_nodes node ON node.snapshot_id=head.snapshot_id
WHERE head.source_connection_id=si.source_connection_id AND node.node_id=ci.node_id LIMIT 1) cn ON TRUE
LEFT JOIN content_objects co ON co.id=p.content_object_id
LEFT JOIN LATERAL(SELECT j.type,j.state,j.attempt,j.available_at,j.updated_at FROM jobs j WHERE
(j.payload->>'publication_id'=p.id OR (j.type='artifact.fetch' AND j.payload->>'version_id'=p.source_item_version_id))
@@ -101,7 +124,7 @@ const monitorTasksCTE = `WITH history_publications AS (
ELSE 'waiting' END AS stage
FROM base
), projected AS (
SELECT id,title,path,source_id,source_name,target_scope,target_kb,version_id,retry_count,updated_at,action,stage,status,failure_id,
SELECT id,title,path,parent_node_id,node_id,source_id,source_name,target_scope,target_kb,version_id,retry_count,updated_at,action,stage,status,failure_id,
CASE WHEN status<>'attention' THEN ''
WHEN action='remove' THEN CASE WHEN job_type='test.remove' AND job_state='failed' AND retrieval_state IN ('failed','disabling') AND policy_state='blocked' THEN 'remove' ELSE '' END
WHEN failure_type='artifact.fetch' THEN 'fetch'
@@ -130,7 +153,7 @@ func (s *Store) ListMonitorTasks(ctx context.Context, f MonitorTaskFilter) (Moni
return MonitorTaskPage{}, errors.New("invalid monitor pagination")
}
var raw []byte
err := s.db.QueryRow(ctx, monitorTasksCTE+`SELECT jsonb_build_object('items',COALESCE((SELECT jsonb_agg(to_jsonb(x)||jsonb_build_object('history',COALESCE((SELECT jsonb_agg(e ORDER BY e.at DESC,e.kind,e.detail) FROM (SELECT * FROM history_events ORDER BY at DESC,kind,detail LIMIT 50)e),'[]'::jsonb)) ORDER BY x.updated_at DESC,x.id) FROM (SELECT * FROM filtered ORDER BY updated_at DESC,id LIMIT $8 OFFSET $9)x),'[]'::jsonb),'total',(SELECT count(*) FROM filtered),'limit',$8::int,'offset',$9::int,'retryable',(SELECT count(*) FROM filtered WHERE retry_kind<>''),'sources',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT source_id AS id,source_name AS name FROM projected)x),'[]'::jsonb),'targets',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT target_kb AS id,target_kb AS name FROM projected)x),'[]'::jsonb))`, f.Search, f.Source, f.Scope, f.Action, f.Status, f.Stage, f.ID, f.Limit, f.Offset, f.Target, f.Since, f.Until).Scan(&raw)
err := s.db.QueryRow(ctx, monitorTasksCTE+`SELECT jsonb_build_object('items',COALESCE((SELECT jsonb_agg(to_jsonb(x)||jsonb_build_object('history',COALESCE((SELECT jsonb_agg(e ORDER BY e.at DESC,e.kind,e.detail) FROM (SELECT * FROM history_events ORDER BY at DESC,kind,detail LIMIT 50)e),'[]'::jsonb)) ORDER BY x.updated_at DESC,x.id) FROM (SELECT * FROM filtered ORDER BY updated_at DESC,id LIMIT $8 OFFSET $9)x),'[]'::jsonb),'total',(SELECT count(*) FROM filtered),'limit',$8::int,'offset',$9::int,'retryable',(SELECT count(*) FROM filtered WHERE retry_kind<>''),'sources',COALESCE((SELECT jsonb_agg(x ORDER BY x.name) FROM (SELECT DISTINCT source_id AS id,source_name AS name FROM projected)x),'[]'::jsonb),'targets',COALESCE((SELECT jsonb_agg(x ORDER BY x.scope,x.id) FROM (SELECT target_kb AS id,MIN(target_scope) AS scope FROM projected GROUP BY target_kb)x),'[]'::jsonb))`, f.Search, f.Source, f.Scope, f.Action, f.Status, f.Stage, f.ID, f.Limit, f.Offset, f.Target, f.Since, f.Until).Scan(&raw)
if err != nil {
return MonitorTaskPage{}, err
}
@@ -35,7 +35,7 @@ func (s *Store) RouteCatalogFilesWithOperation(ctx context.Context, request gove
return governance.CatalogRouteResult{}, false, err
}
resultJSON, replayed, err := s.executeOperation(ctx, "catalog.route", operationID, fingerprint, request.Now, func(tx pgx.Tx) (json.RawMessage, error) {
result, err := routeCatalogFilesTx(ctx, tx, request)
result, err := routeCatalogFilesTx(ctx, tx, s, request)
if err != nil {
return nil, err
}
+114 -6
View File
@@ -23,14 +23,14 @@ import (
// 开始处理 promotes them within the configured concurrency budget. Blocked
// intents retire any planned publication and flip the item policy so the
// knowledge-base diff demands removal of anything still live.
func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, files []governance.CatalogRouteFile, now time.Time) (governance.CatalogRouteResult, error) {
func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest, files []governance.CatalogRouteFile, now time.Time) (governance.CatalogRouteResult, error) {
targetKnowledgeBaseIDs := request.TargetKnowledgeBaseIDs
if len(targetKnowledgeBaseIDs) == 0 && request.TargetKnowledgeBaseID != "" {
targetKnowledgeBaseIDs = []string{request.TargetKnowledgeBaseID}
}
result := governance.CatalogRouteResult{SelectedFiles: len(files)}
for _, file := range files {
recorded, fetchQueued, planned, blocked, err := fulfillCatalogIntent(ctx, tx, request, file, targetKnowledgeBaseIDs, now)
recorded, fetchQueued, planned, blocked, err := fulfillCatalogIntent(ctx, tx, store, request, file, targetKnowledgeBaseIDs, now)
if err != nil {
return governance.CatalogRouteResult{}, err
}
@@ -54,7 +54,7 @@ func fulfillCatalogIntentsTx(ctx context.Context, tx pgx.Tx, request governance.
// fulfillCatalogIntent applies one file decision. It returns recorded=false
// only when the node vanished mid-transaction; fetchQueued reports a newly
// enqueued artifact.fetch job and planned the number of publications created.
func fulfillCatalogIntent(ctx context.Context, tx pgx.Tx, request governance.CatalogRouteRequest, file governance.CatalogRouteFile, targetKnowledgeBaseIDs []string, now time.Time) (bool, bool, int, bool, error) {
func fulfillCatalogIntent(ctx context.Context, tx pgx.Tx, store *Store, request governance.CatalogRouteRequest, file governance.CatalogRouteFile, targetKnowledgeBaseIDs []string, now time.Time) (bool, bool, int, bool, error) {
policy := string(request.Visibility)
if _, err := tx.Exec(ctx, `INSERT INTO catalog_import_intents(
source_connection_id,node_id,visibility,decided_by,reason,relative_path,name,size_bytes,modified_at,content_sha256,
@@ -118,11 +118,11 @@ ORDER BY head.activated_at DESC NULLS LAST LIMIT 1 FOR UPDATE OF node`, request.
if _, err := tx.Exec(ctx, `INSERT INTO source_items(
id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,revision,
visibility,visibility_origin,source_change,absence_streak,identity_confidence,
policy_state,created_at,updated_at)
VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id',$6,NOW(),NOW())`,
policy_state,normalized_path,parent_external_id,created_at,updated_at)
VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id',$6,$8,$9,NOW(),NOW())`,
newItemID, request.ConnectionID, "cat:"+file.NodeID,
sha256Hex("policy:"+request.ConnectionID+"\x00"+file.NodeID),
file.Name, policy, itemVisibilityFor(request.Visibility)); err != nil {
file.Name, policy, itemVisibilityFor(request.Visibility), file.RelativePath, file.ParentNodeID); err != nil {
return false, false, 0, false, fmt.Errorf("materialize policy source item: %w", err)
}
if _, err := tx.Exec(ctx, `UPDATE catalog_import_intents SET source_item_id=$3 WHERE source_connection_id=$1 AND node_id=$2`,
@@ -131,6 +131,15 @@ VALUES($1,$2,$3,$4,$5,'file','',$7,'configured_scope','unchanged',0,'object_id',
}
itemID = newItemID
}
// 历史行(当时没写来源路径)只补空值:意图已把 item 绑定到本连接的这个 node,
// 身份可证;已有路径绝不被覆盖,避免把下架连接重绑成当前来源。
if _, err := tx.Exec(ctx, `UPDATE source_items SET
normalized_path=CASE WHEN normalized_path='' THEN $2 ELSE normalized_path END,
parent_external_id=CASE WHEN parent_external_id='' THEN $3 ELSE parent_external_id END,
updated_at=CASE WHEN normalized_path='' OR parent_external_id='' THEN NOW() ELSE updated_at END
WHERE id=$1`, itemID, file.RelativePath, file.ParentNodeID); err != nil {
return false, false, 0, false, fmt.Errorf("persist policy source path: %w", err)
}
// Bind the snapshot nodes too (new or reused item): the browser's
// 已导入/已解析 counters join source_catalog_nodes.source_item_id; without
// this write every catalog-only source keeps showing "尚未导入" even after
@@ -231,6 +240,11 @@ ON CONFLICT (source_item_version_id,test_kb_id) DO NOTHING`,
}
planned += int(tag.RowsAffected())
}
if contentState == string(governance.ContentVerified) {
if err := store.autoStartVerifiedPublicationsTx(ctx, tx, versionID, now); err != nil {
return false, false, 0, false, err
}
}
fetchQueued := false
if contentState != string(governance.ContentVerified) {
@@ -286,6 +300,97 @@ func sha256Hex(value string) string {
return hex.EncodeToString(sum[:])
}
// autoStartVerifiedPublicationsTx continues the normal ingestion chain in the
// SAME transaction that made the bytes verified. It deliberately re-checks the
// saved policy, the current binding and the live source state: a file routed
// before a policy/binding change must not be uploaded to a stale target.
func (s *Store) autoStartVerifiedPublicationsTx(ctx context.Context, tx pgx.Tx, versionID string, now time.Time) error {
if versionID == "" {
return errors.New("auto-start requires a version")
}
rows, err := tx.Query(ctx, `
WITH binding AS (
SELECT COALESCE(NULLIF(internal_kb_id,''), $3::text) AS internal_kb_id,
COALESCE(NULLIF(external_kb_id,''), $4::text) AS external_kb_id
FROM routing_kb_bindings WHERE id='active'
), eligible AS (
SELECT publication.id
FROM test_publications publication
JOIN source_item_versions version ON version.id=publication.source_item_version_id
JOIN content_objects content ON content.id=version.content_object_id
JOIN source_items item ON item.id=version.source_item_id
JOIN source_connections connection ON connection.id=item.source_connection_id
LEFT JOIN LATERAL (
SELECT intent.visibility FROM catalog_import_intents intent
WHERE intent.source_item_id=item.id AND intent.source_connection_id=item.source_connection_id
ORDER BY intent.updated_at DESC,intent.node_id LIMIT 1
) intent ON TRUE
CROSS JOIN binding
WHERE version.id=$1
AND publication.superseded_at IS NULL
AND publication.processing_state='planned'
AND publication.ingest_state='pending'
AND publication.knowledge_id=''
AND publication.retrieval_state='unpublished'
AND version.content_state='verified'
AND content.content_state='verified'
AND content.local_spool_ref<>''
AND content.size_bytes>0
AND connection.enabled
AND item.policy_state IN (publication.target_scope,'both')
AND intent.visibility IN (publication.target_scope,'both')
AND NOT filename_is_filtered(item.source_connection_id,item.normalized_path,item.title)
AND NOT EXISTS (SELECT 1 FROM jobs job WHERE job.type='test.upload' AND job.payload->>'publication_id'=publication.id)
AND ((publication.target_scope='internal' AND binding.internal_kb_id<>'' AND publication.test_kb_id=binding.internal_kb_id)
OR (publication.target_scope='external' AND binding.external_kb_id<>'' AND publication.test_kb_id=binding.external_kb_id))
)
UPDATE test_publications publication SET processing_state='pending',updated_at=$2
FROM eligible WHERE publication.id=eligible.id
RETURNING publication.id`, versionID, now, s.defaultInternalKBID, s.defaultExternalKBID)
if err != nil {
return fmt.Errorf("auto-start verified publications: %w", err)
}
ids := make([]string, 0, 2)
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
rows.Close()
return fmt.Errorf("scan auto-started publication: %w", err)
}
ids = append(ids, id)
}
if err := rows.Err(); err != nil {
rows.Close()
return fmt.Errorf("iterate auto-started publications: %w", err)
}
rows.Close()
for _, publicationID := range ids {
confirmationID, err := newOpaqueID("pc-")
if err != nil {
return err
}
jobID, err := newOpaqueID("job-")
if err != nil {
return err
}
payload, err := json.Marshal(map[string]string{"publication_id": publicationID})
if err != nil {
return errors.New("encode auto upload job")
}
if _, err := tx.Exec(ctx, `INSERT INTO processing_confirmations(id,publication_id,operator_ref,reason,confirmed_at,created_at)
VALUES($1,$2,'system:auto','取件 verified 自动接续',$3,$3)
ON CONFLICT (publication_id) DO NOTHING`, confirmationID, publicationID, now); err != nil {
return fmt.Errorf("record auto processing confirmation: %w", err)
}
if _, err := tx.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,priority,available_at,max_attempts,idempotency_key,created_at,updated_at)
VALUES($1,'test.upload',$2::jsonb,'pending',10,$3,5,$4,$3,$3)
ON CONFLICT (idempotency_key) DO NOTHING`, jobID, payload, now, "auto-test-upload:"+publicationID); err != nil {
return fmt.Errorf("enqueue auto upload: %w", err)
}
}
return nil
}
// MarkArtifactFetched finalizes one artifact.fetch success: it (re)uses the
// content_objects row for the verified hash (content-level dedupe), attaches it
// to the pending version and flips the intent to ready. matchedLocal records
@@ -349,6 +454,9 @@ WHERE id=$1`,
WHERE source_connection_id=$1 AND node_id=$2`, connectionID, nodeID); err != nil {
return fmt.Errorf("mark intent fetched: %w", err)
}
if err := s.autoStartVerifiedPublicationsTx(ctx, tx, versionID, now); err != nil {
return fmt.Errorf("continue fetched artifact into upload: %w", err)
}
if ownsTransaction {
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit artifact fetch: %w", err)
+8
View File
@@ -134,6 +134,14 @@ SELECT id FROM updated
// One job type, newest first: a caller which needs "the recent jobs of MY type"
// must not page the global queue (other traffic would hide its own rows).
const jobByIDSQL = `
SELECT id, type, payload, state, priority, available_at,
lease_owner, lease_until, attempt, max_attempts,
last_error, idempotency_key, created_at, updated_at
FROM jobs
WHERE id = $1
`
const listJobsByTypeSQL = `
SELECT id, type, payload, state, priority, available_at,
lease_owner, lease_until, attempt, max_attempts,

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