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) } } // 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) } } // TestLoadReconciliationActionViewJoinsWithoutAmbiguity freezes the action-view // SQL: it joins reconciliation_runs and test_publications, both of which also // own id/title/path, so an unqualified column list fails with // `column reference "id" is ambiguous` and every writeback/requeue/remove // answered 500 instead of touching the finding. func TestLoadReconciliationActionViewJoinsWithoutAmbiguity(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) } started := time.Date(2026, 12, 1, 2, 0, 0, 0, time.UTC) 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-action','dingtalk','处置视图用例',TRUE)`) exec(`INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_uri_hash,title,item_type,policy_state) VALUES('si-action','conn-action','action.md',repeat('d',64),'处置视图','file','blocked')`) exec(`INSERT INTO source_item_versions(id,source_item_id,revision,content_state) VALUES('sv-action','si-action','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-action','sv-action','kb-action','doc-action','uploaded','completed','unpublished')`) exec(`INSERT INTO reconciliation_runs(id,test_kb_id,state,trigger,started_at,counts,created_at) VALUES('run-action','kb-action','succeeded','manual',$1,'{}'::jsonb,$1)`, started) exec(`INSERT INTO reconciliation_findings(id,run_id,finding_type,publication_id,knowledge_id,title,ledger_state,suggested_action) VALUES('finding-action','run-action','R6','pub-action','doc-action','处置视图','completed','enter_removal')`) store := NewStore(pool) view, err := store.LoadReconciliationActionView(ctx, "finding-action") if err != nil { t.Fatalf("action view error = %v (ambiguous columns surface here)", err) } if view.TestKBID != "kb-action" || !view.CurrentExists || view.CurrentProcessingState != "completed" || view.CurrentKnowledgeID != "doc-action" || view.Finding.ID != "finding-action" { t.Fatalf("action view = %#v", view) } }