From 4528a55e6a308822fe0eba70a4614325e7b361c4 Mon Sep 17 00:00:00 2001 From: Zhero & Rin Date: Tue, 1 Dec 2026 12:19:54 +0800 Subject: [PATCH] =?UTF-8?q?feat(reconciliation):=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E5=AF=B9=E8=B4=A6=E5=90=8E=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为什么:T6a 需要一张批次/差异表、全量只读扫描、R1-R8 判定和 finding 级处置;现有解析监控只转述台账状态,无法回答库内是否一致。 做什么:迁移 000084(upload_md5、runs/findings/actions、共享 removal_candidates 视图);WeKnora 字段与 1000/页扫描;runtime 只读客户端(0400 Key、503 降级);扫描/矩阵/动作/定时/僵死回收;9 条接口与 RBAC;overview 队列与删两张常量卡。 边界:只对测试库;对账零写请求;R1/R2 单条确认;R6 复用 /removal;R2 只管理员;生产链路未改。 验证:make verify 全绿(17 项);新增矩阵/扫描 R1-R8/零写/失败整批/动作/运行时/密钥权限测试。 --- .env.example | 11 + cmd/api/main.go | 52 +- cmd/worker/library_role_test.go | 6 +- cmd/worker/main.go | 56 +- cmd/worker/main_test.go | 8 +- cmd/worker/reconciliation_scheduler.go | 64 ++ compose.yaml | 21 + docs/IMPORT_RECONCILIATION_REQUIREMENTS.md | 19 +- docs/WEKNORA_091_PHASE_PLAN.md | 2 +- internal/appconfig/config.go | 152 +++-- internal/governance/model.go | 13 + internal/governance/monitor.go | 25 + internal/governance/reconciliation.go | 138 +++++ internal/httpapi/reconciliation.go | 227 +++++++ internal/httpapi/reconciliation_test.go | 128 ++++ internal/httpapi/server.go | 55 +- internal/monitoring/real.go | 23 +- ...reconciliation_removal_integration_test.go | 58 ++ internal/monitoring/simulation.go | 2 - internal/monitoring/simulation_test.go | 2 +- .../migrations/000084_reconciliation.down.sql | 5 + .../migrations/000084_reconciliation.up.sql | 119 ++++ internal/platform/postgres/migrations_test.go | 12 +- internal/platform/postgres/reconciliation.go | 578 ++++++++++++++++++ .../reconciliation_integration_test.go | 74 +++ .../platform/postgres/test_publications.go | 10 +- .../test_publications_integration_test.go | 6 +- .../postgres/test_publications_test.go | 6 +- internal/platform/weknora/client.go | 16 +- internal/platform/weknora/runtime.go | 171 ++++++ internal/platform/weknora/secret.go | 39 ++ internal/platform/weknora/secret_test.go | 17 + internal/platform/weknora/types.go | 7 + internal/reconciliation/matrix.go | 115 ++++ internal/reconciliation/runtime.go | 137 +++++ internal/reconciliation/runtime_test.go | 70 +++ internal/reconciliation/scan.go | 479 +++++++++++++++ internal/reconciliation/service.go | 447 ++++++++++++++ internal/reconciliation/service_test.go | 334 ++++++++++ internal/weknoraaccess/client.go | 16 +- internal/workflows/testweknora/poll.go | 15 +- internal/workflows/testweknora/upload.go | 46 +- internal/workflows/testweknora/upload_test.go | 2 +- 43 files changed, 3661 insertions(+), 122 deletions(-) create mode 100644 cmd/worker/reconciliation_scheduler.go create mode 100644 internal/governance/reconciliation.go create mode 100644 internal/httpapi/reconciliation.go create mode 100644 internal/httpapi/reconciliation_test.go create mode 100644 internal/monitoring/reconciliation_removal_integration_test.go create mode 100644 internal/platform/postgres/migrations/000084_reconciliation.down.sql create mode 100644 internal/platform/postgres/migrations/000084_reconciliation.up.sql create mode 100644 internal/platform/postgres/reconciliation.go create mode 100644 internal/platform/postgres/reconciliation_integration_test.go create mode 100644 internal/platform/weknora/runtime.go create mode 100644 internal/reconciliation/matrix.go create mode 100644 internal/reconciliation/runtime.go create mode 100644 internal/reconciliation/runtime_test.go create mode 100644 internal/reconciliation/scan.go create mode 100644 internal/reconciliation/service.go create mode 100644 internal/reconciliation/service_test.go diff --git a/.env.example b/.env.example index ec54654..ea5f592 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/cmd/api/main.go b/cmd/api/main.go index e4e315c..8c6f57e 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -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,54 @@ 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, + }) + 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 +340,7 @@ 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, InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID, ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID, RoutingBindings: postgresstore.NewStore(pool), diff --git a/cmd/worker/library_role_test.go b/cmd/worker/library_role_test.go index 60eca33..d290cae 100644 --- a/cmd/worker/library_role_test.go +++ b/cmd/worker/library_role_test.go @@ -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) } diff --git a/cmd/worker/main.go b/cmd/worker/main.go index 44888ef..79b9151 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -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,44 @@ 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, + }) + if err != nil { + return err + } + } + handlers, err := workerHandlers(store, config, kbBindings, reconciliationService) if err != nil { return err } @@ -331,6 +369,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 +414,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 +689,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 } diff --git a/cmd/worker/main_test.go b/cmd/worker/main_test.go index ccc3917..04392d2 100644 --- a/cmd/worker/main_test.go +++ b/cmd/worker/main_test.go @@ -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) } diff --git a/cmd/worker/reconciliation_scheduler.go b/cmd/worker/reconciliation_scheduler.go new file mode 100644 index 0000000..a2de6b9 --- /dev/null +++ b/cmd/worker/reconciliation_scheduler.go @@ -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")) + } + } + } +} diff --git a/compose.yaml b/compose.yaml index e9a47b8..472b09e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -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}" diff --git a/docs/IMPORT_RECONCILIATION_REQUIREMENTS.md b/docs/IMPORT_RECONCILIATION_REQUIREMENTS.md index 78c105c..8e1e184 100644 --- a/docs/IMPORT_RECONCILIATION_REQUIREMENTS.md +++ b/docs/IMPORT_RECONCILIATION_REQUIREMENTS.md @@ -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,19 @@ 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`。 +**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`、`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 中打开的链接,可为空)。 +**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 +176,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 +242,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` 只重试已失败移除 | diff --git a/docs/WEKNORA_091_PHASE_PLAN.md b/docs/WEKNORA_091_PHASE_PLAN.md index f314943..2b277a1 100644 --- a/docs/WEKNORA_091_PHASE_PLAN.md +++ b/docs/WEKNORA_091_PHASE_PLAN.md @@ -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 天"提示)。 diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go index 8719f43..fe0750d 100644 --- a/internal/appconfig/config.go +++ b/internal/appconfig/config.go @@ -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 { diff --git a/internal/governance/model.go b/internal/governance/model.go index 06a85c5..f4f4608 100644 --- a/internal/governance/model.go +++ b/internal/governance/model.go @@ -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: diff --git a/internal/governance/monitor.go b/internal/governance/monitor.go index 3d1c6aa..8ef2fba 100644 --- a/internal/governance/monitor.go +++ b/internal/governance/monitor.go @@ -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 { diff --git a/internal/governance/reconciliation.go b/internal/governance/reconciliation.go new file mode 100644 index 0000000..38d9d6b --- /dev/null +++ b/internal/governance/reconciliation.go @@ -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 +} diff --git a/internal/httpapi/reconciliation.go b/internal/httpapi/reconciliation.go new file mode 100644 index 0000000..05cd363 --- /dev/null +++ b/internal/httpapi/reconciliation.go @@ -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) +} diff --git a/internal/httpapi/reconciliation_test.go b/internal/httpapi/reconciliation_test.go new file mode 100644 index 0000000..f3b5325 --- /dev/null +++ b/internal/httpapi/reconciliation_test.go @@ -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) + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index f58e787..554f272 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -121,19 +121,22 @@ 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 InternalRoutingKnowledgeBaseID string ExternalRoutingKnowledgeBaseID string RoutingBindings RoutingBindingStore @@ -495,6 +498,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) diff --git a/internal/monitoring/real.go b/internal/monitoring/real.go index 4b6db22..2eb678c 100644 --- a/internal/monitoring/real.go +++ b/internal/monitoring/real.go @@ -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 { diff --git a/internal/monitoring/reconciliation_removal_integration_test.go b/internal/monitoring/reconciliation_removal_integration_test.go new file mode 100644 index 0000000..49fe302 --- /dev/null +++ b/internal/monitoring/reconciliation_removal_integration_test.go @@ -0,0 +1,58 @@ +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')`) + 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-view','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) + } +} diff --git a/internal/monitoring/simulation.go b/internal/monitoring/simulation.go index 5ff34b7..901b24e 100644 --- a/internal/monitoring/simulation.go +++ b/internal/monitoring/simulation.go @@ -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}, diff --git a/internal/monitoring/simulation_test.go b/internal/monitoring/simulation_test.go index 153a973..bc51d0e 100644 --- a/internal/monitoring/simulation_test.go +++ b/internal/monitoring/simulation_test.go @@ -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 diff --git a/internal/platform/postgres/migrations/000084_reconciliation.down.sql b/internal/platform/postgres/migrations/000084_reconciliation.down.sql new file mode 100644 index 0000000..b1ffd4a --- /dev/null +++ b/internal/platform/postgres/migrations/000084_reconciliation.down.sql @@ -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; \ No newline at end of file diff --git a/internal/platform/postgres/migrations/000084_reconciliation.up.sql b/internal/platform/postgres/migrations/000084_reconciliation.up.sql new file mode 100644 index 0000000..0dabfa2 --- /dev/null +++ b/internal/platform/postgres/migrations/000084_reconciliation.up.sql @@ -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'; \ No newline at end of file diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index ebad2f0..bd83dbf 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -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 || diff --git a/internal/platform/postgres/reconciliation.go b/internal/platform/postgres/reconciliation.go new file mode 100644 index 0000000..4f194d5 --- /dev/null +++ b/internal/platform/postgres/reconciliation.go @@ -0,0 +1,578 @@ +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=$2,error_code='stale_timeout' +WHERE state='running' AND started_at < $3`, 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 { + 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, finding.ConfirmationState, 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 (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) + 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) + 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) + 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 +} diff --git a/internal/platform/postgres/reconciliation_integration_test.go b/internal/platform/postgres/reconciliation_integration_test.go new file mode 100644 index 0000000..0710fb8 --- /dev/null +++ b/internal/platform/postgres/reconciliation_integration_test.go @@ -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) + } +} diff --git a/internal/platform/postgres/test_publications.go b/internal/platform/postgres/test_publications.go index 9342115..771888b 100644 --- a/internal/platform/postgres/test_publications.go +++ b/internal/platform/postgres/test_publications.go @@ -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, diff --git a/internal/platform/postgres/test_publications_integration_test.go b/internal/platform/postgres/test_publications_integration_test.go index 4c68024..c19e117 100644 --- a/internal/platform/postgres/test_publications_integration_test.go +++ b/internal/platform/postgres/test_publications_integration_test.go @@ -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) } diff --git a/internal/platform/postgres/test_publications_test.go b/internal/platform/postgres/test_publications_test.go index 6b9eb62..1dd26f2 100644 --- a/internal/platform/postgres/test_publications_test.go +++ b/internal/platform/postgres/test_publications_test.go @@ -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) { diff --git a/internal/platform/weknora/client.go b/internal/platform/weknora/client.go index 2776947..726558c 100644 --- a/internal/platform/weknora/client.go +++ b/internal/platform/weknora/client.go @@ -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 } diff --git a/internal/platform/weknora/runtime.go b/internal/platform/weknora/runtime.go new file mode 100644 index 0000000..bc0650d --- /dev/null +++ b/internal/platform/weknora/runtime.go @@ -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 +} diff --git a/internal/platform/weknora/secret.go b/internal/platform/weknora/secret.go index 14632bd..462357a 100644 --- a/internal/platform/weknora/secret.go +++ b/internal/platform/weknora/secret.go @@ -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 +} diff --git a/internal/platform/weknora/secret_test.go b/internal/platform/weknora/secret_test.go index 4c4a1b3..ef6fab4 100644 --- a/internal/platform/weknora/secret_test.go +++ b/internal/platform/weknora/secret_test.go @@ -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") + } +} diff --git a/internal/platform/weknora/types.go b/internal/platform/weknora/types.go index b3ebe6f..b3171de 100644 --- a/internal/platform/weknora/types.go +++ b/internal/platform/weknora/types.go @@ -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"` diff --git a/internal/reconciliation/matrix.go b/internal/reconciliation/matrix.go new file mode 100644 index 0000000..3c4ae0c --- /dev/null +++ b/internal/reconciliation/matrix.go @@ -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) +} diff --git a/internal/reconciliation/runtime.go b/internal/reconciliation/runtime.go new file mode 100644 index 0000000..e6d927e --- /dev/null +++ b/internal/reconciliation/runtime.go @@ -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]) +} diff --git a/internal/reconciliation/runtime_test.go b/internal/reconciliation/runtime_test.go new file mode 100644 index 0000000..64ea115 --- /dev/null +++ b/internal/reconciliation/runtime_test.go @@ -0,0 +1,70 @@ +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) + } +} diff --git a/internal/reconciliation/scan.go b/internal/reconciliation/scan.go new file mode 100644 index 0000000..f10effe --- /dev/null +++ b/internal/reconciliation/scan.go @@ -0,0 +1,479 @@ +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 || len(items) < scanPageSize { + break + } + if total > 0 && int64(len(seen)) >= total { + 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) + 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(metadataString(item.Metadata, "content_sha256")) + ledgerSHA := strings.ToLower(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] +} diff --git a/internal/reconciliation/service.go b/internal/reconciliation/service.go new file mode 100644 index 0000000..4e9347b --- /dev/null +++ b/internal/reconciliation/service.go @@ -0,0 +1,447 @@ +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 +} + +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 +} + +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, + }, 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 +} diff --git a/internal/reconciliation/service_test.go b/internal/reconciliation/service_test.go new file mode 100644 index 0000000..0a734ea --- /dev/null +++ b/internal/reconciliation/service_test.go @@ -0,0 +1,334 @@ +package reconciliation + +import ( + "context" + "errors" + "testing" + "time" + + "knowledge-governance/internal/governance" + "knowledge-governance/internal/platform/weknora" +) + +func TestMatrixCoversEveryLedgerAndUpstreamState(t *testing.T) { + rows := []string{"planned", "pending", "processing", "finalizing", "completed", "failed", "stalled", "cancelled"} + columns := []string{"pending", "processing", "finalizing", "completed", "failed", "cancelled", "deleting"} + for _, row := range rows { + for _, column := range columns { + verdict := classify(row, column) + if verdict == verdictSkip && row != "" { + t.Fatalf("classify(%s,%s) unexpectedly skipped", row, column) + } + if row == "completed" && column == "completed" && verdict != verdictConsistent { + t.Fatalf("completed/completed = %v", verdict) + } + if row == "stalled" && column == "completed" && verdict != verdictMismatch { + t.Fatalf("stalled/completed = %v", verdict) + } + if column == "deleting" && verdict != verdictDeleting { + t.Fatalf("%s/deleting = %v", row, verdict) + } + } + } + if classify("completed", "pending") != verdictMismatch || classify("cancelled", "cancelled") != verdictConsistent { + t.Fatal("explicit completed/cancelled rows are wrong") + } + 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"}}, + } + remote := &fakeReconciliationRemote{ + items: items, missing: map[string]bool{"doc-r1": true}, + gets: map[string]weknora.Knowledge{"doc-r2": items[0]}, + } + 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}) + if err != nil { + t.Fatal(err) + } + if err := service.ExecuteRun(context.Background(), "run-1"); err != nil { + t.Fatal(err) + } + if store.completedRun == nil { + t.Fatal("run was not completed") + } + if remote.deleteCalls != 0 { + t.Fatalf("reconciliation wrote remotely: %d", remote.deleteCalls) + } + if len(remote.pageSizes) == 0 || remote.pageSizes[0] != scanPageSize { + t.Fatalf("page size = %v, want %d", remote.pageSizes, scanPageSize) + } + if remote.maxInFlight != 1 { + t.Fatalf("scan in-flight peak = %d, want 1", remote.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) + } +} + +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) + } +} diff --git a/internal/weknoraaccess/client.go b/internal/weknoraaccess/client.go index b4ba2f2..97f6590 100644 --- a/internal/weknoraaccess/client.go +++ b/internal/weknoraaccess/client.go @@ -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, }) } diff --git a/internal/workflows/testweknora/poll.go b/internal/workflows/testweknora/poll.go index ca5bebf..e1af4e1 100644 --- a/internal/workflows/testweknora/poll.go +++ b/internal/workflows/testweknora/poll.go @@ -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) } diff --git a/internal/workflows/testweknora/upload.go b/internal/workflows/testweknora/upload.go index 84542e0..7d39feb 100644 --- a/internal/workflows/testweknora/upload.go +++ b/internal/workflows/testweknora/upload.go @@ -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) diff --git a/internal/workflows/testweknora/upload_test.go b/internal/workflows/testweknora/upload_test.go index 257b857..b514575 100644 --- a/internal/workflows/testweknora/upload_test.go +++ b/internal/workflows/testweknora/upload_test.go @@ -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