From 082f77fc1816f5e4dfd60ca8d1ba2d43357a7a05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zhero=20=26=20=E5=8A=A9=E7=90=86?= <836283459@qq.com> Date: Tue, 1 Dec 2026 18:56:05 +0800 Subject: [PATCH] =?UTF-8?q?fix(reconciliation):=20R6=20=E6=94=B9=E7=94=A8?= =?UTF-8?q?=20removal=5Fcandidates=20=E8=A7=86=E5=9B=BE=EF=BC=8C=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E6=89=B9=E6=AF=8F=E6=97=A5=E5=8F=AA=E5=8D=A0=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E5=90=8D=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 白盒补充复核提出的三项: - P1 R6 与 /monitor/overview「需下架」计数口径不一致:R6 原先只在扫描结果里存在 且上游 parse_status=completed 时才生成,上游仍在 processing/finalizing 或单条读取 失败导致扫描缺行时,总览有数、对账无记录(陷阱 15)。改为直接由 removal_candidates 视图行生成,台账细节按 publication 回填,计数与总览同一来源;补单测覆盖 「上游 processing」「扫描未见」两种差异。 - P2 定时批失败后每个 tick 都重建:每日占位只排除 running/succeeded,failed 不占位, 一次失败当天会每分钟刷批。占位条件加入 failed,重跑改为显式手动触发;补 PG 集成用例。 - P2 队列不可用时前端显示 0 等待 · 0 运行:改为按 available 判定并显示不可用文案; 补组件用例。 --- .../reconciliation_integration_test.go | 40 +++++++++++++ .../platform/postgres/reconciliation_store.go | 2 +- internal/reconciliation/scan.go | 60 ++++++++++++++----- internal/reconciliation/service_test.go | 58 ++++++++++++++++++ web/src/ReconciliationFindings.test.tsx | 45 +++++++++++++- web/src/ReconciliationFindings.tsx | 2 +- 6 files changed, 190 insertions(+), 17 deletions(-) diff --git a/internal/platform/postgres/reconciliation_integration_test.go b/internal/platform/postgres/reconciliation_integration_test.go index 0710fb8..f581e5d 100644 --- a/internal/platform/postgres/reconciliation_integration_test.go +++ b/internal/platform/postgres/reconciliation_integration_test.go @@ -72,3 +72,43 @@ func TestReconciliationRunUniquenessStaleAndRetentionIntegration(t *testing.T) { t.Fatalf("new findings=%d err=%v", count, err) } } + +// TestScheduledReconciliationClaimsOncePerDayAfterFailure freezes the operator +// expectation "每天最多一批": a failed scheduled batch keeps the day's slot so a +// transient upstream error cannot spawn a new batch on every scheduler tick. +// A retry after a failure is an explicit manual trigger. +func TestScheduledReconciliationClaimsOncePerDayAfterFailure(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) + dayStart := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC) + run := func(id string, started time.Time) governance.ReconciliationRun { + return governance.ReconciliationRun{ID: id, KBID: "kb-sched", State: "running", Trigger: "schedule", + StartedAt: started, Counts: governance.ReconciliationCounts{}} + } + first, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-1", dayStart.Add(2*time.Hour)), dayStart, dayStart.Add(2*time.Hour)) + if err != nil || !claimed { + t.Fatalf("first claim claimed=%t err=%v", claimed, err) + } + if err := store.FailReconciliationRun(ctx, first.ID, "remote_scan_failed", dayStart.Add(2*time.Minute)); err != nil { + t.Fatal(err) + } + if _, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-2", dayStart.Add(3*time.Minute)), dayStart, dayStart.Add(3*time.Minute)); err != nil || claimed { + t.Fatalf("same-day reclaim after failure claimed=%t err=%v", claimed, err) + } + nextDay := dayStart.Add(24 * time.Hour) + if _, claimed, err := store.ClaimScheduledReconciliationRun(ctx, run("sched-3", nextDay.Add(2*time.Hour)), nextDay, nextDay.Add(2*time.Hour)); err != nil || !claimed { + t.Fatalf("next-day claim claimed=%t err=%v", claimed, err) + } +} diff --git a/internal/platform/postgres/reconciliation_store.go b/internal/platform/postgres/reconciliation_store.go index 7b23f1d..ba5ac3a 100644 --- a/internal/platform/postgres/reconciliation_store.go +++ b/internal/platform/postgres/reconciliation_store.go @@ -77,7 +77,7 @@ func (s *Store) ClaimScheduledReconciliationRun(ctx context.Context, run governa 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 + WHERE test_kb_id=$2 AND trigger='schedule' AND state IN ('running','succeeded','failed') AND started_at >= $6 ) ON CONFLICT DO NOTHING RETURNING `+reconciliationRunColumns, diff --git a/internal/reconciliation/scan.go b/internal/reconciliation/scan.go index 10016e0..4060c49 100644 --- a/internal/reconciliation/scan.go +++ b/internal/reconciliation/scan.go @@ -278,11 +278,7 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati if err != nil { return nil, err } - removalByPublication := make(map[string]bool, len(removal)) - for _, row := range removal { - removalByPublication[row.PublicationID] = true - } - + // 「需下架」的台账细节沿用上面按 publication 建的台账索引。 for _, row := range ledger { if !expectedLive(row) { continue @@ -305,15 +301,6 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati 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 仍有活动状态")) @@ -355,6 +342,51 @@ func (s *Service) buildFindings(ctx context.Context, run governance.Reconciliati } } + // R6: 应下架仍在。判定口径 = removal_candidates 视图(与 /monitor/overview 的 + // 「需下架」共用同一实现,陷阱 15)。这里直接由视图行生成,不再附加「本轮扫描 + // 见到该条目」「上游 parse_status=completed」这类只有对账侧才有的条件——上游仍在 + // processing/finalizing、或单条读取失败导致扫描缺行时,两处数字就会永久不一致。 + for _, row := range removal { + finding := governance.ReconciliationFinding{ + Type: "R6", PublicationID: row.PublicationID, DocumentID: row.KnowledgeID, + Title: row.Title, Path: row.Path, Source: row.SourceName, TargetScope: row.TargetScope, + // 视图只收录 processing_state='completed' 的台账行。 + LedgerState: "completed", EvidenceLevel: "none", SuggestedAction: "enter_removal", + Detail: "来源已判禁止导入,条目仍在测试库可检索", + } + if own, ok := ledgerByPublication[row.PublicationID]; ok { + if finding.DocumentID == "" { + finding.DocumentID = own.KnowledgeID + } + if finding.Title == "" { + finding.Title = own.Title + } + if finding.Path == "" { + finding.Path = own.Path + } + if finding.Source == "" { + finding.Source = own.SourceName + } + if finding.TargetScope == "" { + finding.TargetScope = own.TargetScope + } + if own.ProcessingState != "" { + finding.LedgerState = own.ProcessingState + } + finding.LedgerSHA256 = own.SHA256 + } + if item, ok := byID[finding.DocumentID]; ok { + if normalized, known := normalizeParseStatus(item.ParseStatus); known { + finding.NormalizedState = normalized + } + finding.WeKnoraParseState = item.ParseStatus + finding.WeKnoraFileMD5 = normalizeMD5(item.FileHash) + } else if finding.DocumentID != "" { + finding.Detail = "来源已判禁止导入;本轮扫描未见该条目,计数仍与总览「需下架」一致" + } + add(finding) + } + // R8: one publication id maps to more than one live row. grouped := make(map[string][]weknora.Knowledge) for _, item := range items { diff --git a/internal/reconciliation/service_test.go b/internal/reconciliation/service_test.go index a07d8f2..6a64242 100644 --- a/internal/reconciliation/service_test.go +++ b/internal/reconciliation/service_test.go @@ -480,3 +480,61 @@ func TestRemoveR2RechecksOwnershipAndTreats404AsSuccess(t *testing.T) { t.Fatalf("owned removal err=%v hit=%t", err, store.removeHit) } } + +// TestExecuteRunR6UsesRemovalCandidatesViewOnly freezes 陷阱 15: R6 and +// /monitor/overview must read one implementation. An upstream document still +// processing/finalizing, or a single read that misses the listing, must not +// remove a row from the R6 set — otherwise the two pages report different +// "需下架" numbers for the same instant. +func TestExecuteRunR6UsesRemovalCandidatesViewOnly(t *testing.T) { + now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + ledger := []governance.ReconciliationLedgerRow{ + {PublicationID: "pub-a", KnowledgeID: "doc-a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)}, + {PublicationID: "pub-b", KnowledgeID: "doc-b", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)}, + {PublicationID: "pub-c", KnowledgeID: "doc-c", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UpdatedAt: now.Add(-time.Hour)}, + } + items := []weknora.Knowledge{ + {ID: "doc-a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-a"}}, + {ID: "doc-c", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-c"}}, + } + store := &fakeReconciliationStore{ + run: governance.ReconciliationRun{ID: "run-r6", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now}, + ledger: ledger, + // The view is the authority: it lists three rows, including one whose + // upstream document is still processing and one absent from the scan. + removal: []governance.ReconciliationLedgerRow{ + {PublicationID: "pub-a", KnowledgeID: "doc-a"}, + {PublicationID: "pub-b", KnowledgeID: "doc-b"}, + {PublicationID: "pub-c", KnowledgeID: "doc-c"}, + }, + } + remote := &fakeReconciliationRemote{items: items, missing: map[string]bool{"doc-b": true}} + service, err := New(Config{Store: store, Remote: remote, Now: func() time.Time { return now }, + Grace: 30 * time.Minute, StallAfter: 2 * time.Hour, StaleAfter: 6 * time.Hour, + ConfirmConcurrency: 1, KeepRuns: 30, MaxAge: 90 * 24 * time.Hour, + WeKnoraWebBase: func(context.Context) string { return "https://test.example/" }}) + if err != nil { + t.Fatal(err) + } + if err := service.ExecuteRun(context.Background(), "run-r6"); err != nil { + t.Fatal(err) + } + r6 := map[string]governance.ReconciliationFinding{} + for _, finding := range store.findings { + if finding.Type == "R6" { + r6[finding.PublicationID] = finding + } + } + if len(r6) != len(store.removal) { + t.Fatalf("R6 count = %d, removal candidates = %d; findings=%#v", len(r6), len(store.removal), store.findings) + } + if processing, ok := r6["pub-a"]; !ok || processing.WeKnoraParseState != "processing" || processing.NormalizedState != "processing" { + t.Fatalf("R6 must keep an upstream-processing row: %#v", processing) + } + if missing, ok := r6["pub-b"]; !ok || missing.DocumentID != "doc-b" { + t.Fatalf("R6 must keep a row the scan could not list: %#v", missing) + } + if store.completedRun == nil || store.completedRun.Counts["R6"] != len(store.removal) { + t.Fatalf("run counts R6 = %#v", store.completedRun) + } +} diff --git a/web/src/ReconciliationFindings.test.tsx b/web/src/ReconciliationFindings.test.tsx index 4fc271c..fbd2d22 100644 --- a/web/src/ReconciliationFindings.test.tsx +++ b/web/src/ReconciliationFindings.test.tsx @@ -1,6 +1,7 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it, vi } from 'vitest' -import { FindingDetail, ReconciliationFindingsView } from './ReconciliationFindings' +import { FindingDetail, ReconciliationFindingsView, ServiceStrip } from './ReconciliationFindings' +import type { MonitorOverview } from './monitor' import type { ReconciliationFinding, ReconciliationRun } from './reconciliationApi' const run: ReconciliationRun = { @@ -114,3 +115,45 @@ describe('reconciliation findings', () => { expect(html).toContain('在 WeKnora 中打开') }) }) + +describe('ServiceStrip queue availability', () => { + const overview = (queues: MonitorOverview['weknora_queues']) => + ({ weknora_queues: queues, health: [] }) as unknown as MonitorOverview + + it('states an unavailable queue instead of rendering 0 waiting · 0 active', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('队列不可用') + expect(html).not.toContain('0 等待') + }) + + it('prints queue depth when the queue is available', () => { + const html = renderToStaticMarkup( + + ) + expect(html).toContain('2 等待 · 1 运行') + }) +}) diff --git a/web/src/ReconciliationFindings.tsx b/web/src/ReconciliationFindings.tsx index c157f70..ecd6fd5 100644 --- a/web/src/ReconciliationFindings.tsx +++ b/web/src/ReconciliationFindings.tsx @@ -75,7 +75,7 @@ export function ServiceStrip({ overview }: { overview: MonitorOverview | null })
WeKnora 队列: - {queue ? ( + {queue?.available ? ( {queue.queues.reduce((sum, item) => sum + item.pending, 0)} 等待 ·{' '} {queue.queues.reduce((sum, item) => sum + item.active, 0)} 运行 -- 2.52.0