fix(reconciliation): 运行时读复用知识库绑定 Key

- 为什么:运行时读另用 WEKNORA_RUNTIME_KEY_FILE(0400 文件、启动读一次),当前部署没有该文件,队列与处理详情恒不可用;换 Key 还要重启,且与绑定页不同步。
- 做什么:RuntimeProvider 改为每次请求经 kbbinding.Resolve(EnvTest) 取地址与 Key,与 reconciliationRemote 共用同一 resolver;删除配置字段/校验、ReadRuntimeKeyFile 与测试、compose/env、启动 WARN。
- 三态:绑定不可用→503 runtime_read_unavailable;上游 401/403→502 runtime_read_forbidden;超时/DNS→502 runtime_read_unreachable;overview 增 weknora_queue_error,页面三句不同文案并保留 WeKnora 跳转链接。
- 同步:openapi progress 契约与 502、需求书 §5/Q7、阶段计划、运维手册、CHANGELOG。
- 验证:make verify 17 项 success;新增换 Key 二次请求头、401/403/不可达分类、Service 透传、overview 原因码、页面三文案用例。
This commit is contained in:
Zhero & Rin
2026-12-02 10:37:23 +08:00
committed by 姚章浩
parent e4e3d85657
commit fe9d055522
26 changed files with 391 additions and 164 deletions
-2
View File
@@ -27,8 +27,6 @@ QA_AI_MASTER_KEY_FILE=
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
WEKNORA_BINDING_MASTER_KEY_FILE=
# 测试实例平台级只读 Key:绝对路径、0400;留空 = runtime/* 与队列降级。
WEKNORA_RUNTIME_KEY_FILE=
# 导入对账(T6)总开关:只接线对账服务、只用知识库绑定里的租户 Key。
# 与 TEST_WEKNORA_ENABLED(旧取件/上传链路)解耦;默认关闭,生产按授权再开。
RECONCILIATION_ENABLED=false
+8
View File
@@ -1,5 +1,13 @@
# Changelog
## 开发快照 0.1.426(导入对账:运行时读复用知识库绑定 Key)
### Changed
- **运行时读不再单独维护平台只读 Key**:「导入对账」的 WeKnora 队列与「WeKnora 处理详情」改为每次请求解析「系统设置 → 知识库绑定」测试环境的地址与 Key,与对账扫描共用同一个 resolver;换 Key 保存后下一次请求即生效,无需重启。删除 `WEKNORA_RUNTIME_KEY_FILE` 配置、0400 文件读取与启动 WARN,`weknora.ReadRuntimeKeyFile` 一并移除。
- **三种失败可区分**:绑定未配置/不可用 → 503 `runtime_read_unavailable`;上游 401/403 → 502 `runtime_read_forbidden`(缺 `system_runtime_read`);超时/DNS/连接失败 → 502 `runtime_read_unreachable`。`/api/v1/monitor/overview` 在队列不可用时给出 `weknora_queue_error`,页面显示三句不同指引,且保留「在 WeKnora 中打开」链接。
- 同步 `docs/IMPORT_RECONCILIATION_REQUIREMENTS.md` §5/Q7、`docs/WEKNORA_091_PHASE_PLAN.md` 与 `docs/OPERATIONS_RUNBOOK.md`;`api/openapi.yaml` 的 progress 契约增加 502。
## 开发快照 0.1.425(WeKnora 0.9.1:schema 137 + 漏表门禁 + 编辑历史搬运)
### Added
+11 -1
View File
@@ -50,7 +50,7 @@
"/api/v1/reconciliation/findings/{id}/writeback": {"post":{"tags":["Reconciliation"],"operationId":"writebackReconciliationFinding","summary":"仅限 R5:以 WeKnora 状态回写台账 processing_state,写审计;completed 不可降级","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"reconciliation_writeback_stale 或迁移不允许"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/findings/{id}/requeue": {"post":{"tags":["Reconciliation"],"operationId":"requeueReconciliationFinding","summary":"仅限 R1/R4:R1 清空 document_id 后重排上传;R4 先删旧知识再重传,删除失败则台账不变","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"finding 状态或台账身份已变化"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/findings/{id}/remove": {"post":{"tags":["Reconciliation"],"operationId":"removeReconciliationFinding","summary":"仅限 R2:按远端 document_id 从测试库删除;404 视为已删除;重复点击幂等","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"该文档已被现行台账收养"},"500":{"$ref":"#/components/responses/InternalError"}}}},
"/api/v1/reconciliation/documents/{document_id}/progress": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationDocumentProgress","summary":"实时转发并脱敏 WeKnora 文档处理阶段与历史失败;未配置平台只读 Key、Key 无权限、连接不可达时返回 503,code 分别为 runtime_read_unavailable / runtime_key_forbidden / runtime_unreachable","parameters":[{"name":"document_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}}}},
"/api/v1/reconciliation/documents/{document_id}/progress": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationDocumentProgress","summary":"实时转发并脱敏 WeKnora 文档处理阶段与历史失败;绑定未配置/不可用返回 503 runtime_read_unavailable,上游 401/403 返回 502 runtime_key_forbidden,连接或运行时读失败返回 502 runtime_unreachable","parameters":[{"name":"document_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"$ref":"#/components/responses/BadGateway"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}}}},
"/api/v1/qa-ops/master/field-options": {"get":{"operationId":"getQAMasterFieldOptions","tags":["QA operations"],"summary":"只读主表五字段的正式可选范围,与模型共享同一分类字典;不返回业务问答","parameters":[],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}}},
"/api/v1/qa-ops/master/records/{id}/fields": {"post":{"operationId":"patchQAMasterFields","tags":["QA operations"],"summary":"只更新明确选择的字段并留幂等审计;不改原始正文、其他空白、旧复核或冻结证据。未覆盖的是否正确固定为待确认,拒绝是或否;已覆盖点踩固定为否。quality.correctness_rule=coverage-correctness-v1标记覆盖/正确性固定投影,原字段和复核证据保留","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-master-fields"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["input_hash","input_epoch","base_revision","base_review_revision","nonce","fields"],"properties":{"input_hash":{"type":"string","pattern":"^[a-f0-9]{64}$"},"input_epoch":{"type":"integer","minimum":1},"base_revision":{"type":"integer","minimum":0},"base_review_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"fields":{"type":"object","additionalProperties":false,"minProperties":1,"maxProperties":5,"properties":{"is_correct":{"type":"string","enum":["是","否","待确认"]},"product_category":{"type":"string","enum":["CR/CRA/H/AP","CRV","CR配件","Nova及系列","Nova配件","MG400","MG400配件","M1 Pro","VX500","新示教器","DobotStudio Pro","仿真软件","维护工具","教育所有产品","人形机器人","四六足机器人","X-Trainer","码垛解决方案","码垛插件","焊接解决方案","焊接插件","移动复合机器人","生态插件","生态合作","安全皮肤","未知"]},"problem_type":{"type":"string","enum":["参数","故障","使用配置","二次开发","资料获取","咨询","认证","案例","售后","培训与学习","其他"]},"root_cause":{"type":"string","enum":["知识缺失","检索不到","结果不清","答案生成错误","问题质量差","非知识范围","知识过期"]},"coverage":{"type":"string","enum":["是","否","否但不计入"]}}}}}}}}}},
"/api/v1/qa-ops/master/weekly-drafts/{week}": {"get":{"operationId":"getQAWeeklyDraft","tags":["QA operations"],"summary":"读取租户指定北京时间ISO周的持久草稿;不存在时revision=0且不创建记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}},"post":{"operationId":"saveQAWeeklyDraft","tags":["QA operations"],"summary":"防抖编辑保存:版本锁、逐版历史及同nonce重放;正文不会触发外发/归档","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce","markdown"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"markdown":{"type":"string","maxLength":262144,"description":"UTF-8正文最多256KiB;允许空正文,保存草稿不等于发布"}}}}}}}},
@@ -6161,6 +6161,16 @@
}
}
},
"BadGateway": {
"description": "上游 WeKnora 拒绝或不可达:runtime_read_forbidden(Key 缺 system_runtime_read)或 runtime_read_unreachable(超时/DNS/连接失败)。",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"ServiceUnavailable": {
"description": "依赖的第三方或本地工具当前不可用(例如 dws 未登录/权限不足)。",
"content": {
+11 -20
View File
@@ -209,38 +209,29 @@ func run(ctx context.Context, getenv func(string) string) error {
result := readinessProber.Check(probeCtx)
return result.Target, result.Err
}
// The runtime read (queues / document progress) and the reconciliation remote
// must resolve the SAME knowledge-base binding: an admin who saves a new test
// key in the console gets it applied on the next request, without a restart.
resolveTestConnection := func(resolveCtx context.Context) (string, string, error) {
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return target.BaseURL, target.APIKey, resolveErr
}
knowledgeBaseLister := &weKnoraLister{
resolve: func(resolveCtx context.Context) (string, string, error) {
connection, err := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return connection.BaseURL, connection.APIKey, err
},
resolve: resolveTestConnection,
timeout: config.TestWeKnoraHTTPTimeout,
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
}
runtimeKey := ""
if config.WeKnoraRuntimeKeyFile != "" {
key, keyErr := weknora.ReadRuntimeKeyFile(config.WeKnoraRuntimeKeyFile)
if keyErr != nil {
log.Printf("WARN: WeKnora runtime read key is unavailable; runtime endpoints degrade to 503")
} else {
runtimeKey = key
}
}
runtimeProvider := reconciliation.NewRuntimeProvider(reconciliation.RuntimeConfig{
BaseURL: testEndpointResolver,
APIKey: runtimeKey,
Resolve: resolveTestConnection,
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
})
reconciliationRemote := &weknoraaccess.Client{
Resolver: readiness.Resolver{
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
return target.BaseURL, target.APIKey, resolveErr
},
DefaultKB: config.InternalRoutingKnowledgeBaseID,
ResolveConnection: resolveTestConnection,
DefaultKB: config.InternalRoutingKnowledgeBaseID,
},
Timeout: config.TestWeKnoraHTTPTimeout,
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
-3
View File
@@ -68,9 +68,6 @@ services:
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
# 测试实例平台级只读 Key(0400,绝对路径)。空值 = runtime/* 与队列降级;
# Key 本身只挂载 secret 文件,绝不写进 compose。
WEKNORA_RUNTIME_KEY_FILE: "${WEKNORA_RUNTIME_KEY_FILE:-}"
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
+7 -7
View File
@@ -109,7 +109,7 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5
| --- | --- | --- |
| 全量列出库内条目 | `GET /knowledge-bases/{id}/knowledge`(分页;可按 `parse_status`、`source`、时间、目录筛选) | 现有租户 API Key |
| 单条确认 | `GET /knowledge/{id}` | 现有租户 API Key |
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | **平台级 API Key,能力 `system_runtime_read`**(上游 `routes_auth_tenant.go:356`) |
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | 知识库绑定(测试环境)里的 Key,需能力 `system_runtime_read`(上游 `routes_auth_tenant.go:356`) |
| 队列深度 | `GET /system/admin/runtime/queues` | 同上 |
条目中对账要用的字段:`id`、`knowledge_base_id`、`channel`、`metadata`、`file_hash`、`parse_status`、`stall_state`、`enable_status`、`updated_at`。
@@ -118,12 +118,12 @@ WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5
**列表的盲区**:不传 `parse_status` 时上游隐藏 `deleting` 行(`repository/knowledge.go:176`),所以“列表里没有”不等于“已删除”,R1 必须单条 GET 复核。
**平台级 Key 的配置契约(Q7 已裁定)**
**运行时读 Key 的配置契约(Q7,2026-12-02 改判)**
- 键名 `WEKNORA_RUNTIME_KEY_FILE`,值为**绝对路径**,secret 文件挂载进容器;不写进 compose 环境变量、不进 Git。
- 启动时读取一次,权限 0400;换 Key 需重启平台(与现有 `*_API_KEY_FILE` 一致,不做热加载)。
- “变量为空”与“变量有值但文件缺失/不可读”要区分:前者静默降级;后者启动不失败,写一条 WARN 日志,运行时按未配置处理。
- 两种情况都让 `runtime/queues` 返回 503 `runtime_read_unavailable`、`/monitor/overview` 的 `weknora_queues` 为 `null`;`runtime/documents/{id}` 另按上游结果细分:未配置 Key → `runtime_read_unavailable`,401/403 → `runtime_key_forbidden`,其他连接/上游失败 → `runtime_unreachable`。对账本身只需租户 Key,照常运行。
- 不再单独维护平台级只读 Key:「导入对账」的 `runtime/queues` 与 `runtime/documents/{id}`(以及页面上的「WeKnora 处理详情」)直接使用「系统设置 → 知识库绑定」测试环境保存的地址与 Key,与对账扫描共用同一个 resolver。
- 每次请求解析绑定;管理员换 Key 保存后,下一次请求即生效,不需要重启 API。不再读取任何 Key 文件。
- 绑定未配置或无法解密 → 503 `runtime_read_unavailable`,页面指向绑定页;上游 401/403 → 502 `runtime_key_forbidden`,页面提示去 WeKnora 授权 `system_runtime_read`;连接或运行时读失败 → 502 `runtime_unreachable`,页面提示连不上 WeKnora。
- `/monitor/overview` 的 `weknora_queues` 不可用时为 `null`,并用 `weknora_queue_error` 携带上述原因码;三种情况都不影响对账批次本身(对账只用租户 Key 列库与读单条)。
## 6. 运行方式
@@ -240,7 +240,7 @@ T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
| Q7 | 运行时读 Key 的配置键名 | **已裁定(2026-12-02 改判)**:不再单独配置;复用知识库绑定(测试环境)的地址与 Key |
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加“距上次发布 N 天” |
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受并发增删造成的个别漏项在下一批补上,不引入游标 |
+2
View File
@@ -82,6 +82,8 @@ http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,
里的旧 Key。内外库留空表示取消该方向绑定:测试侧回退到部署默认库,生产侧回退到
「同 ID 语义」,提示里会写明。
**导入对账的运行时读。** 队列栏与「WeKnora 处理详情」复用本页保存的测试环境地址与 Key(该 Key 需在 WeKnora 授予 `system_runtime_read`),不再挂载单独的只读 Key 文件。换 Key 保存后下一次刷新即生效,无需重启 API。三种失败提示分别指向:绑定未配置/不可用 → 本页;缺权限 → WeKnora 授权;连不上 → 检查地址与网络。
在**测试治理机**上检验已有通道。`/health` 返回 200 证明转发可用,无凭据列库返回 401 表明请求已到认证层。接着在治理页面安全输入该实例的 Key 并验证真实库列表。本次核验时,生产通道探活成功,匿名列库返回 401。带生产凭据列库和保存映射仍待验收。
```bash
+3 -3
View File
@@ -120,7 +120,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
- [ ] `schema_migrations` 应为 `137, false`
- [ ] 抽查原有知识库的检索、问答是否正常
- [ ] 测试环境额外检查:平台走一轮「取件 → 上传 → 解析 → 完成」
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 创建平台级 API Key,只授予 `system_runtime_read` 能力,以 secret 文件形式交给平台(不写进 Git 或 compose),然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。生产不需要这个 Key
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 给「系统设置 → 知识库绑定」里保存的那把 Key 授予 `system_runtime_read` 能力,然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。不再创建/挂载独立的平台只读 Key;生产不需要该能力
- [ ] 生产额外检查:平台发布通道只读预检(`release-diag`)通过
**回退**:不能直接换回旧镜像。向下迁移会删除凭据表、截短审计字段。正确做法是停止写入后,用升级前的备份恢复数据库、存储和配置,再切回 v0.9.0 镜像。
@@ -145,7 +145,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
- 新建 `reconciliation_runs` / `reconciliation_findings` 两张表:`runs` 永久保留;`findings` 按 `run_id` 整批清理,保留最近 30 批且不超过 90 天(Q5)。同一测试库的 `running` 批次用部分唯一索引约束(`WHERE state='running'`)。
- 对账扫描使用 `page_size=1000`:要把 `internal/platform/weknora/client.go` 的 `validPage` 上限从 100 放开(或给对账单独一条扫描路径),不能沿用上传恢复的 100。扫描全程串行(在途 1 个请求),R1/R2 确认可用 `reconciliation_confirm_concurrency`(默认 1、上限 8),不复用 `ingestion_concurrency`。
- 与整库导出/发布不互斥;批次开始和结束时各检测一次是否有导出/发布作业在跑,命中则写 `window_overlapped=true`,该批 R1/R2 的 `confirmation_state='pending'`(Q6)。
- 平台级只读 Key 走 `WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,启动读取一次,不做热加载);未配置或文件不可读时 `runtime/queues` 返回 503 `runtime_read_unavailable`,`runtime/documents/{id}` 按上游结果细分 `runtime_read_unavailable` / `runtime_key_forbidden` / `runtime_unreachable`,对账不受影响(Q7)。
- 运行时读(队列与处理详情)复用知识库绑定(测试环境)的地址与 Key,每次请求解析、保存后即时生效,不单独维护 Key 文件;绑定不可用返回 503 `runtime_read_unavailable`,上游 401/403 返回 502 `runtime_key_forbidden`,连接或运行时读失败返回 502 `runtime_unreachable`,对账不受影响(Q7,2026-12-02 改判)。
- 状态映射只写在服务端一处,接口返回 `normalized_state`;R5 回写按迁移矩阵校验,`completed` 不可降级。
- 处置动作:新增 finding 级 `requeue`(R1/R4)与 `remove`(R2);R6 复用现有 `POST /test-publications/{id}/removal`(`removal-retry` 只重试已失败移除)。R1/R4 不能走 `retryPublicationsBatch`,R2 不能走测试库移除,原因见需求 §7(Q9)。
- 扫描保留 offset 翻页,不引入游标;并发增删造成的个别漏项在下一批补上(Q10)。
@@ -164,7 +164,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
| Q7 | 运行时读 Key 的配置键名 | **已裁定(2026-12-02 改判)**:不再单独配置;复用知识库绑定(测试环境)的地址与 Key |
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加"距上次发布 N 天" |
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受个别漏项下一批补上,不引入游标 |
-7
View File
@@ -59,9 +59,6 @@ type Config struct {
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
WeKnoraBindingMasterKeyFile string
// WeKnoraRuntimeKeyFile 是测试实例平台级只读 Key(0400,绝对路径)。空值=
// runtime/* 与 overview 队列降级为不可用;对账本身只用租户 Key。
WeKnoraRuntimeKeyFile string
// ReconciliationSettings:批次执行参数。全部可配,但都有安全默认值。
// ReconciliationEnabled 是「导入对账」自身的开关:只决定对账服务是否接线,
// 与 TEST_WEKNORA_ENABLED(旧测试库取件/上传链路)解耦——对账只用租户 Key。
@@ -242,7 +239,6 @@ func Load(getenv func(string) string) (Config, error) {
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
WeKnoraRuntimeKeyFile: strings.TrimSpace(getenv("WEKNORA_RUNTIME_KEY_FILE")),
ReconciliationDailyAt: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_DAILY_AT")), "02:00"),
ReconciliationTimezone: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_TIMEZONE")), "Asia/Shanghai"),
ReconciliationScheduleEnabled: true,
@@ -406,9 +402,6 @@ func Load(getenv func(string) string) (Config, error) {
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
}
if config.WeKnoraRuntimeKeyFile != "" && !filepath.IsAbs(config.WeKnoraRuntimeKeyFile) {
return Config{}, errors.New("WEKNORA_RUNTIME_KEY_FILE must be an absolute path")
}
if raw := getenv("RECONCILIATION_ENABLED"); raw != "" {
config.ReconciliationEnabled, err = strconv.ParseBool(raw)
if err != nil {
+4
View File
@@ -115,6 +115,10 @@ type MonitorOverview struct {
// WeKnoraQueues is a safe projection of the test instance runtime queues.
// nil means "not configured or unreadable", never "healthy empty".
WeKnoraQueues *WeKnoraQueueSummary `json:"weknora_queues"`
// WeKnoraQueueError carries the classified reason when WeKnoraQueues is nil
// (binding missing, key lacks permission, or instance unreachable). Empty
// means no runtime queue reader was wired.
WeKnoraQueueError string `json:"weknora_queue_error,omitempty"`
}
// WeKnoraQueueSummary is the bounded queue projection the console may show.
+2 -2
View File
@@ -47,9 +47,9 @@ func writeReconciliationError(w http.ResponseWriter, err error) {
case errors.Is(err, reconciliation.ErrActionConflict), errors.Is(err, reconciliation.ErrActionNotAllowed):
writeJSON(w, http.StatusConflict, map[string]string{"error": "reconciliation_state_changed", "code": "reconciliation_state_changed"})
case errors.Is(err, reconciliation.ErrRuntimeForbidden):
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_key_forbidden", "code": "runtime_key_forbidden"})
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "runtime_key_forbidden", "code": "runtime_key_forbidden"})
case errors.Is(err, reconciliation.ErrRuntimeUnreachable):
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_unreachable", "code": "runtime_unreachable"})
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "runtime_unreachable", "code": "runtime_unreachable"})
case errors.Is(err, reconciliation.ErrRuntimeUnavailable):
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_read_unavailable", "code": "runtime_read_unavailable"})
case errors.Is(err, reconciliation.ErrRemoteFailed):
+8 -7
View File
@@ -147,12 +147,13 @@ func TestReconciliationProgressRejectsMalformedDocumentIDWith400(t *testing.T) {
func TestReconciliationProgressClassifiesRuntimeFailures(t *testing.T) {
cases := []struct {
err error
code string
err error
status int
code string
}{
{reconciliation.ErrRuntimeForbidden, "runtime_key_forbidden"},
{reconciliation.ErrRuntimeUnreachable, "runtime_unreachable"},
{reconciliation.ErrRuntimeUnavailable, "runtime_read_unavailable"},
{reconciliation.ErrRuntimeForbidden, http.StatusBadGateway, "runtime_key_forbidden"},
{reconciliation.ErrRuntimeUnreachable, http.StatusBadGateway, "runtime_unreachable"},
{reconciliation.ErrRuntimeUnavailable, http.StatusServiceUnavailable, "runtime_read_unavailable"},
}
for _, tc := range cases {
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: &reconciliationServiceStub{err: tc.err}})
@@ -161,8 +162,8 @@ func TestReconciliationProgressClassifiesRuntimeFailures(t *testing.T) {
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/documents/doc-1/progress", roleViewer, ""))
if recorder.Code != http.StatusServiceUnavailable || !strings.Contains(recorder.Body.String(), tc.code) {
t.Fatalf("%v = %d %s, want 503 %s", tc.err, recorder.Code, recorder.Body.String(), tc.code)
if recorder.Code != tc.status || !strings.Contains(recorder.Body.String(), tc.code) {
t.Fatalf("%v = %d %s, want %d %s", tc.err, recorder.Code, recorder.Body.String(), tc.status, tc.code)
}
}
}
+15 -3
View File
@@ -16,6 +16,7 @@ import (
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/reconciliation"
)
type Database interface {
@@ -133,9 +134,7 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
governance.MonitorService{Key: "oss", Name: "OSS", State: "unknown", Detail: "未配置独立健康探测", ObservedAt: now},
)
if provider.runtimeQueues != nil {
if queues, queueErr := provider.runtimeQueues.Queues(ctx); queueErr == nil {
overview.WeKnoraQueues = queues
}
overview.WeKnoraQueues, overview.WeKnoraQueueError = runtimeQueueProjection(ctx, provider.runtimeQueues)
}
rows, err := provider.db.Query(ctx, `SELECT p.test_kb_id,
CASE WHEN COUNT(DISTINCT p.target_scope)=1 THEN MIN(p.target_scope) ELSE 'mixed' END,
@@ -396,3 +395,16 @@ func monitorStageDetail(ingestState, processingState, errorCode string) string {
return "等待远端状态更新"
}
}
// runtimeQueueProjection keeps the overview at 200 while stating why the queue
// is absent: nil queues + the classified code, never a healthy empty queue.
func runtimeQueueProjection(ctx context.Context, reader QueueReader) (*governance.WeKnoraQueueSummary, string) {
if reader == nil {
return nil, ""
}
queues, err := reader.Queues(ctx)
if err != nil {
return nil, reconciliation.RuntimeErrorCode(err)
}
return queues, ""
}
+46 -1
View File
@@ -1,6 +1,13 @@
package monitoring
import "testing"
import (
"context"
"errors"
"testing"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/reconciliation"
)
func TestParseCPUStatAndMemoryInfo(t *testing.T) {
idle, total, err := parseCPUStat("cpu 100 20 30 400 50 6 7 8 0 0\n")
@@ -22,3 +29,41 @@ func TestCPUPercentUsesTwoMonotonicSamples(t *testing.T) {
t.Fatal("non-monotonic CPU counters must fail closed to zero")
}
}
type stubQueueReader struct {
summary *governance.WeKnoraQueueSummary
err error
}
func (reader stubQueueReader) Queues(context.Context) (*governance.WeKnoraQueueSummary, error) {
return reader.summary, reader.err
}
func TestRuntimeQueueProjectionStatesWhyQueueIsAbsent(t *testing.T) {
cases := []struct {
name string
err error
code string
}{
{name: "binding unavailable", err: reconciliation.ErrRuntimeUnavailable, code: "runtime_read_unavailable"},
{name: "key forbidden", err: reconciliation.ErrRuntimeForbidden, code: "runtime_read_forbidden"},
{name: "unreachable", err: reconciliation.ErrRuntimeUnreachable, code: "runtime_read_unreachable"},
{name: "unclassified", err: errors.New("boom"), code: ""},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
queues, code := runtimeQueueProjection(context.Background(), stubQueueReader{err: testCase.err})
if queues != nil || code != testCase.code {
t.Fatalf("queues=%v code=%q, want nil/%q", queues, code, testCase.code)
}
})
}
summary := &governance.WeKnoraQueueSummary{Available: true}
queues, code := runtimeQueueProjection(context.Background(), stubQueueReader{summary: summary})
if queues != summary || code != "" {
t.Fatalf("available queue projection = %v/%q", queues, code)
}
if queues, code := runtimeQueueProjection(context.Background(), nil); queues != nil || code != "" {
t.Fatalf("unwired projection = %v/%q", queues, code)
}
}
-39
View File
@@ -47,42 +47,3 @@ func ReadAPIKeyFile(path string) (string, error) {
}
return key, nil
}
// ReadRuntimeKeyFile reads the platform-level read-only key. Q7 fixes the
// contract at mode 0400: unlike tenant keys (0600), this key must not be
// readable by the process owner's group and never leaves the API process.
func ReadRuntimeKeyFile(path string) (string, error) {
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return "", fmt.Errorf("open runtime key file: %w", err)
}
file := os.NewFile(uintptr(fd), "weknora-runtime-key")
if file == nil {
_ = syscall.Close(fd)
return "", errors.New("open runtime key file: invalid file descriptor")
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return "", fmt.Errorf("inspect runtime key file: %w", err)
}
if !info.Mode().IsRegular() {
return "", errors.New("runtime key file must be a regular file")
}
if info.Mode().Perm() != 0o400 {
return "", errors.New("runtime key file permissions must be 0400")
}
body, err := io.ReadAll(io.LimitReader(file, maxAPIKeyFileBytes+1))
if err != nil {
return "", fmt.Errorf("read runtime key file: %w", err)
}
if len(body) > maxAPIKeyFileBytes {
return "", errors.New("runtime key file is too large")
}
key := strings.TrimSpace(string(body))
if key == "" {
return "", errors.New("runtime key file is empty")
}
return key, nil
}
-17
View File
@@ -53,20 +53,3 @@ func TestReadAPIKeyFileRejectsUnsafeInputsWithoutLeakingContent(t *testing.T) {
}
}
}
func TestReadRuntimeKeyFileRequires0400(t *testing.T) {
path := t.TempDir() + "/runtime-key"
if err := os.WriteFile(path, []byte("runtime-secret\n"), 0o400); err != nil {
t.Fatal(err)
}
key, err := ReadRuntimeKeyFile(path)
if err != nil || key != "runtime-secret" {
t.Fatalf("key=%q err=%v", key, err)
}
if err := os.Chmod(path, 0o600); err != nil {
t.Fatal(err)
}
if _, err := ReadRuntimeKeyFile(path); err == nil {
t.Fatal("0600 runtime key must be rejected")
}
}
+33 -20
View File
@@ -2,6 +2,7 @@ package reconciliation
import (
"context"
"net/http"
"strings"
"time"
@@ -10,9 +11,12 @@ import (
"knowledge-governance/internal/platform/weknora"
)
// RuntimeConfig.Resolve runs for every request instead of once at startup: the
// runtime read uses the same knowledge-base binding (test environment) as the
// reconciliation remote, so an admin saving a new key must take effect on the
// next request without restarting the API.
type RuntimeConfig struct {
BaseURL func(context.Context) string
APIKey string
Resolve func(context.Context) (baseURL, apiKey string, err error)
Timeout time.Duration
AllowDockerHTTP bool
AllowPrivateHTTP bool
@@ -20,8 +24,7 @@ type RuntimeConfig struct {
}
type RuntimeProvider struct {
baseURL func(context.Context) string
apiKey string
resolve func(context.Context) (baseURL, apiKey string, err error)
timeout time.Duration
allowDockerHTTP bool
allowPrivateHTTP bool
@@ -33,26 +36,28 @@ func NewRuntimeProvider(config RuntimeConfig) *RuntimeProvider {
config.Now = time.Now
}
return &RuntimeProvider{
baseURL: config.BaseURL, apiKey: strings.TrimSpace(config.APIKey), timeout: config.Timeout,
resolve: config.Resolve, timeout: config.Timeout,
allowDockerHTTP: config.AllowDockerHTTP, allowPrivateHTTP: config.AllowPrivateHTTP, now: config.Now,
}
}
func (p *RuntimeProvider) Available() bool {
return p != nil && p.apiKey != "" && p.baseURL != nil
}
func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, error) {
if !p.Available() {
if p == nil || p.resolve == nil {
return nil, ErrRuntimeUnavailable
}
baseURL := strings.TrimSpace(p.baseURL(ctx))
if baseURL == "" {
baseURL, apiKey, err := p.resolve(ctx)
if err != nil {
// Not configured, storage locked, or the saved key cannot be opened:
// all of them mean "no usable binding", never "upstream rejected us".
return nil, ErrRuntimeUnavailable
}
baseURL, apiKey = strings.TrimSpace(baseURL), strings.TrimSpace(apiKey)
if baseURL == "" || apiKey == "" {
return nil, ErrRuntimeUnavailable
}
client, err := weknora.NewRuntimeClient(weknora.RuntimeClientConfig{
BaseURL: baseURL,
APIKey: p.apiKey,
APIKey: apiKey,
Timeout: p.timeout,
AllowDockerHTTP: p.allowDockerHTTP,
AllowPrivateHTTP: p.allowPrivateHTTP,
@@ -63,6 +68,18 @@ func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, e
return client, nil
}
// classifyRuntimeReadFailure separates the two reasons an operator can act on:
// 401/403 means the bound key lacks system_runtime_read; everything else
// (timeout, DNS, connection, upstream error) means the read itself failed.
func classifyRuntimeReadFailure(err error) error {
switch weknora.StatusCode(err) {
case http.StatusUnauthorized, http.StatusForbidden:
return ErrRuntimeForbidden
default:
return ErrRuntimeUnreachable
}
}
func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueSummary, error) {
client, err := p.client(ctx)
if err != nil {
@@ -74,7 +91,7 @@ func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueS
defer cancel()
queues, err := client.Queues(queueCtx)
if err != nil {
return nil, ErrRuntimeUnavailable
return nil, classifyRuntimeReadFailure(err)
}
summary := &governance.WeKnoraQueueSummary{
Available: queues.Available, QueuesError: queues.QueuesError, WorkersError: queues.WorkersError,
@@ -97,14 +114,10 @@ func (p *RuntimeProvider) DocumentProgress(ctx context.Context, documentID strin
}
detail, err := client.DocumentProgress(ctx, documentID)
if err != nil {
switch {
case weknora.IsNotFound(err):
if weknora.IsNotFound(err) {
return governance.ReconciliationProgress{}, err
case weknora.StatusCode(err) == http.StatusUnauthorized || weknora.StatusCode(err) == http.StatusForbidden:
return governance.ReconciliationProgress{}, ErrRuntimeForbidden
default:
return governance.ReconciliationProgress{}, ErrRuntimeUnreachable
}
return governance.ReconciliationProgress{}, classifyRuntimeReadFailure(err)
}
progress := governance.ReconciliationProgress{
DocumentID: detail.Document.ID, ParseStatus: detail.Document.ParseStatus,
+125 -7
View File
@@ -7,12 +7,17 @@ import (
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"knowledge-governance/internal/platform/weknora"
)
func staticConnection(baseURL, apiKey string) func(context.Context) (string, string, error) {
return func(context.Context) (string, string, error) { return baseURL, apiKey, nil }
}
func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-API-Key") != "runtime-key" {
@@ -37,8 +42,8 @@ func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
}))
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
Resolve: staticConnection(server.URL, "runtime-key"),
Timeout: 5 * time.Second,
})
queues, err := provider.Queues(context.Background())
if err != nil || !queues.Available || len(queues.Queues) != 1 || queues.Queues[0].Pending != 3 {
@@ -53,22 +58,135 @@ func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
}
}
// The binding is editable from the console, so the provider must ask for the
// key on every request instead of freezing the first one it sees.
func TestRuntimeProviderResolvesKeyOnEveryRequest(t *testing.T) {
var mu sync.Mutex
var seen []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
seen = append(seen, r.Header.Get("X-API-Key"))
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]any{"available": true, "queues": []map[string]any{}})
}))
defer server.Close()
mu.Lock()
key := "old-key"
mu.Unlock()
provider := NewRuntimeProvider(RuntimeConfig{
Resolve: func(context.Context) (string, string, error) {
mu.Lock()
defer mu.Unlock()
return server.URL, key, nil
},
Timeout: 5 * time.Second,
})
if _, err := provider.Queues(context.Background()); err != nil {
t.Fatal(err)
}
mu.Lock()
key = "new-key"
mu.Unlock()
if _, err := provider.Queues(context.Background()); err != nil {
t.Fatal(err)
}
mu.Lock()
defer mu.Unlock()
if len(seen) != 2 || seen[0] != "old-key" || seen[1] != "new-key" {
t.Fatalf("request keys = %v, want [old-key new-key]", seen)
}
}
func TestRuntimeProviderClassifiesUpstreamFailures(t *testing.T) {
cases := []struct {
name string
status int
want error
}{
{name: "unauthorized", status: http.StatusUnauthorized, want: ErrRuntimeForbidden},
{name: "forbidden", status: http.StatusForbidden, want: ErrRuntimeForbidden},
{name: "server error still unavailable", status: http.StatusInternalServerError, want: ErrRuntimeUnavailable},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(testCase.status)
}))
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
Resolve: staticConnection(server.URL, "runtime-key"),
Timeout: 5 * time.Second,
})
if _, err := provider.Queues(context.Background()); !errors.Is(err, testCase.want) {
t.Fatalf("queues err = %v, want %v", err, testCase.want)
}
if _, err := provider.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, testCase.want) {
t.Fatalf("progress err = %v, want %v", err, testCase.want)
}
})
}
}
func TestRuntimeProviderClassifiesUnreachable(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
url := server.URL
server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
Resolve: staticConnection(url, "runtime-key"),
Timeout: time.Second,
})
if _, err := provider.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnreachable) {
t.Fatalf("queues err = %v, want %v", err, ErrRuntimeUnreachable)
}
if _, err := provider.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, ErrRuntimeUnreachable) {
t.Fatalf("progress err = %v, want %v", err, ErrRuntimeUnreachable)
}
}
func TestRuntimeProviderUnavailableAndNotFound(t *testing.T) {
unavailable := NewRuntimeProvider(RuntimeConfig{BaseURL: func(context.Context) string { return "https://example.test" }})
unavailable := NewRuntimeProvider(RuntimeConfig{
Resolve: func(context.Context) (string, string, error) { return "", "", nil },
})
if _, err := unavailable.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnavailable) {
t.Fatalf("unconfigured queues err=%v", err)
}
broken := NewRuntimeProvider(RuntimeConfig{
Resolve: func(context.Context) (string, string, error) {
return "", "", errors.New("binding storage is not ready")
},
})
if _, err := broken.DocumentProgress(context.Background(), "doc-1"); !errors.Is(err, ErrRuntimeUnavailable) {
t.Fatalf("broken binding err=%v", err)
}
server := httptest.NewServer(http.NotFoundHandler())
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
Resolve: staticConnection(server.URL, "runtime-key"),
Timeout: 5 * time.Second,
})
if _, err := provider.DocumentProgress(context.Background(), "missing"); err == nil || weknora.StatusCode(err) != 404 {
t.Fatalf("missing document err=%v", err)
}
}
func TestRuntimeErrorCodeDistinguishesStates(t *testing.T) {
cases := map[string]error{
"runtime_read_unavailable": ErrRuntimeUnavailable,
"runtime_read_forbidden": ErrRuntimeForbidden,
"runtime_read_unreachable": ErrRuntimeUnreachable,
"": errors.New("unclassified"),
}
for want, err := range cases {
if got := RuntimeErrorCode(err); got != want {
t.Fatalf("RuntimeErrorCode(%v) = %q, want %q", err, got, want)
}
}
if got := RuntimeErrorCode(nil); got != "" {
t.Fatalf("RuntimeErrorCode(nil) = %q", got)
}
}
// The progress passthrough is a projection, not a proxy: whatever extra fields
// the platform endpoint returns (keys, authorization headers, token echoes) must
// never reach the browser. This guards the shape if someone later switches to
@@ -89,8 +207,8 @@ func TestRuntimeProviderDropsSensitiveUpstreamFields(t *testing.T) {
}))
defer server.Close()
provider := NewRuntimeProvider(RuntimeConfig{
BaseURL: func(context.Context) string { return server.URL },
APIKey: "runtime-key", Timeout: 5 * time.Second,
Resolve: staticConnection(server.URL, "runtime-key"),
Timeout: 5 * time.Second,
})
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
if err != nil {
+21 -1
View File
@@ -21,12 +21,27 @@ var (
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
ErrRemoteFailed = errors.New("reconciliation remote call failed")
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
// ErrRuntimeForbidden / ErrRuntimeUnreachable 把「Key 无权限」与「连不上」
// ErrRuntimeForbidden / ErrRuntimeUnreachable 把「Key 无权限」与「连不上」
// 从 ErrRuntimeUnavailable 里拆出来:页面要给两种不同的中文,不能再折叠。
ErrRuntimeForbidden = errors.New("weknora runtime key forbidden")
ErrRuntimeUnreachable = errors.New("weknora runtime read unreachable")
)
// RuntimeErrorCode is the stable code the browser branches on. Unclassified
// failures return "" so callers keep their generic fallback instead of guessing.
func RuntimeErrorCode(err error) string {
switch {
case errors.Is(err, ErrRuntimeForbidden):
return "runtime_key_forbidden"
case errors.Is(err, ErrRuntimeUnreachable):
return "runtime_unreachable"
case errors.Is(err, ErrRuntimeUnavailable):
return "runtime_read_unavailable"
default:
return ""
}
}
type Store interface {
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
@@ -335,6 +350,11 @@ func (s *Service) Progress(ctx context.Context, documentID string) (governance.R
return governance.ReconciliationProgress{}, err
case weknora.StatusCode(err) == 404:
return governance.ReconciliationProgress{}, ErrNotFound
case errors.Is(err, ErrRuntimeUnavailable), errors.Is(err, ErrRuntimeForbidden), errors.Is(err, ErrRuntimeUnreachable):
// The provider already classified the failure; collapsing it here would
// erase the distinction between "no binding", "no permission" and
// "unreachable" that the page needs.
return governance.ReconciliationProgress{}, err
default:
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
}
+30 -9
View File
@@ -581,17 +581,38 @@ func TestCreateRunEnqueuesJobWithinJobIDLimit(t *testing.T) {
}
}
type progressRuntimeStub struct{ err error }
type failingRuntime struct{ err error }
func (s progressRuntimeStub) DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error) {
return governance.ReconciliationProgress{}, s.err
func (runtime failingRuntime) DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error) {
return governance.ReconciliationProgress{}, runtime.err
}
func TestProgressPassesProviderClassificationInsteadOfRefolding(t *testing.T) {
for _, want := range []error{ErrRuntimeForbidden, ErrRuntimeUnreachable, ErrRuntimeUnavailable} {
service := &Service{runtime: progressRuntimeStub{err: want}}
if _, err := service.Progress(context.Background(), "doc-1"); !errors.Is(err, want) {
t.Fatalf("Progress err=%v, want %v", err, want)
}
// Progress must not re-collapse the provider's classification: the page needs
// "no binding", "no permission" and "unreachable" to stay distinct.
func TestProgressPreservesClassifiedRuntimeErrors(t *testing.T) {
cases := []struct {
name string
err error
want error
}{
{name: "unavailable", err: ErrRuntimeUnavailable, want: ErrRuntimeUnavailable},
{name: "forbidden", err: ErrRuntimeForbidden, want: ErrRuntimeForbidden},
{name: "unreachable", err: ErrRuntimeUnreachable, want: ErrRuntimeUnreachable},
{name: "not found", err: &weknora.HTTPError{StatusCode: http.StatusNotFound}, want: ErrNotFound},
{name: "unclassified", err: errors.New("boom"), want: ErrRuntimeUnavailable},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
service, err := New(Config{
Store: &fakeReconciliationStore{}, Remote: &fakeReconciliationRemote{},
Runtime: failingRuntime{err: testCase.err},
})
if err != nil {
t.Fatal(err)
}
if _, err := service.Progress(context.Background(), "doc-1"); !errors.Is(err, testCase.want) {
t.Fatalf("Progress err = %v, want %v", err, testCase.want)
}
})
}
}
+22 -8
View File
@@ -132,19 +132,33 @@ describe('reconciliation findings', () => {
})
describe('ServiceStrip queue availability', () => {
const overview = (queues: MonitorOverview['weknora_queues']) =>
({ weknora_queues: queues, health: [] }) as unknown as MonitorOverview
const overview = (queues: MonitorOverview['weknora_queues'], queueError?: string) =>
({ weknora_queues: queues, weknora_queue_error: queueError, health: [] }) as unknown as MonitorOverview
it('states an unavailable queue instead of rendering 0 waiting · 0 active', () => {
const html = renderToStaticMarkup(
<ServiceStrip
overview={overview({ available: false, queues_error: true, workers_error: false, queues: [], timestamp: 0 })}
/>
)
expect(html).toContain('队列不可用')
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_read_unavailable')} />)
expect(html).toContain('未配置知识库绑定或绑定不可用')
expect(html).not.toContain('0 等待')
})
it('tells the operator to authorize the missing permission', () => {
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_read_forbidden')} />)
expect(html).toContain('当前 Key 缺少平台运行时读权限')
expect(html).not.toContain('连不上 WeKnora')
expect(html).not.toContain('runtime_read_forbidden')
})
it('reports an unreachable instance instead of a missing key', () => {
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null, 'runtime_read_unreachable')} />)
expect(html).toContain('连不上 WeKnora')
expect(html).not.toContain('缺少平台运行时读权限')
})
it('falls back to a neutral sentence for an unknown reason', () => {
const html = renderToStaticMarkup(<ServiceStrip overview={overview(null)} />)
expect(html).toContain('队列暂不可用')
})
it('prints queue depth when the queue is available', () => {
const html = renderToStaticMarkup(
<ServiceStrip
+2 -1
View File
@@ -69,6 +69,7 @@ interface FindingsProps {
// weknora_queues; an unavailable queue is stated, never rendered as a zero.
export function ServiceStrip({ overview }: { overview: MonitorOverview | null }) {
const queue = overview?.weknora_queues
const queueError = overview?.weknora_queue_error
const ready = overview?.health.filter((item) => item.readiness === 'ready').length
const attention = overview?.health.filter(
(item) => item.applicable && item.configured && item.readiness !== 'ready'
@@ -83,7 +84,7 @@ export function ServiceStrip({ overview }: { overview: MonitorOverview | null })
{queue.queues.reduce((sum, item) => sum + item.active, 0)} 运行
</b>
) : (
<b className="monitor-muted">未配置只读 Key 或队列不可用</b>
<b className="monitor-muted">{queueError ? reconciliationFailureText(queueError) : '队列暂不可用'}</b>
)}
</span>
<span>
+35 -2
View File
@@ -19,7 +19,7 @@ afterEach(() => {
vi.unstubAllGlobals()
})
describe('WeKnora progress drawer block', () => {
it('degrades to a read-only key message on 503', async () => {
it('degrades to a binding message on 503', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
@@ -30,7 +30,40 @@ describe('WeKnora progress drawer block', () => {
)
await act(async () => root.render(<WeKnoraProgress documentID="doc-1" />))
await act(async () => await Promise.resolve())
expect(container.textContent).toContain('缺少平台运行时读权限')
expect(container.textContent).toContain('未配置知识库绑定或绑定不可用')
})
it('names the missing permission when the key is rejected', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(JSON.stringify({ error: 'runtime_key_forbidden', code: 'runtime_key_forbidden' }), {
status: 502,
})
)
)
await act(async () =>
root.render(
<WeKnoraProgress documentID="doc-1" weknoraURL="https://weknora.test/platform/knowledge-bases/kb-1" />
)
)
await act(async () => await Promise.resolve())
expect(container.textContent).toContain('当前 Key 缺少平台运行时读权限')
expect(container.textContent).not.toContain('runtime_key_forbidden')
expect(container.querySelector('a[href="https://weknora.test/platform/knowledge-bases/kb-1"]')).not.toBeNull()
})
it('says the instance is unreachable instead of blaming the key', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(JSON.stringify({ error: 'runtime_unreachable', code: 'runtime_unreachable' }), {
status: 502,
})
)
)
await act(async () => root.render(<WeKnoraProgress documentID="doc-1" />))
await act(async () => await Promise.resolve())
expect(container.textContent).toContain('连不上 WeKnora')
expect(container.textContent).not.toContain('缺少平台运行时读权限')
})
it('shows stages and failures when available', async () => {
vi.stubGlobal(
+1 -1
View File
@@ -62,7 +62,7 @@ describe('platform task drawer', () => {
)
await act(async () => root.render(<TaskDetail item={item} onClose={vi.fn()} />))
await act(async () => await Promise.resolve())
expect(container.textContent).toContain('缺少平台运行时读权限')
expect(container.textContent).toContain('未配置知识库绑定或绑定不可用')
expect(container.querySelector('a[href="https://weknora.test/platform/knowledge-bases/kb-1"]')).not.toBeNull()
})
})
+2
View File
@@ -85,6 +85,8 @@ export interface MonitorOverview {
pipeline?: IngestionPipeline
health: ServiceHealth[]
weknora_queues?: WeKnoraQueues | null
/** 队列不可用时后端给出的原因码:runtime_read_unavailable / forbidden / unreachable */
weknora_queue_error?: string
}
export interface MonitorFile {
name: string
+3 -3
View File
@@ -7,9 +7,9 @@ import { ReconciliationRequestError } from './reconciliationApi'
export const reconciliationMessages = {
notEnabled: '导入对账未启用,请联系管理员开启',
bindingMissing: '系统设置 → 知识库绑定:测试环境未配置',
runtimeKeyMissing: '缺少平台运行时读权限:请确认平台只读 Key 已配置并已授权',
runtimeKeyForbidden: '缺少平台运行时读权限:请在 WeKnora 为平台只读 Key 授予 system_runtime_read',
runtimeUnreachable: '测试知识库连接不可达或运行时读失败:请检查系统设置 → 知识库绑定中的地址与网络',
runtimeKeyMissing: '未配置知识库绑定或绑定不可用:请到「系统设置 → 知识库绑定」填写测试环境地址与 Key',
runtimeKeyForbidden: '当前 Key 缺少平台运行时读权限:请在 WeKnora 授权 system_runtime_read',
runtimeUnreachable: '连不上 WeKnora 或运行时读失败:请检查「系统设置 → 知识库绑定」中的地址与网络',
runInProgress: '该测试知识库已有对账批次在运行,请等本轮结束后再试',
stateChanged: '记录状态已变化,请刷新后重试',
remoteFailed: '测试知识库连接失败:请检查系统设置 → 知识库绑定中的测试环境地址与 Key',