feat(reconciliation): T6 导入对账(契约/后端/前端) #41
@@ -27,6 +27,17 @@ QA_AI_MASTER_KEY_FILE=
|
||||
# 「知识库绑定」密钥密文的独立主密钥(32字节、0600 常规文件),挂载到 api 与 worker。
|
||||
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
|
||||
WEKNORA_BINDING_MASTER_KEY_FILE=
|
||||
# 测试实例平台级只读 Key:绝对路径、0400;留空 = runtime/* 与队列降级。
|
||||
WEKNORA_RUNTIME_KEY_FILE=
|
||||
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
|
||||
|
||||
@@ -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.TestWeKnoraEnabled {
|
||||
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.TestWeKnoraEnabled && 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,18 @@ 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_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 +147,15 @@ 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_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}"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# 需求书:解析监控重构为「导入对账」
|
||||
|
||||
> 状态:v0.5(2026-11-30),已批准;Q1、Q5、Q6、Q7、Q9、Q10、Q11 已裁定。
|
||||
> 状态: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 的需求正文。
|
||||
|
||||
@@ -145,19 +146,21 @@ T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,
|
||||
|
||||
| 方法 | 路径 | 说明 | 角色 |
|
||||
| --- | --- | --- | --- |
|
||||
| POST | `/api/v1/reconciliation/runs` | 请求体 `{test_kb_id}`;返回 202 和 run 对象;该库已有运行中批次时返回 409 `reconciliation_run_in_progress` | 管理员、文档工程师 |
|
||||
| GET | `/api/v1/reconciliation/runs?test_kb_id=&limit=&offset=` | 批次列表,按开始时间倒序 | 所有登录角色 |
|
||||
| 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/{knowledge_id}/progress` | 实时转发 WeKnora `runtime/documents/{id}`,经过脱敏;未配置平台 Key 时返回 503 `runtime_read_unavailable` | 所有登录角色 |
|
||||
| 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 两张常量"未知"卡 | 不变 |
|
||||
|
||||
**run 对象**:`id`、`test_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`。
|
||||
**`/api/v1/monitor/tasks`(已有,T6a 增量)**:每行新增可选 `weknora_url`(目标测试知识库的 WeKnora 控制台链接;未配置测试端点时为空字符串),供文件详情抽屉在 progress 返回 503 时显示跳转链接。该字段为附加字段,既有字段与筛选语义不变;与 finding 的 `weknora_url` 使用同一拼接规则(`internal/platform/weknora.KnowledgeBaseConsoleURL`)。
|
||||
|
||||
**finding 对象**:`id`、`run_id`、`type`(R1–R8)、`publication_id`、`knowledge_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 中打开的链接,可为空)。
|
||||
**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`)
|
||||
|
||||
@@ -175,9 +178,9 @@ T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,
|
||||
- 台账在本批次后已被别的动作改过时返回 409 `reconciliation_writeback_stale`。
|
||||
- 回写只改 `processing_state`,不动 `retrieval_state`,不触发发布。
|
||||
|
||||
**progress 对象**:`knowledge_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`。
|
||||
**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 能复用现有接口**(`removal-retry`);R1/R4 不能走 `retryPublicationsBatch`(只接受 `failed`/`stalled`,`job_failures.go:448`),R2 不能走测试库移除(拒绝 `superseded`,`test_publication_removal.go:68`),所以这两个是新接口,不是同义接口。
|
||||
处置动作的落点:`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,前端)
|
||||
|
||||
@@ -241,3 +244,5 @@ T6a 的**第一个提交**必须先把以下接口写进 `api/openapi.yaml`,
|
||||
| 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` 只重试已失败移除 |
|
||||
|
||||
@@ -147,7 +147,7 @@ T6a 对账后端(第一个提交 = OpenAPI 契约)──► T6b 对账前端
|
||||
- 与整库导出/发布不互斥;批次开始和结束时各检测一次是否有导出/发布作业在跑,命中则写 `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 复用现有 `removal-retry`。R1/R4 不能走 `retryPublicationsBatch`,R2 不能走测试库移除,原因见需求 §7(Q9)。
|
||||
- 处置动作:新增 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 天"提示)。
|
||||
|
||||
+109
-43
@@ -53,16 +53,29 @@ 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:批次执行参数。全部可配,但都有安全默认值。
|
||||
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 +211,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 +397,49 @@ 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_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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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