Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a655f4cca8 | |||
| 5c34ef1429 | |||
| a55c8844a8 | |||
| 6e0382c3ba | |||
| 00154aafe6 | |||
| a6c662556d | |||
| 27ee14cc97 | |||
| 095aa3ed68 | |||
| 7d21251605 | |||
| e855261b4d | |||
| 629694546c | |||
| 06907331c4 | |||
| dafb1898c1 | |||
| cf833a0a77 | |||
| 4528a55e6a | |||
| 580695ca2e | |||
| 5af9b14a11 | |||
| 73413c59ee | |||
| 32c773e24d | |||
| f97c62cc99 | |||
| ca870564b0 |
@@ -27,6 +27,20 @@ QA_AI_MASTER_KEY_FILE=
|
||||
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 测试实例平台级只读 Key:绝对路径、0400;留空 = runtime/* 与队列降级。
|
||||
WEKNORA_RUNTIME_KEY_FILE=
|
||||
# 导入对账(T6)总开关:只接线对账服务、只用知识库绑定里的租户 Key。
|
||||
# 与 TEST_WEKNORA_ENABLED(旧取件/上传链路)解耦;默认关闭,生产按授权再开。
|
||||
RECONCILIATION_ENABLED=false
|
||||
RECONCILIATION_SCHEDULE_ENABLED=true
|
||||
RECONCILIATION_DAILY_AT=02:00
|
||||
RECONCILIATION_TIMEZONE=Asia/Shanghai
|
||||
RECONCILIATION_GRACE=30m
|
||||
RECONCILIATION_STALL_AFTER=2h
|
||||
RECONCILIATION_STALE_AFTER=6h
|
||||
RECONCILIATION_CONFIRM_CONCURRENCY=1
|
||||
RECONCILIATION_KEEP_RUNS=30
|
||||
RECONCILIATION_MAX_AGE=2160h
|
||||
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
|
||||
# 只影响治理 API/worker 访问 WeKnora 的地址校验;控制台自身的密钥录入不再由该开关控制。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP=false
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.425(WeKnora 0.9.1:schema 137 + 漏表门禁 + 编辑历史搬运)
|
||||
|
||||
### Added
|
||||
|
||||
- **libraryprofile 新增 v0.9.1(137)**:由 v0.9.0 声明克隆,只改版本字段;`For(137)`/`Supported()`
|
||||
与错误信息同步。135–137 只改审计列宽/凭据表/IM 唯一索引,不碰知识域,测试断言 v090/v091
|
||||
除版本外逐字段相等。
|
||||
- **知识域关联表分类**:每个版本声明 `copied/derived/excluded` 及理由;覆盖真实 0.9.x 的 18 张
|
||||
候选表与条件迁移的 `embeddings`。
|
||||
- **漏表门禁**:导出前(源库只读快照事务)与导入前(写事务内、DELETE 前)扫描带
|
||||
`knowledge_base_id/knowledge_id/kb_id` 的表;未分类且有本库数据 → `release_undeclared_kb_table`
|
||||
(表名+行数,不可重试);未分类空表放行并留警告(导入侧写入 `WriteSet.Warnings`)。
|
||||
- **编辑历史搬运**:`chunk_revisions`、`wiki_page_revisions` 进入 v090/v091 的必需表与归档部件,
|
||||
复用范围改写 + 目标身份映射 + 自然键预检;插在父表之后、删除/回滚先删两表;只导出活跃父行,
|
||||
父行完全缺失即拒绝;唯一索引映射后仍唯一;`editor_id` 原样保留(目标显示未知编辑者)。
|
||||
|
||||
### Changed
|
||||
|
||||
- **兼容性(人类裁定 Q1=B)**:两表部件为 **RequiredParts**。T1 部署前生成的 0.9.0 库归档/预备份
|
||||
将因缺少这两个部件而无法加载;升级前如需保留回滚能力,先在旧版本完成回滚或保留旧二进制。
|
||||
- 修订正文不参与资源发现(Q2=B):`resource://` 文本原样保留;资源作用域/校验/恢复保护统一排除两表。
|
||||
- 同步 `docs/library-target-id-mapping.md`、`docs/library-data-contract.md`、`docs/library-capture.md`,
|
||||
并按 T0 要求把 `docs/architecture/three-agent-handoff-workflow.md` §2 的 main 直推改为分支 + PR。
|
||||
|
||||
## 开发快照 0.1.424(存储与备份:删批次前预检,失败零删除)
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -44,6 +44,13 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/api/v1/reconciliation/runs": {"post":{"tags":["Reconciliation"],"operationId":"createReconciliationRun","summary":"手动触发一个测试库的对账批次;同一知识库已有 running 批次时返回 409","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["kb_id"],"properties":{"kb_id":{"type":"string","minLength":1,"maxLength":255}}}}}},"responses":{"202":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"409":{"description":"reconciliation_run_in_progress"},"500":{"$ref":"#/components/responses/InternalError"}}},"get":{"tags":["Reconciliation"],"operationId":"listReconciliationRuns","summary":"按开始时间倒序列出对账批次","parameters":[{"name":"kb_id","in":"query","required":false,"schema":{"type":"string","maxLength":255}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100,"default":20}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","minimum":0,"maximum":1000000,"default":0}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"角色或写入意图不足"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/runs/{id}": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationRun","summary":"读取单个对账批次","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/runs/{id}/findings": {"get":{"tags":["Reconciliation"],"operationId":"listReconciliationFindings","summary":"按类型和关键词筛选批次差异明细","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"type","in":"query","required":false,"schema":{"type":"string","enum":["R1","R2","R3","R4","R5","R6","R7","R8"]}},{"name":"q","in":"query","required":false,"schema":{"type":"string","maxLength":512}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","minimum":1,"maximum":100,"default":20}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","minimum":0,"maximum":1000000,"default":0}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/findings/{id}/writeback": {"post":{"tags":["Reconciliation"],"operationId":"writebackReconciliationFinding","summary":"仅限 R5:以 WeKnora 状态回写台账 processing_state,写审计;completed 不可降级","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"reconciliation_writeback_stale 或迁移不允许"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/findings/{id}/requeue": {"post":{"tags":["Reconciliation"],"operationId":"requeueReconciliationFinding","summary":"仅限 R1/R4:R1 清空 document_id 后重排上传;R4 先删旧知识再重传,删除失败则台账不变","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员或文档工程师"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"finding 状态或台账身份已变化"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/findings/{id}/remove": {"post":{"tags":["Reconciliation"],"operationId":"removeReconciliationFinding","summary":"仅限 R2:按远端 document_id 从测试库删除;404 视为已删除;重复点击幂等","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"reconciliation-action"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"该文档已被现行台账收养"},"500":{"$ref":"#/components/responses/InternalError"}}}},
|
||||
"/api/v1/reconciliation/documents/{document_id}/progress": {"get":{"tags":["Reconciliation"],"operationId":"getReconciliationDocumentProgress","summary":"实时转发并脱敏 WeKnora 文档处理阶段与历史失败;未配置平台只读 Key 时返回 503 runtime_read_unavailable","parameters":[{"name":"document_id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}}}},
|
||||
"/api/v1/qa-ops/master/field-options": {"get":{"operationId":"getQAMasterFieldOptions","tags":["QA operations"],"summary":"只读主表五字段的正式可选范围,与模型共享同一分类字典;不返回业务问答","parameters":[],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}}},
|
||||
"/api/v1/qa-ops/master/records/{id}/fields": {"post":{"operationId":"patchQAMasterFields","tags":["QA operations"],"summary":"只更新明确选择的字段并留幂等审计;不改原始正文、其他空白、旧复核或冻结证据。未覆盖的是否正确固定为待确认,拒绝是或否;已覆盖点踩固定为否。quality.correctness_rule=coverage-correctness-v1标记覆盖/正确性固定投影,原字段和复核证据保留","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-master-fields"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["input_hash","input_epoch","base_revision","base_review_revision","nonce","fields"],"properties":{"input_hash":{"type":"string","pattern":"^[a-f0-9]{64}$"},"input_epoch":{"type":"integer","minimum":1},"base_revision":{"type":"integer","minimum":0},"base_review_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"fields":{"type":"object","additionalProperties":false,"minProperties":1,"maxProperties":5,"properties":{"is_correct":{"type":"string","enum":["是","否","待确认"]},"product_category":{"type":"string","enum":["CR/CRA/H/AP","CRV","CR配件","Nova及系列","Nova配件","MG400","MG400配件","M1 Pro","VX500","新示教器","DobotStudio Pro","仿真软件","维护工具","教育所有产品","人形机器人","四六足机器人","X-Trainer","码垛解决方案","码垛插件","焊接解决方案","焊接插件","移动复合机器人","生态插件","生态合作","安全皮肤","未知"]},"problem_type":{"type":"string","enum":["参数","故障","使用配置","二次开发","资料获取","咨询","认证","案例","售后","培训与学习","其他"]},"root_cause":{"type":"string","enum":["知识缺失","检索不到","结果不清","答案生成错误","问题质量差","非知识范围","知识过期"]},"coverage":{"type":"string","enum":["是","否","否但不计入"]}}}}}}}}}},
|
||||
"/api/v1/qa-ops/master/weekly-drafts/{week}": {"get":{"operationId":"getQAWeeklyDraft","tags":["QA operations"],"summary":"读取租户指定北京时间ISO周的持久草稿;不存在时revision=0且不创建记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}},"post":{"operationId":"saveQAWeeklyDraft","tags":["QA operations"],"summary":"防抖编辑保存:版本锁、逐版历史及同nonce重放;正文不会触发外发/归档","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce","markdown"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"markdown":{"type":"string","maxLength":262144,"description":"UTF-8正文最多256KiB;允许空正文,保存草稿不等于发布"}}}}}}}},
|
||||
@@ -4867,6 +4874,10 @@
|
||||
"target_kb": {
|
||||
"type": "string"
|
||||
},
|
||||
"weknora_url": {
|
||||
"type": "string",
|
||||
"description": "目标测试知识库在 WeKnora 控制台的链接;未配置测试端点时为空"
|
||||
},
|
||||
"action": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -6162,6 +6173,11 @@
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"ReconciliationRun": {"type":"object","additionalProperties":false,"required":["id","kb_id","state","trigger","started_at","finished_at","ledger_count","kb_count","counts","previous_counts","window_overlapped","error_code"],"properties":{"id":{"type":"string"},"kb_id":{"type":"string","minLength":1,"maxLength":255},"state":{"type":"string","enum":["running","succeeded","failed"]},"trigger":{"type":"string","enum":["schedule","manual"]},"started_at":{"type":"string","format":"date-time"},"finished_at":{"type":["string","null"],"format":"date-time"},"ledger_count":{"type":"integer","minimum":0},"kb_count":{"type":"integer","minimum":0},"counts":{"type":"object","additionalProperties":false,"required":["R1","R2","R3","R4","R5","R6","R7","R8"],"properties":{"R1":{"type":"integer","minimum":0},"R2":{"type":"integer","minimum":0},"R3":{"type":"integer","minimum":0},"R4":{"type":"integer","minimum":0},"R5":{"type":"integer","minimum":0},"R6":{"type":"integer","minimum":0},"R7":{"type":"integer","minimum":0},"R8":{"type":"integer","minimum":0}}},"previous_counts":{"type":["object","null"],"additionalProperties":{"type":"integer","minimum":0}},"window_overlapped":{"type":"boolean"},"error_code":{"type":"string"}}},
|
||||
"ReconciliationFinding": {"type":"object","additionalProperties":false,"required":["id","run_id","type","publication_id","document_id","title","path","source","target_scope","ledger_state","weknora_parse_status","normalized_state","ledger_sha256","declared_sha256","weknora_file_md5","evidence_level","confirmation_state","detail","suggested_action","action_state","weknora_url"],"properties":{"id":{"type":"string"},"run_id":{"type":"string"},"type":{"type":"string","enum":["R1","R2","R3","R4","R5","R6","R7","R8"]},"publication_id":{"type":"string"},"document_id":{"type":"string"},"title":{"type":"string"},"path":{"type":"string"},"source":{"type":"string"},"target_scope":{"type":"string","enum":["internal","external","unknown"]},"ledger_state":{"type":"string"},"weknora_parse_status":{"type":"string"},"normalized_state":{"type":"string"},"ledger_sha256":{"type":"string"},"declared_sha256":{"type":"string"},"weknora_file_md5":{"type":"string"},"evidence_level":{"type":"string","enum":["independent","declared_only","none"]},"confirmation_state":{"type":"string","enum":["confirmed","pending"]},"detail":{"type":"string"},"suggested_action":{"type":"string","enum":["requeue_upload","remove_from_test","writeback_state","enter_removal","none"]},"action_state":{"type":"string","enum":["open","done"]},"weknora_url":{"type":"string"}}},
|
||||
"ReconciliationRunPage": {"type":"object","additionalProperties":false,"required":["items","total","limit","offset"],"properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/ReconciliationRun"}},"total":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":100},"offset":{"type":"integer","minimum":0}}},
|
||||
"ReconciliationFindingPage": {"type":"object","additionalProperties":false,"required":["items","total","limit","offset"],"properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/ReconciliationFinding"}},"total":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":100},"offset":{"type":"integer","minimum":0}}},
|
||||
"ReconciliationProgress": {"type":"object","additionalProperties":false,"required":["document_id","parse_status","ingestion_status","wiki_status","stages","failures","has_more_failures","observed_at"],"properties":{"document_id":{"type":"string"},"parse_status":{"type":"string"},"ingestion_status":{"type":"string"},"wiki_status":{"type":"string"},"stages":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["name","status"],"properties":{"name":{"type":"string"},"status":{"type":"string"},"error_code":{"type":"string"},"finished_at":{"type":["string","null"],"format":"date-time"}}}},"failures":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["task_type","fail_count","failed_at","last_error"],"properties":{"task_type":{"type":"string"},"fail_count":{"type":"integer","minimum":0},"failed_at":{"type":"string","format":"date-time"},"last_error":{"type":"string","maxLength":500}}}},"has_more_failures":{"type":"boolean"},"observed_at":{"type":"string","format":"date-time"}}},
|
||||
"KBBindingEnvironmentView": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
|
||||
+53
-1
@@ -31,8 +31,10 @@ import (
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"knowledge-governance/internal/qawemail"
|
||||
"knowledge-governance/internal/readiness"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
"knowledge-governance/internal/version"
|
||||
"knowledge-governance/internal/weknoraaccess"
|
||||
)
|
||||
|
||||
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
|
||||
@@ -216,7 +218,55 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
allowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
allowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP})
|
||||
runtimeKey := ""
|
||||
if config.WeKnoraRuntimeKeyFile != "" {
|
||||
key, keyErr := weknora.ReadRuntimeKeyFile(config.WeKnoraRuntimeKeyFile)
|
||||
if keyErr != nil {
|
||||
log.Printf("WARN: WeKnora runtime read key is unavailable; runtime endpoints degrade to 503")
|
||||
} else {
|
||||
runtimeKey = key
|
||||
}
|
||||
}
|
||||
runtimeProvider := reconciliation.NewRuntimeProvider(reconciliation.RuntimeConfig{
|
||||
BaseURL: testEndpointResolver,
|
||||
APIKey: runtimeKey,
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
})
|
||||
reconciliationRemote := &weknoraaccess.Client{
|
||||
Resolver: readiness.Resolver{
|
||||
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
},
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
},
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
var reconciliationService httpapi.ReconciliationService
|
||||
if config.ReconciliationEnabled {
|
||||
service, serviceErr := reconciliation.New(reconciliation.Config{
|
||||
Store: actionStore,
|
||||
Remote: reconciliationRemote,
|
||||
Runtime: runtimeProvider,
|
||||
Queue: actionStore,
|
||||
Grace: config.ReconciliationGrace,
|
||||
StallAfter: config.ReconciliationStallAfter,
|
||||
StaleAfter: config.ReconciliationStaleAfter,
|
||||
ConfirmConcurrency: config.ReconciliationConfirmConcurrency,
|
||||
KeepRuns: config.ReconciliationKeepRuns,
|
||||
MaxAge: config.ReconciliationMaxAge,
|
||||
WeKnoraWebBase: testEndpointResolver,
|
||||
})
|
||||
if serviceErr != nil {
|
||||
return serviceErr
|
||||
}
|
||||
reconciliationService = service
|
||||
}
|
||||
monitorProvider, err := monitoring.NewRealProvider(monitoring.RealProviderConfig{DB: pool, WeKnoraBaseURL: config.TestWeKnoraBaseURL, TestWeKnoraResolver: testEndpointResolver, ProductionWeKnoraBaseURL: config.ProductionWeKnoraBaseURL, ProductionWeKnoraResolver: productionEndpointResolver, MinerUBaseURL: config.MinerUBaseURL, WeKnoraReadiness: weknoraProbe, WorkerStaleAfter: config.WorkerLivenessStaleAfter, AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP, RuntimeQueues: runtimeProvider})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -291,6 +341,8 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
QAOpsProblem: qaSettings.Problem,
|
||||
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()).WithRoutingDefaults(config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID),
|
||||
Monitor: monitorProvider,
|
||||
Reconciliation: reconciliationService,
|
||||
WeKnoraWebBase: testEndpointResolver,
|
||||
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
|
||||
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
|
||||
RoutingBindings: postgresstore.NewStore(pool),
|
||||
|
||||
@@ -55,7 +55,7 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
|
||||
VersionHistoryGiteaBaseURL: "https://gitea.invalid/Weknora/knowledge-governance",
|
||||
VersionHistoryAllowedOrigins: []string{"https://gitea.invalid"},
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), release, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("release-executor workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -74,12 +74,12 @@ func TestWorkerHandlersFollowWorkerRole(t *testing.T) {
|
||||
TestWeKnoraEnabled: true,
|
||||
TestWeKnoraAPIKeyFile: "/nonexistent/api-key",
|
||||
}
|
||||
if _, err := workerHandlers(nil, capture, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
|
||||
if _, err := workerHandlers(nil, capture, nil, nil); err == nil || !strings.Contains(err.Error(), "test WeKnora API key") {
|
||||
t.Fatalf("capture role must reach the test WeKnora wiring, got %v", err)
|
||||
}
|
||||
capture.TestWeKnoraEnabled = false
|
||||
capture.PPScanEnabled = false
|
||||
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil)
|
||||
handlers, err = workerHandlers(postgresstore.NewStore(nil), capture, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("capture workerHandlers() error = %v", err)
|
||||
}
|
||||
|
||||
+60
-2
@@ -27,6 +27,7 @@ import (
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"knowledge-governance/internal/weknoraaccess"
|
||||
artifactfetch "knowledge-governance/internal/workflows/artifactfetch"
|
||||
@@ -260,7 +261,50 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
} else if repaired > 0 {
|
||||
log.Printf("library job reconcile: %d orphan job(s) marked failed", repaired)
|
||||
}
|
||||
handlers, err := workerHandlers(store, config, kbBindings)
|
||||
var reconciliationService *reconciliation.Service
|
||||
if config.ReconciliationEnabled && config.LibraryWorkerRole.ExecutesSourceWork() {
|
||||
reconciliationRemote := &weknoraaccess.Client{
|
||||
Resolver: readiness.Resolver{
|
||||
LoadBinding: func(resolveCtx context.Context) (string, error) {
|
||||
internal, _, _, bindingErr := store.LoadRoutingKBBindings(resolveCtx)
|
||||
return internal, bindingErr
|
||||
},
|
||||
ResolveConnection: func(resolveCtx context.Context) (string, string, error) {
|
||||
if kbBindings != nil {
|
||||
target, resolveErr := kbBindings.Resolve(resolveCtx, kbbinding.EnvTest)
|
||||
return target.BaseURL, target.APIKey, resolveErr
|
||||
}
|
||||
key, keyErr := weknora.ReadAPIKeyFile(config.TestWeKnoraAPIKeyFile)
|
||||
return config.TestWeKnoraBaseURL, key, keyErr
|
||||
},
|
||||
DefaultKB: config.InternalRoutingKnowledgeBaseID,
|
||||
},
|
||||
Timeout: config.TestWeKnoraHTTPTimeout,
|
||||
AllowDockerHTTP: config.TestWeKnoraAllowDockerHTTP,
|
||||
AllowPrivateHTTP: config.WeKnoraAllowPrivateHTTP,
|
||||
}
|
||||
reconciliationService, err = reconciliation.New(reconciliation.Config{
|
||||
Store: store,
|
||||
Remote: reconciliationRemote,
|
||||
Queue: store,
|
||||
Grace: config.ReconciliationGrace,
|
||||
StallAfter: config.ReconciliationStallAfter,
|
||||
StaleAfter: config.ReconciliationStaleAfter,
|
||||
ConfirmConcurrency: config.ReconciliationConfirmConcurrency,
|
||||
KeepRuns: config.ReconciliationKeepRuns,
|
||||
MaxAge: config.ReconciliationMaxAge,
|
||||
WeKnoraWebBase: func(resolveCtx context.Context) string {
|
||||
if kbBindings != nil {
|
||||
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvTest)
|
||||
}
|
||||
return config.TestWeKnoraBaseURL
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
handlers, err := workerHandlers(store, config, kbBindings, reconciliationService)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -331,6 +375,9 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
|
||||
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
|
||||
})
|
||||
if reconciliationService != nil {
|
||||
go runReconciliationScheduler(ctx, store, reconciliationService, config)
|
||||
}
|
||||
}
|
||||
log.Printf("worker %s started role=%s release=%t source=%t (source refresh scheduler every %s)",
|
||||
config.WorkerID, config.LibraryWorkerRole, config.LibraryWorkerRole.ExecutesRelease(),
|
||||
@@ -373,7 +420,7 @@ func completeLibraryCaptureJob(ctx context.Context, store libraryCapturePersiste
|
||||
return nil
|
||||
}
|
||||
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store) (map[string]jobs.Handler, error) {
|
||||
func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindings *kbbinding.Store, reconciliationService *reconciliation.Service) (map[string]jobs.Handler, error) {
|
||||
handlers := map[string]jobs.Handler{
|
||||
"demo": func(_ context.Context, job jobs.Job) error {
|
||||
log.Printf("completed demo job id=%s", job.ID)
|
||||
@@ -648,6 +695,17 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config, kbBindi
|
||||
handlers["test.poll"] = poll.Handle
|
||||
handlers["test.validate"] = validate.Handle
|
||||
handlers["test.remove"] = remove.Handle
|
||||
if reconciliationService != nil {
|
||||
handlers["reconciliation.run"] = func(handlerCtx context.Context, job jobs.Job) error {
|
||||
var payload struct {
|
||||
RunID string `json:"run_id"`
|
||||
}
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil || payload.RunID == "" {
|
||||
return jobs.Permanent(jobs.ErrCodeHandlerFallback, errors.New("invalid reconciliation run payload"))
|
||||
}
|
||||
return reconciliationService.ExecuteRun(handlerCtx, payload.RunID)
|
||||
}
|
||||
}
|
||||
return handlers, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestRunRequiresDatabaseURL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWorkerHandlersExcludeReleaseAndTestJobsByDefault(t *testing.T) {
|
||||
handlers, err := workerHandlers(nil, appconfig.Config{}, nil)
|
||||
handlers, err := workerHandlers(nil, appconfig.Config{}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
|
||||
PPScanLedgerPath: filepath.Join(root, "state.jsonl"),
|
||||
PPScanManifestPath: filepath.Join(root, "manifest.json"),
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func TestWorkerHandlersRegisterPPScanWhenExplicitlyEnabled(t *testing.T) {
|
||||
|
||||
func TestWorkerHandlersRequireAPIKeyWhenTestWeKnoraEnabled(t *testing.T) {
|
||||
config := appconfig.Config{TestWeKnoraEnabled: true, TestWeKnoraAPIKeyFile: "/nonexistent/api-key"}
|
||||
_, err := workerHandlers(nil, config, nil)
|
||||
_, err := workerHandlers(nil, config, nil, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "read test WeKnora API key") {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func TestWorkerHandlersRegisterTestJobsForExplicitDockerHTTP(t *testing.T) {
|
||||
TestWeKnoraMaxUploadBytes: 1024,
|
||||
TestAcceptancePolicyVersion: "structural-v1",
|
||||
}
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil)
|
||||
handlers, err := workerHandlers(postgresstore.NewStore(nil), config, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("workerHandlers() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
// runReconciliationScheduler claims at most one scheduled batch per test KB
|
||||
// per local day. The claim is in PostgreSQL; multiple workers racing here are
|
||||
// harmless. The first tick is delayed by one interval, like the source refresh
|
||||
// scheduler, so startup does not enqueue a backlog before handlers are ready.
|
||||
func runReconciliationScheduler(ctx context.Context, store *postgres.Store, service *reconciliation.Service, config appconfig.Config) {
|
||||
if service == nil || !config.ReconciliationScheduleEnabled {
|
||||
return
|
||||
}
|
||||
location, err := time.LoadLocation(config.ReconciliationTimezone)
|
||||
if err != nil {
|
||||
log.Printf("reconciliation scheduler disabled: invalid timezone %q", config.ReconciliationTimezone)
|
||||
return
|
||||
}
|
||||
daily, err := time.Parse("15:04", config.ReconciliationDailyAt)
|
||||
if err != nil {
|
||||
log.Printf("reconciliation scheduler disabled: invalid daily time %q", config.ReconciliationDailyAt)
|
||||
return
|
||||
}
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case tick := <-ticker.C:
|
||||
local := tick.In(location)
|
||||
at := time.Date(local.Year(), local.Month(), local.Day(), daily.Hour(), daily.Minute(), 0, 0, location)
|
||||
if local.Before(at) {
|
||||
continue
|
||||
}
|
||||
internal, external, _, bindingErr := store.LoadRoutingKBBindings(ctx)
|
||||
if bindingErr != nil {
|
||||
log.Printf("reconciliation scheduler cannot read current bindings: %v", bindingErr)
|
||||
continue
|
||||
}
|
||||
if internal == "" {
|
||||
internal = config.InternalRoutingKnowledgeBaseID
|
||||
}
|
||||
if external == "" {
|
||||
external = config.ExternalRoutingKnowledgeBaseID
|
||||
}
|
||||
created, scheduleErr := service.ScheduleDue(ctx, []string{internal, external}, at.UTC(), tick.UTC())
|
||||
if scheduleErr != nil {
|
||||
log.Printf("reconciliation scheduler error: %v", scheduleErr)
|
||||
continue
|
||||
}
|
||||
if created > 0 {
|
||||
log.Printf("reconciliation scheduler created %d batch(es) for local day %s", created, local.Format("2006-01-02"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,19 @@ services:
|
||||
# 「知识库绑定」密文的独立主密钥(0600、32字节);与 QA 的密钥相互独立。
|
||||
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
|
||||
# 测试实例平台级只读 Key(0400,绝对路径)。空值 = runtime/* 与队列降级;
|
||||
# Key 本身只挂载 secret 文件,绝不写进 compose。
|
||||
WEKNORA_RUNTIME_KEY_FILE: "${WEKNORA_RUNTIME_KEY_FILE:-}"
|
||||
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
|
||||
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
|
||||
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
|
||||
RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}"
|
||||
RECONCILIATION_GRACE: "${RECONCILIATION_GRACE:-30m}"
|
||||
RECONCILIATION_STALL_AFTER: "${RECONCILIATION_STALL_AFTER:-2h}"
|
||||
RECONCILIATION_STALE_AFTER: "${RECONCILIATION_STALE_AFTER:-6h}"
|
||||
RECONCILIATION_CONFIRM_CONCURRENCY: "${RECONCILIATION_CONFIRM_CONCURRENCY:-1}"
|
||||
RECONCILIATION_KEEP_RUNS: "${RECONCILIATION_KEEP_RUNS:-30}"
|
||||
RECONCILIATION_MAX_AGE: "${RECONCILIATION_MAX_AGE:-2160h}"
|
||||
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
|
||||
# 链路本地,公网 http 仍被拒绝)。客户端与探活共用同一判定;控制台密钥录入不受此开关控制。
|
||||
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
|
||||
@@ -135,6 +148,16 @@ services:
|
||||
TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
|
||||
TEST_WEKNORA_KB_ID: "${TEST_WEKNORA_KB_ID:-}"
|
||||
TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key
|
||||
RECONCILIATION_ENABLED: "${RECONCILIATION_ENABLED:-false}"
|
||||
RECONCILIATION_SCHEDULE_ENABLED: "${RECONCILIATION_SCHEDULE_ENABLED:-true}"
|
||||
RECONCILIATION_DAILY_AT: "${RECONCILIATION_DAILY_AT:-02:00}"
|
||||
RECONCILIATION_TIMEZONE: "${RECONCILIATION_TIMEZONE:-Asia/Shanghai}"
|
||||
RECONCILIATION_GRACE: "${RECONCILIATION_GRACE:-30m}"
|
||||
RECONCILIATION_STALL_AFTER: "${RECONCILIATION_STALL_AFTER:-2h}"
|
||||
RECONCILIATION_STALE_AFTER: "${RECONCILIATION_STALE_AFTER:-6h}"
|
||||
RECONCILIATION_CONFIRM_CONCURRENCY: "${RECONCILIATION_CONFIRM_CONCURRENCY:-1}"
|
||||
RECONCILIATION_KEEP_RUNS: "${RECONCILIATION_KEEP_RUNS:-30}"
|
||||
RECONCILIATION_MAX_AGE: "${RECONCILIATION_MAX_AGE:-2160h}"
|
||||
GOVERNANCE_SPOOL_ROOT: /var/lib/governance/spool
|
||||
INGESTION_SPOOL_ROOT: /var/lib/governance/ingestion
|
||||
TEST_WEKNORA_HTTP_TIMEOUT: "${TEST_WEKNORA_HTTP_TIMEOUT:-60s}"
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
# 需求书:解析监控重构为「导入对账」
|
||||
|
||||
> 状态:v0.6(2026-12-01),已批准;Q1、Q5、Q6、Q7、Q9、Q10、Q11、Q12、Q13 已裁定。
|
||||
> Q12/Q13 为 T6a 开工时人类确认:API 字段用 `kb_id`/`document_id`(数据库列名不变),R6 用 `/test-publications/{id}/removal` 而非 `removal-retry`。
|
||||
> 依据:本仓 `origin/main` `ca87056` 与上游 WeKnora v0.9.1 源码(`~/weknora-explore/WeKnora-v0.9.1`)的直接阅读。
|
||||
> 本期总计划、分工与工单拆分见 [WEKNORA_091_PHASE_PLAN.md](WEKNORA_091_PHASE_PLAN.md);本文是其中 T6 的需求正文。
|
||||
|
||||
## 1. 背景与结论
|
||||
|
||||
现「解析监控」(`internal/monitoring`、`internal/httpapi/monitor_tasks.go`、`web/src/WeKnoraMonitor.tsx`、`web/src/monitorTasks.ts`)做三件事:服务探活、按测试库统计处理状态、文件处理大表(筛选/重试/详情)。其中「解析」「索引增强」两个阶段的进度与失败细节,是平台轮询 WeKnora 后转述出来的。
|
||||
|
||||
WeKnora v0.9.1 新增了系统管理员「任务队列」(CHANGELOG #4732、#5895):按文档查看入库与 Wiki 进度、处理阶段、历史失败。平台再把这些阶段细节转述一遍,等于和上游做同一件事,违反硬约束 1,而且转述永远比源头旧。
|
||||
|
||||
**结论:WeKnora 内部的处理细节交给 WeKnora 看;平台只做 WeKnora 看不到、也只有平台能做的事:把「台账 ↔ 知识库」(之后扩展到「来源 ↔ 台账」「测试库 ↔ 生产库」)对起来,发现并处置不一致。** 页面由「解析监控」改为「导入对账」。
|
||||
|
||||
⚠️ **边界**:台账上的 `processing_state` 是**工作流状态**,审核、组批、发布门禁都依赖它,**本需求不删除它**,也不改写平台轮询 WeKnora 确认完成的逻辑。去掉的只是界面上"解析阶段明细"这层转述;台账状态与 WeKnora 实际状态不一致的情况,由对账的 R5 发现并修正。
|
||||
|
||||
## 2. 职责划分
|
||||
|
||||
| 问题 | 归属 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 取件、上传是否成功 | 平台 | WeKnora 收到文件之前的阶段,上游看不到 |
|
||||
| 解析/切片/向量/Wiki 进行到哪一步、为何失败 | WeKnora | 平台按需实时读取展示,不落库、不自建阶段机 |
|
||||
| 解析失败后重新解析 | WeKnora(仅测试环境) | 一期只给跳转链接。生产只做推理,任何重解析都不能指向生产 |
|
||||
| 该在库里的是否都在、在的是否该在、内容是否最新 | **平台(本需求核心)** | 只有平台同时掌握来源身份、台账与目标库 |
|
||||
| 应下架内容是否已移除 | 平台 | 依据来源策略 `policy_state=blocked` |
|
||||
|
||||
## 3. 分期
|
||||
|
||||
| 期 | 对账两侧 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| **一期(本期)** | 平台台账(`test_publications` 中 `superseded_at IS NULL` 的行)↔ 测试 WeKnora 知识库 | 两侧数据都已具备;依赖测试 WeKnora 已升级到 v0.9.1 |
|
||||
| 二期 | 来源 ↔ 平台台账 | 漏取、来源已删除平台仍现行;各来源扫描能力不同,需逐源确认 |
|
||||
| 三期 | 测试库 ↔ 生产库 | 生产只做推理,内容全部由整库发布从测试搬运,所以这一期核对的是"搬运是否完整"。复用 `librarysnapshot`/`librarydiff`,按稳定 ID 和内容摘要比对 |
|
||||
|
||||
下文只展开一期。
|
||||
|
||||
### 3.1 一期边界:只对测试库;生产的下架靠发布链路
|
||||
|
||||
一期只对测试 WeKnora 做对账,**生产库没有对账对象**。生产的下架保证不在本需求内,它依赖两段已有链路:
|
||||
|
||||
1. 来源判 `blocked`:`planned` 行置 `superseded_at`,来源项 `policy_state='blocked'`(`policy_intents.go`)。
|
||||
2. 变更集确认后:已入库行置 `retrieval_state='disabling'` 并入队 `test.remove`,移除完成后为 `disabled`(`change_set_execution.go`、`publication_removal.go`)。
|
||||
3. 下一轮整库发布以测试库为源做 diff,生产库里多出来的文档判 `Removed` 后删除。
|
||||
|
||||
所以**生产下架的最迟时间 = 测试移除完成 + 下一次整库发布**。两次发布之间的空窗期,生产仍可检索已被判禁止的内容,一期发现不了。这一条必须写进页面的范围说明;是否再显示「距上次整库发布 N 天」见 Q8(未裁定)。
|
||||
|
||||
## 4. 差异类型(一期)
|
||||
|
||||
**身份配对口径(已核实)**:平台上传时写入 `metadata.publication_id`、`metadata.content_sha256`,并设 `channel=governance`(`internal/workflows/testweknora/upload.go`,main 上第 141 行起);台账记录 `knowledge_id`。配对优先用 `knowledge_id`,其次用 `metadata.publication_id`。
|
||||
|
||||
⚠️ WeKnora 对相同字节去重,同一份文件放在两个来源目录时,**多条台账可以合法地指向同一个 knowledge**(同文件中 ErrConflict 分支的收养逻辑)。只有能找到收养的审计证据才算合法(与陷阱 16 同理)。
|
||||
|
||||
**两个谓词(全文只用这两个;不再出现未定义的「现行行」)**
|
||||
|
||||
- `ledger_current`:`test_publications.superseded_at IS NULL`。用于 R2、R8 反查台账,以及所有“现行”计数。
|
||||
- `ledger_expected_live`:`ledger_current` 且 `knowledge_id <> ''`、`processing_state <> 'failed'`、`retrieval_state NOT IN ('disabling','disabled')`。用于 R1、R4、R5、R7 的正向核对。
|
||||
|
||||
`ledger_expected_live` 必须排除 `disabling`/`disabled`:移除完成只改 `retrieval_state`,`knowledge_id` 会保留(`publication_removal.go` 的 `RecordRemovalCompleted`),不排除就会把正常下架的条目永久误报成 R1。
|
||||
|
||||
| 编号 | 差异 | 判定口径 | 默认处置 |
|
||||
| --- | --- | --- | --- |
|
||||
| R1 丢失 | 台账认为应仍在库,库里没有 | `ledger_expected_live`,且单条 `GET /knowledge/{id}` 返回 404;“列表里没看到”不算证据 | 建议「重排上传」(复用现有动作) |
|
||||
| R2 孤儿 | 库里有平台导入的条目,台账没有现行行指向它 | `channel=governance`,且 `metadata.publication_id` 没有 `ledger_current` 台账行,也没有 `ledger_current` 行以 `knowledge_id` 指向它;同字节被兄弟台账合法收养(其 `publication_id` 有 `ledger_current` 行)不算孤儿 | 只报告;移除走现有「测试库移除」,需人工确认 |
|
||||
| R3 非平台导入 | 库里有不是平台导入的条目 | `channel≠governance` | 只统计、单列,不算错误 |
|
||||
| R4 内容过期 | 库里的内容不是台账现行版本 | `ledger_expected_live`;`metadata.content_sha256` ≠ 台账现行版本 sha256(来源链见下),或有独立 MD5 证据且与 `file_hash` 不符 | 建议重新上传 |
|
||||
| R5 状态不一致 | 两边状态长期对不上 | 台账 `processing_state` 与 WeKnora `parse_status` 按 §4 矩阵归一后不同,且以 `run.started_at` 计算已超过宽限期(默认 30 分钟,可配);回写受迁移表约束 | 人工点击「以 WeKnora 为准回写」,写审计 |
|
||||
| R6 应下架仍在 | 来源已判禁止导入,库里仍可检索 | `superseded_at IS NULL`、`knowledge_id<>''`、`processing_state='completed'`、`retrieval_state NOT IN ('disabling','disabled')`、`item.policy_state='blocked'`;**与 `/monitor/overview` 的「需下架」共用同一个实现**,不得两处各写一遍 | 进入现有「需下架」流程 |
|
||||
| R7 卡住 | 长时间没有进展 | 上游 `stall_state=stalled`;或 `pending`/`processing` 超过阈值(默认 2 小时,可配,按 `run.started_at` 计算);或 `deleting` 超过同一阈值(删除卡住) | 展示 WeKnora 阶段与失败记录,并给出跳转 |
|
||||
| R8 一对多异常 | 一条台账对应多个现行条目 | 同 tenant、同 KB 下按 `metadata.publication_id` 分组,**排除 `parse_status` 为 `failed`/`deleting` 的条目**后仍大于 1。上游去重作用域是「同 tenant + 同 KB + 同 file_type + file_hash,排除 failed/deleting」(`repository/knowledge.go:435-466`),所以“同 hash 一条 failed + 一条现役”“同字节 .md 与 .txt”都是合法共存,不进 R8 | 只报告,人工处理 |
|
||||
|
||||
**状态归一与判定矩阵**
|
||||
|
||||
上游 `parse_status`:`pending` / `processing` / `finalizing` / `completed` / `failed` / `cancelled` / `deleting`(`internal/types/knowledge.go`)。台账 `processing_state`:`planned` / `pending` / `processing` / `finalizing` / `completed` / `failed` / `stalled`。
|
||||
|
||||
归一表(上游 → 台账词汇):`pending→pending`、`processing→processing`、`finalizing→finalizing`、`completed→completed`、`failed→failed`、`cancelled→cancelled`、`deleting→deleting`。`cancelled`、`deleting` 在台账没有对应状态,保留原名,**不得静默归到“其他”**。
|
||||
|
||||
判定矩阵(行 = 台账,列 = 归一后的上游状态):
|
||||
|
||||
| 台账 \ 上游 | pending | processing | finalizing | completed | failed | cancelled | deleting |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| planned | — | — | — | — | — | — | — |
|
||||
| pending | ✓ | G | G | G | G | G | D |
|
||||
| processing | G | ✓ | G | G | G | G | D |
|
||||
| finalizing | G | G | ✓ | G | G | G | D |
|
||||
| completed | G | G | G | ✓ | G | G | D |
|
||||
| failed | G | G | G | G | ✓ | G | D |
|
||||
| stalled | S | S | S | G | S | S | D |
|
||||
|
||||
- ✓ 一致。
|
||||
- G:超过宽限期报 R5;`completed` 行对任何 G 只报告、`suggested_action=none`(禁止把已完成降级)。
|
||||
- S:报 R7,展示上游阶段与失败记录。
|
||||
- D:等待删除完成;超过 2 小时仍是 `deleting` 转 R7。
|
||||
- —:`planned` 正常没有 `knowledge_id`,不比较;若出现 `planned` 且有 `knowledge_id`,按 G 处理并标为台账异常。
|
||||
|
||||
矩阵只写在服务端一处;接口以 `normalized_state` 字段直接返回归一结果,前端不内置映射表(前端拿不到 Go 常量)。
|
||||
|
||||
**内容校验的证据链**:台账的 sha256 不在 `test_publications` 上,来源链固定为 `test_publications.source_item_version_id → source_item_versions.content_object_id → content_objects.sha256`;实现不得为此在台账加列。
|
||||
|
||||
- `metadata.content_sha256`:平台上传时写入的**声明**。
|
||||
- `file_hash`:WeKnora 对收到字节算的 **MD5**(上游 `knowledge_util.go:131`),**独立证据**。
|
||||
- 本期起上传时在台账新增 `upload_md5`(迁移),对账用它与 `file_hash` 比对。
|
||||
|
||||
证据等级:`independent`(声明 sha256 与 MD5 都可核且一致)、`declared_only`(历史数据只有 `metadata` 声明)、`none`(metadata 缺失或无 MD5 可比)。只有前两级可判 R4;`none` 只统计、不判差异。
|
||||
|
||||
## 5. 数据来源(已核实上游接口)
|
||||
|
||||
| 用途 | WeKnora 接口 | 鉴权 |
|
||||
| --- | --- | --- |
|
||||
| 全量列出库内条目 | `GET /knowledge-bases/{id}/knowledge`(分页;可按 `parse_status`、`source`、时间、目录筛选) | 现有租户 API Key |
|
||||
| 单条确认 | `GET /knowledge/{id}` | 现有租户 API Key |
|
||||
| 处理阶段与失败(只读展示) | `GET /system/admin/runtime/documents/{knowledge_id}`:stages、failures、parse/ingestion/wiki 状态 | **平台级 API Key,能力 `system_runtime_read`**(上游 `routes_auth_tenant.go:356`) |
|
||||
| 队列深度 | `GET /system/admin/runtime/queues` | 同上 |
|
||||
|
||||
条目中对账要用的字段:`id`、`knowledge_base_id`、`channel`、`metadata`、`file_hash`、`parse_status`、`stall_state`、`enable_status`、`updated_at`。
|
||||
|
||||
**扫描参数**:列表接口 `page_size` 的上游上限是 1000(`types/search.go:320`),对账必须用 1000;平台现有客户端把上限卡在 100(`internal/platform/weknora/client.go:361`),T6a 要为对账放开到 1000,不能沿用上传恢复的 100。1 万条的库因此是 10 次请求而不是 100 次。
|
||||
|
||||
**列表的盲区**:不传 `parse_status` 时上游隐藏 `deleting` 行(`repository/knowledge.go:176`),所以“列表里没有”不等于“已删除”,R1 必须单条 GET 复核。
|
||||
|
||||
**平台级 Key 的配置契约(Q7 已裁定)**
|
||||
|
||||
- 键名 `WEKNORA_RUNTIME_KEY_FILE`,值为**绝对路径**,secret 文件挂载进容器;不写进 compose 环境变量、不进 Git。
|
||||
- 启动时读取一次,权限 0400;换 Key 需重启平台(与现有 `*_API_KEY_FILE` 一致,不做热加载)。
|
||||
- “变量为空”与“变量有值但文件缺失/不可读”要区分:前者静默降级;后者启动不失败,写一条 WARN 日志,运行时按未配置处理。
|
||||
- 两种情况都让 `runtime/queues`、`runtime/documents/{id}` 返回 503 `runtime_read_unavailable`,`/monitor/overview` 的 `weknora_queues` 为 `null`;对账本身只需租户 Key,照常运行。
|
||||
|
||||
## 6. 运行方式
|
||||
|
||||
- **开关**:`RECONCILIATION_ENABLED`(默认 `false`)只决定对账服务是否接线——关着时 9 个接口统一 503 `reconciliation_not_configured`;它与 `TEST_WEKNORA_ENABLED`(旧的取件/上传链路)解耦,因为对账只用知识库绑定里的租户 Key。候选/测试环境显式开启,生产按授权再开。
|
||||
- **对账批次**:每次对账生成一个批次(run),记录开始/结束时间、两侧计数、各类差异计数和明细。结果持久化,可以和上一成功批次比较。触发方式:定时(默认每天 02:00,可配)+ 页面手动触发。
|
||||
- **唯一观测时刻**:批次以 `run.started_at` 作为唯一的“现在”。R5 宽限期、R7 阈值和所有相对时间判断都用它,不用 `time.Now()`。同一批次因此可重放、可解释,验收里的“连续两次一致”才有定义。
|
||||
- **全量扫描必须完整**:整页翻完才算完成,中途失败整批标为 `failed`,不产出部分结论。不能用“最近 N 条”代替全量(陷阱 17)。扫描使用 `page_size=1000`(§5)。这里的“完整”指本批把所有页翻完,不承诺对并发写入做快照:扫描期间有增删时可能漏掉个别条目,漏掉的在下一批补上,批次记 `window_overlapped` 供解释;不为此引入游标或重扫(Q10)。
|
||||
- **先确认再判缺**:R1、R2 定论前必须逐条单独读一次(`GET /knowledge/{id}`),区分 404、`deleting` 和翻页窗口漂移;没有单条证据的 R1/R2 不写 finding。
|
||||
- **并发**:同一测试库同时只能有一个 `running` 批次,用部分唯一索引兜底:`CREATE UNIQUE INDEX ... ON reconciliation_runs(test_kb_id) WHERE state='running'`;应用层的 409 只是友好提示。
|
||||
- **僵死批次回收(Q11)**:`running` 超过 6 小时(可配)视为失败,启动或下次触发时自动置 `failed` 并释放并发位;否则进程崩溃会让该库永久 409。
|
||||
- **与整库导出/发布重叠(Q6 已裁定)**:不互斥。批次开始或运行期间检测到整库导出/发布作业在跑,则 `run.window_overlapped=true`;该批次的 R1、R2 照常写入,但 `confirmation_state='pending'`,页面显示「待确认」,计数保留。
|
||||
- **findings 保留(Q5 已裁定)**:`runs` 永久保留(含 counts/previous_counts);`findings` 只保留**最近 30 批且不超过 90 天**,超出后按 `run_id` 整批删除,不逐行删。清理在每批对账结束后执行,幂等;删明细不影响批次计数和历史对比。
|
||||
- **对账只读**:对账过程不向 WeKnora 发起任何写请求。处置动作是人点击触发的独立动作,复用现有带审计的动作。
|
||||
- **并发与限速**:默认全程串行(同一时刻只有 1 个在途请求)。翻页**不并发**:offset 分页本来就会漂,并发只会让重复/漏页更难复现;R1/R2 的单条确认可以小并发,配置项 `reconciliation_confirm_concurrency`,默认 1、上限 8。**不复用入库的 `ingestion_concurrency`**:对账是夜间批处理,1 万条也只有 10 次翻页请求,不需要和取件/上传抢配额。
|
||||
|
||||
## 7. 接口契约(后端 T6a 与前端 T6b 的分界线)
|
||||
|
||||
T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,作为冻结契约;T6b 按契约在 T6a 之后开发(同一执行人,只改 `web/`)。契约以后要改,必须 T6a/T6b 两边都确认,并同步更新本节。
|
||||
|
||||
响应风格、错误体、鉴权方式沿用现有 `/api/v1/monitor/*` 的约定。响应中不得出现 URL 凭据、Key、Authorization。
|
||||
|
||||
| 方法 | 路径 | 说明 | 角色 |
|
||||
| --- | --- | --- | --- |
|
||||
| POST | `/api/v1/reconciliation/runs` | 请求体 `{kb_id}`;返回 202 和 run 对象;该库已有运行中批次时返回 409 `reconciliation_run_in_progress` | 管理员、文档工程师 |
|
||||
| GET | `/api/v1/reconciliation/runs?kb_id=&limit=&offset=` | 批次列表,按开始时间倒序 | 所有登录角色 |
|
||||
| GET | `/api/v1/reconciliation/runs/{id}` | 单个批次 | 所有登录角色 |
|
||||
| GET | `/api/v1/reconciliation/runs/{id}/findings?type=&q=&limit=&offset=` | 差异明细,`limit` ≤ 100 | 所有登录角色 |
|
||||
| POST | `/api/v1/reconciliation/findings/{id}/writeback` | 仅限 R5:以 WeKnora 状态回写台账,写审计;返回更新后的 finding | 管理员、文档工程师 |
|
||||
| POST | `/api/v1/reconciliation/findings/{id}/requeue` | 仅限 R1/R4:R1 清空 `knowledge_id` 后重排上传;R4 先删旧 knowledge 再重传,删除失败则动作失败且台账不变;写审计 | 管理员、文档工程师 |
|
||||
| POST | `/api/v1/reconciliation/findings/{id}/remove` | 仅限 R2:按 `knowledge_id` 从测试库删除,404 视为已删除;写审计;重复点击幂等 | 管理员 |
|
||||
| GET | `/api/v1/reconciliation/documents/{document_id}/progress` | 实时转发 WeKnora `runtime/documents/{id}`,经过脱敏;未配置平台 Key 时返回 503 `runtime_read_unavailable` | 所有登录角色 |
|
||||
| GET | `/api/v1/monitor/overview`(已有) | 新增 `weknora_queues` 字段(来自 `runtime/queues`,不可用时为 null);删除 Embedding/LLM 两张常量"未知"卡 | 不变 |
|
||||
|
||||
**`/api/v1/monitor/tasks`(已有,T6a 增量)**:每行新增可选 `weknora_url`(目标测试知识库的 WeKnora 控制台链接;未配置测试端点时为空字符串),供文件详情抽屉在 progress 返回 503 时显示跳转链接。该字段为附加字段,既有字段与筛选语义不变;与 finding 的 `weknora_url` 使用同一拼接规则(`internal/platform/weknora.KnowledgeBaseConsoleURL`)。
|
||||
|
||||
**run 对象**:`id`、`kb_id`、`state`(`running` \| `succeeded` \| `failed`)、`trigger`(`schedule` \| `manual`)、`started_at`(同时是观测时刻)、`finished_at`、`ledger_count`、`kb_count`、`counts`(键为 R1–R8,值为整数)、`previous_counts`(上一成功批次的 counts,没有则为 null)、`window_overlapped`(bool,Q6)、`error_code`。
|
||||
|
||||
**finding 对象**:`id`、`run_id`、`type`(R1–R8)、`publication_id`、`document_id`、`title`、`path`、`source`、`target_scope`、`ledger_state`、`weknora_parse_status`、`normalized_state`(按 §4 矩阵归一后的值,供前端直接显示)、`ledger_sha256`、`declared_sha256`、`weknora_file_md5`、`evidence_level`(`independent` \| `declared_only` \| `none`)、`confirmation_state`(`confirmed` \| `pending`,仅 R1/R2 在 `window_overlapped` 批次里可为 pending)、`detail`(中文一句话)、`suggested_action`(`requeue_upload` \| `remove_from_test` \| `writeback_state` \| `enter_removal` \| `none`)、`action_state`(`open` \| `done`)、`weknora_url`(在 WeKnora 中打开的链接,可为空)。
|
||||
|
||||
**R5 回写的迁移约束**(`POST /api/v1/reconciliation/findings/{id}/writeback`)
|
||||
|
||||
| 当前台账 | 允许回写到 |
|
||||
| --- | --- |
|
||||
| `pending` | `processing`、`finalizing`、`completed`、`failed` |
|
||||
| `processing` | `finalizing`、`completed`、`failed` |
|
||||
| `finalizing` | `completed`、`failed` |
|
||||
| `failed` | `pending`、`processing`、`completed` |
|
||||
| `stalled` | `pending`、`processing`、`failed` |
|
||||
|
||||
- `completed` 不允许回写到任何其他状态;`planned` 不是回写目标;`stalled` 是平台派生状态,不可写。
|
||||
- 目标是归一后的上游状态;`cancelled`、`deleting` 没有台账对应,不提供回写(`suggested_action=none`)。
|
||||
- 幂等:台账已等于目标时返回 200,不写新审计。
|
||||
- 台账在本批次后已被别的动作改过时返回 409 `reconciliation_writeback_stale`。
|
||||
- 回写只改 `processing_state`,不动 `retrieval_state`,不触发发布。
|
||||
|
||||
**progress 对象**:`document_id`、`parse_status`、`ingestion_status`、`wiki_status`、`stages[]`(name、status、error_code、finished_at)、`failures[]`(task_type、fail_count、failed_at、last_error,后者截断到 500 字符)、`has_more_failures`、`observed_at`。
|
||||
|
||||
处置动作的落点:`writeback_state`(R5)、`requeue_upload`(R1/R4)、`remove_from_test`(R2)、`enter_removal`(R6)各一个入口。**只有 R6 能复用现有接口**(`POST /test-publications/{id}/removal`;`removal-retry` 只重试已失败的移除,不发起首次移除);R1/R4 不能走 `retryPublicationsBatch`(只接受 `failed`/`stalled`,`job_failures.go:448`),R2 不能走测试库移除(拒绝 `superseded`,`test_publication_removal.go:68`),所以这两个是新接口,不是同义接口。
|
||||
|
||||
## 8. 页面改造(T6b,前端)
|
||||
|
||||
| 现有部分 | 去向 |
|
||||
| --- | --- |
|
||||
| 左侧导航「解析监控」 | 改名为「导入对账」,路由保留旧地址并重定向 |
|
||||
| 服务与依赖卡片区 | 收成页面顶部一行状态条;「队列」读 `weknora_queues`;删除 Embedding/LLM 两张常量"未知"卡 |
|
||||
| 按测试库的状态计数 | 改为「最近一次对账」概览:批次时间、状态、R1–R8 计数及与上一批的变化,附「立即对账」按钮(按角色显示) |
|
||||
| 文件处理大表 | 拆成两个页签:①**差异清单**(按类型、关键词筛选,每行显示证据等级、处置建议和按钮;`window_overlapped` 批次的 R1/R2 显示「待确认」徽标);②**平台侧流水**(沿用 `/monitor/tasks`,阶段筛选里的“解析”“索引增强”合并为“WeKnora 处理中”) |
|
||||
| 文件详情抽屉 | 平台侧信息保持不变;新增「WeKnora 处理详情」区块,实时调用 progress 接口,展示阶段时间线和历史失败;503 时显示"未配置只读 Key"和跳转链接 |
|
||||
|
||||
⚠️ 两个页签口径不同:差异清单只看 `superseded_at IS NULL` 的行;平台侧流水沿用 `/monitor/tasks`,**不过滤被顶替行**(`internal/monitoring/real.go:197-214`)。这是有意的,页面要写一句说明,避免同一文件在两个页签结论不同被当成 bug。
|
||||
|
||||
差异清单页脚注明保留范围:明细只保留最近 30 批且不超过 90 天,更早批次只保留计数。
|
||||
|
||||
视觉沿用现有规范:dobot.cn 钴蓝 #0039C8 + 中性灰,不用紫色;导航保持 16px / 44px。
|
||||
|
||||
## 9. 验收标准
|
||||
|
||||
**后端(T6a)**
|
||||
1. 用夹具(或在测试库人工构造)覆盖 R1–R8 每类至少一个样本,对账逐条命中,且没有多报。
|
||||
2. 用固定夹具和固定 `started_at` 重放同一批次两次,差异集合逐条一致;跨批次的时间类差异(R5/R7)按各自 `started_at` 解释,不要求两次相同。
|
||||
3. 对账过程中向 WeKnora 发出的写请求数为 0(以测试中的 HTTP 桩记录为证)。
|
||||
4. 扫描中途注入错误后,批次为 `failed`,没有写入任何 finding。
|
||||
5. 合法的"同字节多台账收养"不被报为 R8。
|
||||
6. `cancelled`、`deleting` 有显式映射,并有测试覆盖。
|
||||
7. 接口响应和日志中不出现 Key、Authorization 等密钥(有测试断言)。
|
||||
8. 并发触发同一库,第二个请求返回 409。
|
||||
9. OpenAPI 契约测试通过,`make verify` 全绿。
|
||||
10. `window_overlapped` 批次:R1/R2 的 `confirmation_state='pending'`,其他类型不受影响;接口和页面都能看到。
|
||||
11. 保留策略:第 31 批或超过 90 天的 findings 被按 run 整体删除,runs 与 previous_counts 保留;清理重复执行无副作用。
|
||||
12. 状态矩阵用表驱动测试覆盖 7×7,`cancelled`/`deleting` 有显式归一值,没有“其他”分支。
|
||||
13. R5 回写:`completed` 不可降级;禁止的迁移返回 409 且台账不变;重复回写幂等且不重复写审计。
|
||||
14. 已移除的行(`retrieval_state in ('disabling','disabled')`)不报 R1。
|
||||
15. R6 与 `/monitor/overview` 的「需下架」计数由同一实现产出,测试断言两处数字一致。
|
||||
16. 扫描请求的 `page_size=1000`(HTTP 桩断言),不再出现 100。
|
||||
17. 扫描期间在途请求数恒为 1(桩记录并发峰值),确认阶段不超过 `reconciliation_confirm_concurrency`。
|
||||
18. R1 重排:清空 `knowledge_id`、置 `pending`、入队上传,旧 knowledge 不存在时也能成功;R4 先删旧 knowledge,删除失败时动作返回错误且台账不变。
|
||||
19. R2 删除:按 `knowledge_id` 删除,404 视为成功,重复点击幂等。
|
||||
20. 僵死批次:`running` 超过阈值自动置 `failed`,之后可以再触发。
|
||||
|
||||
**前端(T6b)**
|
||||
1. 每个页签和抽屉都有加载、空、错误、无权限四种状态,并有组件测试覆盖。
|
||||
2. 只读角色看不到「立即对账」和处置按钮。
|
||||
3. progress 返回 503 时降级展示,页面不报错。
|
||||
4. 在 1440 / 1024 / 768 宽度下没有页面级横向溢出。
|
||||
5. `npm run build` 和前端测试通过,`make verify` 全绿。
|
||||
|
||||
## 10. 决策记录
|
||||
|
||||
| # | 问题 | 默认建议 |
|
||||
| --- | --- | --- |
|
||||
| Q1 | 是否为平台在**测试** WeKnora 开一个 `system_runtime_read` 平台级只读 Key | **已裁定:开**(只开在测试环境) |
|
||||
| Q2 | 历史上传里没有 metadata 的条数 | T6a 开发时先统计,结果写进工单评论 |
|
||||
| Q3 | 对账频率、R5 宽限期、R7 阈值 | 未裁定,按默认值执行:每天 02:00;30 分钟;2 小时(可配置) |
|
||||
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
|
||||
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
|
||||
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
|
||||
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
|
||||
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加“距上次发布 N 天” |
|
||||
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
|
||||
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受并发增删造成的个别漏项在下一批补上,不引入游标 |
|
||||
| Q11 | 僵死 `running` 批次 | **已裁定**:超过 6 小时(可配)自动置 `failed` |
|
||||
| Q12 | API 字段命名 | **已裁定**:`kb_id`/`document_id`;数据库列名仍为 `test_kb_id`/`knowledge_id`,避免 OpenAPI 安全门禁全局禁名 |
|
||||
| Q13 | R6 处置入口 | **已裁定**:`POST /test-publications/{id}/removal`;`removal-retry` 只重试已失败移除 |
|
||||
@@ -0,0 +1,179 @@
|
||||
# 本期计划:WeKnora 升级 v0.9.1 + 导入对账
|
||||
|
||||
> 状态:v0.4(2026-11-30),用户已裁定 D0 / D1 / Q1 / Q5 / Q6 / Q7 / Q9 / Q10 / Q11,可以开工。不建 Gitea 工单,本文即任务书。
|
||||
> 基线:`origin/main` `ca87056`;上游 WeKnora v0.9.1 源码 `~/weknora-explore/WeKnora-v0.9.1`。
|
||||
> 导入对账的需求正文见 [IMPORT_RECONCILIATION_REQUIREMENTS.md](IMPORT_RECONCILIATION_REQUIREMENTS.md)。
|
||||
|
||||
## 0. 目标
|
||||
|
||||
1. 测试、生产 WeKnora 从 v0.9.0 升级到 v0.9.1,升级后整库发布照常可用。
|
||||
2. 「解析监控」重构为「导入对账」一期(台账 ↔ 测试库)。
|
||||
|
||||
发布架构保持不变(2026-11-30 与用户确认):**测试环境负责解析、人工加工和新功能验证;生产环境只做推理,不跑 MinerU、不做解析;内容只通过平台整库发布(直接读写 WeKnora 的 PG/ES)从测试搬运到生产。**
|
||||
|
||||
## 1. 分工
|
||||
|
||||
| 角色 | 负责 | 不做 |
|
||||
| --- | --- | --- |
|
||||
| **用户** | 批准需求与工单;执行现场运维(升级、备份);授权生产发布;回答各工单里的决策项 | — |
|
||||
| **DeepSeek(开发)** | T1、T6a、T6b 的开发、测试、迁移和项目文档;T3 演练的脚本和命令准备 | 不改验收标准;不部署;不执行生产写操作 |
|
||||
| **验收工作流** | 按本文验收矩阵逐项判定 PASS / FAIL,结论绑定提交 SHA(由用户指派) | 不修代码 |
|
||||
|
||||
交接证据和验收结论的格式沿用 [three-agent-handoff-workflow.md](architecture/three-agent-handoff-workflow.md) §6 的模板(只借格式,不再有三个角色)。
|
||||
|
||||
**交付流程(D0,已裁定:走 PR)**:按 `AGENTS.md` 执行。每个工单从最新 `origin/main` 拉一个短分支,通过 PR 合入;CI `build` 通过,且验收工作流 PASS 后才合并;合并后读回 `merged=true` 和 `merge_commit_sha`。`three-agent-handoff-workflow.md` §2 中"main 直推、不走 PR"的口径作废,由 DeepSeek 在 T1 的 PR 里顺手把该节改成与 AGENTS.md 一致。
|
||||
|
||||
**不建 Gitea 工单**:本文就是任务书。交接证据(起止 SHA、测试命令与真实输出)和验收结论写在对应 PR 的描述和评论里,格式沿用上面提到的 §6 模板。
|
||||
|
||||
**串行规则**:T1、T6a、T6b 全部由 DeepSeek 开发,串行进行(T1 → T6a 契约 → T6a 实现 → T6b)。T6b 只改 `web/`,与 T6a 交错时不动后端文件,避免冲突。
|
||||
|
||||
## 2. 工单总览与依赖
|
||||
|
||||
```
|
||||
T1 libraryprofile v0.9.1 + 漏表门禁 ──合并并部署──► T2 升级测试 WeKnora ──► T3 测试整库导出演练
|
||||
│
|
||||
▼
|
||||
T4 升级生产 WeKnora ◄── T3 通过
|
||||
│
|
||||
▼
|
||||
T5 整库发布 + 读回
|
||||
|
||||
T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端(按契约并行,联调需 T2 完成)
|
||||
```
|
||||
|
||||
| 工单 | 内容 | 执行 | 验收 | 前置 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| T1 | libraryprofile 补 v0.9.1 + 漏表门禁 | DeepSeek | 验收工作流 | 无 |
|
||||
| T2 | 升级测试 WeKnora | 用户(按 §4 清单) | 用户 + 验收工作流 | T1 已合并并部署到平台 |
|
||||
| T3 | 测试整库导出演练 | DeepSeek 准备命令,用户授权执行 | 验收工作流 | T2 |
|
||||
| T4 | 升级生产 WeKnora | 用户(按 §4 清单) | 用户 + 验收工作流 | T3 PASS |
|
||||
| T5 | 整库发布到生产 + 读回 | 用户在平台授权发布 | 验收工作流(读回证据) | T4 |
|
||||
| T6a | 导入对账后端 | DeepSeek | 验收工作流 | 无(联调需 T2) |
|
||||
| T6b | 导入对账前端 | DeepSeek | 验收工作流 | T6a 契约提交 |
|
||||
|
||||
**需求单落库口径(6 张)**:T1、T2、T3、T4、T5、T6。T6 把上面的 T6a 与 T6b 合成一张,契约仍是第一个提交;下面保留 T6a/T6b 只是写清先后顺序。
|
||||
|
||||
## 3. T1:libraryprofile 补 v0.9.1 + 漏表门禁
|
||||
|
||||
### 3.1 背景(已核实)
|
||||
|
||||
- 整库导出和导入按目标库 `schema_migrations` 的版本,从 `internal/libraryprofile/profile.go` 选中一份声明;目前只有 74(v0.7.1)和 134(v0.9.0)。v0.9.1 的版本是 137,`libraryprofile.For(137)` 会失败,**升级后整库发布会被拒绝**。
|
||||
- 上游 135–137 号迁移(已逐个读过):135 加宽 `audit_logs.actor_user_id`;136 新建 `credential_vault_items`(只有 tenant_id/user_id,与知识库无关);137 重建 `im_channel_sessions` 的唯一索引。**三个都不涉及知识相关的表、列或触发器**。`chunk_images_sync` 触发器只在 000113 中定义,之后没有被修改。
|
||||
- **已有缺口(与升级无关,0.9.0 起就存在)**:现有的 schema 探测只检查"声明过的表是否存在"(`releaseadapter/v071/schema_profile.go:111`),不会发现"有本库数据、但没有声明"的表。按上游迁移文件统计,0.9.x 中带 `knowledge_base_id` 或 `knowledge_id` 列、却不在 v090 声明里的表有:
|
||||
|
||||
| 表 | 内容 | 建议归类 |
|
||||
| --- | --- | --- |
|
||||
| `chunk_images` | 由 chunks 上的触发器维护的派生表 | 派生(已在 v090 的触发器声明中覆盖) |
|
||||
| `chunk_revisions` | 切片编辑历史(000078) | **搬运(D1 已裁定)** |
|
||||
| `wiki_page_revisions` | Wiki 页面编辑历史(000075) | **搬运(D1 已裁定)** |
|
||||
| `knowledge_processing_spans` | 解析流水线的阶段遥测(000055) | 排除:处理过程数据,生产不解析 |
|
||||
| `sessions`、`messages` | 对话数据 | 排除:生产自己的运行数据,不能被覆盖 |
|
||||
| `memory_doc_affinity` | 记忆与文档的关联 | 排除:运行数据 |
|
||||
| `user_kb_pins`、`kb_shares`、`im_channels`、`data_sources` | 用户置顶、共享、IM 渠道、数据源配置 | 排除:各环境自己的配置 |
|
||||
|
||||
### 3.2 需求
|
||||
|
||||
1. **新增 v0.9.1 声明**:版本 137,`WeKnoraVersion: "v0.9.1"`。表、列、部件、触发器与 v090 相同,**必须复用 v090 的声明来构造,不能复制一份**(硬约束 1)。`Supported()` 加入 137,`For` 的错误信息同步更新。
|
||||
2. **每张关联表都要归类**:在 profile 中为每个版本维护「关联表分类」:`copied`(搬运,即现有的 Required/Optional)、`derived`(由触发器或应用派生)、`excluded`(不搬,必须写明原因)。分类只写在 profile 这一处。
|
||||
3. **漏表门禁**:在测试端导出前、生产端导入前各执行一次。从 information_schema 找出 public 下所有带 `knowledge_base_id`、`knowledge_id` 或 `kb_id` 列的表:
|
||||
- 已分类的表:放行。
|
||||
- 未分类的表:若含有**本次发布范围内**的数据,拒绝并返回 `release_undeclared_kb_table`,错误信息列出表名和行数,不可重试;若没有数据,放行,但在发布记录里写一条警告。
|
||||
4. **搬运编辑历史(D1 已裁定:搬)**:`chunk_revisions`、`wiki_page_revisions` 加入 v0.9.0 和 v0.9.1 两份声明的 copied 表与归档部件(v0.7.1 中没有这两张表,不动)。它们必须和现有表走**同一套**范围改写与 ID 映射,不能另写一条路径:
|
||||
|
||||
| 表 | 身份 | 范围改写 | 引用映射 | 不改写 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `chunk_revisions` | id | tenant_id、knowledge_base_id | knowledge_id、chunk_id | revision、content、editor_id、edit_source、时间列 |
|
||||
| `wiki_page_revisions` | id | tenant_id、knowledge_base_id | page_id | slug、version、正文类字段、aliases、editor_id、时间列 |
|
||||
|
||||
- **写入顺序**:在父表(chunks、wiki_pages)之后写入;删除和回滚时先删这两张表。两张表在上游都没有外键,但存在逻辑引用。
|
||||
- **悬挂引用**:沿用现有规则,指向未登记身份的引用一律拒绝,不静默跳过。上游删除切片或页面时会同步硬删除对应的历史记录(`repository/chunk.go:726`、`repository/wiki_page.go:261-285`),所以正常情况下不应出现悬挂引用;T3 演练要实测确认。
|
||||
- **editor_id 原样保留**:测试环境的用户 ID 在生产上可能查不到,生产页面上会显示为未知编辑者。这是已知且可以接受的代价,要在 `docs/library-target-id-mapping.md` 中写明。
|
||||
- **ES**:两张表不进检索索引。DeepSeek 需要读上游代码确认这一点,并把结论写进 PR 描述。
|
||||
- **唯一索引**:`chunk_revisions(chunk_id, revision)` 是唯一索引,chunk_id 映射后仍然唯一,需要有测试覆盖。
|
||||
- **同步更新文档**:`docs/library-target-id-mapping.md` 的映射表、`docs/library-data-contract.md`(如果其中列了表清单)。
|
||||
|
||||
### 3.3 验收(验收工作流)
|
||||
|
||||
1. `libraryprofile.For(137)` 返回 v0.9.1 声明;v090 与 v091 的声明除版本号外完全一致(用测试断言,而不是两份复制的常量)。
|
||||
2. 门禁测试:未分类表有数据 → 拒绝,错误码和表名都正确;未分类表为空 → 放行并有警告;`derived`/`excluded` 表 → 放行。
|
||||
3. 现有的 74 / 134 测试全部保持通过。
|
||||
4. `make verify` 全绿;提交符合 AGENTS.md 规范。
|
||||
5. 编辑历史两张表:有测试覆盖范围改写、ID 映射、写入/删除顺序、悬挂引用拒绝、唯一索引;导出 → 写入 → 校验 → 回滚的整轮测试中,两张表的行数和内容摘要都一致。
|
||||
6. PR 描述附上:对上游 135–137 号迁移的审查结论;如果开发会话能访问测试 WeKnora,附上对真实 0.9.0 库 information_schema 的只读查询结果。
|
||||
|
||||
## 4. T2 / T4:升级 WeKnora(用户执行的清单)
|
||||
|
||||
依据上游 `website-docs/07-releases/v0.9.1.md#upgrade-notes`。测试和生产各执行一遍,**生产必须等 T3 PASS 之后再做**。
|
||||
|
||||
**升级前**
|
||||
- [ ] 平台已部署包含 T1 的版本(在平台入口查看版本号)
|
||||
- [ ] 备份 PostgreSQL、文件存储、部署配置(`.env`、compose 覆盖文件)
|
||||
- [ ] 生产额外执行:`bash scripts/target_kb_snapshot.sh` 留档,并用 `go run ./cmd/guardcheck <快照根> <kb_id>` 核验
|
||||
- [ ] 记录升级前状态:`SELECT version, dirty FROM schema_migrations;`,应为 `134, false`
|
||||
- [ ] 生产额外确认:MinerU 和解析 worker 处于关闭状态(生产只做推理)
|
||||
|
||||
**升级**
|
||||
- [ ] `.env` 中设置 `WEKNORA_VERSION=v0.9.1`;检查是否有单独覆盖过的组件镜像标签
|
||||
- [ ] `docker compose pull && docker compose up -d`
|
||||
|
||||
**升级后**
|
||||
- [ ] `schema_migrations` 应为 `137, false`
|
||||
- [ ] 抽查原有知识库的检索、问答是否正常
|
||||
- [ ] 测试环境额外检查:平台走一轮「取件 → 上传 → 解析 → 完成」
|
||||
- [ ] 测试环境额外操作(Q1 已裁定:开):在测试 WeKnora 创建平台级 API Key,只授予 `system_runtime_read` 能力,以 secret 文件形式交给平台(不写进 Git 或 compose),然后确认 `GET /api/v1/system/admin/runtime/documents` 可以访问。生产不需要这个 Key
|
||||
- [ ] 生产额外检查:平台发布通道只读预检(`release-diag`)通过
|
||||
|
||||
**回退**:不能直接换回旧镜像。向下迁移会删除凭据表、截短审计字段。正确做法是停止写入后,用升级前的备份恢复数据库、存储和配置,再切回 v0.9.0 镜像。
|
||||
|
||||
## 5. T3:测试整库导出演练
|
||||
|
||||
- **目的**:在升级到 0.9.1 的测试库上,证明新声明和门禁在真实库上可用;同时作为 T4 的放行条件。
|
||||
- **DeepSeek**:根据 `docs/library-capture.md`、`docs/library-sync-acceptance.md`、`docs/library-migration-contract.md` 和 `libraryctl` 的现有子命令,整理出逐条执行的命令清单(只读或只写测试侧),写进工单,由用户授权后执行。
|
||||
- **验收(验收工作流)**:快照清单里的 schema 版本是 137;`chunk_revisions`、`wiki_page_revisions` 两个部件存在,行数与源库一致,没有悬挂引用;所有部件齐全,哈希可以复算(`libraryctl snapshot-verify`);漏表门禁实际执行过,并对真实库输出了分类结果;与上一次 0.9.0 快照相比,表计数没有异常变化。
|
||||
|
||||
## 6. T5:整库发布到生产 + 读回
|
||||
|
||||
- 按 `docs/RELEASE_RUNBOOK.md` 和 OPERATIONS_RUNBOOK §5–6 执行:发布前留档门禁 → 授权发布 → 读回。
|
||||
- **验收(验收工作流)**:发布记录为成功;读回一致;用 `librarydiff` 对比测试快照与生产,差异为 0(`excluded` 表除外,并列明);生产抽样 10 个问题检索正常;漏表门禁在生产端也执行过。
|
||||
|
||||
## 7. T6a / T6b:导入对账
|
||||
|
||||
需求、接口契约和验收标准都在 [IMPORT_RECONCILIATION_REQUIREMENTS.md](IMPORT_RECONCILIATION_REQUIREMENTS.md):
|
||||
|
||||
- T6a 的第一个提交只包含 §7 的 OpenAPI 契约,先由验收工作流审契约并冻结,再继续实现。
|
||||
- 本期 T6a 范围内加入"上传时记录上传字节的 MD5":需要一个台账迁移(`upload_md5`),以及上传流程的改动。
|
||||
- 新建 `reconciliation_runs` / `reconciliation_findings` 两张表:`runs` 永久保留;`findings` 按 `run_id` 整批清理,保留最近 30 批且不超过 90 天(Q5)。同一测试库的 `running` 批次用部分唯一索引约束(`WHERE state='running'`)。
|
||||
- 对账扫描使用 `page_size=1000`:要把 `internal/platform/weknora/client.go` 的 `validPage` 上限从 100 放开(或给对账单独一条扫描路径),不能沿用上传恢复的 100。扫描全程串行(在途 1 个请求),R1/R2 确认可用 `reconciliation_confirm_concurrency`(默认 1、上限 8),不复用 `ingestion_concurrency`。
|
||||
- 与整库导出/发布不互斥;批次开始和结束时各检测一次是否有导出/发布作业在跑,命中则写 `window_overlapped=true`,该批 R1/R2 的 `confirmation_state='pending'`(Q6)。
|
||||
- 平台级只读 Key 走 `WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,启动读取一次,不做热加载);未配置或文件不可读时 `runtime/*` 返回 503 `runtime_read_unavailable`,对账不受影响(Q7)。
|
||||
- 状态映射只写在服务端一处,接口返回 `normalized_state`;R5 回写按迁移矩阵校验,`completed` 不可降级。
|
||||
- 处置动作:新增 finding 级 `requeue`(R1/R4)与 `remove`(R2);R6 复用现有 `POST /test-publications/{id}/removal`(`removal-retry` 只重试已失败移除)。R1/R4 不能走 `retryPublicationsBatch`,R2 不能走测试库移除,原因见需求 §7(Q9)。
|
||||
- 扫描保留 offset 翻页,不引入游标;并发增删造成的个别漏项在下一批补上(Q10)。
|
||||
- 僵死 `running` 超过 6 小时(可配)自动置 `failed`,释放并发位(Q11)。
|
||||
- 一期只对测试库。生产的下架依赖"测试移除 + 下一轮整库发布",这段空窗期不在对账范围内,必须写进页面范围说明(Q8 未裁定是否再加"距上次发布 N 天"提示)。
|
||||
- T6b 先用契约桩数据开发,T2 完成后再和真实后端联调。
|
||||
|
||||
## 8. 决策记录
|
||||
|
||||
| # | 问题 | 结论(2026-11-30 用户裁定) |
|
||||
| --- | --- | --- |
|
||||
| D0 | 交付流程 | 按 AGENTS.md 走分支 + PR |
|
||||
| D1 | 编辑历史(`chunk_revisions`、`wiki_page_revisions`)是否搬到生产 | 搬 |
|
||||
| Q1 | 是否在测试 WeKnora 为平台开 `system_runtime_read` 只读 Key | 开 |
|
||||
| Q3 | 对账频率、R5 宽限期、R7 阈值 | 未裁定,按默认值执行:每天 02:00;30 分钟;2 小时(做成可配置项) |
|
||||
| Q4 | R2 孤儿的移除权限 | 未裁定,按默认值执行:只限管理员 |
|
||||
| Q5 | findings 保留期与清理策略 | **已裁定**:`runs` 永久保留;`findings` 保留最近 30 批且不超过 90 天,超出按 `run_id` 整批删除 |
|
||||
| Q6 | 对账与整库导出/发布是否互斥 | **已裁定**:不互斥;重叠批次标 `window_overlapped`,R1/R2 的 `confirmation_state` 降为 `pending` |
|
||||
| Q7 | 平台级 Key 的配置键名 | **已裁定**:`WEKNORA_RUNTIME_KEY_FILE`(绝对路径 secret 文件,不进 compose/Git) |
|
||||
| Q8 | 生产下架空窗期是否在页面提示天数 | 未裁定;默认只在页面范围说明里写边界,不加"距上次发布 N 天" |
|
||||
| Q9 | R1/R2/R4 的处置动作 | **已裁定:要能修**;新增 finding 级 `requeue`、`remove` 两个接口 |
|
||||
| Q10 | 扫描一致性 | **已裁定**:保留 offset 翻页,接受个别漏项下一批补上,不引入游标 |
|
||||
| Q11 | 僵死 `running` 批次 | **已裁定**:超过 6 小时(可配)自动置 `failed` |
|
||||
|
||||
## 9. 执行顺序速览
|
||||
|
||||
1. DeepSeek 做 T1,提 PR → 验收工作流 → 合并 → 部署到平台(按现有发布流程)。
|
||||
2. DeepSeek 在 T1 合并后开始 T6a,第一个提交是 OpenAPI 契约;契约经验收工作流冻结后,继续 T6a 实现和 T6b。
|
||||
3. 你执行 T2(升级测试)并创建只读 Key → DeepSeek 准备 T3 命令,你授权执行 → 验收工作流。
|
||||
4. T3 通过后,你执行 T4(升级生产)→ 在平台授权 T5 发布 → 验收工作流读回证据。
|
||||
5. T6 和测试环境联调 → 验收工作流 → 合并 → 部署。
|
||||
@@ -10,7 +10,7 @@
|
||||
| 合同条目 | 本文位置 |
|
||||
|---|---|
|
||||
| 1 三角色职责 | §1 |
|
||||
| 2 main 单线、串行修改 | §2 |
|
||||
| 2 分支 + PR、串行修改 | §2 |
|
||||
| 3 六个状态名、标签互斥、blocked 要素 | §3 |
|
||||
| 4 每轮可交接的修改链路(自测→commit→快照 tag→推送→核实→review) | §4、§5 |
|
||||
| 5 不可变与回退规则 | §5 |
|
||||
@@ -30,11 +30,12 @@
|
||||
角色约束是**流程约束**,不是技术 ACL 隔离:本机共用 Gitea 管理员凭据,谁也拦不住谁越权,
|
||||
所以每个角色都要靠"读回核实"而非"相信对方自述"来交付。
|
||||
|
||||
## 2. main 单线、单仓库串行
|
||||
## 2. 分支 + PR 单线、单仓库串行
|
||||
|
||||
- 只使用 `main` 一条线:**不创建分支、不建 worktree、不走 PR、不做合并**(通用引擎规范里 PR 是可选姿态,
|
||||
本仓沿用"以直推为主"的口径)。
|
||||
- 同一仓库的代码修改**串行**:一个工单在主开发阶段只由一个开发会话持有。
|
||||
- 只使用受保护的 `main` 作为集成目标:**不直推 main**;每个工单从最新 `origin/main` 拉一个短命分支,
|
||||
通过 PR 合入,合并前 CI `build`(`make verify`)必须通过。口径以 `AGENTS.md` 为准,本节不再保留
|
||||
“main 直推”的旧做法。
|
||||
- 同一仓库的代码修改**串行**:一个工单在主开发阶段只由一个开发会话持有;PR 完成后短命分支删除。
|
||||
- **review 期间开发停止修改代码**:工单进入 `status:review` 后,除按 `rework` 要求修复外不再改动。
|
||||
- 切换现场前先取证:`git status --short --branch`、`git worktree list`、`git rev-parse origin/main`。
|
||||
工作区不干净、或存在不属于本工单的改动时**不得混入**,安全处理不了就置 `status:blocked`。
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
2. 用**只读会话**(`default_transaction_read_only=on`)连来源 PostgreSQL;连接串只在进程内存里。
|
||||
3. 核对来源已结清:所有文档 `parse_status=completed`、无待处理操作、无死信(任一不满足就拒绝,不看其他 KB 的局部状态)。
|
||||
4. 从持久数据推出兼容契约:迁移版本、dirty、租户、Embedding 模型与维度、检索引擎、索引名、索引映射摘要(`text-embedding-v4` / 1024 维 / schema 74)。
|
||||
5. 在**维护窗口**内停住声明过的写入者(只对声明为 writer 的服务发 SIGTERM,等它真的停下),导出 PostgreSQL 十表 + Elasticsearch 正文与向量 + 对象资源,做双向覆盖与摘要核验,封存为内容寻址产物。
|
||||
5. 在**维护窗口**内停住声明过的写入者(只对声明为 writer 的服务发 SIGTERM,等它真的停下),按来源 schema profile 导出知识域表(0.7.1 十表;0.9.x 另含 `chunk_revisions`、`wiki_page_revisions`)+ Elasticsearch 正文与向量 + 对象资源,做双向覆盖与摘要核验,封存为内容寻址产物。
|
||||
6. 无论成败都恢复写入者并等到 healthy;崩溃留下的日志用 `libraryctl recover` 收尾。
|
||||
7. 打印快照 ID、分项(kind/name/数量/字节/SHA256)与兼容契约。
|
||||
|
||||
|
||||
@@ -28,6 +28,21 @@
|
||||
|
||||
既有目标历史软删除行按原 destructive predicate 进入 before-image,不用来源活跃行过滤规则裁剪恢复数据。来源导出只包含活跃内容;可归属于本库的异常边在过滤前检查。完全没有任何父或范围锚的历史记录不能猜成属于本库:不全局扫出后删除、不自动迁移;这不是“所有历史孤儿已修复”。
|
||||
|
||||
## 2.1 0.9.x 追加:编辑历史两表(T1)
|
||||
|
||||
0.7.1 没有这两张表;0.9.0(134)与 0.9.1(137)起整库发布按 `libraryprofile` 声明搬运:
|
||||
|
||||
| 表 | 身份 | 范围/引用 | 保真边界 |
|
||||
|---|---|---|---|
|
||||
| `chunk_revisions` | `id`(varchar 36) | 范围改写 `tenant_id`/`knowledge_base_id`;映射 `knowledge_id`、`chunk_id` | `revision`/`content`/`is_enabled`/`editor_id`/`edit_source`/时间列原样;唯一索引 `(chunk_id, revision)` 映射后仍唯一 |
|
||||
| `wiki_page_revisions` | `id`(varchar 36) | 范围改写 `tenant_id`/`knowledge_base_id`;映射 `page_id` | `slug`/`version`/正文类字段/`aliases`/`editor_id`/时间列原样;唯一索引 `(page_id, version)` 映射后仍唯一 |
|
||||
|
||||
- 写入在父表(`chunks` / `wiki_pages`)之后;删除/回滚先删两表。
|
||||
- 只导出**活跃父行**的修订:父行软删属于本次范围外;父行完全不存在属于数据异常,导出即拒绝。
|
||||
- 修订正文里的 `resource://` 按历史事实原样保留,不参与资源发现(人类裁定 Q2=B)。
|
||||
- `editor_id` 不映射:目标可能查不到来源用户,页面显示未知编辑者;这是已接受代价。
|
||||
- 两表不进 Elasticsearch;整库校验比对行数 + 逐行内容摘要(时间戳类字段按既有规则豁免)。
|
||||
|
||||
## 3. 资源引用的实际格式
|
||||
|
||||
只读参考源码:`WeKnora-v0.7.1-dev/internal/types/resource.go` 中 `ResourceHandleLength=22` 与 `ParseResourcePath`;本轮没有修改WeKnora源码。
|
||||
|
||||
@@ -33,6 +33,8 @@ target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 var
|
||||
| wiki_folders | id | parent_id |
|
||||
| wiki_pages | id | folder_id, chunk_refs, source_refs(保留 `id|title`), page_metadata(仅精确匹配) |
|
||||
| wiki_page_issues | id | page_id, knowledge_id, chunk_id |
|
||||
| chunk_revisions | id | knowledge_id, chunk_id |
|
||||
| wiki_page_revisions | id | page_id |
|
||||
| resource_bindings | id | owner_id(按 owner_type) |
|
||||
| resources | **不映射** | resource_id 保持共享身份 |
|
||||
| 索引文档 | 文档物理 ID | chunk_id, knowledge_id, source_id, tag_id |
|
||||
@@ -40,6 +42,20 @@ target_id = 前 16 字节按 8-4-4-4-12 十六进制格式化(置 RFC 4122 var
|
||||
正文、标题、摘要、向量、slug、in_links/out_links、pages_affected 不改写;本地自增列
|
||||
(如 `wiki_log_entries.id`)仍由既有 LocalIDs 分配。引用指向未登记身份时拒绝(悬挂引用不静默放行)。
|
||||
|
||||
### 0.9.x 编辑历史(v090 / v091)
|
||||
|
||||
- `chunk_revisions`:身份 `id`;范围改写 `tenant_id`、`knowledge_base_id`;引用映射
|
||||
`knowledge_id → knowledges`、`chunk_id → chunks`;`revision`、`content`、`is_enabled`、
|
||||
`editor_id`、`edit_source`、时间列不改写。
|
||||
- `wiki_page_revisions`:身份 `id`;范围改写 `tenant_id`、`knowledge_base_id`;引用映射
|
||||
`page_id → wiki_pages`;`slug`、`version`、正文类字段、`aliases`、`editor_id`、时间列不改写。
|
||||
- 两表在父表(`chunks` / `wiki_pages`)之后写入;删除与回滚先删这两张表。
|
||||
- 唯一索引 `(chunk_id, revision)` / `(page_id, version)` 在映射后仍唯一(有测试)。
|
||||
- `editor_id` 原样保留:测试环境的用户 ID 在生产上可能查不到,生产页面会显示为未知编辑者。
|
||||
这是已知且可接受的代价,写在这里避免被当成缺陷重复排查。
|
||||
- 两表不进检索索引;修订正文里的 `resource://` 文本按历史事实原样保留,不参与资源发现
|
||||
(Q2=B,2026-11-30 人类裁定)。
|
||||
|
||||
## 一致性边界
|
||||
|
||||
- 写集合登记的是目标身份;verify 的身份摘要与内容摘要都按同一 `rowTransform` 计算;
|
||||
|
||||
+124
-43
@@ -8,6 +8,12 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
// 运行镜像是 alpine,不带 /usr/share/zoneinfo;而本包在 Load 时就用
|
||||
// time.LoadLocation 校验具名时区(RECONCILIATION_TIMEZONE 等)。只有嵌进
|
||||
// 二进制才不依赖基础镜像:api 之前能过,纯粹是因为 internal/httpapi 顺带了
|
||||
// 这个空白导入,worker / release-worker 没有,于是候选与发布容器的 worker
|
||||
// 在启动时直接退出(unknown time zone Asia/Shanghai)。
|
||||
_ "time/tzdata"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
@@ -53,16 +59,32 @@ type Config struct {
|
||||
// WeKnoraBindingMasterKeyFile 是「知识库绑定」密文的独立主密钥文件(0600、32字节)。
|
||||
// 未配置时新页面仍可读旧部署的 file 凭据,但保存新密钥会被拒绝(不落明文)。
|
||||
WeKnoraBindingMasterKeyFile string
|
||||
GovernanceSpoolRoot string
|
||||
IngestionSpoolRoot string
|
||||
ArtifactFetchMaxBytes int64
|
||||
WorkerLivenessStaleAfter time.Duration
|
||||
TestWeKnoraHTTPTimeout time.Duration
|
||||
TestWeKnoraPollInitial time.Duration
|
||||
TestWeKnoraPollMax time.Duration
|
||||
TestWeKnoraStalledAfter time.Duration
|
||||
TestWeKnoraMaxUploadBytes int64
|
||||
TestAcceptancePolicyVersion string
|
||||
// WeKnoraRuntimeKeyFile 是测试实例平台级只读 Key(0400,绝对路径)。空值=
|
||||
// runtime/* 与 overview 队列降级为不可用;对账本身只用租户 Key。
|
||||
WeKnoraRuntimeKeyFile string
|
||||
// ReconciliationSettings:批次执行参数。全部可配,但都有安全默认值。
|
||||
// ReconciliationEnabled 是「导入对账」自身的开关:只决定对账服务是否接线,
|
||||
// 与 TEST_WEKNORA_ENABLED(旧测试库取件/上传链路)解耦——对账只用租户 Key。
|
||||
ReconciliationEnabled bool
|
||||
ReconciliationScheduleEnabled bool
|
||||
ReconciliationDailyAt string
|
||||
ReconciliationTimezone string
|
||||
ReconciliationGrace time.Duration
|
||||
ReconciliationStallAfter time.Duration
|
||||
ReconciliationStaleAfter time.Duration
|
||||
ReconciliationConfirmConcurrency int
|
||||
ReconciliationKeepRuns int
|
||||
ReconciliationMaxAge time.Duration
|
||||
GovernanceSpoolRoot string
|
||||
IngestionSpoolRoot string
|
||||
ArtifactFetchMaxBytes int64
|
||||
WorkerLivenessStaleAfter time.Duration
|
||||
TestWeKnoraHTTPTimeout time.Duration
|
||||
TestWeKnoraPollInitial time.Duration
|
||||
TestWeKnoraPollMax time.Duration
|
||||
TestWeKnoraStalledAfter time.Duration
|
||||
TestWeKnoraMaxUploadBytes int64
|
||||
TestAcceptancePolicyVersion string
|
||||
// TestAutoReviewPolicy:验收通过后是否自动批准(off|internal|all;默认 internal)。
|
||||
TestAutoReviewPolicy string
|
||||
// 目标库所在主机(整库逻辑备份真正执行的地方)。凭据是挂载进来的 0600 ssh
|
||||
@@ -198,39 +220,49 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be a positive duration")
|
||||
}
|
||||
config := Config{
|
||||
DatabaseURL: getenv("DATABASE_URL"),
|
||||
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
|
||||
WorkerID: valueOrDefault(getenv("WORKER_ID"), "worker-1"),
|
||||
PollInterval: time.Second,
|
||||
LeaseDuration: 30 * time.Second,
|
||||
RetryDelay: 5 * time.Second,
|
||||
SourceRefreshSchedulerInterval: 30 * time.Second,
|
||||
ReleaseConfigFile: strings.TrimSpace(getenv("RELEASE_CONFIG_FILE")),
|
||||
ProductionReleaseAuthorizerRef: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTHORIZER_REF")),
|
||||
ProductionReleaseAuthTokenFile: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTH_TOKEN_FILE")),
|
||||
ProductionWeKnoraBaseURL: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_BASE_URL")),
|
||||
ProductionWeKnoraAPIKeyFile: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_API_KEY_FILE")),
|
||||
PPScanAllowedRoot: strings.TrimSpace(getenv("PP_SCAN_ALLOWED_ROOT")),
|
||||
PPScanLedgerPath: strings.TrimSpace(getenv("PP_SCAN_LEDGER_PATH")),
|
||||
PPScanManifestPath: strings.TrimSpace(getenv("PP_SCAN_MANIFEST_PATH")),
|
||||
TestWeKnoraBaseURL: strings.TrimSpace(getenv("TEST_WEKNORA_BASE_URL")),
|
||||
MinerUBaseURL: strings.TrimSpace(getenv("MINERU_BASE_URL")),
|
||||
TestWeKnoraKBID: strings.TrimSpace(getenv("TEST_WEKNORA_KB_ID")),
|
||||
InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")),
|
||||
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
|
||||
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
|
||||
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
|
||||
GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"),
|
||||
IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")),
|
||||
ArtifactFetchMaxBytes: 200 * 1024 * 1024,
|
||||
WorkerLivenessStaleAfter: 2 * time.Minute,
|
||||
TestWeKnoraHTTPTimeout: 60 * time.Second,
|
||||
TestWeKnoraPollInitial: 10 * time.Second,
|
||||
TestWeKnoraPollMax: time.Minute,
|
||||
TestWeKnoraStalledAfter: 30 * time.Minute,
|
||||
TestWeKnoraMaxUploadBytes: 50 * 1024 * 1024,
|
||||
TestAcceptancePolicyVersion: valueOrDefault(getenv("TEST_ACCEPTANCE_POLICY_VERSION"), "structural-v1"),
|
||||
TestAutoReviewPolicy: valueOrDefault(getenv("TEST_AUTO_REVIEW_POLICY"), string(governance.AutoReviewInternal)),
|
||||
DatabaseURL: getenv("DATABASE_URL"),
|
||||
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
|
||||
WorkerID: valueOrDefault(getenv("WORKER_ID"), "worker-1"),
|
||||
PollInterval: time.Second,
|
||||
LeaseDuration: 30 * time.Second,
|
||||
RetryDelay: 5 * time.Second,
|
||||
SourceRefreshSchedulerInterval: 30 * time.Second,
|
||||
ReleaseConfigFile: strings.TrimSpace(getenv("RELEASE_CONFIG_FILE")),
|
||||
ProductionReleaseAuthorizerRef: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTHORIZER_REF")),
|
||||
ProductionReleaseAuthTokenFile: strings.TrimSpace(getenv("PRODUCTION_RELEASE_AUTH_TOKEN_FILE")),
|
||||
ProductionWeKnoraBaseURL: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_BASE_URL")),
|
||||
ProductionWeKnoraAPIKeyFile: strings.TrimSpace(getenv("PRODUCTION_WEKNORA_API_KEY_FILE")),
|
||||
PPScanAllowedRoot: strings.TrimSpace(getenv("PP_SCAN_ALLOWED_ROOT")),
|
||||
PPScanLedgerPath: strings.TrimSpace(getenv("PP_SCAN_LEDGER_PATH")),
|
||||
PPScanManifestPath: strings.TrimSpace(getenv("PP_SCAN_MANIFEST_PATH")),
|
||||
TestWeKnoraBaseURL: strings.TrimSpace(getenv("TEST_WEKNORA_BASE_URL")),
|
||||
MinerUBaseURL: strings.TrimSpace(getenv("MINERU_BASE_URL")),
|
||||
TestWeKnoraKBID: strings.TrimSpace(getenv("TEST_WEKNORA_KB_ID")),
|
||||
InternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_INTERNAL_WEKNORA_KB_ID")),
|
||||
ExternalRoutingKnowledgeBaseID: strings.TrimSpace(getenv("TEST_EXTERNAL_WEKNORA_KB_ID")),
|
||||
TestWeKnoraAPIKeyFile: valueOrDefault(getenv("TEST_WEKNORA_API_KEY_FILE"), "/run/secrets/test_weknora_api_key"),
|
||||
WeKnoraBindingMasterKeyFile: strings.TrimSpace(getenv("WEKNORA_BINDING_MASTER_KEY_FILE")),
|
||||
WeKnoraRuntimeKeyFile: strings.TrimSpace(getenv("WEKNORA_RUNTIME_KEY_FILE")),
|
||||
ReconciliationDailyAt: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_DAILY_AT")), "02:00"),
|
||||
ReconciliationTimezone: valueOrDefault(strings.TrimSpace(getenv("RECONCILIATION_TIMEZONE")), "Asia/Shanghai"),
|
||||
ReconciliationScheduleEnabled: true,
|
||||
ReconciliationGrace: 30 * time.Minute,
|
||||
ReconciliationStallAfter: 2 * time.Hour,
|
||||
ReconciliationStaleAfter: 6 * time.Hour,
|
||||
ReconciliationConfirmConcurrency: 1,
|
||||
ReconciliationKeepRuns: 30,
|
||||
ReconciliationMaxAge: 90 * 24 * time.Hour,
|
||||
GovernanceSpoolRoot: valueOrDefault(getenv("GOVERNANCE_SPOOL_ROOT"), "/var/lib/governance/spool"),
|
||||
IngestionSpoolRoot: strings.TrimSpace(getenv("INGESTION_SPOOL_ROOT")),
|
||||
ArtifactFetchMaxBytes: 200 * 1024 * 1024,
|
||||
WorkerLivenessStaleAfter: 2 * time.Minute,
|
||||
TestWeKnoraHTTPTimeout: 60 * time.Second,
|
||||
TestWeKnoraPollInitial: 10 * time.Second,
|
||||
TestWeKnoraPollMax: time.Minute,
|
||||
TestWeKnoraStalledAfter: 30 * time.Minute,
|
||||
TestWeKnoraMaxUploadBytes: 50 * 1024 * 1024,
|
||||
TestAcceptancePolicyVersion: valueOrDefault(getenv("TEST_ACCEPTANCE_POLICY_VERSION"), "structural-v1"),
|
||||
TestAutoReviewPolicy: valueOrDefault(getenv("TEST_AUTO_REVIEW_POLICY"), string(governance.AutoReviewInternal)),
|
||||
// 整库逻辑备份的目标主机:三项同时给出才接线(脚本目录/备份根有默认值)。
|
||||
BackupHostSSHConfig: strings.TrimSpace(getenv("BACKUP_HOST_SSH_CONFIG")),
|
||||
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
|
||||
@@ -374,6 +406,55 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if config.WeKnoraBindingMasterKeyFile != "" && !filepath.IsAbs(config.WeKnoraBindingMasterKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_BINDING_MASTER_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if config.WeKnoraRuntimeKeyFile != "" && !filepath.IsAbs(config.WeKnoraRuntimeKeyFile) {
|
||||
return Config{}, errors.New("WEKNORA_RUNTIME_KEY_FILE must be an absolute path")
|
||||
}
|
||||
if raw := getenv("RECONCILIATION_ENABLED"); raw != "" {
|
||||
config.ReconciliationEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("RECONCILIATION_ENABLED: %w", err)
|
||||
}
|
||||
}
|
||||
if raw := getenv("RECONCILIATION_SCHEDULE_ENABLED"); raw != "" {
|
||||
config.ReconciliationScheduleEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("RECONCILIATION_SCHEDULE_ENABLED: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := time.Parse("15:04", config.ReconciliationDailyAt); err != nil {
|
||||
return Config{}, errors.New("RECONCILIATION_DAILY_AT must be HH:MM")
|
||||
}
|
||||
if _, err := time.LoadLocation(config.ReconciliationTimezone); err != nil {
|
||||
return Config{}, fmt.Errorf("RECONCILIATION_TIMEZONE: %w", err)
|
||||
}
|
||||
if config.ReconciliationConfirmConcurrency < 1 || config.ReconciliationConfirmConcurrency > 8 {
|
||||
return Config{}, errors.New("RECONCILIATION_CONFIRM_CONCURRENCY must be between 1 and 8")
|
||||
}
|
||||
if value, err := positiveInt64OrDefault(strings.TrimSpace(getenv("RECONCILIATION_CONFIRM_CONCURRENCY")), int64(config.ReconciliationConfirmConcurrency)); err != nil {
|
||||
return Config{}, errors.New("RECONCILIATION_CONFIRM_CONCURRENCY must be a positive integer")
|
||||
} else {
|
||||
config.ReconciliationConfirmConcurrency = int(value)
|
||||
}
|
||||
if config.ReconciliationConfirmConcurrency > 8 {
|
||||
return Config{}, errors.New("RECONCILIATION_CONFIRM_CONCURRENCY must be between 1 and 8")
|
||||
}
|
||||
if value, err := positiveInt64OrDefault(strings.TrimSpace(getenv("RECONCILIATION_KEEP_RUNS")), int64(config.ReconciliationKeepRuns)); err != nil {
|
||||
return Config{}, errors.New("RECONCILIATION_KEEP_RUNS must be a positive integer")
|
||||
} else {
|
||||
config.ReconciliationKeepRuns = int(value)
|
||||
}
|
||||
for name, target := range map[string]*time.Duration{
|
||||
"RECONCILIATION_GRACE": &config.ReconciliationGrace,
|
||||
"RECONCILIATION_STALL_AFTER": &config.ReconciliationStallAfter,
|
||||
"RECONCILIATION_STALE_AFTER": &config.ReconciliationStaleAfter,
|
||||
"RECONCILIATION_MAX_AGE": &config.ReconciliationMaxAge,
|
||||
} {
|
||||
value, err := durationOrDefault(strings.TrimSpace(getenv(name)), *target)
|
||||
if err != nil || value <= 0 {
|
||||
return Config{}, fmt.Errorf("%s must be a positive duration", name)
|
||||
}
|
||||
*target = value
|
||||
}
|
||||
if raw := getenv("PP_SCAN_ENABLED"); raw != "" {
|
||||
config.PPScanEnabled, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
|
||||
@@ -6,6 +6,28 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLoadParsesReconciliationEnabledWithoutLegacyTestWeKnora(t *testing.T) {
|
||||
values := map[string]string{"DATA" + "BASE_URL": "postgres://example"}
|
||||
config, err := Load(func(key string) string { return values[key] })
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error = %v", err)
|
||||
}
|
||||
if config.ReconciliationEnabled {
|
||||
t.Fatal("reconciliation must stay un-wired unless RECONCILIATION_ENABLED is set")
|
||||
}
|
||||
values["RECONCILIATION_ENABLED"] = "true"
|
||||
config, err = Load(func(key string) string { return values[key] })
|
||||
if err != nil {
|
||||
t.Fatalf("Load() with RECONCILIATION_ENABLED error = %v", err)
|
||||
}
|
||||
if !config.ReconciliationEnabled {
|
||||
t.Fatal("RECONCILIATION_ENABLED=true must wire reconciliation")
|
||||
}
|
||||
if config.TestWeKnoraEnabled {
|
||||
t.Fatal("reconciliation must not require or imply the legacy test WeKnora pipeline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadUsesSafeDefaults(t *testing.T) {
|
||||
values := map[string]string{"DATABASE_URL": "postgres://example"}
|
||||
config, err := Load(func(key string) string { return values[key] })
|
||||
|
||||
@@ -139,6 +139,19 @@ const (
|
||||
ProcessingCancelled ProcessingState = "cancelled"
|
||||
)
|
||||
|
||||
// NormalizeWeKnoraParseStatus is the single upstream-to-platform vocabulary
|
||||
// whitelist shared by polling and reconciliation. Unknown values are rejected
|
||||
// instead of being collapsed into an "other" bucket: a new upstream state must
|
||||
// be added deliberately.
|
||||
func NormalizeWeKnoraParseStatus(status string) (string, bool) {
|
||||
switch status {
|
||||
case "pending", "processing", "finalizing", "completed", "failed", "cancelled", "deleting":
|
||||
return status, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func (state ProcessingState) Valid() bool {
|
||||
switch state {
|
||||
case ProcessingPending, ProcessingProcessing, ProcessingFinalizing, ProcessingCompleted, ProcessingFailed, ProcessingStalled, ProcessingCancelled:
|
||||
|
||||
@@ -112,6 +112,31 @@ type MonitorOverview struct {
|
||||
KnowledgeBases []KnowledgeBaseProgress `json:"knowledge_bases"`
|
||||
Pipeline IngestionPipeline `json:"pipeline"`
|
||||
Health []ServiceHealth `json:"health"`
|
||||
// WeKnoraQueues is a safe projection of the test instance runtime queues.
|
||||
// nil means "not configured or unreadable", never "healthy empty".
|
||||
WeKnoraQueues *WeKnoraQueueSummary `json:"weknora_queues"`
|
||||
}
|
||||
|
||||
// WeKnoraQueueSummary is the bounded queue projection the console may show.
|
||||
// It deliberately excludes worker addresses, model endpoints and task payloads.
|
||||
type WeKnoraQueueSummary struct {
|
||||
Available bool `json:"available"`
|
||||
QueuesError bool `json:"queues_error"`
|
||||
WorkersError bool `json:"workers_error"`
|
||||
Queues []WeKnoraQueue `json:"queues"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
}
|
||||
|
||||
type WeKnoraQueue struct {
|
||||
Name string `json:"name"`
|
||||
Pool string `json:"pool"`
|
||||
Pending int `json:"pending"`
|
||||
Active int `json:"active"`
|
||||
Scheduled int `json:"scheduled"`
|
||||
Retry int `json:"retry"`
|
||||
Archived int `json:"archived"`
|
||||
Processed int `json:"processed"`
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
|
||||
type KnowledgeMonitorFile struct {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package governance
|
||||
|
||||
import "time"
|
||||
|
||||
// ReconciliationCounts is keyed by R1..R8. Normalize keeps every key present so
|
||||
// the API and page never have to distinguish "absent" from "zero".
|
||||
type ReconciliationCounts map[string]int
|
||||
|
||||
func (counts ReconciliationCounts) Normalize() ReconciliationCounts {
|
||||
out := make(ReconciliationCounts, 8)
|
||||
for _, key := range []string{"R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8"} {
|
||||
out[key] = counts[key]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type ReconciliationRun struct {
|
||||
ID string `json:"id"`
|
||||
KBID string `json:"kb_id"`
|
||||
State string `json:"state"`
|
||||
Trigger string `json:"trigger"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
LedgerCount int `json:"ledger_count"`
|
||||
KBCount int `json:"kb_count"`
|
||||
Counts ReconciliationCounts `json:"counts"`
|
||||
PreviousCounts ReconciliationCounts `json:"previous_counts"`
|
||||
WindowOverlapped bool `json:"window_overlapped"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
}
|
||||
|
||||
type ReconciliationFinding struct {
|
||||
ID string `json:"id"`
|
||||
RunID string `json:"run_id"`
|
||||
Type string `json:"type"`
|
||||
PublicationID string `json:"publication_id"`
|
||||
DocumentID string `json:"document_id"`
|
||||
Title string `json:"title"`
|
||||
Path string `json:"path"`
|
||||
Source string `json:"source"`
|
||||
TargetScope string `json:"target_scope"`
|
||||
LedgerState string `json:"ledger_state"`
|
||||
WeKnoraParseState string `json:"weknora_parse_status"`
|
||||
NormalizedState string `json:"normalized_state"`
|
||||
LedgerSHA256 string `json:"ledger_sha256"`
|
||||
DeclaredSHA256 string `json:"declared_sha256"`
|
||||
WeKnoraFileMD5 string `json:"weknora_file_md5"`
|
||||
EvidenceLevel string `json:"evidence_level"`
|
||||
ConfirmationState string `json:"confirmation_state"`
|
||||
Detail string `json:"detail"`
|
||||
SuggestedAction string `json:"suggested_action"`
|
||||
ActionState string `json:"action_state"`
|
||||
WeKnoraURL string `json:"weknora_url"`
|
||||
}
|
||||
|
||||
type ReconciliationLedgerRow struct {
|
||||
PublicationID string
|
||||
KnowledgeID string
|
||||
ProcessingState string
|
||||
RetrievalState string
|
||||
TargetScope string
|
||||
ProcessingStartedAt *time.Time
|
||||
UpdatedAt time.Time
|
||||
UploadMD5 string
|
||||
SourceItemID string
|
||||
Title string
|
||||
Path string
|
||||
SourceName string
|
||||
PolicyState string
|
||||
SHA256 string
|
||||
}
|
||||
|
||||
type ReconciliationRunFilter struct {
|
||||
KBID string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type ReconciliationRunPage struct {
|
||||
Items []ReconciliationRun `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
type ReconciliationFindingFilter struct {
|
||||
RunID string
|
||||
Type string
|
||||
Query string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type ReconciliationFindingPage struct {
|
||||
Items []ReconciliationFinding `json:"items"`
|
||||
Total int `json:"total"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
type ReconciliationStage struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
type ReconciliationFailure struct {
|
||||
TaskType string `json:"task_type"`
|
||||
FailCount int `json:"fail_count"`
|
||||
FailedAt time.Time `json:"failed_at"`
|
||||
LastError string `json:"last_error"`
|
||||
}
|
||||
|
||||
type ReconciliationProgress struct {
|
||||
DocumentID string `json:"document_id"`
|
||||
ParseStatus string `json:"parse_status"`
|
||||
IngestionStatus string `json:"ingestion_status"`
|
||||
WikiStatus string `json:"wiki_status"`
|
||||
Stages []ReconciliationStage `json:"stages"`
|
||||
Failures []ReconciliationFailure `json:"failures"`
|
||||
HasMoreFailures bool `json:"has_more_failures"`
|
||||
ObservedAt time.Time `json:"observed_at"`
|
||||
}
|
||||
|
||||
// ReconciliationActionView is the minimum row an action needs to re-check that
|
||||
// the scan snapshot is still true. Actions must never trust the finding alone.
|
||||
type ReconciliationActionView struct {
|
||||
Finding ReconciliationFinding
|
||||
TestKBID string
|
||||
RunStartedAt time.Time
|
||||
CurrentExists bool
|
||||
CurrentProcessingState string
|
||||
CurrentKnowledgeID string
|
||||
CurrentSuperseded bool
|
||||
CurrentRetrievalState string
|
||||
CurrentTargetScope string
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -73,7 +74,7 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
|
||||
return
|
||||
}
|
||||
for _, pair := range [][2]string{{f.Scope, "|internal|external"}, {f.Action, "|add|update|remove"}, {f.Status, "|active|waiting|running|retrying|attention|completed|cancelled"}, {f.Stage, "|waiting|fetch|upload|parsing|indexing|removal|finished"}} {
|
||||
for _, pair := range [][2]string{{f.Scope, "|internal|external"}, {f.Action, "|add|update|remove"}, {f.Status, "|active|waiting|running|retrying|attention|completed|cancelled"}, {f.Stage, "|waiting|fetch|upload|parsing|indexing|removal|finished|weknora"}} {
|
||||
if !strings.Contains("|"+pair[1]+"|", "|"+pair[0]+"|") {
|
||||
writeJSON(w, 400, map[string]string{"error": "invalid filter"})
|
||||
return
|
||||
@@ -97,6 +98,14 @@ func listMonitorTasks(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, 500, map[string]string{"error": "无法读取文件处理状态"})
|
||||
return
|
||||
}
|
||||
// One origin per request: every row uses the same effective test endpoint the
|
||||
// reconciliation scan used, so a KB opens at the same place from both tabs.
|
||||
if config.WeKnoraWebBase != nil {
|
||||
origin := config.WeKnoraWebBase(r.Context())
|
||||
for i := range page.Items {
|
||||
page.Items[i].WeKnoraURL = weknora.KnowledgeBaseConsoleURL(origin, page.Items[i].TargetKB)
|
||||
}
|
||||
}
|
||||
// 目标同名不罕见(两侧都叫“对内知识库”):把当前生效绑定随页返回,
|
||||
// 前端才能在同一口径下标注“当前绑定/历史”,而不是拿本页条目反推全局。
|
||||
internal, external := config.effectiveRoutingTargets(r.Context())
|
||||
|
||||
@@ -11,11 +11,16 @@ import (
|
||||
type monitorTasksTestStore struct {
|
||||
fakeJobStore
|
||||
filter postgresstore.MonitorTaskFilter
|
||||
items []postgresstore.MonitorTask
|
||||
}
|
||||
|
||||
func (s *monitorTasksTestStore) ListMonitorTasks(_ context.Context, f postgresstore.MonitorTaskFilter) (postgresstore.MonitorTaskPage, error) {
|
||||
s.filter = f
|
||||
return postgresstore.MonitorTaskPage{Items: []postgresstore.MonitorTask{}, Total: 145, Limit: f.Limit, Offset: f.Offset}, nil
|
||||
items := s.items
|
||||
if items == nil {
|
||||
items = []postgresstore.MonitorTask{}
|
||||
}
|
||||
return postgresstore.MonitorTaskPage{Items: items, Total: 145, Limit: f.Limit, Offset: f.Offset}, nil
|
||||
}
|
||||
func TestMonitorTasksRoute(t *testing.T) {
|
||||
s := &monitorTasksTestStore{}
|
||||
@@ -33,6 +38,13 @@ func TestMonitorTasksRoute(t *testing.T) {
|
||||
if s.filter.Status != "active" || s.filter.Offset != 40 {
|
||||
t.Fatalf("filter %#v", s.filter)
|
||||
}
|
||||
// §8 merges 解析/索引增强 into one "WeKnora 处理中" facet.
|
||||
merged := httptest.NewRequest("GET", "/api/v1/monitor/tasks?stage=weknora", nil).WithContext(req.Context())
|
||||
wm := httptest.NewRecorder()
|
||||
h.ServeHTTP(wm, merged)
|
||||
if wm.Code != 200 || s.filter.Stage != "weknora" {
|
||||
t.Fatalf("weknora stage: %d filter %#v", wm.Code, s.filter)
|
||||
}
|
||||
for _, query := range []string{"status=garbage", "stage=internal&scope=internal", "limit=101", "offset=-1", "since=bad"} {
|
||||
r := httptest.NewRequest("GET", "/api/v1/monitor/tasks?"+query, nil).WithContext(req.Context())
|
||||
rr := httptest.NewRecorder()
|
||||
@@ -88,3 +100,62 @@ func TestMonitorTasksReportsEffectiveTargetBindings(t *testing.T) {
|
||||
t.Fatalf("bindings = %#v, want the persisted current bindings", payload.Data.Bindings)
|
||||
}
|
||||
}
|
||||
|
||||
// The platform drawer's 503 fallback needs the same jump link a finding carries.
|
||||
// The handler, not the browser, decides the origin: it must use the effective
|
||||
// test endpoint, and an unwired resolver must leave the field empty instead of
|
||||
// inventing a host.
|
||||
func TestMonitorTasksAddsWeKnoraConsoleURL(t *testing.T) {
|
||||
store := &monitorTasksTestStore{items: []postgresstore.MonitorTask{{ID: "mt-1", TargetKB: "kb-1"}}}
|
||||
handler, err := NewHandler(Config{
|
||||
Store: store,
|
||||
WeKnoraWebBase: func(context.Context) string { return "https://weknora.test/" },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest("GET", "/api/v1/monitor/tasks?limit=20", nil)
|
||||
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleViewer}))
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, req)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("status %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
Data struct {
|
||||
Items []struct {
|
||||
WeKnoraURL string `json:"weknora_url"`
|
||||
} `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(payload.Data.Items) != 1 || payload.Data.Items[0].WeKnoraURL != "https://weknora.test/platform/knowledge-bases/kb-1" {
|
||||
t.Fatalf("weknora_url = %#v", payload.Data.Items)
|
||||
}
|
||||
|
||||
store.items = []postgresstore.MonitorTask{{ID: "mt-1", TargetKB: "kb-1"}}
|
||||
unwired, err := NewHandler(Config{Store: store})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recorder = httptest.NewRecorder()
|
||||
unwired.ServeHTTP(recorder, req)
|
||||
if recorder.Code != 200 {
|
||||
t.Fatalf("unwired status %d: %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
payload = struct {
|
||||
Data struct {
|
||||
Items []struct {
|
||||
WeKnoraURL string `json:"weknora_url"`
|
||||
} `json:"items"`
|
||||
} `json:"data"`
|
||||
}{}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(payload.Data.Items) != 1 || payload.Data.Items[0].WeKnoraURL != "" {
|
||||
t.Fatalf("unwired weknora_url = %#v", payload.Data.Items)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
type ReconciliationService interface {
|
||||
CreateRun(context.Context, string, string) (governance.ReconciliationRun, error)
|
||||
ListRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error)
|
||||
GetRun(context.Context, string) (governance.ReconciliationRun, error)
|
||||
ListFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error)
|
||||
Writeback(context.Context, string, string, string) (governance.ReconciliationFinding, error)
|
||||
Requeue(context.Context, string, string, string) (governance.ReconciliationFinding, error)
|
||||
Remove(context.Context, string, string, string) (governance.ReconciliationFinding, error)
|
||||
Progress(context.Context, string) (governance.ReconciliationProgress, error)
|
||||
}
|
||||
|
||||
const reconciliationActionHeader = "reconciliation-action"
|
||||
|
||||
func requireReconciliationAction(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Header.Get("X-Governance-Action") != reconciliationActionHeader {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "write intent required"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validReconciliationID(value string, max int) bool {
|
||||
if value == "" || len(value) > max || strings.TrimSpace(value) != value {
|
||||
return false
|
||||
}
|
||||
return !strings.ContainsAny(value, "\x00\r\n/?#\\")
|
||||
}
|
||||
|
||||
func writeReconciliationError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, reconciliation.ErrRunInProgress):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "reconciliation_run_in_progress", "code": "reconciliation_run_in_progress"})
|
||||
case errors.Is(err, reconciliation.ErrNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "reconciliation record not found"})
|
||||
case errors.Is(err, reconciliation.ErrActionConflict), errors.Is(err, reconciliation.ErrActionNotAllowed):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "reconciliation_state_changed", "code": "reconciliation_state_changed"})
|
||||
case errors.Is(err, reconciliation.ErrRuntimeUnavailable):
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "runtime_read_unavailable", "code": "runtime_read_unavailable"})
|
||||
case errors.Is(err, reconciliation.ErrRemoteFailed):
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "reconciliation_remote_failed", "code": "reconciliation_remote_failed"})
|
||||
default:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "reconciliation_failed"})
|
||||
}
|
||||
}
|
||||
|
||||
func createReconciliationRun(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if identity.Role != roleEngineer && identity.Role != roleAdmin {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
if !requireReconciliationAction(w, r) {
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
KBID string `json:"kb_id"`
|
||||
}
|
||||
if err := decodeStrictJSON(r, &input); err != nil || !validReconciliationID(input.KBID, 255) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid kb_id"})
|
||||
return
|
||||
}
|
||||
run, err := config.Reconciliation.CreateRun(r.Context(), input.KBID, "manual")
|
||||
if err != nil {
|
||||
writeReconciliationError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"data": run})
|
||||
}
|
||||
|
||||
func listReconciliationRuns(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
limit, offset, ok := parseLimitOffset(w, r, 20)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
kbID := strings.TrimSpace(r.URL.Query().Get("kb_id"))
|
||||
if kbID != "" && !validReconciliationID(kbID, 255) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid kb_id"})
|
||||
return
|
||||
}
|
||||
page, err := config.Reconciliation.ListRuns(r.Context(), governance.ReconciliationRunFilter{KBID: kbID, Limit: limit, Offset: offset})
|
||||
if err != nil {
|
||||
writeReconciliationError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": page})
|
||||
}
|
||||
|
||||
func getReconciliationRun(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if !validReconciliationID(id, 128) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid run id"})
|
||||
return
|
||||
}
|
||||
run, err := config.Reconciliation.GetRun(r.Context(), id)
|
||||
if err != nil {
|
||||
writeReconciliationError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": run})
|
||||
}
|
||||
|
||||
func listReconciliationFindings(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
runID := r.PathValue("id")
|
||||
if !validReconciliationID(runID, 128) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid run id"})
|
||||
return
|
||||
}
|
||||
limit, offset, ok := parseLimitOffset(w, r, 20)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
findingType := strings.TrimSpace(r.URL.Query().Get("type"))
|
||||
if findingType != "" {
|
||||
switch findingType {
|
||||
case "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8":
|
||||
default:
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid finding type"})
|
||||
return
|
||||
}
|
||||
}
|
||||
query := r.URL.Query().Get("q")
|
||||
if len(query) > 512 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "q is too long"})
|
||||
return
|
||||
}
|
||||
page, err := config.Reconciliation.ListFindings(r.Context(), governance.ReconciliationFindingFilter{
|
||||
RunID: runID, Type: findingType, Query: query, Limit: limit, Offset: offset,
|
||||
})
|
||||
if err != nil {
|
||||
writeReconciliationError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": page})
|
||||
}
|
||||
|
||||
func reconciliationAction(w http.ResponseWriter, r *http.Request, config Config, adminOnly bool, action func(context.Context, string, string, string) (governance.ReconciliationFinding, error)) {
|
||||
identity, ok := requireSessionIdentity(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if adminOnly && identity.Role != roleAdmin {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
if !adminOnly && identity.Role != roleEngineer && identity.Role != roleAdmin {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
|
||||
return
|
||||
}
|
||||
if !requireReconciliationAction(w, r) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if !validReconciliationID(id, 128) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid finding id"})
|
||||
return
|
||||
}
|
||||
finding, err := action(r.Context(), id, actorFor(r), "导入对账处置")
|
||||
if err != nil {
|
||||
writeReconciliationError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": finding})
|
||||
}
|
||||
|
||||
func writebackReconciliationFinding(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
reconciliationAction(w, r, config, false, config.Reconciliation.Writeback)
|
||||
}
|
||||
|
||||
func requeueReconciliationFinding(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
reconciliationAction(w, r, config, false, config.Reconciliation.Requeue)
|
||||
}
|
||||
|
||||
func removeReconciliationFinding(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
reconciliationAction(w, r, config, true, config.Reconciliation.Remove)
|
||||
}
|
||||
|
||||
func getReconciliationDocumentProgress(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
documentID := r.PathValue("document_id")
|
||||
if !validReconciliationID(documentID, 64) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid document id"})
|
||||
return
|
||||
}
|
||||
progress, err := config.Reconciliation.Progress(r.Context(), documentID)
|
||||
if err != nil {
|
||||
writeReconciliationError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": progress})
|
||||
}
|
||||
|
||||
func requireReconciliation(w http.ResponseWriter, r *http.Request, config Config, handler func(http.ResponseWriter, *http.Request, Config)) {
|
||||
if config.Reconciliation == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "reconciliation_not_configured", "code": "reconciliation_not_configured"})
|
||||
return
|
||||
}
|
||||
handler(w, r, config)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/reconciliation"
|
||||
)
|
||||
|
||||
type reconciliationServiceStub struct {
|
||||
created bool
|
||||
progress governance.ReconciliationProgress
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *reconciliationServiceStub) CreateRun(context.Context, string, string) (governance.ReconciliationRun, error) {
|
||||
s.created = true
|
||||
return governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running"}, s.err
|
||||
}
|
||||
func (s *reconciliationServiceStub) ListRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
|
||||
return governance.ReconciliationRunPage{Items: []governance.ReconciliationRun{}}, s.err
|
||||
}
|
||||
func (s *reconciliationServiceStub) GetRun(context.Context, string) (governance.ReconciliationRun, error) {
|
||||
return governance.ReconciliationRun{ID: "run-1"}, s.err
|
||||
}
|
||||
func (s *reconciliationServiceStub) ListFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
|
||||
return governance.ReconciliationFindingPage{Items: []governance.ReconciliationFinding{}}, s.err
|
||||
}
|
||||
func (s *reconciliationServiceStub) Writeback(context.Context, string, string, string) (governance.ReconciliationFinding, error) {
|
||||
return governance.ReconciliationFinding{ID: "f1", ActionState: "done"}, s.err
|
||||
}
|
||||
func (s *reconciliationServiceStub) Requeue(context.Context, string, string, string) (governance.ReconciliationFinding, error) {
|
||||
return governance.ReconciliationFinding{ID: "f1", ActionState: "done"}, s.err
|
||||
}
|
||||
func (s *reconciliationServiceStub) Remove(context.Context, string, string, string) (governance.ReconciliationFinding, error) {
|
||||
return governance.ReconciliationFinding{ID: "f1", ActionState: "done"}, s.err
|
||||
}
|
||||
func (s *reconciliationServiceStub) Progress(context.Context, string) (governance.ReconciliationProgress, error) {
|
||||
return s.progress, s.err
|
||||
}
|
||||
|
||||
func reconciliationRequest(method, path, role, body string) *http.Request {
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: role}))
|
||||
return request
|
||||
}
|
||||
|
||||
func TestReconciliationRoutesEnforceRolesAndWriteIntent(t *testing.T) {
|
||||
service := &reconciliationServiceStub{}
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: service})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
viewer := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/runs", roleViewer, `{"kb_id":"kb-1"}`)
|
||||
viewer.Header.Set("X-Governance-Action", "reconciliation-action")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, viewer)
|
||||
if recorder.Code != http.StatusForbidden || service.created {
|
||||
t.Fatalf("viewer create = %d created=%t", recorder.Code, service.created)
|
||||
}
|
||||
engineer := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/runs", roleEngineer, `{"kb_id":"kb-1"}`)
|
||||
engineer.Header.Set("X-Governance-Action", "reconciliation-action")
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, engineer)
|
||||
if recorder.Code != http.StatusAccepted || !service.created {
|
||||
t.Fatalf("engineer create = %d created=%t %s", recorder.Code, service.created, recorder.Body.String())
|
||||
}
|
||||
missingIntent := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/findings/f1/requeue", roleEngineer, "")
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, missingIntent)
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("missing write intent = %d", recorder.Code)
|
||||
}
|
||||
engineerRemove := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/findings/f1/remove", roleEngineer, "")
|
||||
engineerRemove.Header.Set("X-Governance-Action", "reconciliation-action")
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, engineerRemove)
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("engineer remove = %d", recorder.Code)
|
||||
}
|
||||
adminRemove := reconciliationRequest(http.MethodPost, "/api/v1/reconciliation/findings/f1/remove", roleAdmin, "")
|
||||
adminRemove.Header.Set("X-Governance-Action", "reconciliation-action")
|
||||
recorder = httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, adminRemove)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("admin remove = %d %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconciliationProgress503AndUnwiredRoute(t *testing.T) {
|
||||
service := &reconciliationServiceStub{err: reconciliation.ErrRuntimeUnavailable}
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: service})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/documents/doc-1/progress", roleViewer, "")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusServiceUnavailable || !strings.Contains(recorder.Body.String(), "runtime_read_unavailable") {
|
||||
t.Fatalf("progress = %d %s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
unwired, err := NewHandler(Config{Store: &fakeJobStore{}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recorder = httptest.NewRecorder()
|
||||
unwired.ServeHTTP(recorder, reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/runs", roleViewer, ""))
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("unwired runs = %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconciliationFindingTypeValidation(t *testing.T) {
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, Reconciliation: &reconciliationServiceStub{}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := reconciliationRequest(http.MethodGet, "/api/v1/reconciliation/runs/run-1/findings?type=R9", roleViewer, "")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid type = %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
+46
-13
@@ -121,19 +121,26 @@ func libraryWithDeadline(w http.ResponseWriter, r *http.Request, limit time.Dura
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
QAAI *qaopsai.Store
|
||||
QAAITrustTLSProxy bool
|
||||
QAQuality QAQualityStore
|
||||
QAOrgSync QAOrgSyncStore
|
||||
QAOrgSyncEnabled bool
|
||||
QAOrg QAOrgStore
|
||||
QAOps QAOpsReader
|
||||
QAWeeklyMail any
|
||||
QAOpsTenantKey string
|
||||
QAOpsEnabled bool
|
||||
QAOpsProblem string
|
||||
Store Store
|
||||
Monitor MonitorProvider
|
||||
QAAI *qaopsai.Store
|
||||
QAAITrustTLSProxy bool
|
||||
QAQuality QAQualityStore
|
||||
QAOrgSync QAOrgSyncStore
|
||||
QAOrgSyncEnabled bool
|
||||
QAOrg QAOrgStore
|
||||
QAOps QAOpsReader
|
||||
QAWeeklyMail any
|
||||
QAOpsTenantKey string
|
||||
QAOpsEnabled bool
|
||||
QAOpsProblem string
|
||||
Store Store
|
||||
Monitor MonitorProvider
|
||||
// Reconciliation is the T6 reconciliation domain. Nil keeps the routes
|
||||
// unavailable instead of returning fake empty batches.
|
||||
Reconciliation ReconciliationService
|
||||
// WeKnoraWebBase resolves the test WeKnora console origin used to build the
|
||||
// drawer jump link on /monitor/tasks rows. Nil (or an empty answer) leaves
|
||||
// weknora_url empty; the contract allows that, and no host is invented.
|
||||
WeKnoraWebBase func(context.Context) string
|
||||
InternalRoutingKnowledgeBaseID string
|
||||
ExternalRoutingKnowledgeBaseID string
|
||||
RoutingBindings RoutingBindingStore
|
||||
@@ -495,6 +502,32 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/monitor/overview", func(w http.ResponseWriter, r *http.Request) {
|
||||
monitorOverview(w, r, config.Monitor)
|
||||
})
|
||||
// 导入对账(T6a):批次、差异、处置与实时处理详情。未接线时明确 503,
|
||||
// 不返回空批次冒充"没有差异"。
|
||||
mux.HandleFunc("POST /api/v1/reconciliation/runs", func(w http.ResponseWriter, r *http.Request) {
|
||||
requireReconciliation(w, r, config, createReconciliationRun)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/reconciliation/runs", func(w http.ResponseWriter, r *http.Request) {
|
||||
requireReconciliation(w, r, config, listReconciliationRuns)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/reconciliation/runs/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
requireReconciliation(w, r, config, getReconciliationRun)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/reconciliation/runs/{id}/findings", func(w http.ResponseWriter, r *http.Request) {
|
||||
requireReconciliation(w, r, config, listReconciliationFindings)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/reconciliation/findings/{id}/writeback", func(w http.ResponseWriter, r *http.Request) {
|
||||
requireReconciliation(w, r, config, writebackReconciliationFinding)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/reconciliation/findings/{id}/requeue", func(w http.ResponseWriter, r *http.Request) {
|
||||
requireReconciliation(w, r, config, requeueReconciliationFinding)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/reconciliation/findings/{id}/remove", func(w http.ResponseWriter, r *http.Request) {
|
||||
requireReconciliation(w, r, config, removeReconciliationFinding)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/reconciliation/documents/{document_id}/progress", func(w http.ResponseWriter, r *http.Request) {
|
||||
requireReconciliation(w, r, config, getReconciliationDocumentProgress)
|
||||
})
|
||||
// 「版本记录」:当前运行的构建身份(只读,与监控同级可见)
|
||||
mux.HandleFunc("GET /api/v1/build-info", func(w http.ResponseWriter, r *http.Request) {
|
||||
buildInfo(w, r)
|
||||
|
||||
@@ -18,6 +18,27 @@ const LegacyVersion = 74
|
||||
// V090Version 是 0.9.0 的 schema_migrations 版本号(已实测:134、dirty=false、83 表)。
|
||||
const V090Version = 134
|
||||
|
||||
// V091Version 是 0.9.1 的 schema_migrations 版本号(上游 tag v0.9.1,最大迁移 137)。
|
||||
// 135–137 只改审计列宽/凭据表/IM 唯一索引,不碰知识域表、列或触发器,因此 v091
|
||||
// 由 v090 克隆后只改版本字段,不复制一份表/列/触发器常量。
|
||||
const V091Version = 137
|
||||
|
||||
// RelatedTableClass 是知识域关联表的搬运归类。copied = 随整库搬运(即该版本的
|
||||
// Required/Optional 表);derived = 由触发器/应用派生,不单独搬运;excluded =
|
||||
// 明确不搬,必须写明原因。分类只写在 profile 这一处,门禁按它放行。
|
||||
type RelatedTableClass string
|
||||
|
||||
const (
|
||||
RelatedCopied RelatedTableClass = "copied"
|
||||
RelatedDerived RelatedTableClass = "derived"
|
||||
RelatedExcluded RelatedTableClass = "excluded"
|
||||
)
|
||||
|
||||
type RelatedTable struct {
|
||||
Class RelatedTableClass
|
||||
Reason string
|
||||
}
|
||||
|
||||
// PartRequirement 是归档部件的一项要求(kind/name 与 manifest 的部件键一致)。
|
||||
type PartRequirement struct {
|
||||
Kind string
|
||||
@@ -41,6 +62,9 @@ type Profile struct {
|
||||
ReviewedTriggers []string
|
||||
RequiredParts []PartRequirement
|
||||
OptionalParts []PartRequirement
|
||||
// RelatedTables 是该版本全部知识域关联表的归类(copied/derived/excluded)。
|
||||
// 漏表门禁按它判定:未归类且有本库数据的表一律拒绝。
|
||||
RelatedTables map[string]RelatedTable
|
||||
// IndexContractSource 说明该版本的索引名从哪里读。空值等于"读不到",
|
||||
// 不允许回退成空串去匹配任何索引。
|
||||
IndexContractSource string
|
||||
@@ -93,6 +117,9 @@ var profiles = map[int]Profile{
|
||||
"knowledges", "chunks", "knowledge_tags", "knowledge_tag_relations",
|
||||
"resources", "resource_bindings", "wiki_folders", "wiki_pages",
|
||||
"wiki_page_issues",
|
||||
// 编辑历史随内容搬运(D1)。放在父表之后:importRows 按本序插入、
|
||||
// 倒序删除,两张历史表因此在 chunks/wiki_pages 之后写、在它们之前删。
|
||||
"chunk_revisions", "wiki_page_revisions",
|
||||
},
|
||||
// 0.9.0 删掉了 wiki_log_entries;部件集合随之为空,不许假装还有。
|
||||
OptionalTables: []string{"wiki_log_entries"},
|
||||
@@ -106,12 +133,15 @@ var profiles = map[int]Profile{
|
||||
"wiki_pages": {"id", "tenant_id", "knowledge_base_id", "slug"},
|
||||
"wiki_folders": {"id", "tenant_id", "knowledge_base_id"},
|
||||
"wiki_page_issues": {"id", "tenant_id", "knowledge_base_id"},
|
||||
"chunk_revisions": {"id", "tenant_id", "knowledge_base_id", "knowledge_id", "chunk_id"},
|
||||
"wiki_page_revisions": {"id", "tenant_id", "knowledge_base_id", "page_id"},
|
||||
},
|
||||
RequiredParts: []PartRequirement{
|
||||
{"database", "knowledges"}, {"database", "chunks"},
|
||||
{"database", "knowledge_tags"}, {"database", "knowledge_tag_relations"},
|
||||
{"database", "resources"}, {"database", "resource_bindings"},
|
||||
{"wiki", "wiki_folders"}, {"wiki", "wiki_pages"}, {"wiki", "wiki_page_issues"},
|
||||
{"database", "chunk_revisions"}, {"wiki", "wiki_page_revisions"},
|
||||
{"index", "chunks"},
|
||||
},
|
||||
OptionalParts: []PartRequirement{
|
||||
@@ -130,19 +160,74 @@ var profiles = map[int]Profile{
|
||||
},
|
||||
}
|
||||
|
||||
// init 在一次声明上补齐两件事,避免复制常量:
|
||||
// 1. 每个版本的知识域关联表分类(copied 由该版本的 Required/Optional 表派生);
|
||||
// 2. v0.9.1 = v0.9.0 的克隆,只改版本字段。135–137 不碰知识域,表/列/触发器/
|
||||
// 部件必须与 v090 完全一致,任何分叉都会被测试抓住。
|
||||
func init() {
|
||||
for version, profile := range profiles {
|
||||
profile.RelatedTables = classifyKnowledgeTables(profile)
|
||||
profiles[version] = profile
|
||||
}
|
||||
v090 := profiles[V090Version]
|
||||
v091 := v090
|
||||
v091.Name, v091.SchemaVersion, v091.WeKnoraVersion = "v091", V091Version, "v0.9.1"
|
||||
profiles[V091Version] = v091
|
||||
}
|
||||
|
||||
// classifyKnowledgeTables 把该版本声明过的表标成 copied,并补上派生/排除表。
|
||||
// 分类键覆盖真实 0.9.x 中所有带 knowledge_base_id/knowledge_id/kb_id 的表:
|
||||
// 漏一张,漏表门禁就会在该表有数据时拒绝发布。
|
||||
func classifyKnowledgeTables(profile Profile) map[string]RelatedTable {
|
||||
tables := make(map[string]RelatedTable, len(profile.RequiredTables)+len(profile.OptionalTables)+len(excludedKnowledgeTables)+1)
|
||||
for name, reason := range excludedKnowledgeTables {
|
||||
tables[name] = RelatedTable{Class: RelatedExcluded, Reason: reason}
|
||||
}
|
||||
// 派生表:由触发器维护,随父表重算;不单独搬运。
|
||||
tables["chunk_images"] = RelatedTable{Class: RelatedDerived,
|
||||
Reason: "chunks 上的 chunk_images_sync 触发器维护的图片投影表,随 chunks 重算"}
|
||||
for _, name := range profile.RequiredTables {
|
||||
tables[name] = RelatedTable{Class: RelatedCopied, Reason: "知识库内容表,随整库搬运并做范围改写与目标身份映射"}
|
||||
}
|
||||
for _, name := range profile.OptionalTables {
|
||||
tables[name] = RelatedTable{Class: RelatedCopied, Reason: "知识库内容表(可选),存在时随整库搬运并做范围改写与目标身份映射"}
|
||||
}
|
||||
return tables
|
||||
}
|
||||
|
||||
// excludedKnowledgeTables 是明确不搬的知识域关联表及原因。原因必须解释
|
||||
// "为什么生产不需要它/为什么覆盖会破坏目标",不能只写"不搬"。
|
||||
var excludedKnowledgeTables = map[string]string{
|
||||
"knowledge_processing_spans": "解析流水线的阶段遥测;生产只做推理、不解析,搬运会把测试侧处理过程当成生产内容",
|
||||
"sessions": "对话会话属于各环境自己的运行数据,搬运会覆盖/污染目标用户会话",
|
||||
"messages": "对话消息属于各环境自己的运行数据,不能从测试库覆盖生产",
|
||||
"memory_doc_affinity": "记忆与文档的运行期关联,生产会自行建立,搬运会造成跨环境语义错配",
|
||||
"user_kb_pins": "用户置顶是各环境自己的偏好配置,生产用户 ID 在测试侧不存在",
|
||||
"kb_shares": "组织共享关系绑定本实例的组织/用户,跨环境搬运会产生无效授权",
|
||||
"im_channels": "IM 渠道配置属于各环境的接入配置,含环境专属凭据/回调",
|
||||
"data_sources": "数据源配置属于各环境的接入配置,生产不复用测试侧连接",
|
||||
"embeddings": "仅 PG 检索模式(条件迁移)创建的向量表;本平台契约固定 elasticsearch_v8,检索不读它",
|
||||
}
|
||||
|
||||
// RelatedTableClass 返回某张关联表的分类与理由;未分类时 ok=false。
|
||||
func (p Profile) RelatedTableClass(name string) (RelatedTable, bool) {
|
||||
table, ok := p.RelatedTables[name]
|
||||
return table, ok
|
||||
}
|
||||
|
||||
// For 按版本号选中 profile。未知版本一律失败:版本号是"选哪份声明"的索引,
|
||||
// 不是"能不能放行"的依据,所以绝不返回默认 profile。
|
||||
func For(version int) (Profile, error) {
|
||||
profile, ok := profiles[version]
|
||||
if !ok {
|
||||
return Profile{}, fmt.Errorf("unsupported WeKnora schema version %d: supported profiles are 74 (v071) and 134 (v090)", version)
|
||||
return Profile{}, fmt.Errorf("unsupported WeKnora schema version %d: supported profiles are 74 (v071), 134 (v090) and 137 (v091)", version)
|
||||
}
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
// Supported 返回已声明 profile 的版本号(用于文档与错误信息,不用于放行)。
|
||||
func Supported() []int {
|
||||
return []int{LegacyVersion, V090Version}
|
||||
return []int{LegacyVersion, V090Version, V091Version}
|
||||
}
|
||||
|
||||
// TableSet 是"可能出现的表"集合:必需表 + 可选表。
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package libraryprofile
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestForV091IsDeclaredAndSharesV090Contract(t *testing.T) {
|
||||
profile, err := For(V091Version)
|
||||
if err != nil {
|
||||
t.Fatalf("For(137): %v", err)
|
||||
}
|
||||
if profile.SchemaVersion != 137 || profile.Name != "v091" || profile.WeKnoraVersion != "v0.9.1" {
|
||||
t.Fatalf("unexpected v0.9.1 profile: %+v", profile)
|
||||
}
|
||||
supported := Supported()
|
||||
if !reflect.DeepEqual(supported, []int{74, 134, 137}) {
|
||||
t.Fatalf("Supported()=%v", supported)
|
||||
}
|
||||
v090, err := For(V090Version)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 除了版本三字段,v091 必须与 v090 完全一致;任何分叉都意味着表/列/触发器
|
||||
// 被复制或漂移,升级后会与真实 schema 对不上。
|
||||
v091 := profile
|
||||
v091.Name, v091.SchemaVersion, v091.WeKnoraVersion = v090.Name, v090.SchemaVersion, v090.WeKnoraVersion
|
||||
if !reflect.DeepEqual(v090, v091) {
|
||||
t.Fatal("v0.9.1 must be a version-only clone of v0.9.0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclaredTablesAreAllClassifiedCopied(t *testing.T) {
|
||||
for _, version := range Supported() {
|
||||
profile, err := For(version)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, table := range append(append([]string{}, profile.RequiredTables...), profile.OptionalTables...) {
|
||||
class, ok := profile.RelatedTableClass(table)
|
||||
if !ok {
|
||||
t.Fatalf("%s: declared table %s has no classification", profile.Name, table)
|
||||
}
|
||||
if class.Class != RelatedCopied || strings.TrimSpace(class.Reason) == "" {
|
||||
t.Fatalf("%s: declared table %s must be copied with a reason, got %+v", profile.Name, table, class)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryRealKnowledgeScopedTableIsClassified(t *testing.T) {
|
||||
// 真实测试 WeKnora 0.9.0 的只读 information_schema 结果(2026-11-30):
|
||||
// 带 knowledge_base_id/knowledge_id/kb_id 的 public 表共 18 张。漏一张,
|
||||
// 漏表门禁就会在该表有数据时拒绝发布;这里把它锁成契约。
|
||||
realTables := []string{
|
||||
"chunk_images", "chunk_revisions", "chunks", "data_sources", "im_channels",
|
||||
"knowledge_processing_spans", "knowledge_tag_relations", "knowledge_tags",
|
||||
"knowledges", "kb_shares", "memory_doc_affinity", "messages", "sessions",
|
||||
"user_kb_pins", "wiki_folders", "wiki_page_issues", "wiki_page_revisions", "wiki_pages",
|
||||
}
|
||||
// embeddings 是条件迁移(仅 PG 检索模式)创建的,真实测试库不存在,也必须
|
||||
// 预置分类,避免未来启用后被误判为未声明表。
|
||||
optionalRealTables := []string{"embeddings"}
|
||||
for _, version := range []int{V090Version, V091Version} {
|
||||
profile, err := For(version)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, table := range append(append([]string{}, realTables...), optionalRealTables...) {
|
||||
class, ok := profile.RelatedTableClass(table)
|
||||
if !ok {
|
||||
t.Fatalf("%s: real knowledge-scoped table %s is unclassified", profile.Name, table)
|
||||
}
|
||||
if strings.TrimSpace(class.Reason) == "" {
|
||||
t.Fatalf("%s: %s has an empty classification reason", profile.Name, table)
|
||||
}
|
||||
}
|
||||
if class, _ := profile.RelatedTableClass("chunk_images"); class.Class != RelatedDerived {
|
||||
t.Fatalf("chunk_images must be derived, got %+v", class)
|
||||
}
|
||||
for _, table := range []string{"sessions", "messages", "knowledge_processing_spans", "data_sources"} {
|
||||
if class, _ := profile.RelatedTableClass(table); class.Class != RelatedExcluded {
|
||||
t.Fatalf("%s must be excluded, got %+v", table, class)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionTablesAreCopiedAndOrderedAfterParents(t *testing.T) {
|
||||
profile, err := For(V091Version)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
position := func(table string) int {
|
||||
for index, name := range profile.RequiredTables {
|
||||
if name == table {
|
||||
return index
|
||||
}
|
||||
}
|
||||
t.Fatalf("required table %s missing", table)
|
||||
return -1
|
||||
}
|
||||
if position("chunk_revisions") < position("chunks") {
|
||||
t.Fatal("chunk_revisions must be written after chunks")
|
||||
}
|
||||
if position("wiki_page_revisions") < position("wiki_pages") {
|
||||
t.Fatal("wiki_page_revisions must be written after wiki_pages")
|
||||
}
|
||||
if !profile.RequiresPart("database/chunk_revisions") || !profile.RequiresPart("wiki/wiki_page_revisions") {
|
||||
t.Fatal("both revision parts must be required archive parts")
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,9 @@ type WriteSet struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Rows []WriteSetRow `json:"rows"`
|
||||
Universe map[string]TableFingerprint `json:"universe"`
|
||||
// Warnings 是放行但需要留痕的契约警告(例如未分类但为空的表)。omitempty:
|
||||
// 空警告不改变历史计划的规范字节/摘要,旧记录读回仍然一致。
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
// Digest 是对除本字段外全部内容的 sha256:落盘文件名与治理库里的引用都用它,
|
||||
// 记录被改一个字节就对不上。
|
||||
Digest string `json:"digest"`
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package libraryrelease
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 空警告必须不改变历史 V2 计划的规范字节:omitempty 是兼容边界,不是装饰。
|
||||
func TestWriteSetWarningsAreOmittedWhenEmpty(t *testing.T) {
|
||||
base := WriteSet{
|
||||
Version: MigrationWriteSetVersion, ContractVersion: 1,
|
||||
JobID: "job-1", Target: "internal", TenantID: 1, KnowledgeBaseID: "kb-1",
|
||||
BackupSnapshotID: "backup-1", TargetSnapshotID: "snapshot-1",
|
||||
CreatedAt: time.Unix(1700000000, 0).UTC(),
|
||||
Rows: []WriteSetRow{{Table: "knowledges", ID: "doc-1"}},
|
||||
Universe: map[string]TableFingerprint{"knowledges": {Count: 1, Digest: "digest"}},
|
||||
TargetIDMode: TargetIDModeScoped,
|
||||
}
|
||||
seal := func(set WriteSet) string {
|
||||
t.Helper()
|
||||
if err := set.Seal(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return set.Digest
|
||||
}
|
||||
withoutWarnings := seal(base)
|
||||
withEmptyWarnings := base
|
||||
withEmptyWarnings.Warnings = []string{}
|
||||
if got := seal(withEmptyWarnings); got != withoutWarnings {
|
||||
t.Fatalf("empty warnings changed the canonical digest: %s != %s", got, withoutWarnings)
|
||||
}
|
||||
withWarning := base
|
||||
withWarning.Warnings = []string{"release_undeclared_kb_table: 未分类空表已放行"}
|
||||
if got := seal(withWarning); got == withoutWarnings {
|
||||
t.Fatal("a real warning must be part of the durable record")
|
||||
}
|
||||
raw, err := json.Marshal(withWarning)
|
||||
if err != nil || !json.Valid(raw) {
|
||||
t.Fatalf("warning record must serialize: %v", err)
|
||||
}
|
||||
if !containsJSONField(raw, "warnings") {
|
||||
t.Fatal("warning must be persisted in the release record")
|
||||
}
|
||||
}
|
||||
|
||||
func containsJSONField(raw []byte, key string) bool {
|
||||
var object map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &object) != nil {
|
||||
return false
|
||||
}
|
||||
_, ok := object[key]
|
||||
return ok
|
||||
}
|
||||
@@ -7,18 +7,20 @@ import (
|
||||
)
|
||||
|
||||
// 归档部件的完整性按 schema 版本判定:0.9.0 没有 wiki_log_entries,
|
||||
// 0.7.1 缺了它就是残包。这里直接对 manifest 编码做判定,不依赖数据库。
|
||||
// 但必须有编辑历史两表;0.7.1 没有两表、缺 wiki_log_entries 就是残包。
|
||||
func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
|
||||
part := func(kind, name string) Part {
|
||||
return Part{Kind: kind, Name: name, SHA256: strings.Repeat("a", 64), Count: 1}
|
||||
}
|
||||
parts := []Part{
|
||||
legacyParts := []Part{
|
||||
part("database", "knowledges"), part("database", "chunks"), part("database", "resources"),
|
||||
part("database", "resource_bindings"), part("database", "knowledge_tags"),
|
||||
part("database", "knowledge_tag_relations"),
|
||||
part("wiki", "wiki_pages"), part("wiki", "wiki_folders"), part("wiki", "wiki_page_issues"),
|
||||
part("index", "chunks"),
|
||||
}
|
||||
v090Parts := append(append([]Part{}, legacyParts...),
|
||||
part("database", "chunk_revisions"), part("wiki", "wiki_page_revisions"))
|
||||
manifest := func(version int, weknora string, parts []Part) Manifest {
|
||||
return Manifest{
|
||||
ValidationPolicy: ArtifactAcceptancePolicy,
|
||||
@@ -36,23 +38,30 @@ func TestManifestPartSetFollowsSchemaProfile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := encodeManifest(manifest(134, "v0.9.0", parts)); err != nil {
|
||||
t.Fatalf("0.9.0 manifest without wiki_log_entries must be complete: %v", err)
|
||||
if _, err := encodeManifest(manifest(134, "v0.9.0", v090Parts)); err != nil {
|
||||
t.Fatalf("0.9.0 manifest must be complete without wiki_log_entries: %v", err)
|
||||
}
|
||||
if _, err := encodeManifest(manifest(74, "v0.7.1", parts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
|
||||
if _, err := encodeManifest(manifest(137, "v0.9.1", v090Parts)); err != nil {
|
||||
t.Fatalf("0.9.1 must share the 0.9.0 part set: %v", err)
|
||||
}
|
||||
if _, err := encodeManifest(manifest(134, "v0.9.0", legacyParts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
|
||||
t.Fatalf("0.9.0 manifest missing revision parts must be refused, got %v", err)
|
||||
}
|
||||
if _, err := encodeManifest(manifest(74, "v0.7.1", legacyParts)); err == nil || !strings.Contains(err.Error(), "incomplete") {
|
||||
t.Fatalf("0.7.1 manifest missing wiki_log_entries must be refused, got %v", err)
|
||||
}
|
||||
withLog := append(append([]Part{}, parts...), part("wiki", "wiki_log_entries"))
|
||||
if _, err := encodeManifest(manifest(74, "v0.7.1", withLog)); err != nil {
|
||||
legacyWithLog := append(append([]Part{}, legacyParts...), part("wiki", "wiki_log_entries"))
|
||||
if _, err := encodeManifest(manifest(74, "v0.7.1", legacyWithLog)); err != nil {
|
||||
t.Fatalf("0.7.1 manifest with wiki_log_entries must pass: %v", err)
|
||||
}
|
||||
if _, err := encodeManifest(manifest(134, "v0.9.0", withLog)); err != nil {
|
||||
v090WithLog := append(append([]Part{}, v090Parts...), part("wiki", "wiki_log_entries"))
|
||||
if _, err := encodeManifest(manifest(134, "v0.9.0", v090WithLog)); err != nil {
|
||||
t.Fatalf("0.9.0 manifest may still carry an optional wiki_log_entries part: %v", err)
|
||||
}
|
||||
if _, err := encodeManifest(manifest(74, "v0.9.0", withLog)); err == nil {
|
||||
if _, err := encodeManifest(manifest(74, "v0.9.0", legacyWithLog)); err == nil {
|
||||
t.Fatal("version string and profile version must agree")
|
||||
}
|
||||
if _, err := encodeManifest(manifest(135, "v0.9.0", parts)); err == nil {
|
||||
if _, err := encodeManifest(manifest(135, "v0.9.0", v090Parts)); err == nil {
|
||||
t.Fatal("unknown schema version must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,11 +306,10 @@ func (provider *RealProvider) Services(ctx context.Context) []governance.Service
|
||||
health = append(health, provider.weKnoraProbe(ctx, now))
|
||||
health = append(health, provider.productionWeKnoraProbe(ctx, now))
|
||||
health = append(health, provider.httpProbe(ctx, "mineru", "MinerU", provider.minerUBaseURL, now))
|
||||
// Not-applicable dependencies stay explicit (embedding/llm managed by
|
||||
// WeKnora, redis/mq/oss not deployed).
|
||||
// Not-applicable dependencies stay explicit (redis/mq/oss not deployed).
|
||||
// Embedding/LLM are managed inside WeKnora and are not platform services;
|
||||
// listing them here produced two permanent "unknown" cards on the page.
|
||||
health = append(health,
|
||||
provider.track(classify("embedding", "Embedding模型", false, false, ProbeOutcome{ObservedAt: now})),
|
||||
provider.track(classify("llm", "LLM模型", false, false, ProbeOutcome{ObservedAt: now})),
|
||||
provider.track(classify("redis", "Redis / MQ", false, false, ProbeOutcome{ObservedAt: now})),
|
||||
provider.track(classify("oss", "OSS", false, false, ProbeOutcome{ObservedAt: now})),
|
||||
)
|
||||
|
||||
@@ -59,11 +59,18 @@ func TestRealServicesHealthMatrix(t *testing.T) {
|
||||
if byKey["weknora-production/r"] != ReadNotConfigured || byKey["weknora-production/l"] != LiveUnknown {
|
||||
t.Fatalf("unconfigured production endpoint = %v/%v", byKey["weknora-production/l"], byKey["weknora-production/r"])
|
||||
}
|
||||
for _, key := range []string{"redis", "oss", "embedding", "llm"} {
|
||||
for _, key := range []string{"redis", "oss"} {
|
||||
if byKey[key+"/r"] != ReadNotApplicable || byKey[key+"/l"] != LiveUnknown {
|
||||
t.Fatalf("not-deployed %s = %v/%v", key, byKey[key+"/l"], byKey[key+"/r"])
|
||||
}
|
||||
}
|
||||
// Embedding/LLM belong to WeKnora; the platform must not render them as
|
||||
// permanent unknown cards (requirement §8).
|
||||
for _, key := range []string{"embedding", "llm"} {
|
||||
if _, ok := byKey[key+"/r"]; ok {
|
||||
t.Fatalf("platform health still lists %s", key)
|
||||
}
|
||||
}
|
||||
// Readiness must be blocked ONLY by configured+deployed failures: worker.
|
||||
ok, blocked := overallReadiness(health)
|
||||
if ok || len(blocked) != 1 || blocked[0] != "worker" {
|
||||
|
||||
@@ -54,6 +54,13 @@ type RealProviderConfig struct {
|
||||
// same judgement the WeKnora client uses, so a card can never say 「可达」
|
||||
// while the client refuses that URL.
|
||||
AllowPrivateHTTP bool
|
||||
// RuntimeQueues is the optional platform-level read-only queue projection.
|
||||
// Nil or an error leaves WeKnoraQueues null; the page must not render 0.
|
||||
RuntimeQueues QueueReader
|
||||
}
|
||||
|
||||
type QueueReader interface {
|
||||
Queues(context.Context) (*governance.WeKnoraQueueSummary, error)
|
||||
}
|
||||
|
||||
type RealProvider struct {
|
||||
@@ -68,6 +75,7 @@ type RealProvider struct {
|
||||
weknoraReadiness func(ctx context.Context) (string, error)
|
||||
workerStaleAfter time.Duration
|
||||
allowPrivateHTTP bool
|
||||
runtimeQueues QueueReader
|
||||
health *healthTracker
|
||||
}
|
||||
|
||||
@@ -108,7 +116,7 @@ func NewRealProvider(config RealProviderConfig) (*RealProvider, error) {
|
||||
if stale <= 0 {
|
||||
stale = time.Minute
|
||||
}
|
||||
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, allowPrivateHTTP: config.AllowPrivateHTTP, health: newHealthTracker()}, nil
|
||||
return &RealProvider{db: config.DB, now: config.Now, httpClient: config.HTTPClient, weknoraBaseURL: strings.TrimSpace(config.WeKnoraBaseURL), minerUBaseURL: strings.TrimSpace(config.MinerUBaseURL), testWeKnoraResolver: config.TestWeKnoraResolver, productionWeKnoraBaseURL: strings.TrimSpace(config.ProductionWeKnoraBaseURL), productionWeKnoraResolver: config.ProductionWeKnoraResolver, weknoraReadiness: config.WeKnoraReadiness, workerStaleAfter: stale, allowPrivateHTTP: config.AllowPrivateHTTP, runtimeQueues: config.RuntimeQueues, health: newHealthTracker()}, nil
|
||||
}
|
||||
|
||||
func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorOverview, error) {
|
||||
@@ -120,12 +128,15 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
overview.Services = append(overview.Services,
|
||||
provider.httpHealth(ctx, "weknora", "WeKnora API", provider.resolveTestWeKnoraBaseURL(ctx), now),
|
||||
provider.httpHealth(ctx, "weknora-production", "生产 WeKnora", provider.resolveProductionWeKnoraBaseURL(ctx), now),
|
||||
governance.MonitorService{Key: "embedding", Name: "Embedding模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
|
||||
governance.MonitorService{Key: "llm", Name: "LLM模型", State: "unknown", Detail: "由WeKnora管理,尚无独立探测端点", ObservedAt: now},
|
||||
provider.httpHealth(ctx, "mineru", "MinerU", provider.minerUBaseURL, now),
|
||||
governance.MonitorService{Key: "redis", Name: "Redis / MQ", State: "unknown", Detail: "未部署;任务由PostgreSQL持久队列承载", ObservedAt: now},
|
||||
governance.MonitorService{Key: "oss", Name: "OSS", State: "unknown", Detail: "未配置独立健康探测", ObservedAt: now},
|
||||
)
|
||||
if provider.runtimeQueues != nil {
|
||||
if queues, queueErr := provider.runtimeQueues.Queues(ctx); queueErr == nil {
|
||||
overview.WeKnoraQueues = queues
|
||||
}
|
||||
}
|
||||
rows, err := provider.db.Query(ctx, `SELECT p.test_kb_id,
|
||||
CASE WHEN COUNT(DISTINCT p.target_scope)=1 THEN MIN(p.target_scope) ELSE 'mixed' END,
|
||||
COUNT(*) FILTER (WHERE p.superseded_at IS NULL)::integer,
|
||||
@@ -144,15 +155,13 @@ func (provider *RealProvider) Overview(ctx context.Context) (governance.MonitorO
|
||||
-- “是否发布到生产”(unpublished/disabling/disabled/failed),全仓没有任何代码写过 'enabled',
|
||||
-- 所以这条车道恒为 0 —— 2026-10-10 界面验收实测:把已入库的文件改成“禁止导入”后
|
||||
-- 车道仍显示 0,界面承诺的“仍在知识库里的文件会出现在这里”不成立。
|
||||
COUNT(*) FILTER (WHERE p.superseded_at IS NULL AND p.knowledge_id<>''
|
||||
AND p.processing_state='completed'
|
||||
AND p.retrieval_state NOT IN ('disabling','disabled')
|
||||
AND item.policy_state='blocked')::integer,
|
||||
COUNT(removal_candidate.publication_id)::integer,
|
||||
COUNT(*) FILTER (WHERE p.superseded_at IS NULL AND p.processing_state='planned'
|
||||
AND item.policy_state='blocked')::integer
|
||||
FROM test_publications p
|
||||
JOIN source_item_versions version ON version.id=p.source_item_version_id
|
||||
JOIN source_items item ON item.id=version.source_item_id
|
||||
LEFT JOIN removal_candidates removal_candidate ON removal_candidate.publication_id=p.id
|
||||
GROUP BY p.test_kb_id
|
||||
ORDER BY p.test_kb_id`)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package monitoring
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// TestOverviewRemovalDemandAndSharedViewAgree freezes the T6 requirement that
|
||||
// R6 and /monitor/overview read the same predicate. The old lane went
|
||||
// permanently zero because two hand-maintained SQL predicates drifted.
|
||||
func TestOverviewRemovalDemandAndSharedViewAgree(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, isolatedMetricsURL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := postgres.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exec := func(query string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(ctx, query, args...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
exec(`INSERT INTO source_connections(id,source_type,name,enabled) VALUES('conn-recon-view','dingtalk','对账视图用例',TRUE)`)
|
||||
exec(`INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,policy_state)
|
||||
VALUES('si-recon-view','conn-recon-view','recon.md',repeat('b',64),'对账视图','file','blocked')`)
|
||||
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-recon-view','si-recon-view','r1','verified')`)
|
||||
// test_publications is unique on (source_item_version_id,test_kb_id): a second
|
||||
// publication in the same KB must point at its own version, not reuse r1.
|
||||
exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-recon-removing','si-recon-view','r2','verified')`)
|
||||
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
|
||||
VALUES('pub-recon-view','sv-recon-view','kb-recon-view','doc-recon-view','uploaded','completed','unpublished')`)
|
||||
exec(`INSERT INTO test_publications(id,source_item_version_id,test_kb_id,knowledge_id,ingest_state,processing_state,retrieval_state)
|
||||
VALUES('pub-recon-removing','sv-recon-removing','kb-recon-view','doc-recon-removing','uploaded','completed','disabling')`)
|
||||
|
||||
provider, err := NewRealProvider(RealProviderConfig{DB: metricsPool{pool: pool}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
overview, err := provider.Overview(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(overview.KnowledgeBases) != 1 || overview.KnowledgeBases[0].NeedsRemoval != 1 {
|
||||
t.Fatalf("overview = %#v", overview.KnowledgeBases)
|
||||
}
|
||||
var visible int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::integer FROM removal_candidates WHERE test_kb_id='kb-recon-view'`).Scan(&visible); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if visible != overview.KnowledgeBases[0].NeedsRemoval {
|
||||
t.Fatalf("view=%d overview=%d", visible, overview.KnowledgeBases[0].NeedsRemoval)
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,6 @@ func (provider *SimulationProvider) Overview(context.Context) (governance.Monito
|
||||
Host: governance.MonitorHost{CPUPercent: 42, MemoryUsedBytes: 19971597926, MemoryTotalBytes: 34359738368, DiskUsedBytes: 128849018880, DiskTotalBytes: 536870912000, GPUState: "unknown", GPUDetail: "未接入真实GPU监控", Simulated: true},
|
||||
Services: []governance.MonitorService{
|
||||
{Key: "weknora", Name: "WeKnora API", State: "healthy", Detail: "模拟连接正常", LatencyMS: 86, ObservedAt: now, Simulated: true},
|
||||
{Key: "embedding", Name: "Embedding模型", State: "healthy", Detail: "模拟探测通过", LatencyMS: 142, ObservedAt: now, Simulated: true},
|
||||
{Key: "llm", Name: "LLM模型", State: "healthy", Detail: "模拟探测通过", LatencyMS: 318, ObservedAt: now, Simulated: true},
|
||||
{Key: "mineru", Name: "MinerU", State: "healthy", Detail: "模拟处理中2,队列5", LatencyMS: 24, ObservedAt: now, Simulated: true},
|
||||
{Key: "postgres", Name: "PostgreSQL", State: "unknown", Detail: "未接入真实监控", ObservedAt: now, Simulated: true},
|
||||
{Key: "redis", Name: "Redis / MQ", State: "unknown", Detail: "未接入真实监控", ObservedAt: now, Simulated: true},
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestSimulationProviderLabelsEveryValueAndReconcilesKnowledgeCounts(t *testi
|
||||
if overview.Host.DiskTotalBytes <= 0 || overview.Host.DiskUsedBytes <= 0 || overview.Host.GPUState != "unknown" || overview.Host.GPUDetail != "未接入真实GPU监控" {
|
||||
t.Fatalf("host resources=%#v", overview.Host)
|
||||
}
|
||||
requiredServices := map[string]bool{"weknora": false, "mineru": false, "postgres": false, "redis": false, "oss": false, "embedding": false, "llm": false}
|
||||
requiredServices := map[string]bool{"weknora": false, "mineru": false, "postgres": false, "redis": false, "oss": false}
|
||||
for _, service := range overview.Services {
|
||||
if _, ok := requiredServices[service.Key]; ok {
|
||||
requiredServices[service.Key] = true
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
DROP VIEW IF EXISTS removal_candidates;
|
||||
DROP TABLE IF EXISTS reconciliation_finding_actions;
|
||||
DROP TABLE IF EXISTS reconciliation_findings;
|
||||
DROP TABLE IF EXISTS reconciliation_runs;
|
||||
ALTER TABLE test_publications DROP COLUMN IF EXISTS upload_md5;
|
||||
@@ -0,0 +1,119 @@
|
||||
-- T6 一期导入对账:批次、差异、处置审计与上传 MD5。
|
||||
-- 只新增,不改台账既有状态语义;findings 可按 run 整批清理,actions 永久保留。
|
||||
|
||||
ALTER TABLE test_publications
|
||||
ADD COLUMN IF NOT EXISTS upload_md5 CHAR(32) NOT NULL DEFAULT ''
|
||||
CHECK (upload_md5 = '' OR upload_md5 ~ '^[0-9a-f]{32}$');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS reconciliation_runs (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
test_kb_id VARCHAR(255) NOT NULL,
|
||||
state VARCHAR(16) NOT NULL DEFAULT 'running'
|
||||
CHECK (state IN ('running', 'succeeded', 'failed')),
|
||||
trigger VARCHAR(16) NOT NULL
|
||||
CHECK (trigger IN ('schedule', 'manual')),
|
||||
started_at TIMESTAMPTZ NOT NULL,
|
||||
finished_at TIMESTAMPTZ,
|
||||
ledger_count INTEGER NOT NULL DEFAULT 0 CHECK (ledger_count >= 0),
|
||||
kb_count INTEGER NOT NULL DEFAULT 0 CHECK (kb_count >= 0),
|
||||
counts JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
CHECK (jsonb_typeof(counts) = 'object'),
|
||||
previous_counts JSONB
|
||||
CHECK (previous_counts IS NULL OR jsonb_typeof(previous_counts) = 'object'),
|
||||
window_overlapped BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
error_code VARCHAR(64) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- One running batch per test knowledge base. The application 409 is only a
|
||||
-- friendly hint; this index is the real concurrency guard.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS reconciliation_runs_one_running
|
||||
ON reconciliation_runs (test_kb_id) WHERE state = 'running';
|
||||
CREATE INDEX IF NOT EXISTS idx_reconciliation_runs_started
|
||||
ON reconciliation_runs (started_at DESC, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_reconciliation_runs_kb_started
|
||||
ON reconciliation_runs (test_kb_id, started_at DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS reconciliation_findings (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
run_id VARCHAR(36) NOT NULL
|
||||
REFERENCES reconciliation_runs(id) ON DELETE CASCADE,
|
||||
finding_type VARCHAR(2) NOT NULL
|
||||
CHECK (finding_type IN ('R1','R2','R3','R4','R5','R6','R7','R8')),
|
||||
publication_id VARCHAR(36) NOT NULL DEFAULT '',
|
||||
knowledge_id VARCHAR(255) NOT NULL DEFAULT '',
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
path TEXT NOT NULL DEFAULT '',
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
target_scope VARCHAR(16) NOT NULL DEFAULT '',
|
||||
ledger_state VARCHAR(20) NOT NULL DEFAULT '',
|
||||
weknora_parse_status VARCHAR(32) NOT NULL DEFAULT '',
|
||||
normalized_state VARCHAR(32) NOT NULL DEFAULT '',
|
||||
ledger_sha256 CHAR(64) NOT NULL DEFAULT '',
|
||||
declared_sha256 CHAR(64) NOT NULL DEFAULT '',
|
||||
weknora_file_md5 CHAR(32) NOT NULL DEFAULT '',
|
||||
evidence_level VARCHAR(16) NOT NULL DEFAULT 'none'
|
||||
CHECK (evidence_level IN ('independent','declared_only','none')),
|
||||
confirmation_state VARCHAR(16) NOT NULL DEFAULT 'confirmed'
|
||||
CHECK (confirmation_state IN ('confirmed','pending')),
|
||||
detail TEXT NOT NULL DEFAULT '',
|
||||
suggested_action VARCHAR(32) NOT NULL DEFAULT 'none'
|
||||
CHECK (suggested_action IN ('requeue_upload','remove_from_test','writeback_state','enter_removal','none')),
|
||||
action_state VARCHAR(16) NOT NULL DEFAULT 'open'
|
||||
CHECK (action_state IN ('open','done')),
|
||||
weknora_url TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (run_id, finding_type, publication_id, knowledge_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_run
|
||||
ON reconciliation_findings (run_id, finding_type, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_publication
|
||||
ON reconciliation_findings (publication_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_knowledge
|
||||
ON reconciliation_findings (knowledge_id);
|
||||
|
||||
-- Durable action audit. Deliberedly not FK-bound to findings: findings are
|
||||
-- deleted by retention, the audit is not.
|
||||
CREATE TABLE IF NOT EXISTS reconciliation_finding_actions (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
finding_id VARCHAR(36) NOT NULL,
|
||||
run_id VARCHAR(36) NOT NULL,
|
||||
publication_id VARCHAR(36) NOT NULL DEFAULT '',
|
||||
knowledge_id VARCHAR(255) NOT NULL DEFAULT '',
|
||||
action VARCHAR(32) NOT NULL
|
||||
CHECK (action IN ('writeback','requeue','remove')),
|
||||
actor_ref VARCHAR(128) NOT NULL DEFAULT '',
|
||||
outcome VARCHAR(32) NOT NULL,
|
||||
detail TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_reconciliation_actions_finding
|
||||
ON reconciliation_finding_actions (finding_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_reconciliation_actions_publication
|
||||
ON reconciliation_finding_actions (publication_id, created_at DESC);
|
||||
|
||||
-- R6 and /monitor/overview must never disagree about "需下架": both read this
|
||||
-- view. The 2026-10-10 acceptance found the old lane permanently zero because
|
||||
-- two different predicates were maintained by hand.
|
||||
CREATE OR REPLACE VIEW removal_candidates AS
|
||||
SELECT publication.id AS publication_id,
|
||||
publication.test_kb_id,
|
||||
publication.knowledge_id,
|
||||
publication.target_scope,
|
||||
version.id AS source_item_version_id,
|
||||
version.source_item_id,
|
||||
item.title,
|
||||
item.normalized_path,
|
||||
item.source_connection_id,
|
||||
connection.name AS source_name
|
||||
FROM test_publications publication
|
||||
JOIN source_item_versions version ON version.id = publication.source_item_version_id
|
||||
JOIN source_items item ON item.id = version.source_item_id
|
||||
JOIN source_connections connection ON connection.id = item.source_connection_id
|
||||
WHERE publication.superseded_at IS NULL
|
||||
AND publication.knowledge_id <> ''
|
||||
AND publication.processing_state = 'completed'
|
||||
AND publication.retrieval_state NOT IN ('disabling', 'disabled')
|
||||
AND item.policy_state = 'blocked';
|
||||
@@ -11,8 +11,16 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 83 {
|
||||
t.Fatalf("migration count = %d, want 83", len(migrations))
|
||||
if len(migrations) != 84 {
|
||||
t.Fatalf("migration count = %d, want 84", len(migrations))
|
||||
}
|
||||
// 84 是导入对账:台账 upload_md5、runs/findings/actions 与共享需下架视图。
|
||||
if reconciliation := migrations[83]; reconciliation.Version != 84 ||
|
||||
!strings.Contains(reconciliation.UpSQL, "CREATE TABLE IF NOT EXISTS reconciliation_runs") ||
|
||||
!strings.Contains(reconciliation.UpSQL, "CREATE OR REPLACE VIEW removal_candidates") ||
|
||||
!strings.Contains(reconciliation.UpSQL, "upload_md5") ||
|
||||
!strings.Contains(reconciliation.DownSQL, "DROP VIEW IF EXISTS removal_candidates") {
|
||||
t.Fatalf("migration 84 = %#v", reconciliation)
|
||||
}
|
||||
// 83 是密钥保存审计的来源列:只追加取证字段,来源解析不出时留空。
|
||||
if source := migrations[82]; source.Version != 83 ||
|
||||
|
||||
@@ -28,15 +28,20 @@ type MonitorTask struct {
|
||||
SourceName string `json:"source_name"`
|
||||
TargetScope string `json:"target_scope"`
|
||||
TargetKB string `json:"target_kb"`
|
||||
Action string `json:"action"`
|
||||
Stage string `json:"stage"`
|
||||
Status string `json:"status"`
|
||||
Detail string `json:"detail"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
RetryKind string `json:"retry_kind"`
|
||||
FailureID string `json:"failure_id"`
|
||||
RetryCount int `json:"retry_count"`
|
||||
VersionID string `json:"version_id"`
|
||||
DocumentID string `json:"document_id"`
|
||||
// WeKnoraURL is the console link for this row's target knowledge base. The
|
||||
// handler fills it from the effective test endpoint so the detail drawer can
|
||||
// offer the same jump link as a reconciliation finding; empty = not configured.
|
||||
WeKnoraURL string `json:"weknora_url"`
|
||||
Action string `json:"action"`
|
||||
Stage string `json:"stage"`
|
||||
Status string `json:"status"`
|
||||
Detail string `json:"detail"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
RetryKind string `json:"retry_kind"`
|
||||
FailureID string `json:"failure_id"`
|
||||
RetryCount int `json:"retry_count"`
|
||||
VersionID string `json:"version_id"`
|
||||
}
|
||||
type MonitorTaskPage struct {
|
||||
Items []MonitorTask `json:"items"`
|
||||
@@ -124,7 +129,7 @@ const monitorTasksCTE = `WITH history_publications AS (
|
||||
ELSE 'waiting' END AS stage
|
||||
FROM base
|
||||
), projected AS (
|
||||
SELECT id,title,path,parent_node_id,node_id,source_id,source_name,target_scope,target_kb,version_id,retry_count,updated_at,action,stage,status,failure_id,
|
||||
SELECT id,title,path,parent_node_id,node_id,source_id,source_name,target_scope,target_kb,knowledge_id AS document_id,version_id,retry_count,updated_at,action,stage,status,failure_id,
|
||||
CASE WHEN status<>'attention' THEN ''
|
||||
WHEN action='remove' THEN CASE WHEN job_type='test.remove' AND job_state='failed' AND retrieval_state IN ('failed','disabling') AND policy_state='blocked' THEN 'remove' ELSE '' END
|
||||
WHEN failure_type='artifact.fetch' THEN 'fetch'
|
||||
@@ -144,7 +149,7 @@ const monitorTasksCTE = `WITH history_publications AS (
|
||||
SELECT * FROM projected WHERE ($1='' OR strpos(lower(title || ' ' || path),lower($1))>0)
|
||||
AND ($2='' OR source_id=$2) AND ($3='' OR target_scope=$3) AND ($4='' OR action=$4)
|
||||
AND ($5='' OR ($5='active' AND status NOT IN ('completed','cancelled')) OR status=$5)
|
||||
AND ($6='' OR stage=$6) AND ($7='' OR id=$7) AND ($10='' OR target_kb=$10)
|
||||
AND ($6='' OR stage=$6 OR ($6='weknora' AND stage IN ('parsing','indexing'))) AND ($7='' OR id=$7) AND ($10='' OR target_kb=$10)
|
||||
AND ($11='' OR updated_at>=NULLIF($11,'')::timestamptz) AND ($12='' OR updated_at<=NULLIF($12,'')::timestamptz)
|
||||
) `
|
||||
|
||||
|
||||
@@ -128,4 +128,23 @@ func TestMonitorTasksUnifiedPaginationIntegration(t *testing.T) {
|
||||
exec(`UPDATE jobs SET state='retry' WHERE id='mt-fetch-job'`)
|
||||
check("retrying", 0)
|
||||
})
|
||||
t.Run("weknora stage facet merges parsing and indexing in SQL", func(t *testing.T) {
|
||||
insertReviewFixture(t, ctx, pool, 8, "mt-merge-parse", now)
|
||||
insertReviewFixture(t, ctx, pool, 9, "mt-merge-index", now)
|
||||
exec(`UPDATE test_publications SET processing_state='processing' WHERE id='mt-merge-parse'`)
|
||||
exec(`UPDATE test_publications SET processing_state='finalizing' WHERE id='mt-merge-index'`)
|
||||
query := MonitorTaskFilter{Search: "Synthetic mt-merge", Limit: 20}
|
||||
merged, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "weknora", Limit: query.Limit})
|
||||
if err != nil || merged.Total != 2 {
|
||||
t.Fatalf("weknora facet: %#v %v", merged, err)
|
||||
}
|
||||
parsing, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "parsing", Limit: query.Limit})
|
||||
if err != nil || parsing.Total != 1 || parsing.Items[0].ID != "mt-merge-parse" {
|
||||
t.Fatalf("parsing facet: %#v %v", parsing, err)
|
||||
}
|
||||
indexing, err := store.ListMonitorTasks(ctx, MonitorTaskFilter{Search: query.Search, Stage: "indexing", Limit: query.Limit})
|
||||
if err != nil || indexing.Total != 1 || indexing.Items[0].ID != "mt-merge-index" {
|
||||
t.Fatalf("indexing facet: %#v %v", indexing, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
func TestReconciliationRunUniquenessStaleAndRetentionIntegration(t *testing.T) {
|
||||
url := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if url == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, 12, 1, 2, 0, 0, 0, time.UTC)
|
||||
first, err := store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
|
||||
ID: "rec-first", KBID: "kb-unique", State: "running", Trigger: "manual", StartedAt: now,
|
||||
Counts: governance.ReconciliationCounts{},
|
||||
}, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
|
||||
ID: "rec-second", KBID: "kb-unique", State: "running", Trigger: "manual", StartedAt: now,
|
||||
Counts: governance.ReconciliationCounts{},
|
||||
}, now); !errors.Is(err, ErrReconciliationRunInProgress) {
|
||||
t.Fatalf("second claim err=%v", err)
|
||||
}
|
||||
reaped, err := store.ReapStaleReconciliationRuns(ctx, now.Add(7*time.Hour), 6*time.Hour)
|
||||
if err != nil || reaped != 1 {
|
||||
t.Fatalf("reaped=%d err=%v", reaped, err)
|
||||
}
|
||||
second, err := store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
|
||||
ID: "rec-second", KBID: "kb-unique", State: "running", Trigger: "manual", StartedAt: now.Add(7 * time.Hour),
|
||||
Counts: governance.ReconciliationCounts{},
|
||||
}, now.Add(7*time.Hour))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
finishedAt := now.Add(8 * time.Hour)
|
||||
second.FinishedAt = &finishedAt
|
||||
second.Counts = governance.ReconciliationCounts{"R1": 1}
|
||||
if err := store.CompleteReconciliationRun(ctx, second, []governance.ReconciliationFinding{{
|
||||
ID: "finding-second", RunID: second.ID, Type: "R1", DocumentID: "doc",
|
||||
Title: "t", LedgerState: "completed", EvidenceLevel: "none", SuggestedAction: "requeue_upload",
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.CleanupReconciliationFindings(ctx, now.Add(9*time.Hour), 1, 90*24*time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_findings WHERE run_id=$1`, first.ID).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("old findings=%d err=%v", count, err)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_findings WHERE run_id=$1`, second.ID).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatalf("new findings=%d err=%v", count, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrReconciliationRunInProgress = errors.New("reconciliation run already in progress")
|
||||
ErrReconciliationNotFound = errors.New("reconciliation record not found")
|
||||
ErrReconciliationConflict = errors.New("reconciliation state or identity changed")
|
||||
ErrReconciliationNotRunning = errors.New("reconciliation run is not running")
|
||||
)
|
||||
|
||||
const reconciliationRunColumns = `id,test_kb_id,state,trigger,started_at,finished_at,ledger_count,kb_count,counts,previous_counts,window_overlapped,error_code`
|
||||
|
||||
func scanReconciliationRun(row rowScanner) (governance.ReconciliationRun, error) {
|
||||
var run governance.ReconciliationRun
|
||||
var counts, previous []byte
|
||||
if err := row.Scan(&run.ID, &run.KBID, &run.State, &run.Trigger, &run.StartedAt, &run.FinishedAt,
|
||||
&run.LedgerCount, &run.KBCount, &counts, &previous, &run.WindowOverlapped, &run.ErrorCode); err != nil {
|
||||
return governance.ReconciliationRun{}, err
|
||||
}
|
||||
if len(counts) > 0 {
|
||||
if err := json.Unmarshal(counts, &run.Counts); err != nil {
|
||||
return governance.ReconciliationRun{}, fmt.Errorf("decode reconciliation counts: %w", err)
|
||||
}
|
||||
}
|
||||
run.Counts = run.Counts.Normalize()
|
||||
if len(previous) > 0 {
|
||||
var value governance.ReconciliationCounts
|
||||
if err := json.Unmarshal(previous, &value); err != nil {
|
||||
return governance.ReconciliationRun{}, fmt.Errorf("decode previous reconciliation counts: %w", err)
|
||||
}
|
||||
run.PreviousCounts = value.Normalize()
|
||||
}
|
||||
return run, nil
|
||||
}
|
||||
|
||||
// ClaimReconciliationRun inserts a running batch. The partial unique index is
|
||||
// the concurrency authority; a friendly 409 is produced from ErrRunInProgress.
|
||||
func (s *Store) ClaimReconciliationRun(ctx context.Context, run governance.ReconciliationRun, now time.Time) (governance.ReconciliationRun, error) {
|
||||
counts, err := json.Marshal(run.Counts.Normalize())
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, err
|
||||
}
|
||||
row := s.db.QueryRow(ctx, `INSERT INTO reconciliation_runs
|
||||
(id,test_kb_id,state,trigger,started_at,counts,created_at)
|
||||
VALUES($1,$2,'running',$3,$4,$5::jsonb,$6)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING `+reconciliationRunColumns,
|
||||
run.ID, run.KBID, run.Trigger, run.StartedAt, counts, now)
|
||||
claimed, err := scanReconciliationRun(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationRun{}, ErrReconciliationRunInProgress
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, fmt.Errorf("claim reconciliation run: %w", err)
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
|
||||
func (s *Store) ClaimScheduledReconciliationRun(ctx context.Context, run governance.ReconciliationRun, since, now time.Time) (governance.ReconciliationRun, bool, error) {
|
||||
counts, err := json.Marshal(run.Counts.Normalize())
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, false, err
|
||||
}
|
||||
row := s.db.QueryRow(ctx, `INSERT INTO reconciliation_runs
|
||||
(id,test_kb_id,state,trigger,started_at,counts,created_at)
|
||||
SELECT $1,$2,'running','schedule',$3,$4::jsonb,$5
|
||||
WHERE NOT EXISTS(
|
||||
SELECT 1 FROM reconciliation_runs
|
||||
WHERE test_kb_id=$2 AND trigger='schedule' AND state IN ('running','succeeded') AND started_at >= $6
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING `+reconciliationRunColumns,
|
||||
run.ID, run.KBID, run.StartedAt, counts, now, since)
|
||||
claimed, err := scanReconciliationRun(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationRun{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, false, fmt.Errorf("claim scheduled reconciliation run: %w", err)
|
||||
}
|
||||
return claimed, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) ReapStaleReconciliationRuns(ctx context.Context, now time.Time, threshold time.Duration) (int64, error) {
|
||||
if threshold <= 0 {
|
||||
return 0, nil
|
||||
}
|
||||
tag, err := s.db.Exec(ctx, `UPDATE reconciliation_runs
|
||||
SET state='failed',finished_at=$1,error_code='stale_timeout'
|
||||
WHERE state='running' AND started_at < $2`, now, now.Add(-threshold))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("reap stale reconciliation runs: %w", err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (s *Store) LoadReconciliationRun(ctx context.Context, id string) (governance.ReconciliationRun, error) {
|
||||
row := s.db.QueryRow(ctx, `SELECT `+reconciliationRunColumns+` FROM reconciliation_runs WHERE id=$1`, id)
|
||||
run, err := scanReconciliationRun(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationRun{}, ErrReconciliationNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, fmt.Errorf("load reconciliation run: %w", err)
|
||||
}
|
||||
return run, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListReconciliationRuns(ctx context.Context, filter governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
|
||||
page := governance.ReconciliationRunPage{Items: []governance.ReconciliationRun{}, Limit: filter.Limit, Offset: filter.Offset}
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_runs WHERE ($1='' OR test_kb_id=$1)`, filter.KBID).Scan(&page.Total); err != nil {
|
||||
return page, fmt.Errorf("count reconciliation runs: %w", err)
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `SELECT `+reconciliationRunColumns+`
|
||||
FROM reconciliation_runs WHERE ($1='' OR test_kb_id=$1)
|
||||
ORDER BY started_at DESC,id DESC LIMIT $2 OFFSET $3`, filter.KBID, filter.Limit, filter.Offset)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("list reconciliation runs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
run, err := scanReconciliationRun(rows)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("scan reconciliation run: %w", err)
|
||||
}
|
||||
page.Items = append(page.Items, run)
|
||||
}
|
||||
return page, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) LoadReconciliationLedger(ctx context.Context, kbID string) ([]governance.ReconciliationLedgerRow, error) {
|
||||
rows, err := s.db.Query(ctx, `SELECT publication.id,publication.knowledge_id,publication.processing_state,
|
||||
publication.retrieval_state,publication.target_scope,publication.processing_started_at,
|
||||
publication.updated_at,publication.upload_md5,
|
||||
item.id,item.title,COALESCE(NULLIF(item.normalized_path,''),''),connection.name,
|
||||
item.policy_state,COALESCE(content.sha256,'')
|
||||
FROM test_publications publication
|
||||
JOIN source_item_versions version ON version.id=publication.source_item_version_id
|
||||
JOIN source_items item ON item.id=version.source_item_id
|
||||
JOIN source_connections connection ON connection.id=item.source_connection_id
|
||||
LEFT JOIN content_objects content ON content.id=version.content_object_id
|
||||
WHERE publication.test_kb_id=$1 AND publication.superseded_at IS NULL
|
||||
ORDER BY publication.id`, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load reconciliation ledger: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]governance.ReconciliationLedgerRow, 0)
|
||||
for rows.Next() {
|
||||
var row governance.ReconciliationLedgerRow
|
||||
if err := rows.Scan(&row.PublicationID, &row.KnowledgeID, &row.ProcessingState, &row.RetrievalState,
|
||||
&row.TargetScope, &row.ProcessingStartedAt, &row.UpdatedAt, &row.UploadMD5,
|
||||
&row.SourceItemID, &row.Title, &row.Path, &row.SourceName, &row.PolicyState, &row.SHA256); err != nil {
|
||||
return nil, fmt.Errorf("scan reconciliation ledger: %w", err)
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) LoadPreviousReconciliationCounts(ctx context.Context, kbID string, before time.Time) (governance.ReconciliationCounts, bool, error) {
|
||||
var raw []byte
|
||||
err := s.db.QueryRow(ctx, `SELECT counts FROM reconciliation_runs
|
||||
WHERE test_kb_id=$1 AND state='succeeded' AND started_at < $2
|
||||
ORDER BY started_at DESC,id DESC LIMIT 1`, kbID, before).Scan(&raw)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("load previous reconciliation counts: %w", err)
|
||||
}
|
||||
var counts governance.ReconciliationCounts
|
||||
if err := json.Unmarshal(raw, &counts); err != nil {
|
||||
return nil, false, fmt.Errorf("decode previous reconciliation counts: %w", err)
|
||||
}
|
||||
return counts.Normalize(), true, nil
|
||||
}
|
||||
|
||||
func (s *Store) CompleteReconciliationRun(ctx context.Context, run governance.ReconciliationRun, findings []governance.ReconciliationFinding) error {
|
||||
beginner, ok := s.db.(interface {
|
||||
Begin(context.Context) (pgx.Tx, error)
|
||||
})
|
||||
if !ok {
|
||||
return errors.New("reconciliation transactions are unavailable")
|
||||
}
|
||||
tx, err := beginner.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin reconciliation completion: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
counts, err := json.Marshal(run.Counts.Normalize())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var previous any
|
||||
if run.PreviousCounts != nil {
|
||||
raw, err := json.Marshal(run.PreviousCounts.Normalize())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
previous = raw
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE reconciliation_runs
|
||||
SET state='succeeded',finished_at=$2,ledger_count=$3,kb_count=$4,counts=$5::jsonb,
|
||||
previous_counts=$6::jsonb,window_overlapped=$7,error_code=''
|
||||
WHERE id=$1 AND state='running'`, run.ID, run.FinishedAt, run.LedgerCount, run.KBCount, counts, previous, run.WindowOverlapped)
|
||||
if err != nil {
|
||||
return fmt.Errorf("complete reconciliation run: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return ErrReconciliationNotRunning
|
||||
}
|
||||
for _, finding := range findings {
|
||||
// The column default only applies when the insert omits the column; the
|
||||
// service always fills it, but direct callers may pass "" and must not
|
||||
// violate the check constraint.
|
||||
confirmation := finding.ConfirmationState
|
||||
if confirmation == "" {
|
||||
confirmation = "confirmed"
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO reconciliation_findings
|
||||
(id,run_id,finding_type,publication_id,knowledge_id,title,path,source,target_scope,
|
||||
ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
|
||||
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,
|
||||
weknora_url,created_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,'open',$20,$21)`,
|
||||
finding.ID, finding.RunID, finding.Type, finding.PublicationID, finding.DocumentID,
|
||||
finding.Title, finding.Path, finding.Source, finding.TargetScope, finding.LedgerState,
|
||||
finding.WeKnoraParseState, finding.NormalizedState, finding.LedgerSHA256, finding.DeclaredSHA256,
|
||||
finding.WeKnoraFileMD5, finding.EvidenceLevel, confirmation, finding.Detail,
|
||||
finding.SuggestedAction, finding.WeKnoraURL, run.FinishedAt); err != nil {
|
||||
return fmt.Errorf("insert reconciliation finding: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit reconciliation run: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) FailReconciliationRun(ctx context.Context, runID, code string, finished time.Time) error {
|
||||
_, err := s.db.Exec(ctx, `UPDATE reconciliation_runs
|
||||
SET state='failed',finished_at=$2,error_code=$3
|
||||
WHERE id=$1 AND state='running'`, runID, finished, code)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fail reconciliation run: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) CleanupReconciliationFindings(ctx context.Context, now time.Time, keepRuns int, maxAge time.Duration) error {
|
||||
if keepRuns < 1 || maxAge <= 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := s.db.Exec(ctx, `DELETE FROM reconciliation_findings
|
||||
WHERE run_id IN (
|
||||
SELECT id FROM reconciliation_runs
|
||||
WHERE started_at < $1
|
||||
OR id NOT IN (
|
||||
SELECT id FROM reconciliation_runs ORDER BY started_at DESC,id DESC LIMIT $2
|
||||
)
|
||||
)`, now.Add(-maxAge), keepRuns)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cleanup reconciliation findings: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) LibraryJobsActive(ctx context.Context) (bool, error) {
|
||||
var active bool
|
||||
if err := s.db.QueryRow(ctx, `SELECT EXISTS(
|
||||
SELECT 1 FROM jobs WHERE type LIKE 'library.%' AND state IN ('pending','running','retry')
|
||||
)`).Scan(&active); err != nil {
|
||||
return false, fmt.Errorf("inspect library jobs: %w", err)
|
||||
}
|
||||
return active, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListReconciliationRemovalCandidates(ctx context.Context, kbID string) ([]governance.ReconciliationLedgerRow, error) {
|
||||
rows, err := s.db.Query(ctx, `SELECT publication_id,knowledge_id,target_scope,
|
||||
source_item_version_id,source_item_id,title,normalized_path,source_name
|
||||
FROM removal_candidates WHERE test_kb_id=$1 ORDER BY publication_id`, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list removal candidates: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]governance.ReconciliationLedgerRow, 0)
|
||||
for rows.Next() {
|
||||
var row governance.ReconciliationLedgerRow
|
||||
var versionID string
|
||||
if err := rows.Scan(&row.PublicationID, &row.KnowledgeID, &row.TargetScope,
|
||||
&versionID, &row.SourceItemID, &row.Title, &row.Path, &row.SourceName); err != nil {
|
||||
return nil, fmt.Errorf("scan removal candidate: %w", err)
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
const reconciliationFindingColumns = `id,run_id,finding_type,publication_id,knowledge_id,title,path,source,
|
||||
target_scope,ledger_state,weknora_parse_status,normalized_state,ledger_sha256,declared_sha256,
|
||||
weknora_file_md5,evidence_level,confirmation_state,detail,suggested_action,action_state,weknora_url`
|
||||
|
||||
func scanReconciliationFinding(row rowScanner) (governance.ReconciliationFinding, error) {
|
||||
var finding governance.ReconciliationFinding
|
||||
if err := row.Scan(&finding.ID, &finding.RunID, &finding.Type, &finding.PublicationID, &finding.DocumentID,
|
||||
&finding.Title, &finding.Path, &finding.Source, &finding.TargetScope, &finding.LedgerState,
|
||||
&finding.WeKnoraParseState, &finding.NormalizedState, &finding.LedgerSHA256, &finding.DeclaredSHA256,
|
||||
&finding.WeKnoraFileMD5, &finding.EvidenceLevel, &finding.ConfirmationState, &finding.Detail,
|
||||
&finding.SuggestedAction, &finding.ActionState, &finding.WeKnoraURL); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
return finding, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListReconciliationFindings(ctx context.Context, filter governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
|
||||
page := governance.ReconciliationFindingPage{Items: []governance.ReconciliationFinding{}, Limit: filter.Limit, Offset: filter.Offset}
|
||||
if err := s.db.QueryRow(ctx, `SELECT COUNT(*)::integer FROM reconciliation_findings
|
||||
WHERE run_id=$1 AND ($2='' OR finding_type=$2)
|
||||
AND ($3='' OR strpos(lower(title || ' ' || path || ' ' || detail),lower($3))>0)`,
|
||||
filter.RunID, filter.Type, filter.Query).Scan(&page.Total); err != nil {
|
||||
return page, fmt.Errorf("count reconciliation findings: %w", err)
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `SELECT `+reconciliationFindingColumns+`
|
||||
FROM reconciliation_findings
|
||||
WHERE run_id=$1 AND ($2='' OR finding_type=$2)
|
||||
AND ($3='' OR strpos(lower(title || ' ' || path || ' ' || detail),lower($3))>0)
|
||||
ORDER BY finding_type,publication_id,knowledge_id,id LIMIT $4 OFFSET $5`,
|
||||
filter.RunID, filter.Type, filter.Query, filter.Limit, filter.Offset)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("list reconciliation findings: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
finding, err := scanReconciliationFinding(rows)
|
||||
if err != nil {
|
||||
return page, fmt.Errorf("scan reconciliation finding: %w", err)
|
||||
}
|
||||
page.Items = append(page.Items, finding)
|
||||
}
|
||||
return page, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) GetReconciliationFinding(ctx context.Context, id string) (governance.ReconciliationFinding, error) {
|
||||
return getReconciliationFinding(ctx, s.db, id)
|
||||
}
|
||||
|
||||
func getReconciliationFinding(ctx context.Context, queryer interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}, id string) (governance.ReconciliationFinding, error) {
|
||||
row := queryer.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+` FROM reconciliation_findings WHERE id=$1`, id)
|
||||
finding, err := scanReconciliationFinding(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationFinding{}, ErrReconciliationNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, fmt.Errorf("load reconciliation finding: %w", err)
|
||||
}
|
||||
return finding, nil
|
||||
}
|
||||
|
||||
func lockOpenReconciliationFinding(ctx context.Context, tx pgx.Tx, id string) error {
|
||||
var state string
|
||||
if err := tx.QueryRow(ctx, `SELECT action_state FROM reconciliation_findings WHERE id=$1 FOR UPDATE`, id).Scan(&state); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrReconciliationNotFound
|
||||
}
|
||||
return fmt.Errorf("lock reconciliation finding: %w", err)
|
||||
}
|
||||
if state != "open" {
|
||||
return ErrReconciliationConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) LoadReconciliationActionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
|
||||
var view governance.ReconciliationActionView
|
||||
var currentExists bool
|
||||
row := s.db.QueryRow(ctx, `SELECT `+reconciliationFindingColumns+`,
|
||||
run.test_kb_id,run.started_at,
|
||||
publication.id IS NOT NULL,
|
||||
COALESCE(publication.processing_state,''),COALESCE(publication.knowledge_id,''),
|
||||
COALESCE(publication.superseded_at IS NOT NULL,FALSE),COALESCE(publication.retrieval_state,''),
|
||||
COALESCE(publication.target_scope,'')
|
||||
FROM reconciliation_findings finding
|
||||
JOIN reconciliation_runs run ON run.id=finding.run_id
|
||||
LEFT JOIN test_publications publication ON publication.id=finding.publication_id
|
||||
WHERE finding.id=$1`, findingID)
|
||||
if err := row.Scan(&view.Finding.ID, &view.Finding.RunID, &view.Finding.Type, &view.Finding.PublicationID,
|
||||
&view.Finding.DocumentID, &view.Finding.Title, &view.Finding.Path, &view.Finding.Source,
|
||||
&view.Finding.TargetScope, &view.Finding.LedgerState, &view.Finding.WeKnoraParseState,
|
||||
&view.Finding.NormalizedState, &view.Finding.LedgerSHA256, &view.Finding.DeclaredSHA256,
|
||||
&view.Finding.WeKnoraFileMD5, &view.Finding.EvidenceLevel, &view.Finding.ConfirmationState,
|
||||
&view.Finding.Detail, &view.Finding.SuggestedAction, &view.Finding.ActionState, &view.Finding.WeKnoraURL,
|
||||
&view.TestKBID, &view.RunStartedAt, ¤tExists, &view.CurrentProcessingState,
|
||||
&view.CurrentKnowledgeID, &view.CurrentSuperseded, &view.CurrentRetrievalState,
|
||||
&view.CurrentTargetScope); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return view, ErrReconciliationNotFound
|
||||
}
|
||||
return view, fmt.Errorf("load reconciliation action view: %w", err)
|
||||
}
|
||||
view.CurrentExists = currentExists
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func (s *Store) ReconciliationOrphanStillUnowned(ctx context.Context, publicationID, knowledgeID string) (bool, error) {
|
||||
var owned bool
|
||||
if err := s.db.QueryRow(ctx, `SELECT EXISTS(
|
||||
SELECT 1 FROM test_publications
|
||||
WHERE superseded_at IS NULL AND (knowledge_id=$2 OR ($1<>'' AND id=$1))
|
||||
)`, publicationID, knowledgeID).Scan(&owned); err != nil {
|
||||
return false, fmt.Errorf("inspect orphan ownership: %w", err)
|
||||
}
|
||||
return !owned, nil
|
||||
}
|
||||
|
||||
func (s *Store) WritebackReconciliationFinding(ctx context.Context, findingID, targetState, actor, reason string, now time.Time) (governance.ReconciliationFinding, error) {
|
||||
beginner, ok := s.db.(interface {
|
||||
Begin(context.Context) (pgx.Tx, error)
|
||||
})
|
||||
if !ok {
|
||||
return governance.ReconciliationFinding{}, errors.New("reconciliation transactions are unavailable")
|
||||
}
|
||||
tx, err := beginner.Begin(ctx)
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
finding, err := getReconciliationFinding(ctx, tx, findingID)
|
||||
if errors.Is(err, ErrReconciliationNotFound) {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if finding.Type != "R5" || finding.ActionState != "open" {
|
||||
return governance.ReconciliationFinding{}, ErrReconciliationConflict
|
||||
}
|
||||
var processingState string
|
||||
if err := tx.QueryRow(ctx, `SELECT processing_state FROM test_publications
|
||||
WHERE id=$1 AND superseded_at IS NULL FOR UPDATE`, finding.PublicationID).Scan(&processingState); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return governance.ReconciliationFinding{}, ErrReconciliationConflict
|
||||
}
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if processingState != finding.LedgerState {
|
||||
return governance.ReconciliationFinding{}, ErrReconciliationConflict
|
||||
}
|
||||
if processingState != targetState {
|
||||
if _, err := tx.Exec(ctx, `UPDATE test_publications SET processing_state=$2,updated_at=$3
|
||||
WHERE id=$1 AND processing_state=$4`, finding.PublicationID, targetState, now, finding.LedgerState); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if err := s.insertReconciliationActionTx(ctx, tx, finding, "writeback", actor, "started", reason, now); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
finding.ActionState = "done"
|
||||
return finding, nil
|
||||
}
|
||||
|
||||
func (s *Store) RequeueReconciliationPublication(ctx context.Context, findingID, expectedKnowledgeID, actor, reason string, now time.Time) (string, error) {
|
||||
beginner, ok := s.db.(interface {
|
||||
Begin(context.Context) (pgx.Tx, error)
|
||||
})
|
||||
if !ok {
|
||||
return "", errors.New("reconciliation transactions are unavailable")
|
||||
}
|
||||
tx, err := beginner.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
finding, err := getReconciliationFinding(ctx, tx, findingID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if (finding.Type != "R1" && finding.Type != "R4") || finding.ActionState != "open" {
|
||||
return "", ErrReconciliationConflict
|
||||
}
|
||||
var processingState, knowledgeID, targetScope, targetKB string
|
||||
if err := tx.QueryRow(ctx, `SELECT processing_state,knowledge_id,target_scope,test_kb_id
|
||||
FROM test_publications WHERE id=$1 AND superseded_at IS NULL FOR UPDATE`, finding.PublicationID).Scan(
|
||||
&processingState, &knowledgeID, &targetScope, &targetKB); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", ErrReconciliationConflict
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if processingState != finding.LedgerState || knowledgeID != expectedKnowledgeID {
|
||||
return "", ErrReconciliationConflict
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE test_publications SET
|
||||
ingest_state='pending',processing_state='pending',knowledge_id='',poll_sequence=0,
|
||||
last_remote_status='',last_remote_updated_at=NULL,last_observed_at=NULL,
|
||||
processing_started_at=NULL,completed_at=NULL,stalled_at=NULL,last_error='',
|
||||
upload_md5='',test_instance_url='',test_instance_tenant=0,
|
||||
retry_count=retry_count+1,updated_at=$2
|
||||
WHERE id=$1 AND knowledge_id=$3 AND processing_state=$4`,
|
||||
finding.PublicationID, now, expectedKnowledgeID, finding.LedgerState)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("reset reconciliation publication: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return "", ErrReconciliationConflict
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"publication_id": finding.PublicationID,
|
||||
"target_scope": targetScope,
|
||||
"target_kb_id": targetKB,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
jobID := orchestrationJobID("reconciliation.requeue", findingID)
|
||||
tag, err = tx.Exec(ctx, `INSERT INTO jobs(id,type,payload,state,priority,available_at,max_attempts,idempotency_key,created_at,updated_at)
|
||||
VALUES($1,'test.upload',$2,'pending',0,$3,5,$4,$3,$3)
|
||||
ON CONFLICT (idempotency_key) DO NOTHING`, jobID, payload, now, "reconciliation-requeue:"+findingID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("enqueue reconciliation upload: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
if err := tx.QueryRow(ctx, `SELECT id FROM jobs WHERE idempotency_key=$1`, "reconciliation-requeue:"+findingID).Scan(&jobID); err != nil {
|
||||
return "", fmt.Errorf("reconciliation upload job missing: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := s.insertReconciliationActionTx(ctx, tx, finding, "requeue", actor, "started", reason, now); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return jobID, nil
|
||||
}
|
||||
|
||||
func (s *Store) MarkReconciliationOrphanRemoved(ctx context.Context, findingID, actor, reason string, now time.Time) error {
|
||||
beginner, ok := s.db.(interface {
|
||||
Begin(context.Context) (pgx.Tx, error)
|
||||
})
|
||||
if !ok {
|
||||
return errors.New("reconciliation transactions are unavailable")
|
||||
}
|
||||
tx, err := beginner.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if err := lockOpenReconciliationFinding(ctx, tx, findingID); err != nil {
|
||||
return err
|
||||
}
|
||||
finding, err := getReconciliationFinding(ctx, tx, findingID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if finding.Type != "R2" || finding.ActionState != "open" {
|
||||
return ErrReconciliationConflict
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `UPDATE reconciliation_findings SET action_state='done' WHERE id=$1 AND action_state='open'`, findingID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.insertReconciliationActionTx(ctx, tx, finding, "remove", actor, "started", reason, now); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) insertReconciliationActionTx(ctx context.Context, tx pgx.Tx, finding governance.ReconciliationFinding, action, actor, outcome, detail string, now time.Time) error {
|
||||
id, err := newOpaqueID("rca-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO reconciliation_finding_actions
|
||||
(id,finding_id,run_id,publication_id,knowledge_id,action,actor_ref,outcome,detail,created_at)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
|
||||
id, finding.ID, finding.RunID, finding.PublicationID, finding.DocumentID, action, actor, outcome, detail, now)
|
||||
if err != nil {
|
||||
return fmt.Errorf("record reconciliation action: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -246,14 +246,15 @@ const recordUploadAndSchedulePollSQL = `
|
||||
WITH updated AS (
|
||||
UPDATE test_publications
|
||||
SET knowledge_id = $2,
|
||||
upload_md5 = $3,
|
||||
ingest_state = 'uploaded',
|
||||
processing_state = 'pending',
|
||||
poll_sequence = 1,
|
||||
last_remote_status = 'pending',
|
||||
processing_started_at = COALESCE(processing_started_at, $3),
|
||||
last_observed_at = $3,
|
||||
processing_started_at = COALESCE(processing_started_at, $4),
|
||||
last_observed_at = $4,
|
||||
last_error = '',
|
||||
updated_at = $3
|
||||
updated_at = $4
|
||||
WHERE id = $1
|
||||
AND processing_state = 'pending'
|
||||
AND (
|
||||
@@ -622,7 +623,7 @@ func (s *Store) MarkUploading(ctx context.Context, publicationID, instanceURL st
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID, knowledgeID string, now, nextAt time.Time) (int, error) {
|
||||
func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID, knowledgeID, uploadMD5 string, now, nextAt time.Time) (int, error) {
|
||||
payload, err := json.Marshal(struct {
|
||||
PublicationID string `json:"publication_id"`
|
||||
Sequence int `json:"sequence"`
|
||||
@@ -636,6 +637,7 @@ func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID,
|
||||
recordUploadAndSchedulePollSQL,
|
||||
publicationID,
|
||||
knowledgeID,
|
||||
strings.ToLower(strings.TrimSpace(uploadMD5)),
|
||||
now,
|
||||
payload,
|
||||
0,
|
||||
|
||||
@@ -67,13 +67,13 @@ func TestPublicationOrchestrationIsAtomicAndRejectsStaleTransitions(t *testing.T
|
||||
if err := store.MarkUploading(ctx, "publication-1", "", 0, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
|
||||
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", "", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
|
||||
t.Fatalf("record upload = %d, %v", sequence, err)
|
||||
}
|
||||
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
|
||||
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", "", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
|
||||
t.Fatalf("replay upload = %d, %v", sequence, err)
|
||||
}
|
||||
if _, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-conflict", now, now.Add(10*time.Second)); !errors.Is(err, ErrPublicationStateConflict) {
|
||||
if _, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-conflict", "", now, now.Add(10*time.Second)); !errors.Is(err, ErrPublicationStateConflict) {
|
||||
t.Fatalf("conflicting knowledge error = %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestRecordUploadAndSchedulePollIsAtomicAndIdempotent(t *testing.T) {
|
||||
db := &recordingDB{row: sequenceRow{sequence: 1}}
|
||||
now := time.Date(2026, time.September, 4, 2, 5, 0, 0, time.UTC)
|
||||
nextAt := now.Add(10 * time.Second)
|
||||
sequence, err := NewStore(db).RecordUploadAndSchedulePoll(context.Background(), "publication-1", "knowledge-1", now, nextAt)
|
||||
sequence, err := NewStore(db).RecordUploadAndSchedulePoll(context.Background(), "publication-1", "knowledge-1", "", now, nextAt)
|
||||
if err != nil {
|
||||
t.Fatalf("RecordUploadAndSchedulePoll() error = %v", err)
|
||||
}
|
||||
@@ -64,14 +64,14 @@ func TestRecordUploadAndSchedulePollIsAtomicAndIdempotent(t *testing.T) {
|
||||
if updateAt < 0 || insertAt < 0 || updateAt >= insertAt {
|
||||
t.Fatalf("atomic SQL missing ordered update/insert: %q", recordUploadAndSchedulePollSQL)
|
||||
}
|
||||
if db.queryRowSQL != recordUploadAndSchedulePollSQL || len(db.queryRowArgs) != 7 {
|
||||
if db.queryRowSQL != recordUploadAndSchedulePollSQL || len(db.queryRowArgs) != 8 {
|
||||
t.Fatalf("query = %q %#v", db.queryRowSQL, db.queryRowArgs)
|
||||
}
|
||||
if !strings.Contains(recordUploadAndSchedulePollSQL, "'test-poll:' || $1 || ':' || updated.retry_count || ':1'") {
|
||||
t.Fatalf("poll schedule key must carry the retry round: %q", recordUploadAndSchedulePollSQL)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(db.queryRowArgs[3].([]byte), &payload); err != nil {
|
||||
if err := json.Unmarshal(db.queryRowArgs[4].([]byte), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(payload) != 2 || payload["publication_id"] != "publication-1" || payload["sequence"] != float64(1) {
|
||||
|
||||
@@ -429,8 +429,11 @@ func validPathSegment(value string) bool {
|
||||
return strings.TrimSpace(value) != "" && !strings.ContainsAny(value, "/?#\\\x00")
|
||||
}
|
||||
|
||||
// validPage accepts the upstream maximum (1000). Listings that need a smaller
|
||||
// window still pass it explicitly; upload recovery keeps its own 100/page
|
||||
// budget instead of inheriting the reconciliation scan size.
|
||||
func validPage(page, pageSize int) bool {
|
||||
return page > 0 && pageSize > 0 && pageSize <= 100
|
||||
return page > 0 && pageSize > 0 && pageSize <= 1000
|
||||
}
|
||||
|
||||
func (c *Client) endpoint(path string) string {
|
||||
@@ -487,3 +490,14 @@ func (c *Client) decodeBody(resp *http.Response, target any) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// StatusCode returns the HTTP status carried by err, or 0.
|
||||
func StatusCode(err error) int {
|
||||
var httpErr *HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
return httpErr.StatusCode
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func IsNotFound(err error) bool { return StatusCode(err) == http.StatusNotFound }
|
||||
|
||||
@@ -336,6 +336,26 @@ func TestClientProvidesPaginatedInventoryChunkAndScopedSearchReads(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
// Acceptance #16: the reconciliation scan must be one 1000-per-page read, and
|
||||
// the wire query is the evidence — not just the constant passed to the interface.
|
||||
func TestListKnowledgeSendsScanPageSizeOnTheWire(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("page") != "1" || r.URL.Query().Get("page_size") != "1000" {
|
||||
t.Fatalf("knowledge list query = %s", r.URL.RawQuery)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"success":true,"data":[],"total":0,"page":1,"page_size":1000}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "test-api-key", Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := client.ListKnowledge(context.Background(), "kb-1", 1, 1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRejectsRedirectWithoutForwardingAPIKey(t *testing.T) {
|
||||
var targetHits atomic.Int32
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package weknora
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// KnowledgeBaseConsoleURL builds the console link for one knowledge base.
|
||||
// Reconciliation findings and the platform task drawer both use this rule: if
|
||||
// they drift, the same knowledge base opens at two different addresses, and the
|
||||
// 503 fallback link in one drawer points somewhere else than the other.
|
||||
// An empty origin or base id yields an empty link, which both callers treat as
|
||||
// "no link configured" rather than inventing a host.
|
||||
func KnowledgeBaseConsoleURL(origin, knowledgeBaseID string) string {
|
||||
origin, knowledgeBaseID = strings.TrimSpace(origin), strings.TrimSpace(knowledgeBaseID)
|
||||
if origin == "" || knowledgeBaseID == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSuffix(origin, "/") + "/platform/knowledge-bases/" + url.PathEscape(knowledgeBaseID)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package weknora
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestKnowledgeBaseConsoleURLCannotInventAHost(t *testing.T) {
|
||||
cases := []struct{ origin, kb, want string }{
|
||||
{"", "kb-1", ""},
|
||||
{"https://weknora.test", "", ""},
|
||||
{" ", "kb-1", ""},
|
||||
{"https://weknora.test/", "kb-1", "https://weknora.test/platform/knowledge-bases/kb-1"},
|
||||
{" https://weknora.test/ ", " kb-1 ", "https://weknora.test/platform/knowledge-bases/kb-1"},
|
||||
{"https://weknora.test/base", "kb 1", "https://weknora.test/base/platform/knowledge-bases/kb%201"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := KnowledgeBaseConsoleURL(c.origin, c.kb); got != c.want {
|
||||
t.Fatalf("KnowledgeBaseConsoleURL(%q,%q) = %q, want %q", c.origin, c.kb, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package weknora
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RuntimeClient is the platform-level, read-only SystemAdmin client. It is a
|
||||
// separate key from the tenant API key on purpose: capability
|
||||
// system_runtime_read belongs to the test instance, not to one tenant.
|
||||
type RuntimeClientConfig struct {
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Timeout time.Duration
|
||||
MaxResponseBytes int64
|
||||
AllowDockerHTTP bool
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
type RuntimeClient struct {
|
||||
baseURL *url.URL
|
||||
apiKey string
|
||||
httpClient *http.Client
|
||||
maxResponseBytes int64
|
||||
}
|
||||
|
||||
func NewRuntimeClient(config RuntimeClientConfig) (*RuntimeClient, error) {
|
||||
baseURL, err := url.Parse(strings.TrimSpace(config.BaseURL))
|
||||
if err != nil || baseURL.Scheme == "" || baseURL.Host == "" || baseURL.User != nil ||
|
||||
baseURL.RawQuery != "" || baseURL.Fragment != "" {
|
||||
return nil, errors.New("invalid WeKnora runtime base URL")
|
||||
}
|
||||
if !HTTPAllowed(config.BaseURL, HTTPPolicy{AllowPrivateHTTP: config.AllowPrivateHTTP, AllowDockerHTTP: config.AllowDockerHTTP}) {
|
||||
return nil, errors.New("WeKnora runtime base URL must use HTTPS")
|
||||
}
|
||||
if strings.TrimSpace(config.APIKey) == "" {
|
||||
return nil, errors.New("WeKnora runtime API key is required")
|
||||
}
|
||||
if config.Timeout <= 0 {
|
||||
return nil, errors.New("WeKnora runtime HTTP timeout must be positive")
|
||||
}
|
||||
if config.MaxResponseBytes <= 0 {
|
||||
config.MaxResponseBytes = defaultMaxResponseBytes
|
||||
}
|
||||
baseURL.Path = strings.TrimRight(baseURL.Path, "/")
|
||||
return &RuntimeClient{
|
||||
baseURL: baseURL,
|
||||
apiKey: config.APIKey,
|
||||
httpClient: &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
},
|
||||
maxResponseBytes: config.MaxResponseBytes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type RuntimeQueues struct {
|
||||
Available bool `json:"available"`
|
||||
QueuesError bool `json:"queues_error"`
|
||||
WorkersError bool `json:"workers_error"`
|
||||
Queues []RuntimeQueue `json:"queues"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
}
|
||||
|
||||
type RuntimeQueue struct {
|
||||
Name string `json:"name"`
|
||||
Pool string `json:"pool"`
|
||||
Pending int `json:"pending"`
|
||||
Active int `json:"active"`
|
||||
Scheduled int `json:"scheduled"`
|
||||
Retry int `json:"retry"`
|
||||
Archived int `json:"archived"`
|
||||
Processed int `json:"processed"`
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
|
||||
type RuntimeDocumentProgress struct {
|
||||
Document RuntimeDocument `json:"document"`
|
||||
Failures []RuntimeFailure `json:"failures"`
|
||||
HasMoreFailures bool `json:"has_more_failures"`
|
||||
}
|
||||
|
||||
type RuntimeDocument struct {
|
||||
ID string `json:"id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Title string `json:"title"`
|
||||
ParseStatus string `json:"parse_status"`
|
||||
IngestionStatus string `json:"ingestion_status"`
|
||||
WikiStatus string `json:"wiki_status"`
|
||||
Stages []RuntimeStage `json:"stages"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RuntimeStage struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
type RuntimeFailure struct {
|
||||
TaskType string `json:"task_type"`
|
||||
FailCount int `json:"fail_count"`
|
||||
FailedAt time.Time `json:"failed_at"`
|
||||
LastError string `json:"last_error"`
|
||||
}
|
||||
|
||||
func (c *RuntimeClient) Queues(ctx context.Context) (RuntimeQueues, error) {
|
||||
var response RuntimeQueues
|
||||
if err := c.get(ctx, "/api/v1/system/admin/runtime/queues", &response); err != nil {
|
||||
return RuntimeQueues{}, err
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (c *RuntimeClient) DocumentProgress(ctx context.Context, knowledgeID string) (RuntimeDocumentProgress, error) {
|
||||
if !validPathSegment(knowledgeID) || len(knowledgeID) > 64 {
|
||||
return RuntimeDocumentProgress{}, errors.New("invalid knowledge ID")
|
||||
}
|
||||
var envelope struct {
|
||||
Success bool `json:"success"`
|
||||
Data RuntimeDocumentProgress `json:"data"`
|
||||
}
|
||||
if err := c.get(ctx, "/api/v1/system/admin/runtime/documents/"+knowledgeID, &envelope); err != nil {
|
||||
return RuntimeDocumentProgress{}, err
|
||||
}
|
||||
if !envelope.Success {
|
||||
return RuntimeDocumentProgress{}, errors.New("WeKnora returned an unsuccessful document progress response")
|
||||
}
|
||||
return envelope.Data, nil
|
||||
}
|
||||
|
||||
func (c *RuntimeClient) get(ctx context.Context, path string, target any) error {
|
||||
endpoint := *c.baseURL
|
||||
endpoint.Path = strings.TrimRight(c.baseURL.Path, "/") + path
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
|
||||
if err != nil {
|
||||
return errors.New("create WeKnora runtime request")
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("X-API-Key", c.apiKey)
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send WeKnora runtime request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return &HTTPError{StatusCode: resp.StatusCode}
|
||||
}
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
|
||||
if err != nil {
|
||||
return errors.New("read WeKnora runtime response")
|
||||
}
|
||||
if int64(len(payload)) > c.maxResponseBytes {
|
||||
return errors.New("WeKnora runtime response exceeds size limit")
|
||||
}
|
||||
if err := json.Unmarshal(payload, target); err != nil {
|
||||
return errors.New("decode WeKnora runtime response")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -47,3 +47,42 @@ func ReadAPIKeyFile(path string) (string, error) {
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ReadRuntimeKeyFile reads the platform-level read-only key. Q7 fixes the
|
||||
// contract at mode 0400: unlike tenant keys (0600), this key must not be
|
||||
// readable by the process owner's group and never leaves the API process.
|
||||
func ReadRuntimeKeyFile(path string) (string, error) {
|
||||
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("open runtime key file: %w", err)
|
||||
}
|
||||
file := os.NewFile(uintptr(fd), "weknora-runtime-key")
|
||||
if file == nil {
|
||||
_ = syscall.Close(fd)
|
||||
return "", errors.New("open runtime key file: invalid file descriptor")
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("inspect runtime key file: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", errors.New("runtime key file must be a regular file")
|
||||
}
|
||||
if info.Mode().Perm() != 0o400 {
|
||||
return "", errors.New("runtime key file permissions must be 0400")
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(file, maxAPIKeyFileBytes+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read runtime key file: %w", err)
|
||||
}
|
||||
if len(body) > maxAPIKeyFileBytes {
|
||||
return "", errors.New("runtime key file is too large")
|
||||
}
|
||||
key := strings.TrimSpace(string(body))
|
||||
if key == "" {
|
||||
return "", errors.New("runtime key file is empty")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
@@ -53,3 +53,20 @@ func TestReadAPIKeyFileRejectsUnsafeInputsWithoutLeakingContent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadRuntimeKeyFileRequires0400(t *testing.T) {
|
||||
path := t.TempDir() + "/runtime-key"
|
||||
if err := os.WriteFile(path, []byte("runtime-secret\n"), 0o400); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, err := ReadRuntimeKeyFile(path)
|
||||
if err != nil || key != "runtime-secret" {
|
||||
t.Fatalf("key=%q err=%v", key, err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ReadRuntimeKeyFile(path); err == nil {
|
||||
t.Fatal("0600 runtime key must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,17 @@ type UploadRequest struct {
|
||||
|
||||
type Knowledge struct {
|
||||
ID string `json:"id"`
|
||||
TenantID uint64 `json:"tenant_id"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||
Title string `json:"title"`
|
||||
Source string `json:"source"`
|
||||
Channel string `json:"channel"`
|
||||
ParseStatus string `json:"parse_status"`
|
||||
StallState string `json:"stall_state"`
|
||||
EnableStatus string `json:"enable_status"`
|
||||
FileName string `json:"file_name"`
|
||||
FileType string `json:"file_type"`
|
||||
FolderPath string `json:"folder_path"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
FileHash string `json:"file_hash"`
|
||||
Metadata map[string]any `json:"metadata"`
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package reconciliation
|
||||
|
||||
import "knowledge-governance/internal/governance"
|
||||
|
||||
type verdict int
|
||||
|
||||
const (
|
||||
verdictSkip verdict = iota
|
||||
verdictConsistent
|
||||
verdictMismatch
|
||||
verdictStalled
|
||||
verdictDeleting
|
||||
)
|
||||
|
||||
// classify is the single 7x7 matrix. Rows are ledger vocabulary, columns are
|
||||
// normalized WeKnora parse_status. Unknown upstream values are rejected by the
|
||||
// caller before this function, so there is deliberately no "other" branch.
|
||||
func classify(ledger, upstream string) verdict {
|
||||
switch ledger {
|
||||
case "planned":
|
||||
if upstream == "deleting" {
|
||||
return verdictDeleting
|
||||
}
|
||||
return verdictMismatch
|
||||
case "pending":
|
||||
switch upstream {
|
||||
case "pending":
|
||||
return verdictConsistent
|
||||
case "deleting":
|
||||
return verdictDeleting
|
||||
default:
|
||||
return verdictMismatch
|
||||
}
|
||||
case "processing":
|
||||
switch upstream {
|
||||
case "processing":
|
||||
return verdictConsistent
|
||||
case "deleting":
|
||||
return verdictDeleting
|
||||
default:
|
||||
return verdictMismatch
|
||||
}
|
||||
case "finalizing":
|
||||
switch upstream {
|
||||
case "finalizing":
|
||||
return verdictConsistent
|
||||
case "deleting":
|
||||
return verdictDeleting
|
||||
default:
|
||||
return verdictMismatch
|
||||
}
|
||||
case "completed":
|
||||
switch upstream {
|
||||
case "completed":
|
||||
return verdictConsistent
|
||||
case "deleting":
|
||||
return verdictDeleting
|
||||
default:
|
||||
return verdictMismatch
|
||||
}
|
||||
case "failed":
|
||||
switch upstream {
|
||||
case "failed":
|
||||
return verdictConsistent
|
||||
case "deleting":
|
||||
return verdictDeleting
|
||||
default:
|
||||
return verdictMismatch
|
||||
}
|
||||
case "stalled":
|
||||
switch upstream {
|
||||
case "completed":
|
||||
return verdictMismatch
|
||||
case "deleting":
|
||||
return verdictDeleting
|
||||
default:
|
||||
return verdictStalled
|
||||
}
|
||||
case "cancelled":
|
||||
switch upstream {
|
||||
case "cancelled":
|
||||
return verdictConsistent
|
||||
case "deleting":
|
||||
return verdictDeleting
|
||||
default:
|
||||
return verdictMismatch
|
||||
}
|
||||
default:
|
||||
return verdictSkip
|
||||
}
|
||||
}
|
||||
|
||||
// AllowedWriteback is the only writeback migration table. completed cannot be
|
||||
// downgraded; planned is not a target; cancelled/deleting have no ledger
|
||||
// counterpart.
|
||||
func AllowedWriteback(current, target string) bool {
|
||||
switch current {
|
||||
case "pending":
|
||||
return target == "processing" || target == "finalizing" || target == "completed" || target == "failed"
|
||||
case "processing":
|
||||
return target == "finalizing" || target == "completed" || target == "failed"
|
||||
case "finalizing":
|
||||
return target == "completed" || target == "failed"
|
||||
case "failed":
|
||||
return target == "pending" || target == "processing" || target == "completed"
|
||||
case "stalled":
|
||||
return target == "pending" || target == "processing" || target == "failed"
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeParseStatus(status string) (string, bool) {
|
||||
return governance.NormalizeWeKnoraParseStatus(status)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
type RuntimeConfig struct {
|
||||
BaseURL func(context.Context) string
|
||||
APIKey string
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
AllowPrivateHTTP bool
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type RuntimeProvider struct {
|
||||
baseURL func(context.Context) string
|
||||
apiKey string
|
||||
timeout time.Duration
|
||||
allowDockerHTTP bool
|
||||
allowPrivateHTTP bool
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewRuntimeProvider(config RuntimeConfig) *RuntimeProvider {
|
||||
if config.Now == nil {
|
||||
config.Now = time.Now
|
||||
}
|
||||
return &RuntimeProvider{
|
||||
baseURL: config.BaseURL, apiKey: strings.TrimSpace(config.APIKey), timeout: config.Timeout,
|
||||
allowDockerHTTP: config.AllowDockerHTTP, allowPrivateHTTP: config.AllowPrivateHTTP, now: config.Now,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Available() bool {
|
||||
return p != nil && p.apiKey != "" && p.baseURL != nil
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) client(ctx context.Context) (*weknora.RuntimeClient, error) {
|
||||
if !p.Available() {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
baseURL := strings.TrimSpace(p.baseURL(ctx))
|
||||
if baseURL == "" {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
client, err := weknora.NewRuntimeClient(weknora.RuntimeClientConfig{
|
||||
BaseURL: baseURL,
|
||||
APIKey: p.apiKey,
|
||||
Timeout: p.timeout,
|
||||
AllowDockerHTTP: p.allowDockerHTTP,
|
||||
AllowPrivateHTTP: p.allowPrivateHTTP,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) Queues(ctx context.Context) (*governance.WeKnoraQueueSummary, error) {
|
||||
client, err := p.client(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The overview must not hang for the full business timeout just because the
|
||||
// queue endpoint is slow; a short probe is enough to decide null vs data.
|
||||
queueCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
queues, err := client.Queues(queueCtx)
|
||||
if err != nil {
|
||||
return nil, ErrRuntimeUnavailable
|
||||
}
|
||||
summary := &governance.WeKnoraQueueSummary{
|
||||
Available: queues.Available, QueuesError: queues.QueuesError, WorkersError: queues.WorkersError,
|
||||
Queues: make([]governance.WeKnoraQueue, 0, len(queues.Queues)), Timestamp: queues.Timestamp,
|
||||
}
|
||||
for _, queue := range queues.Queues {
|
||||
summary.Queues = append(summary.Queues, governance.WeKnoraQueue{
|
||||
Name: queue.Name, Pool: queue.Pool, Pending: queue.Pending, Active: queue.Active,
|
||||
Scheduled: queue.Scheduled, Retry: queue.Retry, Archived: queue.Archived,
|
||||
Processed: queue.Processed, Failed: queue.Failed,
|
||||
})
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func (p *RuntimeProvider) DocumentProgress(ctx context.Context, documentID string) (governance.ReconciliationProgress, error) {
|
||||
client, err := p.client(ctx)
|
||||
if err != nil {
|
||||
return governance.ReconciliationProgress{}, err
|
||||
}
|
||||
detail, err := client.DocumentProgress(ctx, documentID)
|
||||
if err != nil {
|
||||
if weknora.IsNotFound(err) {
|
||||
return governance.ReconciliationProgress{}, err
|
||||
}
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
}
|
||||
progress := governance.ReconciliationProgress{
|
||||
DocumentID: detail.Document.ID, ParseStatus: detail.Document.ParseStatus,
|
||||
IngestionStatus: detail.Document.IngestionStatus, WikiStatus: detail.Document.WikiStatus,
|
||||
HasMoreFailures: detail.HasMoreFailures, ObservedAt: p.now().UTC(),
|
||||
Stages: make([]governance.ReconciliationStage, 0, len(detail.Document.Stages)),
|
||||
Failures: make([]governance.ReconciliationFailure, 0, len(detail.Failures)),
|
||||
}
|
||||
if progress.DocumentID == "" {
|
||||
progress.DocumentID = documentID
|
||||
}
|
||||
for _, stage := range detail.Document.Stages {
|
||||
progress.Stages = append(progress.Stages, governance.ReconciliationStage{
|
||||
Name: stage.Name, Status: stage.Status, ErrorCode: stage.ErrorCode, FinishedAt: stage.FinishedAt,
|
||||
})
|
||||
}
|
||||
for _, failure := range detail.Failures {
|
||||
progress.Failures = append(progress.Failures, governance.ReconciliationFailure{
|
||||
TaskType: failure.TaskType, FailCount: failure.FailCount, FailedAt: failure.FailedAt,
|
||||
LastError: truncateRunes(failure.LastError, 500),
|
||||
})
|
||||
}
|
||||
return progress, nil
|
||||
}
|
||||
|
||||
func truncateRunes(value string, limit int) string {
|
||||
if limit <= 0 {
|
||||
return ""
|
||||
}
|
||||
runes := []rune(value)
|
||||
if len(runes) <= limit {
|
||||
return value
|
||||
}
|
||||
return string(runes[:limit])
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
func TestRuntimeProviderMapsQueuesAndTruncatesFailures(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-Key") != "runtime-key" {
|
||||
t.Fatalf("missing runtime key header")
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/system/admin/runtime/queues":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"available": true, "queues_error": false, "workers_error": false, "timestamp": 7,
|
||||
"queues": []map[string]any{{"name": "default", "pool": "core", "pending": 3, "active": 1, "failed": 2}},
|
||||
})
|
||||
case "/api/v1/system/admin/runtime/documents/doc-1":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{
|
||||
"document": map[string]any{"id": "doc-1", "parse_status": "failed", "ingestion_status": "failed", "wiki_status": "none",
|
||||
"stages": []map[string]any{{"name": "parse", "status": "failed", "error_code": "x"}}},
|
||||
"failures": []map[string]any{{"task_type": "parse", "fail_count": 2, "failed_at": "2026-12-01T00:00:00Z", "last_error": strings.Repeat("错", 600)}},
|
||||
"has_more_failures": false,
|
||||
}})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
})
|
||||
queues, err := provider.Queues(context.Background())
|
||||
if err != nil || !queues.Available || len(queues.Queues) != 1 || queues.Queues[0].Pending != 3 {
|
||||
t.Fatalf("queues=%#v err=%v", queues, err)
|
||||
}
|
||||
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
|
||||
if err != nil || progress.ParseStatus != "failed" || progress.DocumentID != "doc-1" || len(progress.Stages) != 1 {
|
||||
t.Fatalf("progress=%#v err=%v", progress, err)
|
||||
}
|
||||
if len([]rune(progress.Failures[0].LastError)) != 500 {
|
||||
t.Fatalf("last_error runes = %d", len([]rune(progress.Failures[0].LastError)))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeProviderUnavailableAndNotFound(t *testing.T) {
|
||||
unavailable := NewRuntimeProvider(RuntimeConfig{BaseURL: func(context.Context) string { return "https://example.test" }})
|
||||
if _, err := unavailable.Queues(context.Background()); !errors.Is(err, ErrRuntimeUnavailable) {
|
||||
t.Fatalf("unconfigured queues err=%v", err)
|
||||
}
|
||||
server := httptest.NewServer(http.NotFoundHandler())
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
})
|
||||
if _, err := provider.DocumentProgress(context.Background(), "missing"); err == nil || weknora.StatusCode(err) != 404 {
|
||||
t.Fatalf("missing document err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The progress passthrough is a projection, not a proxy: whatever extra fields
|
||||
// the platform endpoint returns (keys, authorization headers, token echoes) must
|
||||
// never reach the browser. This guards the shape if someone later switches to
|
||||
// forwarding the upstream body.
|
||||
func TestRuntimeProviderDropsSensitiveUpstreamFields(t *testing.T) {
|
||||
const secret = "leak-sentinel"
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{
|
||||
"document": map[string]any{
|
||||
"id": "doc-1", "parse_status": "completed", "ingestion_status": "completed", "wiki_status": "none",
|
||||
"api_key": secret, "apiKey": secret, "authorization": "Bearer " + secret,
|
||||
"headers": map[string]any{"X-API-Key": secret},
|
||||
},
|
||||
"failures": []map[string]any{},
|
||||
"has_more_failures": false,
|
||||
"api_key": secret,
|
||||
}})
|
||||
}))
|
||||
defer server.Close()
|
||||
provider := NewRuntimeProvider(RuntimeConfig{
|
||||
BaseURL: func(context.Context) string { return server.URL },
|
||||
APIKey: "runtime-key", Timeout: 5 * time.Second,
|
||||
})
|
||||
progress, err := provider.DocumentProgress(context.Background(), "doc-1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload, err := json.Marshal(progress)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(payload), secret) || strings.Contains(string(payload), "Bearer ") {
|
||||
t.Fatalf("progress leaked upstream credentials: %s", payload)
|
||||
}
|
||||
if progress.DocumentID != "doc-1" || progress.ParseStatus != "completed" {
|
||||
t.Fatalf("projection dropped real fields: %#v", progress)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
const scanPageSize = 1000
|
||||
|
||||
type confirmResult struct {
|
||||
item weknora.Knowledge
|
||||
notFound bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *Service) scanKnowledge(ctx context.Context, kbID string) ([]weknora.Knowledge, error) {
|
||||
seen := make(map[string]bool)
|
||||
out := make([]weknora.Knowledge, 0)
|
||||
for page := 1; page <= 10000; page++ {
|
||||
items, total, err := s.remote.ListKnowledge(ctx, kbID, page, scanPageSize)
|
||||
if err != nil {
|
||||
return nil, ErrRemoteFailed
|
||||
}
|
||||
added := 0
|
||||
for _, item := range items {
|
||||
if item.ID == "" {
|
||||
return nil, ErrRemoteFailed
|
||||
}
|
||||
if item.KnowledgeBaseID != "" && item.KnowledgeBaseID != kbID {
|
||||
return nil, ErrRemoteFailed
|
||||
}
|
||||
if seen[item.ID] {
|
||||
continue
|
||||
}
|
||||
seen[item.ID] = true
|
||||
out = append(out, item)
|
||||
added++
|
||||
}
|
||||
if len(items) == 0 || added == 0 {
|
||||
break
|
||||
}
|
||||
if total > 0 {
|
||||
if int64(len(seen)) >= total {
|
||||
break
|
||||
}
|
||||
// Keep paging even if the instance returned a smaller page than
|
||||
// requested; only the reported total ends the scan.
|
||||
continue
|
||||
}
|
||||
if len(items) < scanPageSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// confirmAll performs the "先确认再判缺" single reads. The scan phase itself is
|
||||
// strictly serial; only this stage may use the configured concurrency.
|
||||
func (s *Service) confirmAll(ctx context.Context, kbID string, ids []string) map[string]confirmResult {
|
||||
results := make(map[string]confirmResult, len(ids))
|
||||
if len(ids) == 0 {
|
||||
return results
|
||||
}
|
||||
type outcome struct {
|
||||
id string
|
||||
result confirmResult
|
||||
}
|
||||
jobs := make(chan string)
|
||||
outcomes := make(chan outcome, len(ids))
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
workers := s.confirmConcurrency
|
||||
if workers > len(ids) {
|
||||
workers = len(ids)
|
||||
}
|
||||
var wait sync.WaitGroup
|
||||
for i := 0; i < workers; i++ {
|
||||
wait.Add(1)
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
for id := range jobs {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
item, err := s.remote.GetKnowledge(ctx, id)
|
||||
result := confirmResult{item: item, err: err}
|
||||
if weknora.IsNotFound(err) {
|
||||
result = confirmResult{notFound: true}
|
||||
} else if err == nil && item.KnowledgeBaseID != "" && item.KnowledgeBaseID != kbID {
|
||||
result = confirmResult{err: ErrRemoteFailed}
|
||||
}
|
||||
select {
|
||||
case outcomes <- outcome{id: id, result: result}:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
go func() {
|
||||
defer close(jobs)
|
||||
for _, id := range ids {
|
||||
select {
|
||||
case jobs <- id:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
wait.Wait()
|
||||
close(outcomes)
|
||||
}()
|
||||
for outcome := range outcomes {
|
||||
results[outcome.id] = outcome.result
|
||||
if outcome.result.err != nil {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
func (s *Service) buildFindings(ctx context.Context, run governance.ReconciliationRun, ledger []governance.ReconciliationLedgerRow, items []weknora.Knowledge, overlapped bool) ([]governance.ReconciliationFinding, error) {
|
||||
byID := make(map[string]weknora.Knowledge, len(items))
|
||||
ledgerByPublication := make(map[string]governance.ReconciliationLedgerRow, len(ledger))
|
||||
ledgerByKnowledge := make(map[string]governance.ReconciliationLedgerRow, len(ledger))
|
||||
for _, item := range items {
|
||||
byID[item.ID] = item
|
||||
}
|
||||
for _, row := range ledger {
|
||||
ledgerByPublication[row.PublicationID] = row
|
||||
if row.KnowledgeID != "" {
|
||||
if _, exists := ledgerByKnowledge[row.KnowledgeID]; !exists {
|
||||
ledgerByKnowledge[row.KnowledgeID] = row
|
||||
}
|
||||
}
|
||||
}
|
||||
findings := make([]governance.ReconciliationFinding, 0, len(ledger)+len(items)/10)
|
||||
add := func(finding governance.ReconciliationFinding) {
|
||||
finding.RunID = run.ID
|
||||
if finding.ConfirmationState == "" {
|
||||
finding.ConfirmationState = "confirmed"
|
||||
}
|
||||
finding.ActionState = "open"
|
||||
finding.ID = deterministicFindingID(run.ID, finding)
|
||||
if finding.WeKnoraURL == "" && s.weKnoraWebBase != nil {
|
||||
finding.WeKnoraURL = weknora.KnowledgeBaseConsoleURL(s.weKnoraWebBase(ctx), run.KBID)
|
||||
}
|
||||
findings = append(findings, finding)
|
||||
}
|
||||
|
||||
// R1: expected live but absent from the full listing. A list miss is not
|
||||
// evidence; only a single GET 404 is.
|
||||
missing := make([]string, 0)
|
||||
seenMissing := map[string]bool{}
|
||||
for _, row := range ledger {
|
||||
if !expectedLive(row) {
|
||||
continue
|
||||
}
|
||||
if _, ok := byID[row.KnowledgeID]; ok {
|
||||
continue
|
||||
}
|
||||
if !seenMissing[row.KnowledgeID] {
|
||||
seenMissing[row.KnowledgeID] = true
|
||||
missing = append(missing, row.KnowledgeID)
|
||||
}
|
||||
}
|
||||
confirmations := s.confirmAll(ctx, run.KBID, missing)
|
||||
for _, row := range ledger {
|
||||
if !expectedLive(row) {
|
||||
continue
|
||||
}
|
||||
if _, ok := byID[row.KnowledgeID]; ok {
|
||||
continue
|
||||
}
|
||||
result, ok := confirmations[row.KnowledgeID]
|
||||
if !ok {
|
||||
return nil, ErrRemoteFailed
|
||||
}
|
||||
if result.err != nil {
|
||||
return nil, ErrRemoteFailed
|
||||
}
|
||||
if result.notFound {
|
||||
confirmation := "confirmed"
|
||||
if overlapped {
|
||||
confirmation = "pending"
|
||||
}
|
||||
add(governance.ReconciliationFinding{
|
||||
Type: "R1", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
|
||||
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
|
||||
LedgerState: row.ProcessingState, LedgerSHA256: row.SHA256,
|
||||
EvidenceLevel: "none", ConfirmationState: confirmation, SuggestedAction: "requeue_upload",
|
||||
Detail: "台账认为应在库,单条读取返回 404",
|
||||
})
|
||||
continue
|
||||
}
|
||||
// The row exists but the list hid it (deleting). Use it for matrix checks.
|
||||
byID[row.KnowledgeID] = result.item
|
||||
}
|
||||
|
||||
// R2: governance-imported item with no current ledger row pointing at it.
|
||||
orphans := make([]weknora.Knowledge, 0)
|
||||
orphanIDs := make([]string, 0)
|
||||
for _, item := range items {
|
||||
if item.Channel != "governance" {
|
||||
continue
|
||||
}
|
||||
publicationID := metadataString(item.Metadata, "publication_id")
|
||||
if publicationID != "" {
|
||||
if _, ok := ledgerByPublication[publicationID]; ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, ok := ledgerByKnowledge[item.ID]; ok {
|
||||
continue
|
||||
}
|
||||
orphans = append(orphans, item)
|
||||
orphanIDs = append(orphanIDs, item.ID)
|
||||
}
|
||||
orphanConfirmations := s.confirmAll(ctx, run.KBID, orphanIDs)
|
||||
for _, item := range orphans {
|
||||
result, ok := orphanConfirmations[item.ID]
|
||||
if !ok {
|
||||
return nil, ErrRemoteFailed
|
||||
}
|
||||
if result.err != nil {
|
||||
return nil, ErrRemoteFailed
|
||||
}
|
||||
if result.notFound || result.item.ParseStatus == "deleting" {
|
||||
continue
|
||||
}
|
||||
publicationID := metadataString(item.Metadata, "publication_id")
|
||||
if publicationID != "" {
|
||||
if _, ok := ledgerByPublication[publicationID]; ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, ok := ledgerByKnowledge[item.ID]; ok {
|
||||
continue
|
||||
}
|
||||
confirmation := "confirmed"
|
||||
if overlapped {
|
||||
confirmation = "pending"
|
||||
}
|
||||
add(governance.ReconciliationFinding{
|
||||
Type: "R2", PublicationID: publicationID, DocumentID: item.ID,
|
||||
Title: item.Title, Path: item.FolderPath, Source: item.Source, TargetScope: "unknown",
|
||||
WeKnoraParseState: item.ParseStatus, NormalizedState: item.ParseStatus,
|
||||
WeKnoraFileMD5: normalizeMD5(item.FileHash), EvidenceLevel: "none",
|
||||
ConfirmationState: confirmation, SuggestedAction: "remove_from_test",
|
||||
Detail: "库内平台导入条目没有现行台账行指向它",
|
||||
})
|
||||
}
|
||||
|
||||
// R3: not imported by the platform.
|
||||
for _, item := range items {
|
||||
if item.Channel == "governance" {
|
||||
continue
|
||||
}
|
||||
add(governance.ReconciliationFinding{
|
||||
Type: "R3", DocumentID: item.ID, Title: item.Title, Path: item.FolderPath,
|
||||
Source: item.Source, TargetScope: "unknown", WeKnoraParseState: item.ParseStatus,
|
||||
NormalizedState: item.ParseStatus, WeKnoraFileMD5: normalizeMD5(item.FileHash),
|
||||
EvidenceLevel: "none", SuggestedAction: "none", Detail: "非平台导入条目,仅统计",
|
||||
})
|
||||
}
|
||||
|
||||
removal, err := s.store.ListReconciliationRemovalCandidates(ctx, run.KBID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
removalByPublication := make(map[string]bool, len(removal))
|
||||
for _, row := range removal {
|
||||
removalByPublication[row.PublicationID] = true
|
||||
}
|
||||
|
||||
for _, row := range ledger {
|
||||
if !expectedLive(row) {
|
||||
continue
|
||||
}
|
||||
item, ok := byID[row.KnowledgeID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
upstream, known := normalizeParseStatus(item.ParseStatus)
|
||||
if !known {
|
||||
return nil, fmt.Errorf("unsupported WeKnora parse status %q", item.ParseStatus)
|
||||
}
|
||||
normalized := upstream
|
||||
if item.ParseStatus == "deleting" {
|
||||
if age(run.StartedAt, item.UpdatedAt) > s.stallAfter {
|
||||
add(r7Finding(row, item, "删除超过阈值仍未完成"))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if finding, ok := s.r4Finding(row, item, normalized); ok {
|
||||
add(finding)
|
||||
}
|
||||
if removalByPublication[row.PublicationID] && item.ParseStatus == "completed" {
|
||||
add(governance.ReconciliationFinding{
|
||||
Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
|
||||
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
|
||||
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
|
||||
LedgerSHA256: row.SHA256, EvidenceLevel: "none", SuggestedAction: "enter_removal",
|
||||
Detail: "来源已判禁止导入,条目仍在测试库可检索",
|
||||
})
|
||||
}
|
||||
if row.ProcessingState == "cancelled" {
|
||||
if normalized != "cancelled" && ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) >= s.grace {
|
||||
add(r5Finding(row, item, normalized, "none", "台账已取消,WeKnora 仍有活动状态"))
|
||||
}
|
||||
continue
|
||||
}
|
||||
verdict := classify(row.ProcessingState, normalized)
|
||||
stuckAge := ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt)
|
||||
switch verdict {
|
||||
case verdictStalled:
|
||||
add(r7Finding(row, item, "台账或上游已判定停滞"))
|
||||
case verdictDeleting:
|
||||
if age(run.StartedAt, item.UpdatedAt) > s.stallAfter {
|
||||
add(r7Finding(row, item, "删除超过阈值仍未完成"))
|
||||
}
|
||||
case verdictMismatch:
|
||||
if (normalized == "pending" || normalized == "processing" || normalized == "finalizing") && stuckAge > s.stallAfter {
|
||||
add(r7Finding(row, item, "超过阈值没有进展"))
|
||||
continue
|
||||
}
|
||||
if item.StallState == "stalled" {
|
||||
add(r7Finding(row, item, "WeKnora 判定停滞"))
|
||||
continue
|
||||
}
|
||||
if ageFromPointer(run.StartedAt, row.ProcessingStartedAt, row.UpdatedAt) < s.grace {
|
||||
continue
|
||||
}
|
||||
action := "writeback_state"
|
||||
if !AllowedWriteback(row.ProcessingState, normalized) {
|
||||
action = "none"
|
||||
}
|
||||
add(r5Finding(row, item, normalized, action, ""))
|
||||
case verdictConsistent:
|
||||
if item.StallState == "stalled" {
|
||||
add(r7Finding(row, item, "WeKnora 判定停滞"))
|
||||
} else if (normalized == "pending" || normalized == "processing") && stuckAge > s.stallAfter {
|
||||
add(r7Finding(row, item, "超过阈值没有进展"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// R8: one publication id maps to more than one live row.
|
||||
grouped := make(map[string][]weknora.Knowledge)
|
||||
for _, item := range items {
|
||||
if item.Channel != "governance" || item.ParseStatus == "failed" || item.ParseStatus == "deleting" {
|
||||
continue
|
||||
}
|
||||
publicationID := metadataString(item.Metadata, "publication_id")
|
||||
if publicationID == "" {
|
||||
continue
|
||||
}
|
||||
grouped[publicationID] = append(grouped[publicationID], item)
|
||||
}
|
||||
for publicationID, group := range grouped {
|
||||
if len(group) < 2 {
|
||||
continue
|
||||
}
|
||||
first := group[0]
|
||||
add(governance.ReconciliationFinding{
|
||||
Type: "R8", PublicationID: publicationID, DocumentID: first.ID,
|
||||
Title: first.Title, Path: first.FolderPath, Source: first.Source, TargetScope: "unknown",
|
||||
WeKnoraParseState: first.ParseStatus, NormalizedState: first.ParseStatus,
|
||||
WeKnoraFileMD5: normalizeMD5(first.FileHash), EvidenceLevel: "none", SuggestedAction: "none",
|
||||
Detail: fmt.Sprintf("同一台账发布标识对应 %d 条存活条目", len(group)),
|
||||
})
|
||||
}
|
||||
|
||||
sort.Slice(findings, func(i, j int) bool {
|
||||
if findings[i].Type != findings[j].Type {
|
||||
return findings[i].Type < findings[j].Type
|
||||
}
|
||||
if findings[i].PublicationID != findings[j].PublicationID {
|
||||
return findings[i].PublicationID < findings[j].PublicationID
|
||||
}
|
||||
return findings[i].DocumentID < findings[j].DocumentID
|
||||
})
|
||||
return findings, nil
|
||||
}
|
||||
|
||||
func (s *Service) r4Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, normalized string) (governance.ReconciliationFinding, bool) {
|
||||
declared := strings.ToLower(strings.TrimSpace(metadataString(item.Metadata, "content_sha256")))
|
||||
ledgerSHA := strings.ToLower(strings.TrimSpace(row.SHA256))
|
||||
uploadMD5 := normalizeMD5(row.UploadMD5)
|
||||
fileMD5 := normalizeMD5(item.FileHash)
|
||||
evidence := "none"
|
||||
if declared != "" && ledgerSHA != "" {
|
||||
evidence = "declared_only"
|
||||
if uploadMD5 != "" && fileMD5 != "" {
|
||||
evidence = "independent"
|
||||
}
|
||||
}
|
||||
if evidence == "none" {
|
||||
return governance.ReconciliationFinding{}, false
|
||||
}
|
||||
mismatch := declared != ledgerSHA
|
||||
if evidence == "independent" && uploadMD5 != fileMD5 {
|
||||
mismatch = true
|
||||
}
|
||||
if !mismatch {
|
||||
return governance.ReconciliationFinding{}, false
|
||||
}
|
||||
return governance.ReconciliationFinding{
|
||||
Type: "R4", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
|
||||
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
|
||||
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
|
||||
LedgerSHA256: ledgerSHA, DeclaredSHA256: declared, WeKnoraFileMD5: fileMD5,
|
||||
EvidenceLevel: evidence, SuggestedAction: "requeue_upload",
|
||||
Detail: "库内内容摘要与台账现行版本不一致",
|
||||
}, true
|
||||
}
|
||||
|
||||
func r5Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, normalized, action, detail string) governance.ReconciliationFinding {
|
||||
if detail == "" {
|
||||
detail = fmt.Sprintf("台账状态 %s 与 WeKnora %s 不一致,已超过宽限期", row.ProcessingState, normalized)
|
||||
}
|
||||
return governance.ReconciliationFinding{
|
||||
Type: "R5", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
|
||||
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
|
||||
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus, NormalizedState: normalized,
|
||||
LedgerSHA256: row.SHA256, EvidenceLevel: "none", SuggestedAction: action, Detail: detail,
|
||||
}
|
||||
}
|
||||
|
||||
func r7Finding(row governance.ReconciliationLedgerRow, item weknora.Knowledge, detail string) governance.ReconciliationFinding {
|
||||
return governance.ReconciliationFinding{
|
||||
Type: "R7", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID,
|
||||
Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope,
|
||||
LedgerState: row.ProcessingState, WeKnoraParseState: item.ParseStatus,
|
||||
NormalizedState: item.ParseStatus, LedgerSHA256: row.SHA256, EvidenceLevel: "none",
|
||||
SuggestedAction: "none", Detail: detail,
|
||||
}
|
||||
}
|
||||
|
||||
func expectedLive(row governance.ReconciliationLedgerRow) bool {
|
||||
return row.KnowledgeID != "" && row.ProcessingState != "failed" &&
|
||||
row.RetrievalState != "disabling" && row.RetrievalState != "disabled"
|
||||
}
|
||||
|
||||
func age(startedAt, updatedAt time.Time) time.Duration {
|
||||
if updatedAt.IsZero() || startedAt.Before(updatedAt) {
|
||||
return 0
|
||||
}
|
||||
return startedAt.Sub(updatedAt)
|
||||
}
|
||||
|
||||
func ageFromPointer(startedAt time.Time, processingStartedAt *time.Time, updatedAt time.Time) time.Duration {
|
||||
if processingStartedAt != nil && !processingStartedAt.IsZero() {
|
||||
return age(startedAt, *processingStartedAt)
|
||||
}
|
||||
return age(startedAt, updatedAt)
|
||||
}
|
||||
|
||||
func metadataString(metadata map[string]any, key string) string {
|
||||
value, _ := metadata[key].(string)
|
||||
return value
|
||||
}
|
||||
|
||||
func normalizeMD5(value string) string {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
if len(value) != 32 {
|
||||
return ""
|
||||
}
|
||||
for _, char := range value {
|
||||
if (char < '0' || char > '9') && (char < 'a' || char > 'f') {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func deterministicFindingID(runID string, finding governance.ReconciliationFinding) string {
|
||||
digest := sha256.Sum256([]byte(runID + "\x00" + finding.Type + "\x00" + finding.PublicationID + "\x00" + finding.DocumentID))
|
||||
return "rcf-" + hex.EncodeToString(digest[:])[:24]
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrRunInProgress = errors.New("reconciliation run in progress")
|
||||
ErrNotFound = errors.New("reconciliation record not found")
|
||||
ErrActionConflict = errors.New("reconciliation state or identity changed")
|
||||
ErrActionNotAllowed = errors.New("reconciliation action not allowed")
|
||||
ErrRemoteFailed = errors.New("reconciliation remote call failed")
|
||||
ErrRuntimeUnavailable = errors.New("weknora runtime read unavailable")
|
||||
)
|
||||
|
||||
type Store interface {
|
||||
ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error)
|
||||
ClaimReconciliationRun(context.Context, governance.ReconciliationRun, time.Time) (governance.ReconciliationRun, error)
|
||||
ClaimScheduledReconciliationRun(context.Context, governance.ReconciliationRun, time.Time, time.Time) (governance.ReconciliationRun, bool, error)
|
||||
LoadReconciliationRun(context.Context, string) (governance.ReconciliationRun, error)
|
||||
ListReconciliationRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error)
|
||||
ListReconciliationFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error)
|
||||
GetReconciliationFinding(context.Context, string) (governance.ReconciliationFinding, error)
|
||||
LoadReconciliationLedger(context.Context, string) ([]governance.ReconciliationLedgerRow, error)
|
||||
LoadPreviousReconciliationCounts(context.Context, string, time.Time) (governance.ReconciliationCounts, bool, error)
|
||||
CompleteReconciliationRun(context.Context, governance.ReconciliationRun, []governance.ReconciliationFinding) error
|
||||
FailReconciliationRun(context.Context, string, string, time.Time) error
|
||||
CleanupReconciliationFindings(context.Context, time.Time, int, time.Duration) error
|
||||
LibraryJobsActive(context.Context) (bool, error)
|
||||
ListReconciliationRemovalCandidates(context.Context, string) ([]governance.ReconciliationLedgerRow, error)
|
||||
LoadReconciliationActionView(context.Context, string) (governance.ReconciliationActionView, error)
|
||||
ReconciliationOrphanStillUnowned(context.Context, string, string) (bool, error)
|
||||
WritebackReconciliationFinding(context.Context, string, string, string, string, time.Time) (governance.ReconciliationFinding, error)
|
||||
RequeueReconciliationPublication(context.Context, string, string, string, string, time.Time) (string, error)
|
||||
MarkReconciliationOrphanRemoved(context.Context, string, string, string, time.Time) error
|
||||
}
|
||||
|
||||
type Remote interface {
|
||||
BeginTask(context.Context, string) (context.Context, weknora.InstanceIdentity, error)
|
||||
ListKnowledge(context.Context, string, int, int) ([]weknora.Knowledge, int64, error)
|
||||
GetKnowledge(context.Context, string) (weknora.Knowledge, error)
|
||||
DeleteKnowledge(context.Context, string) error
|
||||
}
|
||||
|
||||
type Runtime interface {
|
||||
DocumentProgress(context.Context, string) (governance.ReconciliationProgress, error)
|
||||
}
|
||||
|
||||
type Queue interface {
|
||||
Enqueue(context.Context, jobs.EnqueueRequest, time.Time) (*jobs.Job, error)
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Store Store
|
||||
Remote Remote
|
||||
Runtime Runtime
|
||||
Queue Queue
|
||||
Now func() time.Time
|
||||
Grace time.Duration
|
||||
StallAfter time.Duration
|
||||
StaleAfter time.Duration
|
||||
ConfirmConcurrency int
|
||||
KeepRuns int
|
||||
MaxAge time.Duration
|
||||
// WeKnoraWebBase resolves the WeKnora origin used to build the finding's
|
||||
// jump link. Empty or nil leaves weknora_url empty, which the contract allows.
|
||||
WeKnoraWebBase func(context.Context) string
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
store Store
|
||||
remote Remote
|
||||
runtime Runtime
|
||||
queue Queue
|
||||
now func() time.Time
|
||||
grace time.Duration
|
||||
stallAfter time.Duration
|
||||
staleAfter time.Duration
|
||||
confirmConcurrency int
|
||||
keepRuns int
|
||||
maxAge time.Duration
|
||||
weKnoraWebBase func(context.Context) string
|
||||
}
|
||||
|
||||
func New(config Config) (*Service, error) {
|
||||
if config.Store == nil || config.Remote == nil {
|
||||
return nil, errors.New("reconciliation store and remote client are required")
|
||||
}
|
||||
if config.Now == nil {
|
||||
config.Now = time.Now
|
||||
}
|
||||
if config.Grace <= 0 {
|
||||
config.Grace = 30 * time.Minute
|
||||
}
|
||||
if config.StallAfter <= 0 {
|
||||
config.StallAfter = 2 * time.Hour
|
||||
}
|
||||
if config.StaleAfter <= 0 {
|
||||
config.StaleAfter = 6 * time.Hour
|
||||
}
|
||||
if config.ConfirmConcurrency < 1 {
|
||||
config.ConfirmConcurrency = 1
|
||||
}
|
||||
if config.ConfirmConcurrency > 8 {
|
||||
config.ConfirmConcurrency = 8
|
||||
}
|
||||
if config.KeepRuns < 1 {
|
||||
config.KeepRuns = 30
|
||||
}
|
||||
if config.MaxAge <= 0 {
|
||||
config.MaxAge = 90 * 24 * time.Hour
|
||||
}
|
||||
return &Service{
|
||||
store: config.Store, remote: config.Remote, runtime: config.Runtime, queue: config.Queue,
|
||||
now: config.Now, grace: config.Grace, stallAfter: config.StallAfter, staleAfter: config.StaleAfter,
|
||||
confirmConcurrency: config.ConfirmConcurrency, keepRuns: config.KeepRuns, maxAge: config.MaxAge,
|
||||
weKnoraWebBase: config.WeKnoraWebBase,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newID(prefix string) (string, error) {
|
||||
var value [16]byte
|
||||
if _, err := rand.Read(value[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return prefix + hex.EncodeToString(value[:]), nil
|
||||
}
|
||||
|
||||
func (s *Service) CreateRun(ctx context.Context, kbID, trigger string) (governance.ReconciliationRun, error) {
|
||||
if kbID == "" || len(kbID) > 255 {
|
||||
return governance.ReconciliationRun{}, errors.New("invalid test knowledge base")
|
||||
}
|
||||
now := s.now().UTC()
|
||||
if _, err := s.store.ReapStaleReconciliationRuns(ctx, now, s.staleAfter); err != nil {
|
||||
return governance.ReconciliationRun{}, err
|
||||
}
|
||||
id, err := newID("rec-")
|
||||
if err != nil {
|
||||
return governance.ReconciliationRun{}, err
|
||||
}
|
||||
run, err := s.store.ClaimReconciliationRun(ctx, governance.ReconciliationRun{
|
||||
ID: id, KBID: kbID, State: "running", Trigger: trigger, StartedAt: now,
|
||||
Counts: governance.ReconciliationCounts{},
|
||||
}, now)
|
||||
if err != nil {
|
||||
if errors.Is(err, postgresstore.ErrReconciliationRunInProgress) {
|
||||
return governance.ReconciliationRun{}, ErrRunInProgress
|
||||
}
|
||||
return governance.ReconciliationRun{}, err
|
||||
}
|
||||
if s.queue == nil {
|
||||
_ = s.store.FailReconciliationRun(ctx, id, "queue_unavailable", now)
|
||||
return governance.ReconciliationRun{}, errors.New("reconciliation queue is not configured")
|
||||
}
|
||||
if err := s.enqueueRun(ctx, run.ID, now); err != nil {
|
||||
_ = s.store.FailReconciliationRun(ctx, run.ID, "queue_unavailable", now)
|
||||
return governance.ReconciliationRun{}, err
|
||||
}
|
||||
return run, nil
|
||||
}
|
||||
|
||||
// ScheduleDue claims one scheduled batch per test KB per local day. The caller
|
||||
// computes `since` as today's configured wall-clock instant in the configured
|
||||
// timezone; this method only enforces the claim and enqueue.
|
||||
func (s *Service) ScheduleDue(ctx context.Context, kbIDs []string, since, now time.Time) (int, error) {
|
||||
if _, err := s.store.ReapStaleReconciliationRuns(ctx, now, s.staleAfter); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
created := 0
|
||||
seen := map[string]bool{}
|
||||
for _, kbID := range kbIDs {
|
||||
if kbID == "" || seen[kbID] {
|
||||
continue
|
||||
}
|
||||
seen[kbID] = true
|
||||
id, err := newID("rec-")
|
||||
if err != nil {
|
||||
return created, err
|
||||
}
|
||||
run, claimed, err := s.store.ClaimScheduledReconciliationRun(ctx, governance.ReconciliationRun{
|
||||
ID: id, KBID: kbID, State: "running", Trigger: "schedule", StartedAt: now,
|
||||
Counts: governance.ReconciliationCounts{},
|
||||
}, since, now)
|
||||
if err != nil {
|
||||
return created, err
|
||||
}
|
||||
if !claimed {
|
||||
continue
|
||||
}
|
||||
if err := s.enqueueRun(ctx, run.ID, now); err != nil {
|
||||
_ = s.store.FailReconciliationRun(ctx, run.ID, "queue_unavailable", now)
|
||||
return created, err
|
||||
}
|
||||
created++
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (s *Service) enqueueRun(ctx context.Context, runID string, now time.Time) error {
|
||||
if s.queue == nil {
|
||||
return errors.New("reconciliation queue is not configured")
|
||||
}
|
||||
payload, err := json.Marshal(map[string]string{"run_id": runID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.queue.Enqueue(ctx, jobs.EnqueueRequest{
|
||||
ID: "job-" + runID,
|
||||
Type: "reconciliation.run",
|
||||
Payload: payload,
|
||||
Priority: 5,
|
||||
AvailableAt: now,
|
||||
MaxAttempts: 1,
|
||||
IdempotencyKey: "reconciliation-run:" + runID,
|
||||
}, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Service) ExecuteRun(ctx context.Context, runID string) error {
|
||||
run, err := s.store.LoadReconciliationRun(ctx, runID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if run.State != "running" {
|
||||
return nil
|
||||
}
|
||||
finished := func(code string) error {
|
||||
if code == "" {
|
||||
return nil
|
||||
}
|
||||
return s.store.FailReconciliationRun(context.WithoutCancel(ctx), run.ID, code, s.now().UTC())
|
||||
}
|
||||
pinned, _, err := s.remote.BeginTask(ctx, run.KBID)
|
||||
if err != nil {
|
||||
return finished("remote_unavailable")
|
||||
}
|
||||
ledger, err := s.store.LoadReconciliationLedger(pinned, run.KBID)
|
||||
if err != nil {
|
||||
return finished("ledger_unavailable")
|
||||
}
|
||||
overlappedStart, err := s.store.LibraryJobsActive(pinned)
|
||||
if err != nil {
|
||||
return finished("overlap_check_failed")
|
||||
}
|
||||
items, err := s.scanKnowledge(pinned, run.KBID)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrRemoteFailed) {
|
||||
return finished("remote_scan_failed")
|
||||
}
|
||||
return finished("scan_failed")
|
||||
}
|
||||
overlappedEnd, err := s.store.LibraryJobsActive(pinned)
|
||||
if err != nil {
|
||||
return finished("overlap_check_failed")
|
||||
}
|
||||
overlapped := overlappedStart || overlappedEnd
|
||||
findings, err := s.buildFindings(pinned, run, ledger, items, overlapped)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrRemoteFailed) {
|
||||
return finished("remote_confirm_failed")
|
||||
}
|
||||
return finished("scan_failed")
|
||||
}
|
||||
previous, hasPrevious, err := s.store.LoadPreviousReconciliationCounts(pinned, run.KBID, run.StartedAt)
|
||||
if err != nil {
|
||||
return finished("previous_counts_failed")
|
||||
}
|
||||
counts := governance.ReconciliationCounts{}
|
||||
for _, finding := range findings {
|
||||
counts[finding.Type]++
|
||||
}
|
||||
run.Counts = counts.Normalize()
|
||||
if hasPrevious {
|
||||
run.PreviousCounts = previous
|
||||
}
|
||||
run.LedgerCount = len(ledger)
|
||||
run.KBCount = len(items)
|
||||
run.WindowOverlapped = overlapped
|
||||
finishedAt := s.now().UTC()
|
||||
run.FinishedAt = &finishedAt
|
||||
if err := s.store.CompleteReconciliationRun(pinned, run, findings); err != nil {
|
||||
return finished("complete_failed")
|
||||
}
|
||||
_ = s.store.CleanupReconciliationFindings(context.WithoutCancel(ctx), s.now().UTC(), s.keepRuns, s.maxAge)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) ListRuns(ctx context.Context, filter governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
|
||||
return s.store.ListReconciliationRuns(ctx, filter)
|
||||
}
|
||||
|
||||
func (s *Service) GetRun(ctx context.Context, id string) (governance.ReconciliationRun, error) {
|
||||
run, err := s.store.LoadReconciliationRun(ctx, id)
|
||||
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
|
||||
return governance.ReconciliationRun{}, ErrNotFound
|
||||
}
|
||||
return run, err
|
||||
}
|
||||
|
||||
func (s *Service) ListFindings(ctx context.Context, filter governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
|
||||
return s.store.ListReconciliationFindings(ctx, filter)
|
||||
}
|
||||
|
||||
func (s *Service) Progress(ctx context.Context, documentID string) (governance.ReconciliationProgress, error) {
|
||||
if s.runtime == nil {
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
}
|
||||
progress, err := s.runtime.DocumentProgress(ctx, documentID)
|
||||
switch {
|
||||
case err == nil:
|
||||
return progress, nil
|
||||
case weknora.StatusCode(err) == 404:
|
||||
return governance.ReconciliationProgress{}, ErrNotFound
|
||||
default:
|
||||
return governance.ReconciliationProgress{}, ErrRuntimeUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Writeback(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
|
||||
view, err := s.actionView(ctx, findingID)
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if view.Finding.ActionState == "done" {
|
||||
return view.Finding, nil
|
||||
}
|
||||
target := view.Finding.NormalizedState
|
||||
if view.Finding.Type != "R5" || !AllowedWriteback(view.Finding.LedgerState, target) {
|
||||
return governance.ReconciliationFinding{}, ErrActionNotAllowed
|
||||
}
|
||||
finding, err := s.store.WritebackReconciliationFinding(ctx, findingID, target, actor, trim(reason), s.now().UTC())
|
||||
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
|
||||
return governance.ReconciliationFinding{}, ErrActionConflict
|
||||
}
|
||||
return finding, err
|
||||
}
|
||||
|
||||
func (s *Service) Requeue(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
|
||||
view, err := s.actionView(ctx, findingID)
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if view.Finding.ActionState == "done" {
|
||||
return view.Finding, nil
|
||||
}
|
||||
if view.Finding.Type != "R1" && view.Finding.Type != "R4" {
|
||||
return governance.ReconciliationFinding{}, ErrActionNotAllowed
|
||||
}
|
||||
if view.Finding.DocumentID == "" {
|
||||
return governance.ReconciliationFinding{}, ErrActionConflict
|
||||
}
|
||||
item, getErr := s.remote.GetKnowledge(ctx, view.Finding.DocumentID)
|
||||
switch {
|
||||
case getErr == nil:
|
||||
if view.Finding.Type == "R1" {
|
||||
// R1 said 404; if it is back now, a human must decide again.
|
||||
return governance.ReconciliationFinding{}, ErrActionConflict
|
||||
}
|
||||
if item.KnowledgeBaseID != view.TestKBID {
|
||||
return governance.ReconciliationFinding{}, ErrActionConflict
|
||||
}
|
||||
// R4 must remove the stale object first. Only a successful delete (or
|
||||
// 404, handled below) allows the ledger reset.
|
||||
if err := s.remote.DeleteKnowledge(ctx, view.Finding.DocumentID); err != nil && !weknora.IsNotFound(err) {
|
||||
return governance.ReconciliationFinding{}, ErrRemoteFailed
|
||||
}
|
||||
case weknora.IsNotFound(getErr):
|
||||
// R1/R4 both proceed: the old object is already gone.
|
||||
default:
|
||||
return governance.ReconciliationFinding{}, ErrRemoteFailed
|
||||
}
|
||||
if _, err := s.store.RequeueReconciliationPublication(ctx, findingID, view.Finding.DocumentID, actor, trim(reason), s.now().UTC()); err != nil {
|
||||
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
|
||||
return governance.ReconciliationFinding{}, ErrActionConflict
|
||||
}
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
return s.reloadFinding(ctx, findingID)
|
||||
}
|
||||
|
||||
func (s *Service) Remove(ctx context.Context, findingID, actor, reason string) (governance.ReconciliationFinding, error) {
|
||||
view, err := s.actionView(ctx, findingID)
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if view.Finding.ActionState == "done" {
|
||||
return view.Finding, nil
|
||||
}
|
||||
if view.Finding.Type != "R2" || view.Finding.DocumentID == "" {
|
||||
return governance.ReconciliationFinding{}, ErrActionNotAllowed
|
||||
}
|
||||
orphan, err := s.store.ReconciliationOrphanStillUnowned(ctx, view.Finding.PublicationID, view.Finding.DocumentID)
|
||||
if err != nil {
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
if !orphan {
|
||||
return governance.ReconciliationFinding{}, ErrActionConflict
|
||||
}
|
||||
item, err := s.remote.GetKnowledge(ctx, view.Finding.DocumentID)
|
||||
if err != nil {
|
||||
if !weknora.IsNotFound(err) {
|
||||
return governance.ReconciliationFinding{}, ErrRemoteFailed
|
||||
}
|
||||
} else {
|
||||
if item.KnowledgeBaseID != view.TestKBID {
|
||||
return governance.ReconciliationFinding{}, ErrActionConflict
|
||||
}
|
||||
if err := s.remote.DeleteKnowledge(ctx, view.Finding.DocumentID); err != nil && !weknora.IsNotFound(err) {
|
||||
return governance.ReconciliationFinding{}, ErrRemoteFailed
|
||||
}
|
||||
}
|
||||
if err := s.store.MarkReconciliationOrphanRemoved(ctx, findingID, actor, trim(reason), s.now().UTC()); err != nil {
|
||||
if errors.Is(err, postgresstore.ErrReconciliationConflict) {
|
||||
return governance.ReconciliationFinding{}, ErrActionConflict
|
||||
}
|
||||
return governance.ReconciliationFinding{}, err
|
||||
}
|
||||
return s.reloadFinding(ctx, findingID)
|
||||
}
|
||||
|
||||
func (s *Service) actionView(ctx context.Context, findingID string) (governance.ReconciliationActionView, error) {
|
||||
view, err := s.store.LoadReconciliationActionView(ctx, findingID)
|
||||
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
|
||||
return view, ErrNotFound
|
||||
}
|
||||
return view, err
|
||||
}
|
||||
|
||||
func (s *Service) reloadFinding(ctx context.Context, id string) (governance.ReconciliationFinding, error) {
|
||||
finding, err := s.store.GetReconciliationFinding(ctx, id)
|
||||
if errors.Is(err, postgresstore.ErrReconciliationNotFound) {
|
||||
return finding, ErrNotFound
|
||||
}
|
||||
return finding, err
|
||||
}
|
||||
|
||||
func trim(value string) string {
|
||||
if len(value) > 500 {
|
||||
return value[:500]
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
package reconciliation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/readiness"
|
||||
"knowledge-governance/internal/weknoraaccess"
|
||||
)
|
||||
|
||||
func TestMatrixCoversEveryLedgerAndUpstreamState(t *testing.T) {
|
||||
columns := []string{"pending", "processing", "finalizing", "completed", "failed", "cancelled", "deleting"}
|
||||
want := map[string][]verdict{
|
||||
"planned": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
|
||||
"pending": {verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
|
||||
"processing": {verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
|
||||
"finalizing": {verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting},
|
||||
"completed": {verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictDeleting},
|
||||
"failed": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictDeleting},
|
||||
"stalled": {verdictStalled, verdictStalled, verdictStalled, verdictMismatch, verdictStalled, verdictStalled, verdictDeleting},
|
||||
"cancelled": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictDeleting},
|
||||
}
|
||||
for row, expected := range want {
|
||||
for index, column := range columns {
|
||||
if got := classify(row, column); got != expected[index] {
|
||||
t.Fatalf("classify(%s,%s) = %v, want %v", row, column, got, expected[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
if AllowedWriteback("completed", "pending") || AllowedWriteback("stalled", "completed") ||
|
||||
!AllowedWriteback("failed", "pending") || AllowedWriteback("planned", "pending") ||
|
||||
AllowedWriteback("pending", "cancelled") || AllowedWriteback("pending", "deleting") {
|
||||
t.Fatal("writeback migration table is wrong")
|
||||
}
|
||||
}
|
||||
|
||||
type fakeReconciliationStore struct {
|
||||
run governance.ReconciliationRun
|
||||
ledger []governance.ReconciliationLedgerRow
|
||||
removal []governance.ReconciliationLedgerRow
|
||||
overlapped bool
|
||||
completedRun *governance.ReconciliationRun
|
||||
findings []governance.ReconciliationFinding
|
||||
failCode string
|
||||
actionView governance.ReconciliationActionView
|
||||
actionErr error
|
||||
findingAfter governance.ReconciliationFinding
|
||||
writebackHit bool
|
||||
requeueHit bool
|
||||
removeHit bool
|
||||
requeueDoc string
|
||||
orphan bool
|
||||
}
|
||||
|
||||
func (f *fakeReconciliationStore) ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) ClaimReconciliationRun(_ context.Context, run governance.ReconciliationRun, _ time.Time) (governance.ReconciliationRun, error) {
|
||||
return run, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) ClaimScheduledReconciliationRun(_ context.Context, run governance.ReconciliationRun, _ time.Time, _ time.Time) (governance.ReconciliationRun, bool, error) {
|
||||
return run, true, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) LoadReconciliationRun(context.Context, string) (governance.ReconciliationRun, error) {
|
||||
return f.run, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) ListReconciliationRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) {
|
||||
return governance.ReconciliationRunPage{}, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) ListReconciliationFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) {
|
||||
return governance.ReconciliationFindingPage{}, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) GetReconciliationFinding(context.Context, string) (governance.ReconciliationFinding, error) {
|
||||
if f.findingAfter.ID != "" {
|
||||
return f.findingAfter, nil
|
||||
}
|
||||
return governance.ReconciliationFinding{}, ErrNotFound
|
||||
}
|
||||
func (f *fakeReconciliationStore) LoadReconciliationLedger(context.Context, string) ([]governance.ReconciliationLedgerRow, error) {
|
||||
return f.ledger, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) LoadPreviousReconciliationCounts(context.Context, string, time.Time) (governance.ReconciliationCounts, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) CompleteReconciliationRun(_ context.Context, run governance.ReconciliationRun, findings []governance.ReconciliationFinding) error {
|
||||
f.completedRun = &run
|
||||
f.findings = findings
|
||||
return nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) FailReconciliationRun(_ context.Context, _ string, code string, _ time.Time) error {
|
||||
f.failCode = code
|
||||
return nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) CleanupReconciliationFindings(context.Context, time.Time, int, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) LibraryJobsActive(context.Context) (bool, error) {
|
||||
return f.overlapped, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) ListReconciliationRemovalCandidates(context.Context, string) ([]governance.ReconciliationLedgerRow, error) {
|
||||
return f.removal, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) LoadReconciliationActionView(context.Context, string) (governance.ReconciliationActionView, error) {
|
||||
if f.actionErr != nil {
|
||||
return governance.ReconciliationActionView{}, f.actionErr
|
||||
}
|
||||
return f.actionView, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) ReconciliationOrphanStillUnowned(context.Context, string, string) (bool, error) {
|
||||
return f.orphan, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) WritebackReconciliationFinding(context.Context, string, string, string, string, time.Time) (governance.ReconciliationFinding, error) {
|
||||
f.writebackHit = true
|
||||
return f.findingAfter, nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) RequeueReconciliationPublication(_ context.Context, _ string, expectedDocument string, _ string, _ string, _ time.Time) (string, error) {
|
||||
f.requeueHit = true
|
||||
f.requeueDoc = expectedDocument
|
||||
return "job-1", nil
|
||||
}
|
||||
func (f *fakeReconciliationStore) MarkReconciliationOrphanRemoved(context.Context, string, string, string, time.Time) error {
|
||||
f.removeHit = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeReconciliationRemote struct {
|
||||
items []weknora.Knowledge
|
||||
missing map[string]bool
|
||||
gets map[string]weknora.Knowledge
|
||||
listErr error
|
||||
pageSizes []int
|
||||
deleteCalls int
|
||||
listInFlight int
|
||||
maxInFlight int
|
||||
}
|
||||
|
||||
func (f *fakeReconciliationRemote) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) {
|
||||
return ctx, weknora.InstanceIdentity{BaseURL: "https://test.example", TenantID: 7}, nil
|
||||
}
|
||||
func (f *fakeReconciliationRemote) ListKnowledge(_ context.Context, _ string, _ int, pageSize int) ([]weknora.Knowledge, int64, error) {
|
||||
f.pageSizes = append(f.pageSizes, pageSize)
|
||||
f.listInFlight++
|
||||
if f.listInFlight > f.maxInFlight {
|
||||
f.maxInFlight = f.listInFlight
|
||||
}
|
||||
defer func() { f.listInFlight-- }()
|
||||
if f.listErr != nil {
|
||||
return nil, 0, f.listErr
|
||||
}
|
||||
return f.items, int64(len(f.items)), nil
|
||||
}
|
||||
func (f *fakeReconciliationRemote) GetKnowledge(_ context.Context, id string) (weknora.Knowledge, error) {
|
||||
if f.missing[id] {
|
||||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||||
}
|
||||
if item, ok := f.gets[id]; ok {
|
||||
return item, nil
|
||||
}
|
||||
for _, item := range f.items {
|
||||
if item.ID == id {
|
||||
return item, nil
|
||||
}
|
||||
}
|
||||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||||
}
|
||||
func (f *fakeReconciliationRemote) DeleteKnowledge(context.Context, string) error {
|
||||
f.deleteCalls++
|
||||
return nil
|
||||
}
|
||||
|
||||
func ptrTime(value time.Time) *time.Time { return &value }
|
||||
|
||||
func TestExecuteRunFindsR1ToR8WithoutRemoteWrites(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
ledger := []governance.ReconciliationLedgerRow{
|
||||
{PublicationID: "pub-r1", KnowledgeID: "doc-r1", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", Title: "missing", UpdatedAt: now.Add(-time.Hour)},
|
||||
{PublicationID: "pub-r4", KnowledgeID: "doc-r4", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UploadMD5: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
|
||||
{PublicationID: "pub-r5", KnowledgeID: "doc-r5", ProcessingState: "processing", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
|
||||
{PublicationID: "pub-r6", KnowledgeID: "doc-r6", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", PolicyState: "blocked", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
|
||||
{PublicationID: "pub-r7", KnowledgeID: "doc-r7", ProcessingState: "stalled", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-3 * time.Hour)), UpdatedAt: now.Add(-3 * time.Hour)},
|
||||
{PublicationID: "dup-pub", KnowledgeID: "doc-r8a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)},
|
||||
}
|
||||
items := []weknora.Knowledge{
|
||||
{ID: "doc-r2", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "orphan-pub"}},
|
||||
{ID: "doc-r3", KnowledgeBaseID: "kb-1", Channel: "web", ParseStatus: "completed"},
|
||||
{ID: "doc-r4", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: "cccccccccccccccccccccccccccccccc", Metadata: map[string]any{"publication_id": "pub-r4", "content_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}},
|
||||
{ID: "doc-r5", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-r5"}},
|
||||
{ID: "doc-r6", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-r6"}},
|
||||
{ID: "doc-r7", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-r7"}},
|
||||
{ID: "doc-r8a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "dup-pub"}},
|
||||
{ID: "doc-r8b", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "dup-pub"}},
|
||||
}
|
||||
store := &fakeReconciliationStore{
|
||||
run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now},
|
||||
ledger: ledger,
|
||||
removal: []governance.ReconciliationLedgerRow{{PublicationID: "pub-r6"}},
|
||||
}
|
||||
// The ledger scan must be read-only over the wire, not merely against a fake
|
||||
// that remembers it has no write methods. This server speaks the real client
|
||||
// protocol and records every non-GET request.
|
||||
var mu sync.Mutex
|
||||
var writes []string
|
||||
var pageSizes []int
|
||||
listInFlight, maxInFlight := 0, 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
if r.Method != http.MethodGet {
|
||||
writes = append(writes, r.Method+" "+r.URL.Path)
|
||||
}
|
||||
mu.Unlock()
|
||||
path := r.URL.Path
|
||||
switch {
|
||||
case path == "/api/v1/knowledge-bases/kb-1":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": map[string]any{"id": "kb-1", "tenant_id": 7}})
|
||||
case path == "/api/v1/knowledge-bases/kb-1/knowledge":
|
||||
size, _ := strconv.Atoi(r.URL.Query().Get("page_size"))
|
||||
mu.Lock()
|
||||
pageSizes = append(pageSizes, size)
|
||||
listInFlight++
|
||||
if listInFlight > maxInFlight {
|
||||
maxInFlight = listInFlight
|
||||
}
|
||||
mu.Unlock()
|
||||
defer func() {
|
||||
mu.Lock()
|
||||
listInFlight--
|
||||
mu.Unlock()
|
||||
}()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": items, "total": len(items), "page": 1, "page_size": size})
|
||||
case strings.HasPrefix(path, "/api/v1/knowledge/"):
|
||||
id := strings.TrimPrefix(path, "/api/v1/knowledge/")
|
||||
if id == "doc-r1" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "message": "not found"})
|
||||
return
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.ID == id {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "data": item})
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "message": "not found"})
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
remote := &weknoraaccess.Client{
|
||||
Resolver: readiness.Resolver{ResolveConnection: func(context.Context) (string, string, error) {
|
||||
return server.URL, "test-key", nil
|
||||
}},
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now },
|
||||
Grace: 30 * time.Minute, StallAfter: 2 * time.Hour, StaleAfter: 6 * time.Hour,
|
||||
ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour,
|
||||
WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if store.completedRun == nil {
|
||||
t.Fatalf("run was not completed: fail code %q", store.failCode)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(writes) != 0 {
|
||||
t.Fatalf("reconciliation wrote remotely over HTTP: %v", writes)
|
||||
}
|
||||
if len(pageSizes) == 0 || pageSizes[0] != scanPageSize {
|
||||
t.Fatalf("page size = %v, want %d", pageSizes, scanPageSize)
|
||||
}
|
||||
if maxInFlight != 1 {
|
||||
t.Fatalf("scan in-flight peak = %d, want 1", maxInFlight)
|
||||
}
|
||||
got := map[string]int{}
|
||||
for _, finding := range store.findings {
|
||||
got[finding.Type]++
|
||||
}
|
||||
for _, typ := range []string{"R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8"} {
|
||||
if got[typ] != 1 {
|
||||
t.Fatalf("%s count = %d, findings=%#v", typ, got[typ], store.findings)
|
||||
}
|
||||
}
|
||||
if store.completedRun.Counts["R8"] != 1 || store.completedRun.LedgerCount != len(ledger) || store.completedRun.KBCount != len(items) {
|
||||
t.Fatalf("run counts = %#v", store.completedRun)
|
||||
}
|
||||
// Every finding carries the WeKnora jump link built from the resolved test
|
||||
// origin; an empty base would leave it empty, but a resolved one must not.
|
||||
for _, finding := range store.findings {
|
||||
if finding.WeKnoraURL != "https://test.example/platform/knowledge-bases/kb-1" {
|
||||
t.Fatalf("%s weknora_url = %q", finding.Type, finding.WeKnoraURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Two ledger publications may legitimately hold the same bytes in one test KB
|
||||
// (adoption). R8 is keyed by publication_id, so that case must stay silent.
|
||||
func TestR8DoesNotFlagAdoptedDuplicatesWithDistinctPublications(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
sha := strings.Repeat("a", 64)
|
||||
md5 := strings.Repeat("b", 32)
|
||||
row := func(pub, doc string) governance.ReconciliationLedgerRow {
|
||||
return governance.ReconciliationLedgerRow{
|
||||
PublicationID: pub, KnowledgeID: doc, ProcessingState: "completed", RetrievalState: "unpublished",
|
||||
TargetScope: "internal", Title: doc, SHA256: sha, UploadMD5: md5, UpdatedAt: now.Add(-time.Hour),
|
||||
}
|
||||
}
|
||||
ledger := []governance.ReconciliationLedgerRow{row("pub-a", "doc-a"), row("pub-b", "doc-b")}
|
||||
items := []weknora.Knowledge{
|
||||
{ID: "doc-a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: md5, Metadata: map[string]any{"publication_id": "pub-a", "content_sha256": sha}},
|
||||
{ID: "doc-b", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: md5, Metadata: map[string]any{"publication_id": "pub-b", "content_sha256": sha}},
|
||||
}
|
||||
service, err := New(Config{Store: &fakeReconciliationStore{}, Remote: &fakeReconciliationRemote{}, Now: func() time.Time { return now }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", StartedAt: now}
|
||||
findings, err := service.buildFindings(context.Background(), run, ledger, items, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(findings) != 0 {
|
||||
t.Fatalf("adopted duplicates produced findings: %#v", findings)
|
||||
}
|
||||
}
|
||||
|
||||
// The scan phase is serial, but confirmation may fan out up to the configured
|
||||
// bound and never past it (acceptance #17).
|
||||
func TestConfirmAllRespectsConfiguredConcurrency(t *testing.T) {
|
||||
remote := &concurrencyRemote{}
|
||||
service, err := New(Config{
|
||||
Store: &fakeReconciliationStore{}, Remote: remote, ConfirmConcurrency: 2,
|
||||
Now: time.Now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
results := service.confirmAll(context.Background(), "kb-1", []string{"doc-1", "doc-2", "doc-3", "doc-4"})
|
||||
if len(results) != 4 {
|
||||
t.Fatalf("results = %d", len(results))
|
||||
}
|
||||
for id, result := range results {
|
||||
if !result.notFound {
|
||||
t.Fatalf("%s = %#v", id, result)
|
||||
}
|
||||
}
|
||||
remote.mu.Lock()
|
||||
peak := remote.maxInFlight
|
||||
remote.mu.Unlock()
|
||||
if peak != 2 {
|
||||
t.Fatalf("confirm in-flight peak = %d, want 2", peak)
|
||||
}
|
||||
}
|
||||
|
||||
type concurrencyRemote struct {
|
||||
fakeReconciliationRemote
|
||||
mu sync.Mutex
|
||||
inFlight int
|
||||
maxInFlight int
|
||||
}
|
||||
|
||||
func (r *concurrencyRemote) GetKnowledge(context.Context, string) (weknora.Knowledge, error) {
|
||||
r.mu.Lock()
|
||||
r.inFlight++
|
||||
if r.inFlight > r.maxInFlight {
|
||||
r.maxInFlight = r.inFlight
|
||||
}
|
||||
r.mu.Unlock()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
r.mu.Lock()
|
||||
r.inFlight--
|
||||
r.mu.Unlock()
|
||||
return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
|
||||
}
|
||||
|
||||
func TestExecuteRunFailsWholeBatchWithoutFindings(t *testing.T) {
|
||||
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
store := &fakeReconciliationStore{run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", StartedAt: now}}
|
||||
remote := &fakeReconciliationRemote{listErr: errors.New("remote down")}
|
||||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.ExecuteRun(context.Background(), "run-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if store.completedRun != nil || len(store.findings) != 0 {
|
||||
t.Fatal("partial findings were written on scan failure")
|
||||
}
|
||||
if store.failCode != "remote_scan_failed" {
|
||||
t.Fatalf("fail code = %q", store.failCode)
|
||||
}
|
||||
}
|
||||
|
||||
func actionService(t *testing.T, store *fakeReconciliationStore, remote *fakeReconciliationRemote) *Service {
|
||||
t.Helper()
|
||||
service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time {
|
||||
return time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
func TestWritebackHonorsMigrationTableAndCompletedDowngrade(t *testing.T) {
|
||||
store := &fakeReconciliationStore{
|
||||
actionView: governance.ReconciliationActionView{Finding: governance.ReconciliationFinding{
|
||||
ID: "f1", Type: "R5", PublicationID: "pub-1", DocumentID: "doc-1",
|
||||
LedgerState: "processing", NormalizedState: "completed", ActionState: "open",
|
||||
}},
|
||||
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
|
||||
}
|
||||
service := actionService(t, store, &fakeReconciliationRemote{})
|
||||
if _, err := service.Writeback(context.Background(), "f1", "tester", "ok"); err != nil || !store.writebackHit {
|
||||
t.Fatalf("allowed writeback err=%v hit=%t", err, store.writebackHit)
|
||||
}
|
||||
store.writebackHit = false
|
||||
store.actionView.Finding.LedgerState = "completed"
|
||||
store.actionView.Finding.NormalizedState = "pending"
|
||||
if _, err := service.Writeback(context.Background(), "f1", "tester", "ok"); !errors.Is(err, ErrActionNotAllowed) || store.writebackHit {
|
||||
t.Fatalf("completed downgrade err=%v hit=%t", err, store.writebackHit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequeueR1AndR4UseTheSameSnapshotAndR4DeletesFirst(t *testing.T) {
|
||||
store := &fakeReconciliationStore{
|
||||
actionView: governance.ReconciliationActionView{TestKBID: "kb-1", Finding: governance.ReconciliationFinding{
|
||||
ID: "f1", Type: "R1", PublicationID: "pub-1", DocumentID: "doc-1",
|
||||
LedgerState: "completed", ActionState: "open",
|
||||
}},
|
||||
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
|
||||
}
|
||||
remote := &fakeReconciliationRemote{missing: map[string]bool{"doc-1": true}}
|
||||
service := actionService(t, store, remote)
|
||||
if _, err := service.Requeue(context.Background(), "f1", "tester", "ok"); err != nil || !store.requeueHit || store.requeueDoc != "doc-1" {
|
||||
t.Fatalf("R1 requeue err=%v hit=%t doc=%q", err, store.requeueHit, store.requeueDoc)
|
||||
}
|
||||
store.requeueHit = false
|
||||
store.actionView.Finding.Type = "R4"
|
||||
item := weknora.Knowledge{ID: "doc-1", KnowledgeBaseID: "kb-1"}
|
||||
remote.items = []weknora.Knowledge{item}
|
||||
remote.missing = map[string]bool{}
|
||||
if _, err := service.Requeue(context.Background(), "f1", "tester", "ok"); err != nil || remote.deleteCalls != 1 || !store.requeueHit {
|
||||
t.Fatalf("R4 requeue err=%v deletes=%d hit=%t", err, remote.deleteCalls, store.requeueHit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveR2RechecksOwnershipAndTreats404AsSuccess(t *testing.T) {
|
||||
store := &fakeReconciliationStore{
|
||||
orphan: true,
|
||||
actionView: governance.ReconciliationActionView{TestKBID: "kb-1", Finding: governance.ReconciliationFinding{
|
||||
ID: "f1", Type: "R2", DocumentID: "doc-1", ActionState: "open",
|
||||
}},
|
||||
findingAfter: governance.ReconciliationFinding{ID: "f1", ActionState: "done"},
|
||||
}
|
||||
remote := &fakeReconciliationRemote{missing: map[string]bool{"doc-1": true}}
|
||||
service := actionService(t, store, remote)
|
||||
if _, err := service.Remove(context.Background(), "f1", "tester", "ok"); err != nil || !store.removeHit {
|
||||
t.Fatalf("404 removal err=%v hit=%t", err, store.removeHit)
|
||||
}
|
||||
store.removeHit = false
|
||||
store.orphan = false
|
||||
if _, err := service.Remove(context.Background(), "f1", "tester", "ok"); !errors.Is(err, ErrActionConflict) || store.removeHit {
|
||||
t.Fatalf("owned removal err=%v hit=%t", err, store.removeHit)
|
||||
}
|
||||
}
|
||||
@@ -274,7 +274,9 @@ func validateLibraryCandidate(identity PostgresIdentity, pg PostgresSnapshot, es
|
||||
}
|
||||
var bodies []json.RawMessage
|
||||
for _, table := range pg.Tables {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
if libraryResourceBodyTable(table.Name) {
|
||||
bodies = append(bodies, table.Rows...)
|
||||
}
|
||||
}
|
||||
references, err := libraryResourceHandles(bodies)
|
||||
if err != nil {
|
||||
|
||||
@@ -35,7 +35,7 @@ func exportLibraryBeforeImage(ctx context.Context, db librarySnapshotDB, identit
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
rowsByTable[table] = rows
|
||||
if table != "resource_bindings" && table != "knowledge_tag_relations" {
|
||||
if libraryResourceBodyTable(table) {
|
||||
bodies = append(bodies, rows...)
|
||||
}
|
||||
if table == "resource_bindings" {
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"knowledge-governance/internal/libraryprofile"
|
||||
)
|
||||
|
||||
// 漏表门禁:profile 只声明"必须存在什么",不声明"存在但没见过的表怎么办"。
|
||||
// 于是 0.9.0 起 chunk_revisions / wiki_page_revisions 一直被静默跳过。这里用
|
||||
// information_schema 反向扫描所有带知识列的表,按 profile 分类放行;未分类且
|
||||
// 本次范围内有数据就拒绝,空表放行但留下警告。导出前(源库)与导入前(目标库)
|
||||
// 各执行一次。
|
||||
//
|
||||
// 为什么错误不可重试:表没分类是契约缺口,重试不会让分类长出来;必须补 profile
|
||||
// 或明确排除。错误里带表名与行数,运维不用再猜是哪张表。
|
||||
|
||||
const ReleaseUndeclaredKBTableCode = "release_undeclared_kb_table"
|
||||
|
||||
type UndeclaredKBTable struct {
|
||||
Table string
|
||||
Rows int64
|
||||
}
|
||||
|
||||
type UndeclaredKBTableError struct {
|
||||
Tables []UndeclaredKBTable
|
||||
}
|
||||
|
||||
func (e *UndeclaredKBTableError) Error() string {
|
||||
parts := make([]string, 0, len(e.Tables))
|
||||
for _, table := range e.Tables {
|
||||
if table.Rows < 0 {
|
||||
parts = append(parts, table.Table+"(行数无法判定)")
|
||||
continue
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("%s(%d 行)", table.Table, table.Rows))
|
||||
}
|
||||
return fmt.Sprintf("%s: 未声明的知识域表在本次发布范围内仍有数据:%v;先补 profile 关联表分类并接入整库搬运,或明确排除并写明理由。此错误不可重试。",
|
||||
ReleaseUndeclaredKBTableCode, parts)
|
||||
}
|
||||
|
||||
// knowledgeTableGateMarker 让测试夹具能区分"门禁探测"与"能力探测":两者都查
|
||||
// information_schema.columns,但回答的列形状不同(表+列集合 vs 表+列)。
|
||||
const knowledgeTableGateMarker = "/* knowledge-table-gate */"
|
||||
|
||||
const knowledgeScopedColumnsSQL = knowledgeTableGateMarker + `
|
||||
SELECT c.table_name, array_agg(c.column_name ORDER BY c.column_name)
|
||||
FROM information_schema.columns c
|
||||
JOIN (
|
||||
SELECT DISTINCT table_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema='public' AND column_name IN ('knowledge_base_id','knowledge_id','kb_id')
|
||||
) k ON k.table_name = c.table_name
|
||||
WHERE c.table_schema='public'
|
||||
GROUP BY c.table_name
|
||||
ORDER BY c.table_name`
|
||||
|
||||
// verifyDeclaredKnowledgeTables 返回放行警告(未分类但为空的表);有未分类且
|
||||
// 非空的表时返回 UndeclaredKBTableError。identity 是本知识库范围。
|
||||
func verifyDeclaredKnowledgeTables(ctx context.Context, db schemaProbeDB, identity PostgresIdentity,
|
||||
profile libraryprofile.Profile) ([]string, error) {
|
||||
if identity.TenantID == 0 || !validSearchIdentifier(identity.KnowledgeBaseID) {
|
||||
return nil, errors.New("漏表门禁缺少有效的知识库范围身份")
|
||||
}
|
||||
// 没有分类的 profile 不允许"静默跳过门禁":那等于把契约缺口藏起来。
|
||||
if len(profile.RelatedTables) == 0 {
|
||||
return nil, fmt.Errorf("profile %s 没有关联表分类,拒绝跳过漏表门禁", profile.Name)
|
||||
}
|
||||
rows, err := db.Query(ctx, knowledgeScopedColumnsSQL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取知识域表清单失败: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
unclassified := make([]string, 0, 4)
|
||||
columnsByTable := map[string]map[string]bool{}
|
||||
for rows.Next() {
|
||||
var table string
|
||||
var columns []string
|
||||
if err := rows.Scan(&table, &columns); err != nil {
|
||||
return nil, fmt.Errorf("解析知识域表清单失败: %w", err)
|
||||
}
|
||||
if _, ok := profile.RelatedTableClass(table); ok {
|
||||
continue
|
||||
}
|
||||
set := make(map[string]bool, len(columns))
|
||||
for _, column := range columns {
|
||||
set[column] = true
|
||||
}
|
||||
columnsByTable[table] = set
|
||||
unclassified = append(unclassified, table)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("遍历知识域表清单失败: %w", err)
|
||||
}
|
||||
|
||||
blocked := make([]UndeclaredKBTable, 0, len(unclassified))
|
||||
warnings := make([]string, 0, len(unclassified))
|
||||
for _, table := range unclassified {
|
||||
count, ok := scopedKnowledgeTableCountSQL(table, columnsByTable[table], identity)
|
||||
if !ok {
|
||||
// 候选表却没有可用的范围列:无法证明"本次范围内有没有数据",
|
||||
// 只能按有数据处理,避免把范围外的表误放行。
|
||||
blocked = append(blocked, UndeclaredKBTable{Table: table, Rows: -1})
|
||||
continue
|
||||
}
|
||||
var total int64
|
||||
if err := db.QueryRow(ctx, count.sql, count.args...).Scan(&total); err != nil {
|
||||
return nil, fmt.Errorf("统计未声明表 %s 失败: %w", table, err)
|
||||
}
|
||||
if total > 0 {
|
||||
blocked = append(blocked, UndeclaredKBTable{Table: table, Rows: total})
|
||||
continue
|
||||
}
|
||||
warnings = append(warnings, fmt.Sprintf(
|
||||
"%s: 未分类表 %q 在本次范围内为空,已放行;请补 profile 关联表分类", ReleaseUndeclaredKBTableCode, table))
|
||||
}
|
||||
sort.Slice(blocked, func(i, j int) bool { return blocked[i].Table < blocked[j].Table })
|
||||
sort.Strings(warnings)
|
||||
if len(blocked) > 0 {
|
||||
return nil, &UndeclaredKBTableError{Tables: blocked}
|
||||
}
|
||||
return warnings, nil
|
||||
}
|
||||
|
||||
type scopedCount struct {
|
||||
sql string
|
||||
args []any
|
||||
}
|
||||
|
||||
// scopedKnowledgeTableCountSQL 按"这张表实际有的范围列"构造计数:有
|
||||
// knowledge_base_id 优先按 tenant+kb;有 kb_id 按 tenant+kb_id;只有
|
||||
// knowledge_id 时走 knowledges 子查询。没有 tenant_id 的表(如 kb_shares)
|
||||
// 只能按知识库身份过滤,不能硬塞一个不存在的列。
|
||||
func scopedKnowledgeTableCountSQL(table string, columns map[string]bool,
|
||||
identity PostgresIdentity) (scopedCount, bool) {
|
||||
quoted := pgx.Identifier{"public", table}.Sanitize()
|
||||
hasTenant := columns["tenant_id"]
|
||||
var where string
|
||||
var args []any
|
||||
switch {
|
||||
case columns["knowledge_base_id"]:
|
||||
if hasTenant {
|
||||
where, args = "tenant_id=$1 AND knowledge_base_id=$2", []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||
} else {
|
||||
where, args = "knowledge_base_id=$1", []any{identity.KnowledgeBaseID}
|
||||
}
|
||||
case columns["kb_id"]:
|
||||
if hasTenant {
|
||||
where, args = "tenant_id=$1 AND kb_id=$2", []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||
} else {
|
||||
where, args = "kb_id=$1", []any{identity.KnowledgeBaseID}
|
||||
}
|
||||
case columns["knowledge_id"]:
|
||||
where = "knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)"
|
||||
args = []any{identity.TenantID, identity.KnowledgeBaseID}
|
||||
default:
|
||||
return scopedCount{}, false
|
||||
}
|
||||
return scopedCount{sql: "/* knowledge-table-gate-count */ SELECT count(*) FROM " + quoted + " WHERE " + where, args: args}, true
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"knowledge-governance/internal/libraryprofile"
|
||||
)
|
||||
|
||||
// gateRows 回答门禁的 information_schema 探测:table → 列集合。
|
||||
type gateRows struct {
|
||||
tables [][2]any
|
||||
index int
|
||||
}
|
||||
|
||||
func (r *gateRows) Close() {}
|
||||
func (r *gateRows) Err() error { return nil }
|
||||
func (r *gateRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} }
|
||||
func (r *gateRows) FieldDescriptions() []pgconn.FieldDescription { return nil }
|
||||
func (r *gateRows) RawValues() [][]byte { return nil }
|
||||
func (r *gateRows) Conn() *pgx.Conn { return nil }
|
||||
func (r *gateRows) Next() bool {
|
||||
if r.index >= len(r.tables) {
|
||||
return false
|
||||
}
|
||||
r.index++
|
||||
return true
|
||||
}
|
||||
func (r *gateRows) Scan(dest ...any) error {
|
||||
*dest[0].(*string) = r.tables[r.index-1][0].(string)
|
||||
*dest[1].(*[]string) = r.tables[r.index-1][1].([]string)
|
||||
_ = dest
|
||||
return nil
|
||||
}
|
||||
func (r *gateRows) Values() ([]any, error) { return nil, nil }
|
||||
|
||||
type gateCountRow struct{ value *int64 }
|
||||
|
||||
func (r gateCountRow) Scan(dest ...any) error { *dest[0].(*int64) = *r.value; return nil }
|
||||
|
||||
// gateDB 只实现门禁需要的两个入口:探测表/列 + 按表计数。
|
||||
type gateDB struct {
|
||||
candidates []struct {
|
||||
table string
|
||||
columns []string
|
||||
}
|
||||
counts map[string]int64
|
||||
}
|
||||
|
||||
func (d gateDB) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {
|
||||
if !strings.Contains(sql, "knowledge-table-gate") {
|
||||
return nil, errors.New("unexpected query: " + sql)
|
||||
}
|
||||
rows := &gateRows{}
|
||||
for _, candidate := range d.candidates {
|
||||
rows.tables = append(rows.tables, [2]any{candidate.table, candidate.columns})
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (d gateDB) QueryRow(_ context.Context, sql string, _ ...any) pgx.Row {
|
||||
for table, count := range d.counts {
|
||||
if strings.Contains(sql, `"public"."`+table+`"`) {
|
||||
value := count
|
||||
return gateCountRow{value: &value}
|
||||
}
|
||||
}
|
||||
return gateCountRow{value: new(int64)}
|
||||
}
|
||||
|
||||
func gateProfile(t *testing.T) libraryprofile.Profile {
|
||||
t.Helper()
|
||||
profile, err := libraryprofile.For(libraryprofile.V091Version)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
func TestDeclaredTableGateRejectsUnclassifiedTableWithRows(t *testing.T) {
|
||||
profile := gateProfile(t)
|
||||
db := gateDB{
|
||||
candidates: []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{
|
||||
{"mystery_kb_table", []string{"id", "knowledge_base_id", "tenant_id"}},
|
||||
},
|
||||
counts: map[string]int64{"mystery_kb_table": 7},
|
||||
}
|
||||
_, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||
var blocked *UndeclaredKBTableError
|
||||
if !errors.As(err, &blocked) {
|
||||
t.Fatalf("unclassified table with rows must be refused, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), ReleaseUndeclaredKBTableCode) ||
|
||||
!strings.Contains(err.Error(), "mystery_kb_table") || !strings.Contains(err.Error(), "7 行") {
|
||||
t.Fatalf("error must name code/table/rows, got %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "不可重试") {
|
||||
t.Fatalf("error must state non-retryable, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclaredTableGateAllowsEmptyUnclassifiedTableWithWarning(t *testing.T) {
|
||||
profile := gateProfile(t)
|
||||
db := gateDB{
|
||||
candidates: []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{
|
||||
{"mystery_kb_table", []string{"id", "knowledge_base_id", "tenant_id"}},
|
||||
},
|
||||
counts: map[string]int64{"mystery_kb_table": 0},
|
||||
}
|
||||
warnings, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||
if err != nil {
|
||||
t.Fatalf("empty unclassified table must pass: %v", err)
|
||||
}
|
||||
if len(warnings) != 1 || !strings.Contains(warnings[0], "mystery_kb_table") ||
|
||||
!strings.Contains(warnings[0], ReleaseUndeclaredKBTableCode) {
|
||||
t.Fatalf("expected one persisted warning naming the table, got %v", warnings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclaredTableGateAllowsClassifiedTables(t *testing.T) {
|
||||
profile := gateProfile(t)
|
||||
db := gateDB{
|
||||
candidates: []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{
|
||||
{"chunk_images", []string{"knowledge_base_id", "knowledge_id"}},
|
||||
{"sessions", []string{"knowledge_base_id", "tenant_id"}},
|
||||
{"messages", []string{"knowledge_id", "tenant_id"}},
|
||||
{"data_sources", []string{"knowledge_base_id"}},
|
||||
{"chunks", []string{"knowledge_base_id", "knowledge_id"}},
|
||||
},
|
||||
counts: map[string]int64{"sessions": 27, "messages": 90, "chunk_images": 3},
|
||||
}
|
||||
warnings, err := verifyDeclaredKnowledgeTables(context.Background(), db,
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, profile)
|
||||
if err != nil || len(warnings) != 0 {
|
||||
t.Fatalf("derived/excluded/copied tables must pass silently, got %v/%v", warnings, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclaredTableGateRefusesProfileWithoutClassification(t *testing.T) {
|
||||
_, err := verifyDeclaredKnowledgeTables(context.Background(), gateDB{},
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}, libraryprofile.Profile{Name: "bare"})
|
||||
if err == nil || !strings.Contains(err.Error(), "分类") {
|
||||
t.Fatalf("a profile without classification must not skip the gate, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedKnowledgeTableCountSQLUsesExistingColumns(t *testing.T) {
|
||||
identity := PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"}
|
||||
cases := []struct {
|
||||
name string
|
||||
columns map[string]bool
|
||||
wantSQL string
|
||||
want []any
|
||||
}{
|
||||
{"kb+tenant", map[string]bool{"knowledge_base_id": true, "tenant_id": true},
|
||||
`tenant_id=$1 AND knowledge_base_id=$2`, []any{uint64(10000), "kb-safe"}},
|
||||
{"kb without tenant", map[string]bool{"knowledge_base_id": true},
|
||||
`knowledge_base_id=$1`, []any{"kb-safe"}},
|
||||
{"kb_id+tenant", map[string]bool{"kb_id": true, "tenant_id": true},
|
||||
`tenant_id=$1 AND kb_id=$2`, []any{uint64(10000), "kb-safe"}},
|
||||
{"kb_id without tenant", map[string]bool{"kb_id": true},
|
||||
`kb_id=$1`, []any{"kb-safe"}},
|
||||
{"knowledge only", map[string]bool{"knowledge_id": true},
|
||||
`knowledge_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)`,
|
||||
[]any{uint64(10000), "kb-safe"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
count, ok := scopedKnowledgeTableCountSQL("t", tc.columns, identity)
|
||||
if !ok || !strings.Contains(count.sql, tc.wantSQL) {
|
||||
t.Fatalf("sql=%q ok=%v, want fragment %q", count.sql, ok, tc.wantSQL)
|
||||
}
|
||||
if !reflect.DeepEqual(count.args, tc.want) {
|
||||
t.Fatalf("args=%v, want %v", count.args, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, ok := scopedKnowledgeTableCountSQL("t", map[string]bool{"id": true}, identity); ok {
|
||||
t.Fatal("a table without any scope column must not be treated as countable")
|
||||
}
|
||||
}
|
||||
|
||||
// 导出路径必须真的执行门禁:候选表有数据时在封存前就失败。
|
||||
type gateExportDB struct {
|
||||
candidates []struct {
|
||||
table string
|
||||
columns []string
|
||||
}
|
||||
counts map[string]int64
|
||||
}
|
||||
|
||||
func (d gateExportDB) BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error) {
|
||||
return &gateExportTx{db: d}, nil
|
||||
}
|
||||
|
||||
type gateExportTx struct {
|
||||
pgx.Tx
|
||||
db gateExportDB
|
||||
}
|
||||
|
||||
func (tx *gateExportTx) Commit(context.Context) error { return nil }
|
||||
func (tx *gateExportTx) Rollback(context.Context) error { return nil }
|
||||
func (tx *gateExportTx) QueryRow(_ context.Context, sql string, _ ...any) pgx.Row {
|
||||
if strings.Contains(sql, "schema_migrations") {
|
||||
return gateSchemaRow{}
|
||||
}
|
||||
for table, count := range tx.db.counts {
|
||||
if strings.Contains(sql, `"public"."`+table+`"`) {
|
||||
value := count
|
||||
return gateCountRow{value: &value}
|
||||
}
|
||||
}
|
||||
return gateCountRow{value: new(int64)}
|
||||
}
|
||||
func (tx *gateExportTx) Query(_ context.Context, sql string, _ ...any) (pgx.Rows, error) {
|
||||
if strings.Contains(sql, "knowledge-table-gate") {
|
||||
rows := &gateRows{}
|
||||
for _, candidate := range tx.db.candidates {
|
||||
rows.tables = append(rows.tables, [2]any{candidate.table, candidate.columns})
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
return legacySchemaProbeRows(), nil
|
||||
}
|
||||
|
||||
type gateSchemaRow struct{}
|
||||
|
||||
func (gateSchemaRow) Scan(dest ...any) error {
|
||||
*dest[0].(*int) = 74
|
||||
*dest[1].(*bool) = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestExportRunsDeclaredTableGateBeforeSealing(t *testing.T) {
|
||||
db := gateExportDB{candidates: []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{{"mystery_kb_table", []string{"knowledge_base_id", "tenant_id"}}},
|
||||
counts: map[string]int64{"mystery_kb_table": 2}}
|
||||
_, err := ExportLibrary(context.Background(), db,
|
||||
PostgresIdentity{TenantID: 10000, KnowledgeBaseID: "kb-safe"})
|
||||
if err == nil || !strings.Contains(err.Error(), ReleaseUndeclaredKBTableCode) {
|
||||
t.Fatalf("export must fail closed on undeclared table data, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
@@ -34,6 +38,17 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
if err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
// 漏表门禁:在同一个只读快照事务里做,避免"检查完又长出未声明表"。
|
||||
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, tx, identity, profile.Profile)
|
||||
if err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
for _, warning := range gateWarnings {
|
||||
log.Printf("library export declared-table gate: %s", warning)
|
||||
}
|
||||
if err := verifyRevisionParentClosure(ctx, tx, identity, profile); err != nil {
|
||||
return PostgresSnapshot{}, err
|
||||
}
|
||||
var graph bool
|
||||
if err := tx.QueryRow(ctx, `SELECT COALESCE((indexing_strategy->>'graph_enabled')::boolean,false) FROM knowledge_bases WHERE tenant_id=$1 AND id=$2 AND deleted_at IS NULL`, identity.TenantID, identity.KnowledgeBaseID).Scan(&graph); err != nil {
|
||||
return PostgresSnapshot{}, errors.New("source library unavailable")
|
||||
@@ -85,7 +100,7 @@ func ExportLibraryWithReleases(ctx context.Context, db librarySnapshotDB, identi
|
||||
// The latter includes Wiki manual pages, which document bundles used to miss.
|
||||
var bodies []json.RawMessage
|
||||
for _, table := range snapshot.Tables {
|
||||
if table.Name == "resource_bindings" || table.Name == "knowledge_tag_relations" {
|
||||
if !libraryResourceBodyTable(table.Name) {
|
||||
continue
|
||||
}
|
||||
bodies = append(bodies, table.Rows...)
|
||||
@@ -147,13 +162,62 @@ const librarySettlementSQL = `SELECT
|
||||
(SELECT count(*) FROM task_pending_ops WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2)))),
|
||||
(SELECT count(*) FROM task_dead_letters WHERE tenant_id=$1 AND ((scope='knowledge_base' AND scope_id=$2) OR (scope='knowledge' AND scope_id IN (SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2))))`
|
||||
|
||||
// verifyRevisionParentClosure 只拒绝"父行完全不存在/父关系错乱"的修订行;
|
||||
// 父行被软删的修订属于本次范围外(整库只发活跃内容),随父行一起不导出。
|
||||
// 这与"历史日志按展示事实保留"不同:修订行的 chunk_id/page_id 是结构引用,
|
||||
// 真缺失只可能是数据异常,不能静默跳过。
|
||||
func verifyRevisionParentClosure(ctx context.Context, db schemaProbeDB, identity PostgresIdentity, profile SchemaProfile) error {
|
||||
checks := make([]string, 0, 3)
|
||||
labels := make([]string, 0, 3)
|
||||
if profile.HasTable("chunk_revisions") {
|
||||
checks = append(checks, `(SELECT count(*) FROM chunk_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
|
||||
AND NOT EXISTS (SELECT 1 FROM chunks c WHERE c.id=r.chunk_id AND c.tenant_id=r.tenant_id))`)
|
||||
labels = append(labels, "chunk_revisions 缺少 chunk 父行")
|
||||
checks = append(checks, `(SELECT count(*) FROM chunk_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
|
||||
AND EXISTS (SELECT 1 FROM chunks c WHERE c.id=r.chunk_id AND c.tenant_id=r.tenant_id AND (c.knowledge_id<>r.knowledge_id OR c.knowledge_base_id<>r.knowledge_base_id)))`)
|
||||
labels = append(labels, "chunk_revisions 与父 chunk 的 knowledge_id/knowledge_base_id 不一致")
|
||||
}
|
||||
if profile.HasTable("wiki_page_revisions") {
|
||||
checks = append(checks, `(SELECT count(*) FROM wiki_page_revisions r WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2
|
||||
AND NOT EXISTS (SELECT 1 FROM wiki_pages p WHERE p.id=r.page_id AND p.tenant_id=r.tenant_id AND p.knowledge_base_id=r.knowledge_base_id))`)
|
||||
labels = append(labels, "wiki_page_revisions 缺少 page 父行")
|
||||
}
|
||||
if len(checks) == 0 {
|
||||
return nil
|
||||
}
|
||||
var counts = make([]int64, len(checks))
|
||||
dest := make([]any, len(checks))
|
||||
for index := range counts {
|
||||
dest[index] = &counts[index]
|
||||
}
|
||||
if err := db.QueryRow(ctx, "/* library-revision-closure */ SELECT "+strings.Join(checks, ", "),
|
||||
identity.TenantID, identity.KnowledgeBaseID).Scan(dest...); err != nil {
|
||||
return fmt.Errorf("读取编辑历史父关系失败: %w", err)
|
||||
}
|
||||
problems := make([]string, 0, len(counts))
|
||||
for index, count := range counts {
|
||||
if count > 0 {
|
||||
problems = append(problems, fmt.Sprintf("%s:%d 行", labels[index], count))
|
||||
}
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return fmt.Errorf("编辑历史存在无法解析的父引用,拒绝整库发布:%v", problems)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var libraryContentQueries = []struct{ name, sql string }{
|
||||
{"knowledges", `SELECT to_jsonb(k) FROM knowledges k WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL ORDER BY k.id`},
|
||||
{"chunks", `SELECT to_jsonb(c) FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND c.deleted_at IS NULL ORDER BY c.id`},
|
||||
// 编辑历史:只随活跃父行发布。父行被软删(不在本次范围)时不搬它的历史;
|
||||
// 父行完全缺失属于数据异常,由 verifyRevisionParentClosure 拒绝,不静默跳过。
|
||||
{"chunk_revisions", `SELECT to_jsonb(r) FROM chunk_revisions r JOIN chunks c ON c.id=r.chunk_id AND c.tenant_id=r.tenant_id AND c.knowledge_base_id=r.knowledge_base_id JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2 AND r.knowledge_id=c.knowledge_id AND c.deleted_at IS NULL AND k.deleted_at IS NULL ORDER BY r.id`},
|
||||
{"knowledge_tags", `SELECT to_jsonb(t) FROM knowledge_tags t WHERE t.tenant_id=$1 AND t.knowledge_base_id=$2 AND t.deleted_at IS NULL ORDER BY t.id`},
|
||||
{"knowledge_tag_relations", `SELECT to_jsonb(r) FROM knowledge_tag_relations r JOIN knowledges k ON k.id=r.knowledge_id JOIN knowledge_tags t ON t.id=r.tag_id AND t.tenant_id=k.tenant_id AND t.knowledge_base_id=k.knowledge_base_id WHERE k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL AND t.deleted_at IS NULL ORDER BY r.knowledge_id,r.tag_id`},
|
||||
{"resource_bindings", `SELECT to_jsonb(b) FROM resource_bindings b WHERE b.tenant_id=$1 AND ((b.owner_type='knowledge' AND EXISTS (SELECT 1 FROM knowledges k WHERE k.id=b.owner_id AND k.tenant_id=$1 AND k.knowledge_base_id=$2 AND k.deleted_at IS NULL)) OR (b.owner_type='chunk' AND EXISTS (SELECT 1 FROM chunks c JOIN knowledges k ON k.id=c.knowledge_id AND k.tenant_id=c.tenant_id AND k.knowledge_base_id=c.knowledge_base_id WHERE c.id=b.owner_id AND c.tenant_id=$1 AND c.knowledge_base_id=$2 AND c.deleted_at IS NULL AND k.deleted_at IS NULL))) ORDER BY b.id`},
|
||||
{"wiki_pages", `SELECT to_jsonb(w) FROM wiki_pages w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
||||
// 编辑历史:与 chunk_revisions 同一规则(活跃父行 + 真悬挂由守卫拒绝)。
|
||||
{"wiki_page_revisions", `SELECT to_jsonb(r) FROM wiki_page_revisions r JOIN wiki_pages p ON p.id=r.page_id AND p.tenant_id=r.tenant_id AND p.knowledge_base_id=r.knowledge_base_id WHERE r.tenant_id=$1 AND r.knowledge_base_id=$2 AND p.deleted_at IS NULL ORDER BY r.id`},
|
||||
{"wiki_folders", `SELECT to_jsonb(w) FROM wiki_folders w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
||||
{"wiki_page_issues", `SELECT to_jsonb(w) FROM wiki_page_issues w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 AND w.deleted_at IS NULL ORDER BY w.id`},
|
||||
{"wiki_log_entries", `SELECT to_jsonb(w) FROM wiki_log_entries w WHERE w.tenant_id=$1 AND w.knowledge_base_id=$2 ORDER BY w.id`},
|
||||
|
||||
@@ -103,6 +103,11 @@ func (d *libraryFixtureTx) Query(_ context.Context, q string, _ ...any) (pgx.Row
|
||||
if d.queryError {
|
||||
return nil, errors.New("fixture failure")
|
||||
}
|
||||
// 漏表门禁也查 information_schema,但回答形状是(表,列集合);与能力探测分开打桩,
|
||||
// 否则会被当成两列结果扫描。74 夹具没有任何未分类的知识域表。
|
||||
if strings.Contains(q, "knowledge-table-gate") {
|
||||
return &jsonRows{}, nil
|
||||
}
|
||||
// 能力探测走真实 SQL:假库按 0.7.1 profile 回答,避免"桩放行"。
|
||||
if strings.Contains(q, "information_schema.columns") {
|
||||
return legacySchemaProbeRows(), nil
|
||||
|
||||
@@ -31,7 +31,11 @@ var migrationIdentityContracts = map[string]rowIdentityContract{
|
||||
"wiki_folders": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_pages": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_page_issues": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"},
|
||||
// 编辑历史:稳定字符串身份;id 是它自己的身份,chunk_id/page_id/knowledge_id
|
||||
// 是引用(由 remapRow 显式映射)。两表都没有 deleted_at。
|
||||
"chunk_revisions": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_page_revisions": {Columns: []string{"id"}, Kind: "stable-string"},
|
||||
"wiki_log_entries": {Columns: []string{"id"}, Kind: "local-bigint", LocalColumn: "id", Sequence: "wiki_log_entries_id_seq"},
|
||||
}
|
||||
|
||||
type typedRowIdentity struct {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -344,12 +345,16 @@ func (t *ProductionLibraryTarget) tableState(ctx context.Context, table string)
|
||||
if name == "resources" {
|
||||
continue
|
||||
}
|
||||
// 只需正文表与绑定表;修订历史按 Q2=B 不参与资源发现,不为它做整表扫描。
|
||||
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
|
||||
continue
|
||||
}
|
||||
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
||||
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("读取生产 %s 失败", table)
|
||||
}
|
||||
if name != "resource_bindings" && name != "knowledge_tag_relations" {
|
||||
if name != "resource_bindings" && name != "knowledge_tag_relations" && libraryResourceBodyTable(name) {
|
||||
bodies = append(bodies, items...)
|
||||
}
|
||||
if name == "resource_bindings" {
|
||||
@@ -479,6 +484,16 @@ func (t *ProductionLibraryTarget) importRows(ctx context.Context, archive *libra
|
||||
return errors.New("开启生产事务失败")
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
// 漏表门禁的最终判定:在写事务内、任何 DELETE 之前。放在事务外检查会留下
|
||||
// "查完到写前"的窗口,未声明表的数据可能在这段时间被写进来。
|
||||
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, tx,
|
||||
PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, t.schema.Profile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, warning := range gateWarnings {
|
||||
log.Printf("library import declared-table gate: %s", warning)
|
||||
}
|
||||
for index := len(t.tables) - 1; index >= 0; index-- {
|
||||
table := t.tables[index]
|
||||
if _, ok := parts[table]; !ok {
|
||||
|
||||
@@ -104,7 +104,7 @@ func TestV090ProductionTargetPublishIsolated(t *testing.T) {
|
||||
t.Fatalf("fixture %s %s => %d, want %d", method, path, response.StatusCode, want)
|
||||
}
|
||||
}
|
||||
call("PUT", "/"+index, `{"mappings":{"properties":{"tenant_id":{"type":"long"},"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"chunk_id":{"type":"keyword"},"content":{"type":"text"},"embedding":{"type":"dense_vector","dims":2}}}}`, 200)
|
||||
call("PUT", "/"+index, `{"mappings":{"properties":{"knowledge_base_id":{"type":"keyword"},"knowledge_id":{"type":"keyword"},"chunk_id":{"type":"keyword"},"content":{"type":"text"},"embedding":{"type":"dense_vector","dims":2}}}}`, 200)
|
||||
defer func() {
|
||||
call("DELETE", "/"+index, "", 200)
|
||||
call("HEAD", "/"+index, "", 404)
|
||||
@@ -375,7 +375,7 @@ func v090PublishIndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA stri
|
||||
t.Fatalf("decode chunk: %v", err)
|
||||
}
|
||||
source, err := json.Marshal(map[string]any{
|
||||
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
|
||||
"chunk_id": chunk.ID,
|
||||
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
|
||||
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
||||
"embedding": []float64{0.1, 0.2},
|
||||
|
||||
@@ -57,6 +57,10 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
t.Fatalf("unexpected fixture shape: chunks=%d knowledges=%d",
|
||||
source.Table("chunks").RowCount, source.Table("knowledges").RowCount)
|
||||
}
|
||||
if source.Table("chunk_revisions").RowCount != 1 || source.Table("wiki_page_revisions").RowCount != 1 {
|
||||
t.Fatalf("editing history must be exported: chunk_revisions=%d wiki_page_revisions=%d",
|
||||
source.Table("chunk_revisions").RowCount, source.Table("wiki_page_revisions").RowCount)
|
||||
}
|
||||
|
||||
es := v090IndexSnapshot(t, source, mappingSHA)
|
||||
root := t.TempDir()
|
||||
@@ -90,6 +94,13 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
t.Fatal("0.9.0 archive must not contain a wiki_log_entries part")
|
||||
}
|
||||
}
|
||||
seenParts := map[string]bool{}
|
||||
for _, part := range manifest.Parts {
|
||||
seenParts[part.Kind+"/"+part.Name] = true
|
||||
}
|
||||
if !seenParts["database/chunk_revisions"] || !seenParts["wiki/wiki_page_revisions"] {
|
||||
t.Fatalf("revision parts must be archived: %v", seenParts)
|
||||
}
|
||||
|
||||
dst := v090Pool(t, "KG_V090_TARGET_DSN")
|
||||
if err := seedV090Binding(t, ctx, dst); err != nil {
|
||||
@@ -100,14 +111,21 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
document := PostgresIdentity{TenantID: identity.TenantID, KnowledgeBaseID: identity.KnowledgeBaseID, KnowledgeID: v090Knowledge}
|
||||
if err := importer.Replace(ctx, document, source); err != nil {
|
||||
// 文档级 Replace 只写单文档相关表;编辑历史走整库 Apply(0.9.0 发布目标用例覆盖)。
|
||||
documentSource := withoutRevisionTables(source)
|
||||
if err := importer.Replace(ctx, document, documentSource); err != nil {
|
||||
t.Fatalf("import 0.9.0 snapshot: %v", err)
|
||||
}
|
||||
reloaded, err := ExportLibrary(ctx, dst, identity)
|
||||
if err != nil {
|
||||
t.Fatalf("re-export imported library: %v", err)
|
||||
}
|
||||
compareSnapshotContent(t, source, reloaded)
|
||||
compareSnapshotContent(t, documentSource, withoutRevisionTables(reloaded))
|
||||
for _, table := range []string{"chunk_revisions", "wiki_page_revisions"} {
|
||||
if reloaded.Table(table).RowCount != 0 {
|
||||
t.Fatalf("document-level import must not invent %s rows", table)
|
||||
}
|
||||
}
|
||||
|
||||
// 0.9.0 新增的 NOT NULL 列在导入后必须仍是合法值,且 seq_id 由目标序列分配。
|
||||
var defaults int
|
||||
@@ -130,7 +148,7 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
}
|
||||
|
||||
// 跨版本必须拒绝:0.7.1 归档不能落到 0.9.0 目标。
|
||||
crossVersion := source
|
||||
crossVersion := documentSource
|
||||
crossVersion.SchemaVersion = 74
|
||||
crossVersion.Profile = "v071"
|
||||
err = importer.Replace(ctx, document, crossVersion)
|
||||
@@ -139,6 +157,18 @@ func TestV090LibraryRoundTripIsolated(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func withoutRevisionTables(snapshot PostgresSnapshot) PostgresSnapshot {
|
||||
tables := make([]TableSnapshot, 0, len(snapshot.Tables))
|
||||
for _, table := range snapshot.Tables {
|
||||
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
|
||||
continue
|
||||
}
|
||||
tables = append(tables, table)
|
||||
}
|
||||
snapshot.Tables = tables
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// compareSnapshotContent 逐表逐行比对"共有列"的规范化内容。
|
||||
// chunks.seq_id 是库级序列值、不是文档内容,导入时由目标分配,故排除比对。
|
||||
func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
|
||||
@@ -147,6 +177,9 @@ func compareSnapshotContent(t *testing.T, source, target PostgresSnapshot) {
|
||||
t.Fatalf("table set changed across round trip: %d -> %d", len(source.Tables), len(target.Tables))
|
||||
}
|
||||
for _, table := range source.Tables {
|
||||
if table.Name == "chunk_revisions" || table.Name == "wiki_page_revisions" {
|
||||
continue
|
||||
}
|
||||
want := tableDigests(t, table.Name, table.Rows)
|
||||
got := tableDigests(t, table.Name, target.Table(table.Name).Rows)
|
||||
if table.RowCount != target.Table(table.Name).RowCount || len(want) != len(got) {
|
||||
|
||||
@@ -9,13 +9,26 @@ import (
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
// libraryResourceBodyTable 报告该表是否参与"正文引用资源"的发现与作用域。
|
||||
//
|
||||
// 编辑历史按人类裁定(Q2=B)原样保留 resource:// 文本,不参与资源发现:历史版本
|
||||
// 引用的对象可能早已删除,不能让它决定本次发布必须携带哪些对象。资源发现、目标
|
||||
// 资源作用域、恢复保护三处必须用同一个判定,否则导出与校验会各算一套集合。
|
||||
func libraryResourceBodyTable(table string) bool {
|
||||
switch table {
|
||||
case "resources", "resource_bindings", "knowledge_tag_relations", "chunk_revisions", "wiki_page_revisions":
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Keep capture/verification and deletion protection on the same set of bodies.
|
||||
// predicate is an internal SQL fragment, never caller-supplied content; tables comes
|
||||
// from the resolved schema profile (0.9.0 has no wiki_log_entries to scan).
|
||||
func libraryResourceBodyReferenceSQL(tables []string, predicate string) string {
|
||||
queries := []string{}
|
||||
for _, table := range tables {
|
||||
if table == "resources" || table == "resource_bindings" || table == "knowledge_tag_relations" {
|
||||
if !libraryResourceBodyTable(table) {
|
||||
continue
|
||||
}
|
||||
queries = append(queries, fmt.Sprintf(`SELECT 1 FROM %s c WHERE (%s) AND coalesce(resources.handle,'')<>'' AND position('resource://'||resources.handle IN to_jsonb(c)::text)>0`, table, predicate))
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package v071
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func revisionMapper() *targetIDMapper {
|
||||
mapper := newTargetIDMapper(10001, "kb-target", nil)
|
||||
for table, ids := range map[string][]string{
|
||||
"knowledges": {"doc-src"},
|
||||
"chunks": {"chunk-src"},
|
||||
"wiki_pages": {"page-src"},
|
||||
"chunk_revisions": {"crev-src"},
|
||||
"wiki_page_revisions": {"wrev-src"},
|
||||
} {
|
||||
for _, id := range ids {
|
||||
mapper.registerSourceID(table, id)
|
||||
}
|
||||
}
|
||||
return mapper
|
||||
}
|
||||
|
||||
func TestRevisionRowsUseTheSameScopeAndIdentityMapping(t *testing.T) {
|
||||
mapper := revisionMapper()
|
||||
chunkRevision := map[string]json.RawMessage{
|
||||
"id": json.RawMessage(`"crev-src"`),
|
||||
"knowledge_id": json.RawMessage(`"doc-src"`),
|
||||
"chunk_id": json.RawMessage(`"chunk-src"`),
|
||||
"revision": json.RawMessage(`3`),
|
||||
"content": json.RawMessage(`"edit history text"`),
|
||||
"editor_id": json.RawMessage(`"user-9"`),
|
||||
"knowledge_base_id": json.RawMessage(`"kb-source"`),
|
||||
}
|
||||
if err := mapper.remapRow("chunk_revisions", chunkRevision); err != nil {
|
||||
t.Fatalf("chunk revision mapping: %v", err)
|
||||
}
|
||||
if string(chunkRevision["id"]) != `"`+mapper.mapID("chunk_revisions", "crev-src")+`"` {
|
||||
t.Fatal("revision id must be target-mapped")
|
||||
}
|
||||
if string(chunkRevision["chunk_id"]) != `"`+mapper.mapID("chunks", "chunk-src")+`"` {
|
||||
t.Fatal("chunk_id must map to the target chunk identity")
|
||||
}
|
||||
if string(chunkRevision["knowledge_id"]) != `"`+mapper.mapID("knowledges", "doc-src")+`"` {
|
||||
t.Fatal("knowledge_id must map to the target knowledge identity")
|
||||
}
|
||||
// editor_id 是用户身份,原样保留(目标查不到显示未知编辑者)。
|
||||
if string(chunkRevision["editor_id"]) != `"user-9"` {
|
||||
t.Fatal("editor_id must be preserved")
|
||||
}
|
||||
|
||||
pageRevision := map[string]json.RawMessage{
|
||||
"id": json.RawMessage(`"wrev-src"`),
|
||||
"page_id": json.RawMessage(`"page-src"`),
|
||||
"slug": json.RawMessage(`"legacy-slug"`),
|
||||
"version": json.RawMessage(`2`),
|
||||
"content": json.RawMessage(`"wiki history"`),
|
||||
"knowledge_base_id": json.RawMessage(`"kb-source"`),
|
||||
}
|
||||
if err := mapper.remapRow("wiki_page_revisions", pageRevision); err != nil {
|
||||
t.Fatalf("wiki page revision mapping: %v", err)
|
||||
}
|
||||
if string(pageRevision["page_id"]) != `"`+mapper.mapID("wiki_pages", "page-src")+`"` {
|
||||
t.Fatal("page_id must map to the target page identity")
|
||||
}
|
||||
if string(pageRevision["slug"]) != `"legacy-slug"` {
|
||||
t.Fatal("slug is content, not identity; it must be preserved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionDanglingReferencesAreRefused(t *testing.T) {
|
||||
mapper := revisionMapper()
|
||||
cases := []struct {
|
||||
name string
|
||||
row map[string]json.RawMessage
|
||||
}{
|
||||
{"unknown chunk", map[string]json.RawMessage{
|
||||
"id": json.RawMessage(`"crev-unknown"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||
"chunk_id": json.RawMessage(`"chunk-other"`), "revision": json.RawMessage(`1`),
|
||||
}},
|
||||
{"unknown page", map[string]json.RawMessage{
|
||||
"id": json.RawMessage(`"wrev-unknown"`), "page_id": json.RawMessage(`"page-other"`),
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
table := "chunk_revisions"
|
||||
if tc.name == "unknown page" {
|
||||
table = "wiki_page_revisions"
|
||||
}
|
||||
err := mapper.remapRow(table, tc.row)
|
||||
if !errors.Is(err, errUnmappedTargetReference) || !strings.Contains(err.Error(), "unmapped") {
|
||||
t.Fatalf("dangling reference must be refused, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionUniqueIndexKeysStayUniqueAfterMapping(t *testing.T) {
|
||||
mapper := revisionMapper()
|
||||
// 同一 chunk 的两个 revision:chunk_id 映射后仍相同,revision 仍是 1/2,
|
||||
// 因此 (chunk_id, revision) 唯一性不会被映射破坏。
|
||||
rows := []map[string]json.RawMessage{
|
||||
{"id": json.RawMessage(`"crev-src"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||
"chunk_id": json.RawMessage(`"chunk-src"`), "revision": json.RawMessage(`1`)},
|
||||
{"id": json.RawMessage(`"crev-src2"`), "knowledge_id": json.RawMessage(`"doc-src"`),
|
||||
"chunk_id": json.RawMessage(`"chunk-src"`), "revision": json.RawMessage(`2`)},
|
||||
}
|
||||
mapper.registerSourceID("chunk_revisions", "crev-src2")
|
||||
mapped := map[string]bool{}
|
||||
for _, row := range rows {
|
||||
if err := mapper.remapRow("chunk_revisions", row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := string(row["chunk_id"]) + "/" + string(row["revision"])
|
||||
if mapped[key] {
|
||||
t.Fatalf("mapped unique key collided: %s", key)
|
||||
}
|
||||
mapped[key] = true
|
||||
}
|
||||
if len(mapped) != 2 {
|
||||
t.Fatal("both revision keys must remain distinct")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionTablesAreDeletedBeforeParents(t *testing.T) {
|
||||
position := map[string]int{}
|
||||
for index, table := range jobCreatedRowDeleteOrder {
|
||||
position[table] = index
|
||||
}
|
||||
for _, child := range []string{"wiki_page_revisions", "chunk_revisions"} {
|
||||
if _, ok := position[child]; !ok {
|
||||
t.Fatalf("%s missing from recovery delete order", child)
|
||||
}
|
||||
}
|
||||
if position["chunk_revisions"] > position["chunks"] {
|
||||
t.Fatal("chunk_revisions must be deleted before chunks")
|
||||
}
|
||||
if position["wiki_page_revisions"] > position["wiki_pages"] {
|
||||
t.Fatal("wiki_page_revisions must be deleted before wiki_pages")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevisionTablesAreNotResourceBodies(t *testing.T) {
|
||||
for _, table := range []string{"chunk_revisions", "wiki_page_revisions"} {
|
||||
if libraryResourceBodyTable(table) {
|
||||
t.Fatalf("%s must not participate in resource discovery (Q2=B)", table)
|
||||
}
|
||||
}
|
||||
sql := libraryResourceBodyReferenceSQL([]string{"chunks", "chunk_revisions", "wiki_page_revisions"}, "TRUE")
|
||||
if strings.Contains(sql, "chunk_revisions") || strings.Contains(sql, "wiki_page_revisions") {
|
||||
t.Fatalf("resource reference SQL must exclude revision tables: %s", sql)
|
||||
}
|
||||
if !strings.Contains(sql, "FROM chunks") {
|
||||
t.Fatal("resource reference SQL must still scan live chunks")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStructuredReferenceValidationCoversRevisions(t *testing.T) {
|
||||
snapshot := PostgresSnapshot{Tables: []TableSnapshot{
|
||||
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-1"}`)}),
|
||||
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-1","knowledge_id":"doc-1"}`)}),
|
||||
newTableSnapshot("chunk_revisions", []json.RawMessage{
|
||||
json.RawMessage(`{"id":"crev-1","knowledge_id":"doc-1","chunk_id":"chunk-1"}`),
|
||||
}),
|
||||
newTableSnapshot("wiki_pages", []json.RawMessage{json.RawMessage(`{"id":"page-1"}`)}),
|
||||
newTableSnapshot("wiki_page_revisions", []json.RawMessage{
|
||||
json.RawMessage(`{"id":"wrev-1","page_id":"page-1"}`),
|
||||
}),
|
||||
}}
|
||||
if err := validateLibraryStructuredReferences(snapshot); err != nil {
|
||||
t.Fatalf("resolved revision references must pass: %v", err)
|
||||
}
|
||||
broken := snapshot
|
||||
broken.Tables = []TableSnapshot{
|
||||
newTableSnapshot("knowledges", []json.RawMessage{json.RawMessage(`{"id":"doc-1"}`)}),
|
||||
newTableSnapshot("chunks", []json.RawMessage{json.RawMessage(`{"id":"chunk-1","knowledge_id":"doc-1"}`)}),
|
||||
newTableSnapshot("chunk_revisions", []json.RawMessage{
|
||||
json.RawMessage(`{"id":"crev-1","knowledge_id":"doc-1","chunk_id":"chunk-missing"}`),
|
||||
}),
|
||||
}
|
||||
if err := validateLibraryStructuredReferences(broken); err == nil || !strings.Contains(err.Error(), "chunk_id") {
|
||||
t.Fatalf("missing chunk parent must be refused, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
var tablesWithKB = map[string]bool{
|
||||
"knowledges": true, "chunks": true, "knowledge_tags": true,
|
||||
"wiki_folders": true, "wiki_pages": true, "wiki_page_issues": true, "wiki_log_entries": true,
|
||||
"chunk_revisions": true, "wiki_page_revisions": true,
|
||||
}
|
||||
|
||||
// tableHasTenant 报告这张表是否自带租户列。
|
||||
|
||||
@@ -90,6 +90,21 @@ func validateLibraryStructuredReferences(pg PostgresSnapshot) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 编辑历史:chunk_id/page_id 是结构引用,不是展示事实。父行不在本快照里
|
||||
// (软删父行按导出规则不出现)就拒绝;chunk 还必须与 revision.knowledge_id 同文档。
|
||||
for _, r := range tables["chunk_revisions"] {
|
||||
if e := ref(r, "knowledge_id", "knowledges", false); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := ref(r, "chunk_id", "chunks", true); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, r := range tables["wiki_page_revisions"] {
|
||||
if e := ref(r, "page_id", "wiki_pages", false); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, r := range tables["wiki_folders"] {
|
||||
if e := ref(r, "parent_id", "wiki_folders", false); e != nil {
|
||||
return e
|
||||
|
||||
@@ -173,6 +173,26 @@ func (m *targetIDMapper) remapRow(table string, row map[string]json.RawMessage)
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "chunk_revisions":
|
||||
// 编辑历史与正文走同一套映射:自身身份 + 父文档/父分块引用。
|
||||
// editor_id 是用户身份,原样保留(目标查不到就显示未知编辑者)。
|
||||
if err := m.remapScalar(row, "id", table); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.remapScalar(row, "knowledge_id", "knowledges"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.remapScalar(row, "chunk_id", "chunks"); err != nil {
|
||||
return err
|
||||
}
|
||||
case "wiki_page_revisions":
|
||||
// 自身身份 + page 引用;slug/正文/版本号/aliases 原样保留。
|
||||
if err := m.remapScalar(row, "id", table); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.remapScalar(row, "page_id", "wiki_pages"); err != nil {
|
||||
return err
|
||||
}
|
||||
case "wiki_log_entries":
|
||||
// id 是目标本地的 bigint,由既有 LocalIDs 分配;历史日志可能引用已删除文档,
|
||||
// 这类引用只做"已知才换",不能当作悬挂拒绝(否则整库同步被历史日志卡死)。
|
||||
|
||||
@@ -80,12 +80,15 @@ func (t *ProductionLibraryTarget) productionTableContent(ctx context.Context, ta
|
||||
if name == "resources" {
|
||||
continue
|
||||
}
|
||||
if !libraryResourceBodyTable(name) && name != "resource_bindings" {
|
||||
continue
|
||||
}
|
||||
items, err := exporter.queryRows(ctx, fmt.Sprintf(`SELECT to_jsonb(%s) FROM %s WHERE %s`,
|
||||
name, name, t.scopeWhere(name)), identity.TenantID, identity.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("读取生产 %s 内容失败: %w", table, err)
|
||||
}
|
||||
if name != "resource_bindings" && name != "knowledge_tag_relations" {
|
||||
if name != "resource_bindings" && name != "knowledge_tag_relations" && libraryResourceBodyTable(name) {
|
||||
bodies = append(bodies, items...)
|
||||
}
|
||||
if name == "resource_bindings" {
|
||||
|
||||
@@ -122,6 +122,13 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
t.targetIDMode = libraryrelease.TargetIDModeScoped
|
||||
// 漏表门禁:写第一笔之前的预检。导入事务里还会再查一次(写前最终判定),
|
||||
// 这里负责尽早失败,并把"空表放行"的警告写进持久发布记录。
|
||||
gateWarnings, err := verifyDeclaredKnowledgeTables(ctx, t.pool,
|
||||
PostgresIdentity{TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID}, t.schema.Profile)
|
||||
if err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
if err := validateArchivedLibraryClosure(archive, manifest); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
@@ -152,7 +159,8 @@ func (t *ProductionLibraryTarget) PlanWriteSet(ctx context.Context, plan library
|
||||
SourceTenantID: manifest.TenantID, SourceKnowledgeBaseID: manifest.KnowledgeBaseID, JobID: plan.JobID, Target: plan.Target,
|
||||
TenantID: t.scope.TenantID, KnowledgeBaseID: t.scope.KnowledgeBaseID,
|
||||
BackupSnapshotID: plan.BackupSnapshotID, TargetSnapshotID: plan.TargetSnapshotID,
|
||||
CreatedAt: t.now().UTC(), Universe: plan.Universe, TargetIDMode: libraryrelease.TargetIDModeScoped}
|
||||
CreatedAt: t.now().UTC(), Universe: plan.Universe, Warnings: gateWarnings,
|
||||
TargetIDMode: libraryrelease.TargetIDModeScoped}
|
||||
for _, part := range manifest.Parts {
|
||||
if part.Kind != "database" && part.Kind != "wiki" {
|
||||
continue
|
||||
@@ -350,6 +358,14 @@ func (t *ProductionLibraryTarget) assertWriteSetOwnership(table, id, owner strin
|
||||
return nil
|
||||
}
|
||||
|
||||
// jobCreatedRowDeleteOrder 是恢复清理的顺序契约:子表先删。编辑历史必须排在
|
||||
// 父表 chunks/wiki_pages 之前;顺序写死在一处,并有单测防止新增表时漏改。
|
||||
var jobCreatedRowDeleteOrder = []string{
|
||||
"wiki_page_revisions", "chunk_revisions", "resource_bindings", "chunks", "knowledges",
|
||||
"knowledge_tag_relations", "wiki_page_issues", "wiki_log_entries", "wiki_pages",
|
||||
"wiki_folders", "knowledge_tags", "resources",
|
||||
}
|
||||
|
||||
// clearJobCreatedRows 只删"写前不存在 ∧ 由本次写入 ∧ 不在恢复快照里"的精确身份,
|
||||
// 并且对资源额外要求它仍然没有任何绑定/正文引用(作业失败期间被别的知识库接管
|
||||
// 使用的资源不能删)。
|
||||
@@ -365,9 +381,7 @@ func (t *ProductionLibraryTarget) clearJobCreatedRows(ctx context.Context, set l
|
||||
}
|
||||
defer tx.Rollback(context.WithoutCancel(ctx))
|
||||
|
||||
// 子表先删:resource_bindings → chunks/knowledges、wiki 子表 → wiki 页 → 资源。
|
||||
for _, table := range []string{"resource_bindings", "chunks", "knowledges", "knowledge_tag_relations",
|
||||
"wiki_page_issues", "wiki_log_entries", "wiki_pages", "wiki_folders", "knowledge_tags", "resources"} {
|
||||
for _, table := range jobCreatedRowDeleteOrder {
|
||||
ids := make([]string, 0, 8)
|
||||
for _, id := range set.CreatedIDs(table) {
|
||||
if restored[table][id] {
|
||||
|
||||
@@ -84,6 +84,8 @@ const v090Folder = "wf-v090-1"
|
||||
const v090Page = "wp-v090-1"
|
||||
const v090Tag = "tg-v090-1"
|
||||
const v090Resource = "rs-v090-1"
|
||||
const v090ChunkRevision = "cr-v090-1"
|
||||
const v090PageRevision = "wr-v090-1"
|
||||
|
||||
// seedV090 造 1 KB / 1 文档 / 2 分块 / 1 wiki 页 / 1 wiki 目录 / 1 资源。
|
||||
// Wiki 必须非空:空表通过等于没有验证 wiki 部件。
|
||||
@@ -99,6 +101,8 @@ func seedV090(t *testing.T, ctx context.Context, db *pgxpool.Pool) PostgresIdent
|
||||
`INSERT INTO wiki_folders(id,tenant_id,knowledge_base_id,name,path) VALUES ('` + v090Folder + `',$1,'` + v090KB + `','夹具目录','/fixture')`,
|
||||
`INSERT INTO wiki_pages(id,tenant_id,knowledge_base_id,slug,title,content,source_refs,chunk_refs,folder_id) VALUES ('` + v090Page + `',$1,'` + v090KB + `','fixture-page','夹具页','wiki 正文','["` + v090Knowledge + `"]'::jsonb,'["` + v090ChunkOne + `"]'::jsonb,'` + v090Folder + `')`,
|
||||
`INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES ('` + v090Tag + `',$1,'` + v090KB + `','夹具标签')`,
|
||||
`INSERT INTO chunk_revisions(id,tenant_id,knowledge_base_id,knowledge_id,chunk_id,revision,content,editor_id,edit_source) VALUES ('` + v090ChunkRevision + `',$1,'` + v090KB + `','` + v090Knowledge + `','` + v090ChunkOne + `',1,'第一段旧正文','editor-a','user')`,
|
||||
`INSERT INTO wiki_page_revisions(id,tenant_id,knowledge_base_id,page_id,slug,version,title,content,edit_source,editor_id) VALUES ('` + v090PageRevision + `',$1,'` + v090KB + `','` + v090Page + `','fixture-page',1,'夹具页','旧 wiki 正文','pipeline','')`,
|
||||
`INSERT INTO knowledge_tag_relations(knowledge_id,tag_id) VALUES ('` + v090Knowledge + `','` + v090Tag + `')`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
@@ -166,7 +170,7 @@ func v090IndexSnapshot(t *testing.T, pg PostgresSnapshot, mappingSHA string) Sea
|
||||
t.Fatalf("decode chunk: %v", err)
|
||||
}
|
||||
source, err := json.Marshal(map[string]any{
|
||||
"chunk_id": chunk.ID, "tenant_id": chunk.TenantID,
|
||||
"chunk_id": chunk.ID,
|
||||
"knowledge_base_id": chunk.KnowledgeBaseID, "knowledge_id": chunk.KnowledgeID,
|
||||
"content": chunk.Content, "source_id": chunk.ID, "source_type": 0,
|
||||
})
|
||||
|
||||
@@ -21,9 +21,10 @@ const defaultBusinessTimeout = 60 * time.Second
|
||||
// resolves once, verifies the owning tenant and pins that immutable connection
|
||||
// in the returned context, so no later call can silently switch instances.
|
||||
type Client struct {
|
||||
Resolver readiness.Resolver
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
Resolver readiness.Resolver
|
||||
Timeout time.Duration
|
||||
AllowDockerHTTP bool
|
||||
AllowPrivateHTTP bool
|
||||
}
|
||||
|
||||
type taskConnection struct {
|
||||
@@ -44,10 +45,11 @@ func (client *Client) newRemote(target readiness.Target) (*weknora.Client, error
|
||||
timeout = defaultBusinessTimeout
|
||||
}
|
||||
return weknora.NewClient(weknora.ClientConfig{
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: client.AllowDockerHTTP,
|
||||
BaseURL: target.BaseURL,
|
||||
APIKey: target.APIKey,
|
||||
Timeout: timeout,
|
||||
AllowDockerHTTP: client.AllowDockerHTTP,
|
||||
AllowPrivateHTTP: client.AllowPrivateHTTP,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -146,18 +146,9 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
}
|
||||
|
||||
func mapParseStatus(status string) governance.ProcessingState {
|
||||
switch status {
|
||||
case "pending":
|
||||
return governance.ProcessingPending
|
||||
case "processing":
|
||||
return governance.ProcessingProcessing
|
||||
case "finalizing":
|
||||
return governance.ProcessingFinalizing
|
||||
case "completed":
|
||||
return governance.ProcessingCompleted
|
||||
case "failed":
|
||||
return governance.ProcessingFailed
|
||||
default:
|
||||
normalized, ok := governance.NormalizeWeKnoraParseStatus(status)
|
||||
if !ok {
|
||||
return governance.ProcessingState(status)
|
||||
}
|
||||
return governance.ProcessingState(normalized)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package testweknora
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
@@ -28,7 +30,7 @@ var (
|
||||
type UploadStore interface {
|
||||
LoadPublicationForUpload(context.Context, string) (postgresstore.PublicationForUpload, error)
|
||||
MarkUploading(context.Context, string, string, uint64, time.Time) error
|
||||
RecordUploadAndSchedulePoll(context.Context, string, string, time.Time, time.Time) (int, error)
|
||||
RecordUploadAndSchedulePoll(context.Context, string, string, string, time.Time, time.Time) (int, error)
|
||||
RecordUploadFailure(context.Context, string, string, time.Time) error
|
||||
}
|
||||
|
||||
@@ -115,8 +117,12 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
// A recovery may run after the local spool was cleaned; the ledger must
|
||||
// still record the recovered knowledge. Missing local bytes only means
|
||||
// evidence_level degrades, never that the recovery fails.
|
||||
uploadMD5, _ := handler.hashSpool(candidate)
|
||||
now := handler.now()
|
||||
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, now, now.Add(handler.firstPollDelay)); err != nil {
|
||||
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
|
||||
return ErrUploadStateConflict
|
||||
}
|
||||
return nil
|
||||
@@ -134,16 +140,27 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
if err := handler.store.MarkUploading(ctx, candidate.ID, identity.BaseURL, identity.TenantID, handler.now()); err != nil {
|
||||
return ErrUploadStateConflict
|
||||
}
|
||||
hasher := md5.New()
|
||||
knowledge, uploadErr := handler.client.UploadFile(ctx, weknora.UploadRequest{
|
||||
KnowledgeBaseID: candidate.TestKBID,
|
||||
FileName: safeUploadFileName(candidate.Title, candidate.ID, candidate.ValidatedFormat),
|
||||
Content: artifact,
|
||||
Content: io.TeeReader(artifact, hasher),
|
||||
Metadata: map[string]string{
|
||||
"content_sha256": candidate.SHA256,
|
||||
"publication_id": candidate.ID,
|
||||
},
|
||||
Channel: "governance",
|
||||
})
|
||||
uploadMD5 := hex.EncodeToString(hasher.Sum(nil))
|
||||
if uploadErr != nil {
|
||||
// The server may reject before consuming the whole body (conflict or
|
||||
// retryable transport failure). Recompute from the verified spool so the
|
||||
// ledger never stores a partial hash.
|
||||
uploadMD5, err = handler.hashSpool(candidate)
|
||||
if err != nil {
|
||||
return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_artifact_invalid")
|
||||
}
|
||||
}
|
||||
if err := artifact.VerifyComplete(); err != nil {
|
||||
return jobs.Permanent(jobs.ErrCodeArtifactInvalid, ErrUploadArtifactInvalid)
|
||||
}
|
||||
@@ -176,12 +193,33 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
|
||||
return ErrUploadRemoteIdentity
|
||||
}
|
||||
now := handler.now()
|
||||
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, now, now.Add(handler.firstPollDelay)); err != nil {
|
||||
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
|
||||
return ErrUploadStateConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (handler *UploadHandler) hashSpool(candidate postgresstore.PublicationForUpload) (string, error) {
|
||||
artifact, err := spool.OpenVerified(handler.spoolRoot, spool.Expectation{
|
||||
RelativeRef: candidate.LocalSpoolRef,
|
||||
SHA256: candidate.SHA256,
|
||||
SizeBytes: candidate.SizeBytes,
|
||||
Format: candidate.ValidatedFormat,
|
||||
}, handler.maxUploadBytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer artifact.Close()
|
||||
hasher := md5.New()
|
||||
if _, err := io.Copy(hasher, artifact); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := artifact.VerifyComplete(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(hasher.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func (handler *UploadHandler) recoverAmbiguousUpload(ctx context.Context, candidate postgresstore.PublicationForUpload) (weknora.Knowledge, error) {
|
||||
const pageSize = 100
|
||||
matches := make([]weknora.Knowledge, 0, 2)
|
||||
|
||||
@@ -332,7 +332,7 @@ func (store *uploadStoreStub) MarkUploading(_ context.Context, _ string, instanc
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *uploadStoreStub) RecordUploadAndSchedulePoll(_ context.Context, _ string, knowledgeID string, _ time.Time, nextAt time.Time) (int, error) {
|
||||
func (store *uploadStoreStub) RecordUploadAndSchedulePoll(_ context.Context, _ string, knowledgeID, _ string, _ time.Time, nextAt time.Time) (int, error) {
|
||||
store.recordedKnowledgeID = knowledgeID
|
||||
store.nextPollAt = nextAt
|
||||
return 1, nil
|
||||
|
||||
@@ -110,6 +110,9 @@ def ready(directory, bundle, test_database=None):
|
||||
env['WEKNORA_BINDING_MASTER_KEY_FILE'] = '/run/qa/binding-master.key'
|
||||
# 验收候选要连 QA 的测试 WeKnora(同网段明文 http),与生产部署口径一致。
|
||||
env['WEKNORA_ALLOW_PRIVATE_HTTP'] = 'true'
|
||||
# 导入对账(T6)只对测试库做,候选必须真的接线;它与旧的取件/上传链路
|
||||
# (TEST_WEKNORA_ENABLED)解耦,租户 Key 走知识库绑定。
|
||||
env['RECONCILIATION_ENABLED'] = 'true'
|
||||
app_env = directory / 'app.env'
|
||||
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
|
||||
names = {role: f'{project}-{role}' for role in cd.ROLES}
|
||||
|
||||
@@ -366,9 +366,30 @@ def image_inspect(image):
|
||||
return json.loads(run(['docker', 'image', 'inspect', image], 'read image identity'))[0]
|
||||
|
||||
|
||||
def container_log_tail(name, lines=5, limit=400):
|
||||
"""Give the failure text a symptom, not just a verdict.
|
||||
|
||||
A non-running container used to surface only as "expected container is not
|
||||
running"; the actual cause (missing zoneinfo, refused DSN, bad bind) lives in
|
||||
the container log and was thrown away with the container.
|
||||
"""
|
||||
try:
|
||||
result = subprocess.run(['docker', 'logs', '--tail', str(lines), name], capture_output=True, timeout=15)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return 'no container log'
|
||||
# docker CLI forwards the container's stderr to its own stderr; keep both.
|
||||
text = ' '.join((result.stdout + result.stderr).decode('utf-8', 'replace').split())
|
||||
return text[-limit:] if text else 'no container log'
|
||||
|
||||
|
||||
def inspect(name):
|
||||
obj = json.loads(run(['docker', 'container', 'inspect', name], 'read running container'))[0]
|
||||
require(obj['State']['Status'] == 'running' and matches(IMAGE, obj.get('Image')), 'expected container is not running')
|
||||
state = obj.get('State') or {}
|
||||
if state.get('Status') != 'running':
|
||||
raise CDError(f'{name}: container is {state.get("Status") or "unknown"} '
|
||||
f'(exit {state.get("ExitCode")}); log: {container_log_tail(name)}')
|
||||
require(matches(IMAGE, obj.get('Image')),
|
||||
f'{name}: running image {obj.get("Image")!r} is not an approved image ID')
|
||||
return obj
|
||||
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ describe('WorkspaceShell', () => {
|
||||
)
|
||||
|
||||
expect(html).toContain('aria-label="功能导航"')
|
||||
for (const label of ['来源与目录', '解析监控', '发布管理', '系统设置']) {
|
||||
for (const label of ['来源与目录', '导入对账', '发布管理', '系统设置']) {
|
||||
expect(html).toContain(label)
|
||||
}
|
||||
expect(html).not.toContain('来源链接')
|
||||
@@ -66,10 +66,10 @@ describe('WorkspaceShell', () => {
|
||||
expect(html).not.toContain('class="tab-list"')
|
||||
expect(html).not.toContain('class="workspace-tab')
|
||||
expect(html).toContain('来源与目录')
|
||||
expect(html).toContain('解析监控')
|
||||
expect(html).toContain('导入对账')
|
||||
expect(html).toContain('发布管理')
|
||||
expect(html).toContain('aria-label="当前位置"')
|
||||
expect(html).toContain('<b>解析监控</b>')
|
||||
expect(html).toContain('<b>导入对账</b>')
|
||||
expect(html).toContain('class="nav-item active"')
|
||||
})
|
||||
|
||||
|
||||
+3
-3
@@ -60,7 +60,7 @@ const workspaceStorageKey = 'knowledge-governance.workspace.v1'
|
||||
|
||||
const modules: ReadonlyArray<{ id: ModuleId; label: string; icon: string }> = [
|
||||
{ id: 'dashboard', label: '来源与目录', icon: '◫' },
|
||||
{ id: 'tasks', label: '解析监控', icon: '↻' },
|
||||
{ id: 'tasks', label: '导入对账', icon: '↻' },
|
||||
{ id: 'qaops', label: '问答运营', icon: '▤' },
|
||||
{ id: 'releases', label: '发布管理', icon: '⇧' },
|
||||
{ id: 'settings', label: '系统设置', icon: '⚙' },
|
||||
@@ -1330,7 +1330,7 @@ function releaseGuidance(props: ReleaseManagementProps, pending: number) {
|
||||
step: 2,
|
||||
title: '现在要做:确认测试结果',
|
||||
reason: '暂时不能继续:目前没有可以审核的已通过知识',
|
||||
action: '前往“解析监控”查看处理结果,并核对搜索效果',
|
||||
action: '前往“导入对账”查看处理结果,并核对搜索效果',
|
||||
after: '第 3 步,审核发布内容',
|
||||
impact: '只读查看,不会影响生产',
|
||||
href: '#review-actions',
|
||||
@@ -1512,7 +1512,7 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
|
||||
) : null}
|
||||
{!props.reviewLoading && publishReady.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
没有待发布的已批准知识。到「来源与目录」标注后,在「解析监控」处理完成即可发布。
|
||||
没有待发布的已批准知识。到「来源与目录」标注后,在「导入对账」处理完成即可发布。
|
||||
</div>
|
||||
) : null}
|
||||
{publishReady.length > 0 ? (
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { FindingDetail, ReconciliationFindingsView } from './ReconciliationFindings'
|
||||
import type { ReconciliationFinding, ReconciliationRun } from './reconciliationApi'
|
||||
|
||||
const run: ReconciliationRun = {
|
||||
id: 'run-1',
|
||||
kb_id: 'kb-1',
|
||||
state: 'succeeded',
|
||||
trigger: 'manual',
|
||||
started_at: '2026-12-01T02:00:00Z',
|
||||
finished_at: '2026-12-01T02:01:00Z',
|
||||
ledger_count: 12,
|
||||
kb_count: 11,
|
||||
counts: { R1: 1, R2: 0, R3: 2, R4: 0, R5: 0, R6: 0, R7: 0, R8: 0 },
|
||||
previous_counts: { R1: 0, R2: 0, R3: 2, R4: 0, R5: 0, R6: 0, R7: 0, R8: 0 },
|
||||
window_overlapped: true,
|
||||
error_code: '',
|
||||
}
|
||||
const finding: ReconciliationFinding = {
|
||||
id: 'f1',
|
||||
run_id: 'run-1',
|
||||
type: 'R1',
|
||||
publication_id: 'pub-1',
|
||||
document_id: 'doc-1',
|
||||
title: '缺失文件.pdf',
|
||||
path: '产品/缺失文件.pdf',
|
||||
source: '技术资料',
|
||||
target_scope: 'internal',
|
||||
ledger_state: 'completed',
|
||||
weknora_parse_status: '',
|
||||
normalized_state: '',
|
||||
ledger_sha256: '',
|
||||
declared_sha256: '',
|
||||
weknora_file_md5: '',
|
||||
evidence_level: 'none',
|
||||
confirmation_state: 'pending',
|
||||
detail: '台账认为应在库,单条读取返回 404',
|
||||
suggested_action: 'requeue_upload',
|
||||
action_state: 'open',
|
||||
weknora_url: '',
|
||||
}
|
||||
const props = {
|
||||
overview: null,
|
||||
runs: { items: [run], total: 1, limit: 20, offset: 0 },
|
||||
findings: { items: [finding], total: 1, limit: 20, offset: 0 },
|
||||
filters: { type: '', q: '' },
|
||||
selectedRunID: 'run-1',
|
||||
selectedKB: 'kb-1',
|
||||
kbOptions: [{ id: 'kb-1', name: '测试知识库' }],
|
||||
loading: false,
|
||||
busy: false,
|
||||
canOperate: true,
|
||||
canRemove: true,
|
||||
error: '',
|
||||
message: '',
|
||||
onTab: vi.fn(),
|
||||
onSelectRun: vi.fn(),
|
||||
onSelectKB: vi.fn(),
|
||||
onFilters: vi.fn(),
|
||||
onPage: vi.fn(),
|
||||
onRefresh: vi.fn(),
|
||||
onCreate: vi.fn(),
|
||||
onAction: vi.fn(),
|
||||
onDetail: vi.fn(),
|
||||
}
|
||||
describe('reconciliation findings', () => {
|
||||
it('shows batch counts, pending confirmation, evidence and actions', () => {
|
||||
const html = renderToStaticMarkup(<ReconciliationFindingsView {...props} />)
|
||||
for (const text of [
|
||||
'导入对账',
|
||||
'差异清单',
|
||||
'平台侧流水',
|
||||
'立即对账',
|
||||
'R1 丢失',
|
||||
'待确认',
|
||||
'无',
|
||||
'重排上传',
|
||||
'缺失文件.pdf',
|
||||
])
|
||||
expect(html).toContain(text)
|
||||
expect(html).toContain('当前筛选 1 项')
|
||||
expect(html).toContain('保留最近 30 批')
|
||||
})
|
||||
it('hides trigger and actions from a read-only role', () => {
|
||||
const html = renderToStaticMarkup(<ReconciliationFindingsView {...props} canOperate={false} canRemove={false} />)
|
||||
expect(html).not.toContain('立即对账')
|
||||
expect(html).not.toContain('>重排上传</button>')
|
||||
expect(html).toContain('只读角色')
|
||||
})
|
||||
it('renders loading, empty and error states', () => {
|
||||
const loading = renderToStaticMarkup(
|
||||
<ReconciliationFindingsView
|
||||
{...props}
|
||||
runs={{ items: [], total: 0, limit: 20, offset: 0 }}
|
||||
findings={{ items: [], total: 0, limit: 20, offset: 0 }}
|
||||
selectedRunID=""
|
||||
loading={true}
|
||||
/>
|
||||
)
|
||||
expect(loading).toContain('正在读取差异')
|
||||
expect(loading).toContain('还没有对账批次')
|
||||
const failed = renderToStaticMarkup(<ReconciliationFindingsView {...props} error="读取对账批次失败" />)
|
||||
expect(failed).toContain('读取对账批次失败')
|
||||
})
|
||||
it('links a finding to WeKnora when the backend supplies a URL', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<FindingDetail
|
||||
finding={{ ...finding, weknora_url: 'https://weknora.test/platform/knowledge-bases/kb-1' }}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
expect(html).toContain('href="https://weknora.test/platform/knowledge-bases/kb-1"')
|
||||
expect(html).toContain('在 WeKnora 中打开')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,488 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { MonitorOverview } from './monitor'
|
||||
import type {
|
||||
ReconciliationFinding,
|
||||
ReconciliationFindingPage,
|
||||
ReconciliationFindingType,
|
||||
ReconciliationProgress,
|
||||
ReconciliationRunPage,
|
||||
} from './reconciliationApi'
|
||||
import { fetchReconciliationProgress, ReconciliationRequestError } from './reconciliationApi'
|
||||
import './monitorWorkbench.css'
|
||||
|
||||
const time = (value: string | null | undefined) =>
|
||||
value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—'
|
||||
const typeLabels: Record<ReconciliationFindingType, string> = {
|
||||
R1: 'R1 丢失',
|
||||
R2: 'R2 孤儿',
|
||||
R3: 'R3 非平台导入',
|
||||
R4: 'R4 内容过期',
|
||||
R5: 'R5 状态不一致',
|
||||
R6: 'R6 应下架仍在',
|
||||
R7: 'R7 卡住',
|
||||
R8: 'R8 一对多',
|
||||
}
|
||||
const evidenceLabels = { independent: '独立证据', declared_only: '仅声明', none: '无' }
|
||||
const actionLabels: Record<string, string> = {
|
||||
requeue_upload: '重排上传',
|
||||
remove_from_test: '从测试库移除',
|
||||
writeback_state: '以 WeKnora 为准回写',
|
||||
enter_removal: '进入需下架流程',
|
||||
none: '不处置',
|
||||
}
|
||||
const countKeys = ['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8']
|
||||
|
||||
export interface FindingFilters {
|
||||
type: string
|
||||
q: string
|
||||
}
|
||||
|
||||
interface FindingsProps {
|
||||
overview: MonitorOverview | null
|
||||
runs: ReconciliationRunPage
|
||||
findings: ReconciliationFindingPage
|
||||
filters: FindingFilters
|
||||
selectedRunID: string
|
||||
selectedKB: string
|
||||
kbOptions: { id: string; name: string }[]
|
||||
loading: boolean
|
||||
busy: boolean
|
||||
canOperate: boolean
|
||||
canRemove: boolean
|
||||
error: string
|
||||
message: string
|
||||
onTab: (tab: 'findings' | 'platform') => void
|
||||
onSelectRun: (id: string) => void
|
||||
onSelectKB: (id: string) => void
|
||||
onFilters: (value: FindingFilters) => void
|
||||
onPage: (offset: number) => void
|
||||
onRefresh: () => void
|
||||
onCreate: () => void
|
||||
onAction: (finding: ReconciliationFinding) => void
|
||||
onDetail: (finding: ReconciliationFinding) => void
|
||||
}
|
||||
|
||||
// ServiceStrip is the page-top one-line status required by §8: the service and
|
||||
// dependency area collapses into a row on both tabs. Queue truth comes from
|
||||
// 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 ready = overview?.health.filter((item) => item.readiness === 'ready').length
|
||||
const attention = overview?.health.filter(
|
||||
(item) => item.applicable && item.configured && item.readiness !== 'ready'
|
||||
).length
|
||||
return (
|
||||
<section className="monitor-service-strip" aria-label="服务与队列">
|
||||
<span>
|
||||
WeKnora 队列:
|
||||
{queue ? (
|
||||
<b>
|
||||
{queue.queues.reduce((sum, item) => sum + item.pending, 0)} 等待 ·{' '}
|
||||
{queue.queues.reduce((sum, item) => sum + item.active, 0)} 运行
|
||||
</b>
|
||||
) : (
|
||||
<b className="monitor-muted">未配置只读 Key 或队列不可用</b>
|
||||
)}
|
||||
</span>
|
||||
<span>
|
||||
服务:
|
||||
<b>{ready == null ? '等待运行快照' : `${ready} 可接单`}</b>
|
||||
{attention ? <b className="monitor-bad"> · {attention} 项需关注</b> : null}
|
||||
</span>
|
||||
<span className="monitor-muted">一期只对测试库;生产下架依赖测试移除 + 下一轮整库发布</span>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export function ReconciliationFindingsView(p: FindingsProps) {
|
||||
const run = p.runs.items.find((item) => item.id === p.selectedRunID) || p.runs.items[0] || null
|
||||
const previous = run?.previous_counts || null
|
||||
const pageCount = Math.max(1, Math.ceil(p.findings.total / p.findings.limit))
|
||||
return (
|
||||
<main className="page-shell monitor-workbench">
|
||||
<header className="monitor-heading page-header">
|
||||
<div>
|
||||
<h1 className="page-title">导入对账</h1>
|
||||
<p className="page-subtitle">台账与测试 WeKnora 知识库的差异、证据与处置</p>
|
||||
</div>
|
||||
<span>{p.overview ? `快照 ${time(p.overview.observed_at)}` : '等待运行快照'}</span>
|
||||
<button disabled={p.busy || p.loading} onClick={p.onRefresh}>
|
||||
{p.loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</header>
|
||||
<nav className="monitor-tabs" aria-label="导入对账分区">
|
||||
<button className="active" type="button" onClick={() => p.onTab('findings')}>
|
||||
差异清单
|
||||
</button>
|
||||
<button type="button" onClick={() => p.onTab('platform')}>
|
||||
平台侧流水
|
||||
</button>
|
||||
</nav>
|
||||
{p.error ? (
|
||||
<div className="monitor-alert" role="alert">
|
||||
{p.error}
|
||||
</div>
|
||||
) : null}
|
||||
<ServiceStrip overview={p.overview} />
|
||||
<section className="monitor-recon-overview" aria-label="最近一次对账">
|
||||
<div className="monitor-recon-controls">
|
||||
<label>
|
||||
测试知识库
|
||||
<select value={p.selectedKB} disabled={p.busy} onChange={(e) => p.onSelectKB(e.target.value)}>
|
||||
<option value="">全部测试库</option>
|
||||
{p.kbOptions.map((option) => (
|
||||
<option key={option.id} value={option.id}>
|
||||
{option.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
批次
|
||||
<select
|
||||
value={run?.id || ''}
|
||||
disabled={p.busy || !p.runs.items.length}
|
||||
onChange={(e) => p.onSelectRun(e.target.value)}
|
||||
>
|
||||
{p.runs.items.map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{time(item.started_at)} · {item.state}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{p.canOperate ? (
|
||||
<button className="primary" disabled={p.busy || !p.selectedKB} onClick={p.onCreate}>
|
||||
{p.busy ? '提交中…' : '立即对账'}
|
||||
</button>
|
||||
) : (
|
||||
<span className="monitor-muted">只读角色:可查看差异,不能触发或处置</span>
|
||||
)}
|
||||
</div>
|
||||
{run ? (
|
||||
<>
|
||||
<p className="monitor-muted">
|
||||
{time(run.started_at)} · {run.trigger === 'schedule' ? '定时' : '手动'} · 台账 {run.ledger_count} 条 ·
|
||||
库内 {run.kb_count} 条{run.window_overlapped ? ' · 与整库作业重叠,R1/R2 待确认' : ''}
|
||||
{run.error_code ? ` · 失败:${run.error_code}` : ''}
|
||||
</p>
|
||||
<div className="monitor-diff-counts">
|
||||
{countKeys.map((key) => (
|
||||
<span key={key} className={run.counts[key] ? 'has-diff' : ''}>
|
||||
<b>{run.counts[key] ?? 0}</b>
|
||||
<small>{key}</small>
|
||||
{previous ? (
|
||||
<em>
|
||||
{run.counts[key] === previous[key]
|
||||
? '持平'
|
||||
: `${run.counts[key] > (previous[key] || 0) ? '+' : ''}${run.counts[key] - (previous[key] || 0)}`}
|
||||
</em>
|
||||
) : null}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="monitor-muted">还没有对账批次。选择测试知识库后点「立即对账」。</p>
|
||||
)}
|
||||
{p.message ? (
|
||||
<div className="monitor-result" role="status">
|
||||
{p.message}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
<section className="monitor-files">
|
||||
<div className="monitor-section-heading">
|
||||
<div className="monitor-heading-group">
|
||||
<h2>差异清单</h2>
|
||||
<small className="monitor-scope-note">
|
||||
当前筛选 {p.findings.total} 项 · 本页 {p.findings.items.length} 项
|
||||
</small>
|
||||
</div>
|
||||
<span>明细保留最近 30 批且不超过 90 天</span>
|
||||
</div>
|
||||
<div className="monitor-filters">
|
||||
<input
|
||||
aria-label="搜索差异文件或说明"
|
||||
placeholder="搜索文件名称、目录或说明"
|
||||
value={p.filters.q}
|
||||
disabled={p.busy}
|
||||
onChange={(e) => p.onFilters({ ...p.filters, q: e.target.value })}
|
||||
/>
|
||||
<select
|
||||
aria-label="差异类型"
|
||||
value={p.filters.type}
|
||||
disabled={p.busy}
|
||||
onChange={(e) => p.onFilters({ ...p.filters, type: e.target.value })}
|
||||
>
|
||||
<option value="">全部类型</option>
|
||||
{Object.entries(typeLabels).map(([key, label]) => (
|
||||
<option key={key} value={key}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
className="monitor-link"
|
||||
disabled={p.busy || (!p.filters.q && !p.filters.type)}
|
||||
onClick={() => p.onFilters({ type: '', q: '' })}
|
||||
>
|
||||
清除筛选
|
||||
</button>
|
||||
</div>
|
||||
<div className="monitor-table-scroll" aria-busy={p.loading}>
|
||||
<table className="monitor-unified-table monitor-finding-table">
|
||||
<colgroup>
|
||||
<col style={{ width: '9%' }} />
|
||||
<col style={{ width: '22%' }} />
|
||||
<col style={{ width: '10%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '13%' }} />
|
||||
<col style={{ width: '9%' }} />
|
||||
<col style={{ width: '16%' }} />
|
||||
<col style={{ width: '8%' }} />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>类型</th>
|
||||
<th>文件名称 / 目录</th>
|
||||
<th>来源</th>
|
||||
<th>台账 / WeKnora</th>
|
||||
<th>证据 / 建议</th>
|
||||
<th>确认</th>
|
||||
<th>说明</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{p.findings.items.map((finding) => (
|
||||
<tr key={finding.id}>
|
||||
<td>
|
||||
<span className={`monitor-finding-type ${finding.type.toLowerCase()}`}>
|
||||
{typeLabels[finding.type]}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<b className="monitor-file-name">{finding.title || '未命名文件'}</b>
|
||||
<small title={finding.path}>{finding.path || '未提供目录'}</small>
|
||||
</td>
|
||||
<td>
|
||||
<span className="monitor-clamp">{finding.source || '—'}</span>
|
||||
</td>
|
||||
<td>
|
||||
<small>
|
||||
台账 {finding.ledger_state || '—'} → WeKnora {finding.normalized_state || '—'}
|
||||
</small>
|
||||
</td>
|
||||
<td>
|
||||
<small>{evidenceLabels[finding.evidence_level]}</small>
|
||||
<small>{actionLabels[finding.suggested_action]}</small>
|
||||
</td>
|
||||
<td>
|
||||
{finding.confirmation_state === 'pending' ? (
|
||||
<span className="monitor-badge-pending">待确认</span>
|
||||
) : (
|
||||
<span className="monitor-muted">已确认</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="monitor-detail-cell" title={finding.detail}>
|
||||
{finding.detail}
|
||||
</td>
|
||||
<td>
|
||||
<button className="monitor-link" onClick={() => p.onDetail(finding)}>
|
||||
详情
|
||||
</button>
|
||||
{p.canOperate && finding.action_state === 'open' && finding.suggested_action !== 'none' ? (
|
||||
<button
|
||||
className="monitor-link"
|
||||
disabled={p.busy || (finding.suggested_action === 'remove_from_test' && !p.canRemove)}
|
||||
onClick={() => p.onAction(finding)}
|
||||
>
|
||||
{actionLabels[finding.suggested_action]}
|
||||
</button>
|
||||
) : null}
|
||||
{finding.action_state === 'done' ? <span className="monitor-muted">已处置</span> : null}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!p.findings.items.length ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="monitor-empty">
|
||||
{p.loading ? '正在读取差异…' : run ? '该批次没有差异。' : '先选择一个对账批次。'}
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<footer className="monitor-pagination">
|
||||
<span>
|
||||
当前筛选共 {p.findings.total} 项 · 每页 {p.findings.limit} 项
|
||||
</span>
|
||||
<div>
|
||||
<button
|
||||
disabled={p.busy || p.loading || p.findings.offset === 0}
|
||||
onClick={() => p.onPage(Math.max(0, p.findings.offset - p.findings.limit))}
|
||||
>
|
||||
上一页
|
||||
</button>
|
||||
<span>
|
||||
第 {Math.floor(p.findings.offset / p.findings.limit) + 1} / {pageCount} 页
|
||||
</span>
|
||||
<button
|
||||
disabled={p.busy || p.loading || p.findings.offset + p.findings.limit >= p.findings.total}
|
||||
onClick={() => p.onPage(p.findings.offset + p.findings.limit)}
|
||||
>
|
||||
下一页
|
||||
</button>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
export function WeKnoraProgress({
|
||||
documentID,
|
||||
weknoraURL,
|
||||
compact = false,
|
||||
}: {
|
||||
documentID: string
|
||||
weknoraURL?: string
|
||||
compact?: boolean
|
||||
}) {
|
||||
const [progress, setProgress] = useState<ReconciliationProgress | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
useEffect(() => {
|
||||
if (!documentID) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
const controller = new AbortController()
|
||||
setLoading(true)
|
||||
setError('')
|
||||
void fetchReconciliationProgress(documentID, controller.signal)
|
||||
.then((value) => {
|
||||
if (!controller.signal.aborted) setProgress(value)
|
||||
})
|
||||
.catch((err) => {
|
||||
if (controller.signal.aborted) return
|
||||
setProgress(null)
|
||||
if (err instanceof ReconciliationRequestError && err.code === 'runtime_read_unavailable') {
|
||||
setError('未配置 WeKnora 只读 Key,无法读取实时处理详情。')
|
||||
} else {
|
||||
setError(err instanceof Error ? err.message : '读取 WeKnora 处理详情失败')
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [documentID])
|
||||
return (
|
||||
<section className={compact ? 'monitor-progress compact' : 'monitor-progress'}>
|
||||
<div className="monitor-section-heading">
|
||||
<h3>WeKnora 处理详情</h3>
|
||||
<small>实时读取,不落库</small>
|
||||
</div>
|
||||
{loading ? <p className="monitor-muted">正在读取…</p> : null}
|
||||
{error ? (
|
||||
<p className="monitor-alert">
|
||||
{error}
|
||||
{weknoraURL ? (
|
||||
<>
|
||||
{' '}
|
||||
<a href={weknoraURL} target="_blank" rel="noreferrer">
|
||||
在 WeKnora 中打开
|
||||
</a>
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
) : null}
|
||||
{progress ? (
|
||||
<>
|
||||
<p className="monitor-muted">
|
||||
{progress.parse_status || '—'} · 入库 {progress.ingestion_status || '—'} · Wiki{' '}
|
||||
{progress.wiki_status || '—'} · 读取 {time(progress.observed_at)}
|
||||
</p>
|
||||
{progress.stages.length ? (
|
||||
<ol className="monitor-stages">
|
||||
{progress.stages.map((stage) => (
|
||||
<li key={`${stage.name}-${stage.status}`}>
|
||||
<b>{stage.name}</b> {stage.status}
|
||||
{stage.error_code ? ` · ${stage.error_code}` : ''}
|
||||
{stage.finished_at ? ` · ${time(stage.finished_at)}` : ''}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
) : (
|
||||
<p className="monitor-muted">还没有阶段记录。</p>
|
||||
)}
|
||||
{progress.failures.length ? (
|
||||
<div className="monitor-failures">
|
||||
<b>历史失败</b>
|
||||
{progress.failures.map((failure) => (
|
||||
<p key={`${failure.task_type}-${failure.failed_at}`}>
|
||||
{failure.task_type} · 尝试 {failure.fail_count} · {time(failure.failed_at)} · {failure.last_error}
|
||||
</p>
|
||||
))}
|
||||
{progress.has_more_failures ? <small>仅显示最近 50 条失败。</small> : null}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
export function FindingDetail({ finding, onClose }: { finding: ReconciliationFinding; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
useEffect(() => {
|
||||
ref.current?.showModal()
|
||||
}, [])
|
||||
return (
|
||||
<dialog className="monitor-drawer" ref={ref} onCancel={onClose}>
|
||||
<header>
|
||||
<h2>{typeLabels[finding.type]} · 处理详情</h2>
|
||||
<button onClick={onClose} autoFocus>
|
||||
关闭
|
||||
</button>
|
||||
</header>
|
||||
<h3>{finding.title || '未命名文件'}</h3>
|
||||
<dl>
|
||||
{[
|
||||
['目录', finding.path],
|
||||
['来源', finding.source],
|
||||
['发布标识', finding.publication_id],
|
||||
['远端文档', finding.document_id],
|
||||
['台账状态', finding.ledger_state],
|
||||
['WeKnora 状态', finding.weknora_parse_status],
|
||||
['归一状态', finding.normalized_state],
|
||||
['台账 SHA256', finding.ledger_sha256],
|
||||
['声明 SHA256', finding.declared_sha256],
|
||||
['WeKnora MD5', finding.weknora_file_md5],
|
||||
['证据等级', evidenceLabels[finding.evidence_level]],
|
||||
['确认状态', finding.confirmation_state === 'pending' ? '待确认' : '已确认'],
|
||||
['处置建议', actionLabels[finding.suggested_action]],
|
||||
['说明', finding.detail],
|
||||
].map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd>{value || '—'}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{finding.weknora_url ? (
|
||||
<p>
|
||||
<a href={finding.weknora_url} target="_blank" rel="noreferrer">
|
||||
在 WeKnora 中打开
|
||||
</a>
|
||||
</p>
|
||||
) : null}
|
||||
{finding.document_id ? (
|
||||
<WeKnoraProgress documentID={finding.document_id} weknoraURL={finding.weknora_url} compact />
|
||||
) : null}
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import type { Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { WeKnoraProgress } from './ReconciliationFindings'
|
||||
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
beforeEach(() => {
|
||||
;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
describe('WeKnora progress drawer block', () => {
|
||||
it('degrades to a read-only key message on 503', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'runtime_read_unavailable', code: 'runtime_read_unavailable' }), {
|
||||
status: 503,
|
||||
})
|
||||
)
|
||||
)
|
||||
await act(async () => root.render(<WeKnoraProgress documentID="doc-1" />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('未配置 WeKnora 只读 Key')
|
||||
})
|
||||
it('shows stages and failures when available', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
document_id: 'doc-1',
|
||||
parse_status: 'failed',
|
||||
ingestion_status: 'failed',
|
||||
wiki_status: 'none',
|
||||
stages: [{ name: 'parse', status: 'failed', error_code: 'E1', finished_at: '2026-12-01T00:00:00Z' }],
|
||||
failures: [
|
||||
{ task_type: 'parse', fail_count: 2, failed_at: '2026-12-01T00:00:00Z', last_error: '解析失败' },
|
||||
],
|
||||
has_more_failures: false,
|
||||
observed_at: '2026-12-01T00:00:00Z',
|
||||
},
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
)
|
||||
)
|
||||
await act(async () => root.render(<WeKnoraProgress documentID="doc-1" />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('parse')
|
||||
expect(container.textContent).toContain('解析失败')
|
||||
expect(container.textContent).toContain('failed')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import type { Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { TaskDetail } from './WeKnoraMonitor'
|
||||
import type { MonitorTask } from './monitorTasks'
|
||||
|
||||
const item: MonitorTask = {
|
||||
id: 'tp-1',
|
||||
title: '维护手册.pdf',
|
||||
path: '产品/维护',
|
||||
node_id: 'node-1',
|
||||
parent_node_id: 'folder-1',
|
||||
source_id: 's1',
|
||||
source_name: '技术资料',
|
||||
target_scope: 'internal',
|
||||
target_kb: 'kb-1',
|
||||
document_id: 'doc-1',
|
||||
weknora_url: 'https://weknora.test/platform/knowledge-bases/kb-1',
|
||||
action: 'update',
|
||||
stage: 'parsing',
|
||||
status: 'running',
|
||||
detail: '正在解析处理',
|
||||
updated_at: '2026-12-01T02:00:00Z',
|
||||
retry_kind: '',
|
||||
failure_id: '',
|
||||
retry_count: 0,
|
||||
version_id: 'v1',
|
||||
}
|
||||
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
beforeEach(() => {
|
||||
// React's test-only global; the test environment exposes it without a type.
|
||||
const reactTestGlobal: { IS_REACT_ACT_ENVIRONMENT: boolean } = globalThis as unknown as {
|
||||
IS_REACT_ACT_ENVIRONMENT: boolean
|
||||
}
|
||||
reactTestGlobal.IS_REACT_ACT_ENVIRONMENT = true
|
||||
// jsdom does not implement the dialog methods the drawer calls on mount.
|
||||
HTMLDialogElement.prototype.showModal = function showModal(this: HTMLDialogElement) {
|
||||
this.open = true
|
||||
}
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
describe('platform task drawer', () => {
|
||||
it('offers the WeKnora jump link when progress answers 503', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'runtime_read_unavailable', code: 'runtime_read_unavailable' }), {
|
||||
status: 503,
|
||||
})
|
||||
)
|
||||
)
|
||||
await act(async () => root.render(<TaskDetail item={item} onClose={vi.fn()} />))
|
||||
await act(async () => await Promise.resolve())
|
||||
expect(container.textContent).toContain('未配置 WeKnora 只读 Key')
|
||||
expect(container.querySelector('a[href="https://weknora.test/platform/knowledge-bases/kb-1"]')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -15,6 +15,7 @@ const page: MonitorTaskPage = {
|
||||
source_name: '技术资料',
|
||||
target_scope: 'internal',
|
||||
target_kb: 'test-kb',
|
||||
document_id: 'doc-1',
|
||||
action: 'update',
|
||||
stage: 'parsing',
|
||||
status: 'attention',
|
||||
@@ -35,6 +36,7 @@ const page: MonitorTaskPage = {
|
||||
source_name: '技术资料',
|
||||
target_scope: 'external',
|
||||
target_kb: 'test-public',
|
||||
document_id: 'doc-2',
|
||||
action: 'remove',
|
||||
stage: 'finished',
|
||||
status: 'completed',
|
||||
@@ -65,6 +67,8 @@ const props = {
|
||||
selected: [],
|
||||
busy: false,
|
||||
canOperate: true,
|
||||
tab: 'platform' as const,
|
||||
onTab: vi.fn(),
|
||||
onFilters: vi.fn(),
|
||||
onPage: vi.fn(),
|
||||
onSelection: vi.fn(),
|
||||
@@ -88,18 +92,21 @@ describe('unified monitor', () => {
|
||||
'状态说明',
|
||||
'共 145',
|
||||
'重试所选',
|
||||
'服务与依赖',
|
||||
'monitor-service-strip',
|
||||
'WeKnora 队列:',
|
||||
])
|
||||
expect(html).toContain(s)
|
||||
expect(html).not.toContain('开始处理')
|
||||
expect(html).not.toContain('role="tab"')
|
||||
expect(html).not.toContain('monitor-service-grid')
|
||||
expect(html).toContain('value="active" selected=""')
|
||||
})
|
||||
it('does not claim healthy zeroes or 100% when metrics are unavailable', () => {
|
||||
const html = renderToStaticMarkup(<WeKnoraMonitorView {...props} error="无法读取运行指标" />)
|
||||
expect(html).toContain('无法读取运行指标')
|
||||
expect(html).not.toContain('100%')
|
||||
expect(html).toContain('尚未取得服务状态')
|
||||
expect(html).toContain('等待运行快照')
|
||||
expect(html).not.toContain('0 可接单')
|
||||
})
|
||||
it('keeps removal semantics and does not offer retry for completed rows', () => {
|
||||
const html = renderToStaticMarkup(<WeKnoraMonitorView {...props} />)
|
||||
@@ -131,7 +138,7 @@ describe('target identity and probe attribution', () => {
|
||||
expect(html).toContain('历史')
|
||||
expect(html).toContain('产品/维护')
|
||||
})
|
||||
it('shows liveness and the sanitized probe target separately from readiness', () => {
|
||||
it('surfaces a blocked service in the one-line strip without claiming readiness', () => {
|
||||
const overview = {
|
||||
mode: 'real',
|
||||
simulated: false,
|
||||
@@ -166,7 +173,7 @@ describe('target identity and probe attribution', () => {
|
||||
],
|
||||
}
|
||||
const html = renderToStaticMarkup(<WeKnoraMonitorView {...props} overview={overview} />)
|
||||
expect(html).toContain('存活 up')
|
||||
expect(html).toContain('探测对象 实例 weknora.test · 知识库 1b52c140')
|
||||
expect(html).toContain('0 可接单')
|
||||
expect(html).toContain('1 项需关注')
|
||||
})
|
||||
})
|
||||
|
||||
+229
-74
@@ -7,16 +7,30 @@ import {
|
||||
canRetryTask,
|
||||
actionLabels,
|
||||
stageLabels,
|
||||
stageFilterLabels,
|
||||
taskStatusLabels,
|
||||
targetLabel,
|
||||
} from './monitorTasks'
|
||||
import type { MonitorFilters, MonitorTask, MonitorTaskPage } from './monitorTasks'
|
||||
import { requeueJobFailure, retryPublicationsBatch } from './testPublications'
|
||||
import { requeueJobFailure, retryPublicationsBatch, startPublicationRemoval } from './testPublications'
|
||||
import { fetchActiveUISettings, settingsRefreshDelays } from './uiSettings'
|
||||
import { useOptionalAuth } from './auth'
|
||||
import { WorkspaceContextTabsSetter } from './workspaceContext'
|
||||
import { ReconciliationFindingsView, FindingDetail, ServiceStrip, WeKnoraProgress } from './ReconciliationFindings'
|
||||
import type { FindingFilters } from './ReconciliationFindings'
|
||||
import {
|
||||
createReconciliationRun,
|
||||
fetchReconciliationFindings,
|
||||
fetchReconciliationRuns,
|
||||
removeFinding,
|
||||
requeueFinding,
|
||||
writebackFinding,
|
||||
} from './reconciliationApi'
|
||||
import type { ReconciliationFinding, ReconciliationFindingPage, ReconciliationRunPage } from './reconciliationApi'
|
||||
import './monitorWorkbench.css'
|
||||
|
||||
const emptyRuns: ReconciliationRunPage = { items: [], total: 0, limit: 20, offset: 0 }
|
||||
const emptyFindings: ReconciliationFindingPage = { items: [], total: 0, limit: 20, offset: 0 }
|
||||
const emptyPage: MonitorTaskPage = {
|
||||
items: [],
|
||||
total: 0,
|
||||
@@ -54,6 +68,10 @@ interface ViewProps {
|
||||
error: string
|
||||
message: string
|
||||
canOperate: boolean
|
||||
tab: 'findings' | 'platform'
|
||||
onTab: (tab: 'findings' | 'platform') => void
|
||||
title?: string
|
||||
subtitle?: string
|
||||
onFilters: (value: MonitorFilters) => void
|
||||
onPage: (offset: number) => void
|
||||
onSelection: (rows: MonitorTask[]) => void
|
||||
@@ -83,14 +101,22 @@ export function WeKnoraMonitorView(p: ViewProps) {
|
||||
<main className="page-shell monitor-workbench">
|
||||
<header className="monitor-heading page-header">
|
||||
<div>
|
||||
<h1 className="page-title">解析监控</h1>
|
||||
<p className="page-subtitle">运行概况与文件处理进度</p>
|
||||
<h1 className="page-title">{p.title || '平台侧流水'}</h1>
|
||||
<p className="page-subtitle">{p.subtitle || '上传、解析、移除与重试记录;不按对账口径过滤被顶替行'}</p>
|
||||
</div>
|
||||
<span>{overview ? `快照 ${time(overview.observed_at)}` : '等待运行快照'}</span>
|
||||
<button disabled={busy || loading} onClick={p.onRefresh}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</header>
|
||||
<nav className="monitor-tabs" aria-label="导入对账分区">
|
||||
<button type="button" onClick={() => p.onTab('findings')}>
|
||||
差异清单
|
||||
</button>
|
||||
<button className="active" type="button" onClick={() => p.onTab('platform')}>
|
||||
平台侧流水
|
||||
</button>
|
||||
</nav>
|
||||
{p.error ? (
|
||||
<div className="monitor-alert" role="alert">
|
||||
{p.error}
|
||||
@@ -171,41 +197,7 @@ export function WeKnoraMonitorView(p: ViewProps) {
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
<section className="monitor-service-panel">
|
||||
<div className="monitor-section-heading">
|
||||
<h2>服务与依赖</h2>
|
||||
<span>展开查看状态原因</span>
|
||||
</div>
|
||||
<div className="monitor-service-grid">
|
||||
{overview?.health.length ? (
|
||||
overview.health.map((s) => (
|
||||
<details key={s.key} className="monitor-service">
|
||||
<summary>
|
||||
<span>{s.name}</span>
|
||||
<b
|
||||
className={
|
||||
healthLabel(s) === '可接单'
|
||||
? 'monitor-good'
|
||||
: ['阻断', '不可达'].includes(healthLabel(s))
|
||||
? 'monitor-bad'
|
||||
: ''
|
||||
}
|
||||
>
|
||||
● {healthLabel(s)}
|
||||
</b>
|
||||
</summary>
|
||||
<p>{s.reason || '未提供状态说明'}</p>
|
||||
<small>
|
||||
检测:{time(s.observed_at)} · {s.latency_ms} ms · 存活 {s.liveness || '未确认'}
|
||||
{s.probe_target ? ` · 探测对象 ${s.probe_target}` : ''}
|
||||
</small>
|
||||
</details>
|
||||
))
|
||||
) : (
|
||||
<p className="monitor-muted">尚未取得服务状态</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<ServiceStrip overview={overview} />
|
||||
<section className="monitor-files">
|
||||
<div className="monitor-section-heading">
|
||||
<div className="monitor-heading-group">
|
||||
@@ -308,7 +300,7 @@ export function WeKnoraMonitorView(p: ViewProps) {
|
||||
onChange={(e) => patchFilter('stage', e.target.value)}
|
||||
>
|
||||
<option value="">全部阶段</option>
|
||||
{Object.entries(stageLabels).map(([key, label]) => (
|
||||
{Object.entries(stageFilterLabels).map(([key, label]) => (
|
||||
<option key={key} value={key}>
|
||||
{label}
|
||||
</option>
|
||||
@@ -514,7 +506,7 @@ export function WeKnoraMonitorView(p: ViewProps) {
|
||||
</main>
|
||||
)
|
||||
}
|
||||
function TaskDetail({
|
||||
export function TaskDetail({
|
||||
item,
|
||||
onClose,
|
||||
onLocateSource,
|
||||
@@ -580,6 +572,9 @@ function TaskDetail({
|
||||
))}
|
||||
</section>
|
||||
) : null}
|
||||
{item.document_id ? (
|
||||
<WeKnoraProgress documentID={item.document_id} weknoraURL={item.weknora_url} compact />
|
||||
) : null}
|
||||
<p className="monitor-muted">新增、更新完成表示测试库处理完成;移除完成表示测试库内容移除,不代表生产发布。</p>
|
||||
{item.status === 'attention' ? (
|
||||
<p className="monitor-alert">
|
||||
@@ -601,6 +596,20 @@ export function WeKnoraMonitor({
|
||||
} = {}) {
|
||||
const auth = useOptionalAuth()
|
||||
const canOperate = auth?.identity?.role === 'admin' || auth?.identity?.role === 'engineer'
|
||||
const canRemove = auth?.identity?.role === 'admin'
|
||||
const [tab, setTab] = useState<'findings' | 'platform'>(focus ? 'platform' : 'findings')
|
||||
const [runs, setRuns] = useState<ReconciliationRunPage>(emptyRuns)
|
||||
const [selectedRunID, setSelectedRunID] = useState('')
|
||||
const [findings, setFindings] = useState<ReconciliationFindingPage>(emptyFindings)
|
||||
const [findingFilters, setFindingFilters] = useState<FindingFilters>({ type: '', q: '' })
|
||||
const [findingOffset, setFindingOffset] = useState(0)
|
||||
const [selectedKB, setSelectedKB] = useState('')
|
||||
const [findingDetail, setFindingDetail] = useState<ReconciliationFinding | null>(null)
|
||||
const [reconLoading, setReconLoading] = useState(true)
|
||||
const [reconBusy, setReconBusy] = useState(false)
|
||||
const [reconError, setReconError] = useState('')
|
||||
const [reconMessage, setReconMessage] = useState('')
|
||||
const [reconRev, setReconRev] = useState(0)
|
||||
const [overview, setOverview] = useState<MonitorOverview | null>(null),
|
||||
[metrics, setMetrics] = useState<RunMetrics | null>(null)
|
||||
const [page, setPage] = useState(emptyPage),
|
||||
@@ -624,6 +633,7 @@ export function WeKnoraMonitor({
|
||||
// 会遮蔽已完成文件的筛选;应用后由父消费掉,避免重挂载时旧请求再次覆盖手工筛选。
|
||||
useEffect(() => {
|
||||
if (!focus) return
|
||||
setTab('platform')
|
||||
setFilters({ ...defaultMonitorFilters, q: focus.q, source: focus.source, status: '' })
|
||||
setOffset(0)
|
||||
setSelected([])
|
||||
@@ -649,6 +659,10 @@ export function WeKnoraMonitor({
|
||||
return () => clearTimeout(t)
|
||||
}, [resRev, delays.resourceMs])
|
||||
useEffect(() => {
|
||||
if (tab !== 'platform') {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
const c = new AbortController()
|
||||
setLoading(true)
|
||||
const timer = window.setTimeout(() => {
|
||||
@@ -678,7 +692,7 @@ export function WeKnoraMonitor({
|
||||
clearTimeout(timer)
|
||||
c.abort()
|
||||
}
|
||||
}, [filters, offset, docRev])
|
||||
}, [tab, filters, offset, docRev])
|
||||
useEffect(() => {
|
||||
const c = new AbortController()
|
||||
void fetchMonitorOverview(c.signal)
|
||||
@@ -709,9 +723,110 @@ export function WeKnoraMonitor({
|
||||
})
|
||||
return () => c.abort()
|
||||
}, [resRev])
|
||||
useEffect(() => {
|
||||
if (selectedKB || !overview?.knowledge_bases.length) return
|
||||
setSelectedKB(overview.knowledge_bases[0].id)
|
||||
}, [overview, selectedKB])
|
||||
useEffect(() => {
|
||||
if (tab !== 'findings') return
|
||||
const c = new AbortController()
|
||||
setReconLoading(true)
|
||||
void fetchReconciliationRuns(20, 0, selectedKB, c.signal)
|
||||
.then((page) => {
|
||||
if (c.signal.aborted) return
|
||||
setRuns(page)
|
||||
setReconError('')
|
||||
const current = page.items.find((item) => item.id === selectedRunID)
|
||||
if (!current && page.items[0]) setSelectedRunID(page.items[0].id)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!c.signal.aborted) {
|
||||
setRuns(emptyRuns)
|
||||
setReconError(e instanceof Error ? e.message : '读取对账批次失败')
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!c.signal.aborted) setReconLoading(false)
|
||||
})
|
||||
return () => c.abort()
|
||||
}, [tab, selectedKB, reconRev, selectedRunID])
|
||||
useEffect(() => {
|
||||
if (tab !== 'findings' || !selectedRunID) {
|
||||
setFindings(emptyFindings)
|
||||
return
|
||||
}
|
||||
const c = new AbortController()
|
||||
setReconLoading(true)
|
||||
void fetchReconciliationFindings(selectedRunID, findingFilters.type, findingFilters.q, 20, findingOffset, c.signal)
|
||||
.then((page) => {
|
||||
if (!c.signal.aborted) {
|
||||
setFindings(page)
|
||||
setReconError('')
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!c.signal.aborted) {
|
||||
setFindings(emptyFindings)
|
||||
setReconError(e instanceof Error ? e.message : '读取差异清单失败')
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!c.signal.aborted) setReconLoading(false)
|
||||
})
|
||||
return () => c.abort()
|
||||
}, [tab, selectedRunID, findingFilters, findingOffset, reconRev])
|
||||
const createRun = async () => {
|
||||
if (reconBusy) return
|
||||
const kbID = selectedKB || overview?.knowledge_bases[0]?.id || ''
|
||||
if (!kbID) {
|
||||
setReconMessage('请先选择测试知识库')
|
||||
return
|
||||
}
|
||||
setReconBusy(true)
|
||||
setReconMessage('')
|
||||
try {
|
||||
const run = await createReconciliationRun(kbID)
|
||||
setSelectedRunID(run.id)
|
||||
setReconMessage('已提交对账;扫描在后台执行,完成后刷新可见。')
|
||||
setReconRev((x) => x + 1)
|
||||
} catch (e) {
|
||||
setReconMessage(e instanceof Error ? e.message : '触发对账失败')
|
||||
} finally {
|
||||
setReconBusy(false)
|
||||
}
|
||||
}
|
||||
const actOnFinding = async (finding: ReconciliationFinding) => {
|
||||
if (reconBusy) return
|
||||
if (
|
||||
finding.suggested_action === 'remove_from_test' &&
|
||||
!window.confirm('从测试库删除该孤儿条目?不会删除来源文件或生产内容。')
|
||||
)
|
||||
return
|
||||
setReconBusy(true)
|
||||
setReconMessage('')
|
||||
try {
|
||||
if (finding.suggested_action === 'enter_removal') {
|
||||
if (!finding.publication_id) throw new Error('缺少发布标识,无法进入移除流程')
|
||||
await startPublicationRemoval(finding.publication_id)
|
||||
} else if (finding.suggested_action === 'writeback_state') {
|
||||
await writebackFinding(finding.id)
|
||||
} else if (finding.suggested_action === 'requeue_upload') {
|
||||
await requeueFinding(finding.id)
|
||||
} else if (finding.suggested_action === 'remove_from_test') {
|
||||
await removeFinding(finding.id)
|
||||
}
|
||||
setReconMessage('处置已受理;状态以服务端读回为准。')
|
||||
setReconRev((x) => x + 1)
|
||||
} catch (e) {
|
||||
setReconMessage(e instanceof Error ? e.message : '处置失败')
|
||||
} finally {
|
||||
setReconBusy(false)
|
||||
}
|
||||
}
|
||||
const refresh = () => {
|
||||
setDocRev((x) => x + 1)
|
||||
setResRev((x) => x + 1)
|
||||
setReconRev((x) => x + 1)
|
||||
}
|
||||
const selectAll = async () => {
|
||||
if (busy) return
|
||||
@@ -796,40 +911,80 @@ export function WeKnoraMonitor({
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<WeKnoraMonitorView
|
||||
overview={overview}
|
||||
metrics={metrics}
|
||||
page={page}
|
||||
filters={filters}
|
||||
selected={selected}
|
||||
loading={loading}
|
||||
busy={busy}
|
||||
error={Object.values(errors).filter(Boolean).join(';')}
|
||||
message={message}
|
||||
canOperate={canOperate}
|
||||
onFilters={(v) => {
|
||||
setFilters(v)
|
||||
setOffset(0)
|
||||
setSelected([])
|
||||
setMessage('')
|
||||
setLoading(true)
|
||||
}}
|
||||
onPage={setOffset}
|
||||
onSelection={setSelected}
|
||||
onSelectAll={() => void selectAll()}
|
||||
onRetry={(r) => void retry(r)}
|
||||
onDetail={(row) => {
|
||||
void fetchMonitorTasks({ id: row.id }, 0, 1)
|
||||
.then((p) => {
|
||||
if (p.items[0]) setDetail(p.items[0])
|
||||
else setMessage('该条记录已被新版本替换,请刷新列表')
|
||||
})
|
||||
.catch((e) => setMessage(e instanceof Error ? e.message : '读取详情失败'))
|
||||
}}
|
||||
onRefresh={refresh}
|
||||
onLocateSource={onLocateSource}
|
||||
/>
|
||||
{tab === 'findings' ? (
|
||||
<ReconciliationFindingsView
|
||||
overview={overview}
|
||||
runs={runs}
|
||||
findings={findings}
|
||||
filters={findingFilters}
|
||||
selectedRunID={selectedRunID}
|
||||
selectedKB={selectedKB}
|
||||
kbOptions={(overview?.knowledge_bases || []).map((item) => ({ id: item.id, name: item.name }))}
|
||||
loading={reconLoading}
|
||||
busy={reconBusy}
|
||||
canOperate={canOperate}
|
||||
canRemove={canRemove}
|
||||
error={reconError}
|
||||
message={reconMessage}
|
||||
onTab={setTab}
|
||||
onSelectRun={(id) => {
|
||||
setSelectedRunID(id)
|
||||
setFindingOffset(0)
|
||||
}}
|
||||
onSelectKB={(id) => {
|
||||
setSelectedKB(id)
|
||||
setSelectedRunID('')
|
||||
setFindingOffset(0)
|
||||
}}
|
||||
onFilters={(value) => {
|
||||
setFindingFilters(value)
|
||||
setFindingOffset(0)
|
||||
}}
|
||||
onPage={setFindingOffset}
|
||||
onRefresh={refresh}
|
||||
onCreate={() => void createRun()}
|
||||
onAction={(finding) => void actOnFinding(finding)}
|
||||
onDetail={setFindingDetail}
|
||||
/>
|
||||
) : (
|
||||
<WeKnoraMonitorView
|
||||
overview={overview}
|
||||
metrics={metrics}
|
||||
page={page}
|
||||
filters={filters}
|
||||
selected={selected}
|
||||
loading={loading}
|
||||
busy={busy}
|
||||
error={Object.values(errors).filter(Boolean).join(';')}
|
||||
message={message}
|
||||
canOperate={canOperate}
|
||||
tab={tab}
|
||||
onTab={setTab}
|
||||
onFilters={(v) => {
|
||||
setFilters(v)
|
||||
setOffset(0)
|
||||
setSelected([])
|
||||
setMessage('')
|
||||
setLoading(true)
|
||||
}}
|
||||
onPage={setOffset}
|
||||
onSelection={setSelected}
|
||||
onSelectAll={() => void selectAll()}
|
||||
onRetry={(r) => void retry(r)}
|
||||
onDetail={(row) => {
|
||||
void fetchMonitorTasks({ id: row.id }, 0, 1)
|
||||
.then((p) => {
|
||||
if (p.items[0]) setDetail(p.items[0])
|
||||
else setMessage('该条记录已被新版本替换,请刷新列表')
|
||||
})
|
||||
.catch((e) => setMessage(e instanceof Error ? e.message : '读取详情失败'))
|
||||
}}
|
||||
onRefresh={refresh}
|
||||
onLocateSource={onLocateSource}
|
||||
/>
|
||||
)}
|
||||
{detail ? <TaskDetail item={detail} onClose={() => setDetail(null)} onLocateSource={onLocateSource} /> : null}
|
||||
{findingDetail ? <FindingDetail finding={findingDetail} onClose={() => setFindingDetail(null)} /> : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -57,6 +57,24 @@ export interface IngestionPipeline {
|
||||
fetch_missing: number
|
||||
concurrency: number
|
||||
}
|
||||
export interface WeKnoraQueue {
|
||||
name: string
|
||||
pool: string
|
||||
pending: number
|
||||
active: number
|
||||
scheduled: number
|
||||
retry: number
|
||||
archived: number
|
||||
processed: number
|
||||
failed: number
|
||||
}
|
||||
export interface WeKnoraQueues {
|
||||
available: boolean
|
||||
queues_error: boolean
|
||||
workers_error: boolean
|
||||
queues: WeKnoraQueue[]
|
||||
timestamp: number
|
||||
}
|
||||
export interface MonitorOverview {
|
||||
mode: string
|
||||
simulated: boolean
|
||||
@@ -66,6 +84,7 @@ export interface MonitorOverview {
|
||||
knowledge_bases: KnowledgeProgress[]
|
||||
pipeline?: IngestionPipeline
|
||||
health: ServiceHealth[]
|
||||
weknora_queues?: WeKnoraQueues | null
|
||||
}
|
||||
export interface MonitorFile {
|
||||
name: string
|
||||
|
||||
@@ -9,6 +9,9 @@ export interface MonitorTask {
|
||||
source_name: string
|
||||
target_scope: string
|
||||
target_kb: string
|
||||
document_id?: string
|
||||
// 目标测试知识库的控制台链接;后端按当前生效测试端点生成,未配置时为空。
|
||||
weknora_url?: string
|
||||
action: string
|
||||
stage: string
|
||||
status: string
|
||||
@@ -73,6 +76,16 @@ export const stageLabels: Record<string, string> = {
|
||||
removal: '测试库移除',
|
||||
finished: '结束',
|
||||
}
|
||||
// 阶段筛选按需求 §8 合并「解析」「索引增强」为「WeKnora 处理中」;行内展示仍用
|
||||
// stageLabels 的细粒度阶段,两者不要互相替代。
|
||||
export const stageFilterLabels: Record<string, string> = {
|
||||
waiting: '等待调度',
|
||||
fetch: '取件',
|
||||
upload: '上传',
|
||||
weknora: 'WeKnora 处理中',
|
||||
removal: '测试库移除',
|
||||
finished: '结束',
|
||||
}
|
||||
export const taskStatusLabels: Record<string, string> = {
|
||||
waiting: '等待中',
|
||||
running: '执行中',
|
||||
|
||||
+191
-67
@@ -77,25 +77,14 @@
|
||||
.monitor-numbers .monitor-memory {
|
||||
font-size: 24px;
|
||||
}
|
||||
.monitor-good {
|
||||
color: var(--c-done) !important;
|
||||
}
|
||||
.monitor-bad {
|
||||
color: var(--c-fail) !important;
|
||||
}
|
||||
.monitor-service-panel,
|
||||
.monitor-files {
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: var(--r-lg);
|
||||
background: var(--bg-panel);
|
||||
box-shadow: var(--shadow-card);
|
||||
overflow: hidden;
|
||||
}
|
||||
.monitor-service-panel {
|
||||
padding: 18px 20px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.monitor-files {
|
||||
/* 时间范围浮层要能溢出卡片;圆角由表头/分页各自裁切 */
|
||||
overflow: visible;
|
||||
}
|
||||
@@ -125,56 +114,6 @@
|
||||
font-size: 11px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.monitor-service-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(6, minmax(0, 1fr));
|
||||
gap: 9px;
|
||||
margin-top: 13px;
|
||||
align-items: start;
|
||||
}
|
||||
.monitor-service {
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-soft);
|
||||
padding: 10px 12px;
|
||||
transition:
|
||||
border-color 120ms ease,
|
||||
background 120ms ease;
|
||||
}
|
||||
.monitor-service:hover,
|
||||
.monitor-service[open] {
|
||||
border-color: var(--border-base);
|
||||
background: var(--bg-panel);
|
||||
font-size: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
.monitor-service summary {
|
||||
list-style: none;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.monitor-service summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
.monitor-service summary > span {
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--ink-base);
|
||||
font-weight: 500;
|
||||
}
|
||||
.monitor-service b {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.monitor-service p,
|
||||
.monitor-service small {
|
||||
font-size: 11px;
|
||||
color: var(--ink-mute);
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.monitor-files > .monitor-section-heading {
|
||||
padding: 18px 20px 14px;
|
||||
}
|
||||
@@ -542,9 +481,6 @@
|
||||
.monitor-metric-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.monitor-service-grid {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.monitor-heading {
|
||||
@@ -553,9 +489,6 @@
|
||||
.monitor-heading > span {
|
||||
margin-left: 0;
|
||||
}
|
||||
.monitor-service-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.monitor-metric-grid {
|
||||
gap: 8px;
|
||||
}
|
||||
@@ -593,3 +526,194 @@
|
||||
padding: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
/* T6 导入对账:页签、批次概览、差异表与实时处理详情。沿用钴蓝/中性灰,不引入紫色。 */
|
||||
.monitor-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 0 0 14px;
|
||||
padding: 4px;
|
||||
width: fit-content;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 999px;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.monitor-tabs button {
|
||||
min-height: 32px;
|
||||
padding: 0 16px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--ink-mute);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.monitor-tabs button.active {
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-strong);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.monitor-service-strip {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 22px;
|
||||
margin-bottom: 14px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: var(--r-lg);
|
||||
background: var(--bg-panel);
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.monitor-service-strip b {
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
.monitor-recon-overview {
|
||||
margin-bottom: 16px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: var(--r-lg);
|
||||
background: var(--bg-panel);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
.monitor-recon-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 12px;
|
||||
}
|
||||
.monitor-recon-controls label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.monitor-recon-controls select {
|
||||
min-width: 180px;
|
||||
max-width: 280px;
|
||||
}
|
||||
.monitor-diff-counts {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(8, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.monitor-diff-counts > span {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.monitor-diff-counts b {
|
||||
font-size: 20px;
|
||||
line-height: 1.2;
|
||||
color: var(--ink-strong);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.monitor-diff-counts small,
|
||||
.monitor-diff-counts em {
|
||||
font-size: 10px;
|
||||
font-style: normal;
|
||||
color: var(--ink-mute);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.monitor-diff-counts .has-diff {
|
||||
border-color: color-mix(in srgb, var(--c-fail) 45%, var(--border-base));
|
||||
}
|
||||
.monitor-diff-counts .has-diff b {
|
||||
color: var(--c-fail);
|
||||
}
|
||||
.monitor-finding-type {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-soft);
|
||||
border: 1px solid var(--border-base);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.monitor-finding-type.r1,
|
||||
.monitor-finding-type.r2,
|
||||
.monitor-finding-type.r4,
|
||||
.monitor-finding-type.r7 {
|
||||
border-color: color-mix(in srgb, var(--c-fail) 45%, var(--border-base));
|
||||
color: var(--c-fail);
|
||||
}
|
||||
.monitor-finding-type.r5,
|
||||
.monitor-finding-type.r6 {
|
||||
border-color: color-mix(in srgb, var(--c-warn, #b7791f) 45%, var(--border-base));
|
||||
}
|
||||
.monitor-badge-pending {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: #fff7e6;
|
||||
border: 1px solid #e6b450;
|
||||
color: #8a5a00;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.monitor-progress {
|
||||
margin-top: 16px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--border-base);
|
||||
}
|
||||
.monitor-progress.compact {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.monitor-progress h3 {
|
||||
font-size: 13px;
|
||||
margin: 0;
|
||||
}
|
||||
.monitor-stages {
|
||||
margin: 10px 0 0;
|
||||
padding-left: 18px;
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.monitor-failures {
|
||||
margin-top: 12px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-soft);
|
||||
font-size: 12px;
|
||||
}
|
||||
.monitor-failures p {
|
||||
margin: 6px 0 0;
|
||||
color: var(--ink-mute);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@media (max-width: 1024px) {
|
||||
.monitor-diff-counts {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
.monitor-address-grid,
|
||||
.monitor-metric-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.monitor-diff-counts {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.monitor-recon-controls select {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
.monitor-service-strip {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createReconciliationRun,
|
||||
fetchReconciliationFindings,
|
||||
fetchReconciliationProgress,
|
||||
ReconciliationRequestError,
|
||||
} from './reconciliationApi'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
const run = {
|
||||
id: 'run-1',
|
||||
kb_id: 'kb-1',
|
||||
state: 'running',
|
||||
trigger: 'manual',
|
||||
started_at: '2026-12-01T02:00:00Z',
|
||||
finished_at: null,
|
||||
ledger_count: 0,
|
||||
kb_count: 0,
|
||||
counts: {},
|
||||
previous_counts: null,
|
||||
window_overlapped: false,
|
||||
error_code: '',
|
||||
}
|
||||
describe('reconciliation API client', () => {
|
||||
it('sends the write intent and kb_id when creating a run', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: run }), { status: 202 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const created = await createReconciliationRun('kb-1')
|
||||
expect(created.id).toBe('run-1')
|
||||
const [, init] = fetchMock.mock.calls[0]
|
||||
expect(init.headers['X-Governance-Action']).toBe('reconciliation-action')
|
||||
expect(JSON.parse(String(init.body))).toEqual({ kb_id: 'kb-1' })
|
||||
})
|
||||
it('surfaces 409 run-in-progress code', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ error: 'reconciliation_run_in_progress', code: 'reconciliation_run_in_progress' }),
|
||||
{
|
||||
status: 409,
|
||||
}
|
||||
)
|
||||
)
|
||||
)
|
||||
try {
|
||||
await createReconciliationRun('kb-1')
|
||||
throw new Error('expected 409')
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ReconciliationRequestError)
|
||||
expect((error as ReconciliationRequestError).status).toBe(409)
|
||||
expect((error as ReconciliationRequestError).code).toBe('reconciliation_run_in_progress')
|
||||
}
|
||||
})
|
||||
it('marks 503 progress as runtime_read_unavailable', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'runtime_read_unavailable', code: 'runtime_read_unavailable' }), {
|
||||
status: 503,
|
||||
})
|
||||
)
|
||||
)
|
||||
await expect(fetchReconciliationProgress('doc-1')).rejects.toMatchObject({
|
||||
code: 'runtime_read_unavailable',
|
||||
})
|
||||
})
|
||||
it('parses findings and rejects an unknown type', async () => {
|
||||
const finding = {
|
||||
id: 'f1',
|
||||
run_id: 'run-1',
|
||||
type: 'R1',
|
||||
publication_id: 'pub-1',
|
||||
document_id: 'doc-1',
|
||||
title: 't',
|
||||
path: 'p',
|
||||
source: 's',
|
||||
target_scope: 'internal',
|
||||
ledger_state: 'completed',
|
||||
weknora_parse_status: '',
|
||||
normalized_state: '',
|
||||
ledger_sha256: '',
|
||||
declared_sha256: '',
|
||||
weknora_file_md5: '',
|
||||
evidence_level: 'none',
|
||||
confirmation_state: 'pending',
|
||||
detail: 'd',
|
||||
suggested_action: 'requeue_upload',
|
||||
action_state: 'open',
|
||||
weknora_url: '',
|
||||
}
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: { items: [finding], total: 1, limit: 20, offset: 0 } }), { status: 200 })
|
||||
)
|
||||
)
|
||||
const page = await fetchReconciliationFindings('run-1')
|
||||
expect(page.items[0].confirmation_state).toBe('pending')
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ data: { items: [{ ...finding, type: 'R9' }], total: 1, limit: 20, offset: 0 } }),
|
||||
{
|
||||
status: 200,
|
||||
}
|
||||
)
|
||||
)
|
||||
)
|
||||
await expect(fetchReconciliationFindings('run-1')).rejects.toThrow('对账差异响应无效')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,227 @@
|
||||
export type ReconciliationFindingType = 'R1' | 'R2' | 'R3' | 'R4' | 'R5' | 'R6' | 'R7' | 'R8'
|
||||
export type ReconciliationEvidence = 'independent' | 'declared_only' | 'none'
|
||||
export type ReconciliationConfirmation = 'confirmed' | 'pending'
|
||||
export type ReconciliationAction = 'requeue_upload' | 'remove_from_test' | 'writeback_state' | 'enter_removal' | 'none'
|
||||
|
||||
export interface ReconciliationRun {
|
||||
id: string
|
||||
kb_id: string
|
||||
state: 'running' | 'succeeded' | 'failed'
|
||||
trigger: 'schedule' | 'manual'
|
||||
started_at: string
|
||||
finished_at: string | null
|
||||
ledger_count: number
|
||||
kb_count: number
|
||||
counts: Record<string, number>
|
||||
previous_counts: Record<string, number> | null
|
||||
window_overlapped: boolean
|
||||
error_code: string
|
||||
}
|
||||
export interface ReconciliationRunPage {
|
||||
items: ReconciliationRun[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
export interface ReconciliationFinding {
|
||||
id: string
|
||||
run_id: string
|
||||
type: ReconciliationFindingType
|
||||
publication_id: string
|
||||
document_id: string
|
||||
title: string
|
||||
path: string
|
||||
source: string
|
||||
target_scope: string
|
||||
ledger_state: string
|
||||
weknora_parse_status: string
|
||||
normalized_state: string
|
||||
ledger_sha256: string
|
||||
declared_sha256: string
|
||||
weknora_file_md5: string
|
||||
evidence_level: ReconciliationEvidence
|
||||
confirmation_state: ReconciliationConfirmation
|
||||
detail: string
|
||||
suggested_action: ReconciliationAction
|
||||
action_state: 'open' | 'done'
|
||||
weknora_url: string
|
||||
}
|
||||
export interface ReconciliationFindingPage {
|
||||
items: ReconciliationFinding[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
export interface ReconciliationStage {
|
||||
name: string
|
||||
status: string
|
||||
error_code: string
|
||||
finished_at: string | null
|
||||
}
|
||||
export interface ReconciliationFailure {
|
||||
task_type: string
|
||||
fail_count: number
|
||||
failed_at: string
|
||||
last_error: string
|
||||
}
|
||||
export interface ReconciliationProgress {
|
||||
document_id: string
|
||||
parse_status: string
|
||||
ingestion_status: string
|
||||
wiki_status: string
|
||||
stages: ReconciliationStage[]
|
||||
failures: ReconciliationFailure[]
|
||||
has_more_failures: boolean
|
||||
observed_at: string
|
||||
}
|
||||
|
||||
const record = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
|
||||
const count = (value: unknown) => typeof value === 'number' && Number.isInteger(value) && value >= 0
|
||||
const text = (value: unknown) => (typeof value === 'string' ? value : '')
|
||||
|
||||
export class ReconciliationRequestError extends Error {
|
||||
status: number
|
||||
code: string
|
||||
constructor(message: string, status: number, code: string) {
|
||||
super(message)
|
||||
this.status = status
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
async function request(path: string, init: RequestInit, signal?: AbortSignal): Promise<unknown> {
|
||||
const response = await fetch(path, {
|
||||
...init,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(init.body ? { 'Content-Type': 'application/json' } : {}),
|
||||
...(init.headers || {}),
|
||||
},
|
||||
signal,
|
||||
})
|
||||
const payload = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
const body = record(payload) ? payload : {}
|
||||
throw new ReconciliationRequestError(
|
||||
text(body.error) || `请求失败(HTTP ${response.status})`,
|
||||
response.status,
|
||||
text(body.code)
|
||||
)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
function parseRun(value: unknown): ReconciliationRun {
|
||||
if (
|
||||
!record(value) ||
|
||||
typeof value.id !== 'string' ||
|
||||
typeof value.kb_id !== 'string' ||
|
||||
!['running', 'succeeded', 'failed'].includes(String(value.state)) ||
|
||||
!['schedule', 'manual'].includes(String(value.trigger)) ||
|
||||
typeof value.started_at !== 'string' ||
|
||||
!count(value.ledger_count) ||
|
||||
!count(value.kb_count) ||
|
||||
!record(value.counts) ||
|
||||
typeof value.window_overlapped !== 'boolean'
|
||||
)
|
||||
throw new Error('对账批次响应无效')
|
||||
return value as unknown as ReconciliationRun
|
||||
}
|
||||
|
||||
function parseFinding(value: unknown): ReconciliationFinding {
|
||||
if (
|
||||
!record(value) ||
|
||||
typeof value.id !== 'string' ||
|
||||
!['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8'].includes(String(value.type)) ||
|
||||
!['independent', 'declared_only', 'none'].includes(String(value.evidence_level)) ||
|
||||
!['confirmed', 'pending'].includes(String(value.confirmation_state)) ||
|
||||
!['requeue_upload', 'remove_from_test', 'writeback_state', 'enter_removal', 'none'].includes(
|
||||
String(value.suggested_action)
|
||||
) ||
|
||||
!['open', 'done'].includes(String(value.action_state))
|
||||
)
|
||||
throw new Error('对账差异响应无效')
|
||||
return value as unknown as ReconciliationFinding
|
||||
}
|
||||
|
||||
export async function fetchReconciliationRuns(
|
||||
limit = 20,
|
||||
offset = 0,
|
||||
kbID = '',
|
||||
signal?: AbortSignal
|
||||
): Promise<ReconciliationRunPage> {
|
||||
const query = new URLSearchParams({ limit: String(limit), offset: String(offset) })
|
||||
if (kbID) query.set('kb_id', kbID)
|
||||
const payload = await request(`/api/v1/reconciliation/runs?${query}`, { method: 'GET' }, signal)
|
||||
if (!record(payload) || !record(payload.data) || !Array.isArray(payload.data.items))
|
||||
throw new Error('对账批次列表响应无效')
|
||||
return {
|
||||
items: payload.data.items.map(parseRun),
|
||||
total: Number(payload.data.total) || 0,
|
||||
limit: Number(payload.data.limit) || limit,
|
||||
offset: Number(payload.data.offset) || offset,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchReconciliationFindings(
|
||||
runID: string,
|
||||
type = '',
|
||||
q = '',
|
||||
limit = 20,
|
||||
offset = 0,
|
||||
signal?: AbortSignal
|
||||
): Promise<ReconciliationFindingPage> {
|
||||
const query = new URLSearchParams({ limit: String(limit), offset: String(offset) })
|
||||
if (type) query.set('type', type)
|
||||
if (q) query.set('q', q)
|
||||
const payload = await request(
|
||||
`/api/v1/reconciliation/runs/${encodeURIComponent(runID)}/findings?${query}`,
|
||||
{ method: 'GET' },
|
||||
signal
|
||||
)
|
||||
if (!record(payload) || !record(payload.data) || !Array.isArray(payload.data.items))
|
||||
throw new Error('对账差异列表响应无效')
|
||||
return {
|
||||
items: payload.data.items.map(parseFinding),
|
||||
total: Number(payload.data.total) || 0,
|
||||
limit: Number(payload.data.limit) || limit,
|
||||
offset: Number(payload.data.offset) || offset,
|
||||
}
|
||||
}
|
||||
|
||||
export async function createReconciliationRun(kbID: string): Promise<ReconciliationRun> {
|
||||
const payload = await request('/api/v1/reconciliation/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'X-Governance-Action': 'reconciliation-action' },
|
||||
body: JSON.stringify({ kb_id: kbID }),
|
||||
})
|
||||
if (!record(payload) || !record(payload.data)) throw new Error('触发对账响应无效')
|
||||
return parseRun(payload.data)
|
||||
}
|
||||
|
||||
async function findingAction(id: string, action: 'writeback' | 'requeue' | 'remove'): Promise<ReconciliationFinding> {
|
||||
const payload = await request(`/api/v1/reconciliation/findings/${encodeURIComponent(id)}/${action}`, {
|
||||
method: 'POST',
|
||||
headers: { 'X-Governance-Action': 'reconciliation-action' },
|
||||
})
|
||||
if (!record(payload) || !record(payload.data)) throw new Error('对账处置响应无效')
|
||||
return parseFinding(payload.data)
|
||||
}
|
||||
|
||||
export const writebackFinding = (id: string) => findingAction(id, 'writeback')
|
||||
export const requeueFinding = (id: string) => findingAction(id, 'requeue')
|
||||
export const removeFinding = (id: string) => findingAction(id, 'remove')
|
||||
|
||||
export async function fetchReconciliationProgress(
|
||||
documentID: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<ReconciliationProgress> {
|
||||
const payload = await request(
|
||||
`/api/v1/reconciliation/documents/${encodeURIComponent(documentID)}/progress`,
|
||||
{ method: 'GET' },
|
||||
signal
|
||||
)
|
||||
if (!record(payload) || !record(payload.data) || typeof payload.data.document_id !== 'string')
|
||||
throw new Error('WeKnora 处理详情响应无效')
|
||||
return payload.data as unknown as ReconciliationProgress
|
||||
}
|
||||
Reference in New Issue
Block a user