package reconciliation import ( "context" "errors" "testing" "time" "knowledge-governance/internal/governance" "knowledge-governance/internal/platform/weknora" ) func TestMatrixCoversEveryLedgerAndUpstreamState(t *testing.T) { columns := []string{"pending", "processing", "finalizing", "completed", "failed", "cancelled", "deleting"} want := map[string][]verdict{ "planned": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting}, "pending": {verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting}, "processing": {verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting}, "finalizing": {verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictMismatch, verdictDeleting}, "completed": {verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictMismatch, verdictDeleting}, "failed": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictMismatch, verdictDeleting}, "stalled": {verdictStalled, verdictStalled, verdictStalled, verdictMismatch, verdictStalled, verdictStalled, verdictDeleting}, "cancelled": {verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictMismatch, verdictConsistent, verdictDeleting}, } for row, expected := range want { for index, column := range columns { if got := classify(row, column); got != expected[index] { t.Fatalf("classify(%s,%s) = %v, want %v", row, column, got, expected[index]) } } } if AllowedWriteback("completed", "pending") || AllowedWriteback("stalled", "completed") || !AllowedWriteback("failed", "pending") || AllowedWriteback("planned", "pending") || AllowedWriteback("pending", "cancelled") || AllowedWriteback("pending", "deleting") { t.Fatal("writeback migration table is wrong") } } type fakeReconciliationStore struct { run governance.ReconciliationRun ledger []governance.ReconciliationLedgerRow removal []governance.ReconciliationLedgerRow overlapped bool completedRun *governance.ReconciliationRun findings []governance.ReconciliationFinding failCode string actionView governance.ReconciliationActionView actionErr error findingAfter governance.ReconciliationFinding writebackHit bool requeueHit bool removeHit bool requeueDoc string orphan bool } func (f *fakeReconciliationStore) ReapStaleReconciliationRuns(context.Context, time.Time, time.Duration) (int64, error) { return 0, nil } func (f *fakeReconciliationStore) ClaimReconciliationRun(_ context.Context, run governance.ReconciliationRun, _ time.Time) (governance.ReconciliationRun, error) { return run, nil } func (f *fakeReconciliationStore) ClaimScheduledReconciliationRun(_ context.Context, run governance.ReconciliationRun, _ time.Time, _ time.Time) (governance.ReconciliationRun, bool, error) { return run, true, nil } func (f *fakeReconciliationStore) LoadReconciliationRun(context.Context, string) (governance.ReconciliationRun, error) { return f.run, nil } func (f *fakeReconciliationStore) ListReconciliationRuns(context.Context, governance.ReconciliationRunFilter) (governance.ReconciliationRunPage, error) { return governance.ReconciliationRunPage{}, nil } func (f *fakeReconciliationStore) ListReconciliationFindings(context.Context, governance.ReconciliationFindingFilter) (governance.ReconciliationFindingPage, error) { return governance.ReconciliationFindingPage{}, nil } func (f *fakeReconciliationStore) GetReconciliationFinding(context.Context, string) (governance.ReconciliationFinding, error) { if f.findingAfter.ID != "" { return f.findingAfter, nil } return governance.ReconciliationFinding{}, ErrNotFound } func (f *fakeReconciliationStore) LoadReconciliationLedger(context.Context, string) ([]governance.ReconciliationLedgerRow, error) { return f.ledger, nil } func (f *fakeReconciliationStore) LoadPreviousReconciliationCounts(context.Context, string, time.Time) (governance.ReconciliationCounts, bool, error) { return nil, false, nil } func (f *fakeReconciliationStore) CompleteReconciliationRun(_ context.Context, run governance.ReconciliationRun, findings []governance.ReconciliationFinding) error { f.completedRun = &run f.findings = findings return nil } func (f *fakeReconciliationStore) FailReconciliationRun(_ context.Context, _ string, code string, _ time.Time) error { f.failCode = code return nil } func (f *fakeReconciliationStore) CleanupReconciliationFindings(context.Context, time.Time, int, time.Duration) error { return nil } func (f *fakeReconciliationStore) LibraryJobsActive(context.Context) (bool, error) { return f.overlapped, nil } func (f *fakeReconciliationStore) ListReconciliationRemovalCandidates(context.Context, string) ([]governance.ReconciliationLedgerRow, error) { return f.removal, nil } func (f *fakeReconciliationStore) LoadReconciliationActionView(context.Context, string) (governance.ReconciliationActionView, error) { if f.actionErr != nil { return governance.ReconciliationActionView{}, f.actionErr } return f.actionView, nil } func (f *fakeReconciliationStore) ReconciliationOrphanStillUnowned(context.Context, string, string) (bool, error) { return f.orphan, nil } func (f *fakeReconciliationStore) WritebackReconciliationFinding(context.Context, string, string, string, string, time.Time) (governance.ReconciliationFinding, error) { f.writebackHit = true return f.findingAfter, nil } func (f *fakeReconciliationStore) RequeueReconciliationPublication(_ context.Context, _ string, expectedDocument string, _ string, _ string, _ time.Time) (string, error) { f.requeueHit = true f.requeueDoc = expectedDocument return "job-1", nil } func (f *fakeReconciliationStore) MarkReconciliationOrphanRemoved(context.Context, string, string, string, time.Time) error { f.removeHit = true return nil } type fakeReconciliationRemote struct { items []weknora.Knowledge missing map[string]bool gets map[string]weknora.Knowledge listErr error pageSizes []int deleteCalls int listInFlight int maxInFlight int } func (f *fakeReconciliationRemote) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) { return ctx, weknora.InstanceIdentity{BaseURL: "https://test.example", TenantID: 7}, nil } func (f *fakeReconciliationRemote) ListKnowledge(_ context.Context, _ string, _ int, pageSize int) ([]weknora.Knowledge, int64, error) { f.pageSizes = append(f.pageSizes, pageSize) f.listInFlight++ if f.listInFlight > f.maxInFlight { f.maxInFlight = f.listInFlight } defer func() { f.listInFlight-- }() if f.listErr != nil { return nil, 0, f.listErr } return f.items, int64(len(f.items)), nil } func (f *fakeReconciliationRemote) GetKnowledge(_ context.Context, id string) (weknora.Knowledge, error) { if f.missing[id] { return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404} } if item, ok := f.gets[id]; ok { return item, nil } for _, item := range f.items { if item.ID == id { return item, nil } } return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404} } func (f *fakeReconciliationRemote) DeleteKnowledge(context.Context, string) error { f.deleteCalls++ return nil } func ptrTime(value time.Time) *time.Time { return &value } func TestExecuteRunFindsR1ToR8WithoutRemoteWrites(t *testing.T) { now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) ledger := []governance.ReconciliationLedgerRow{ {PublicationID: "pub-r1", KnowledgeID: "doc-r1", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", Title: "missing", UpdatedAt: now.Add(-time.Hour)}, {PublicationID: "pub-r4", KnowledgeID: "doc-r4", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", UploadMD5: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)}, {PublicationID: "pub-r5", KnowledgeID: "doc-r5", ProcessingState: "processing", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)}, {PublicationID: "pub-r6", KnowledgeID: "doc-r6", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", PolicyState: "blocked", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)}, {PublicationID: "pub-r7", KnowledgeID: "doc-r7", ProcessingState: "stalled", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-3 * time.Hour)), UpdatedAt: now.Add(-3 * time.Hour)}, {PublicationID: "dup-pub", KnowledgeID: "doc-r8a", ProcessingState: "completed", RetrievalState: "unpublished", TargetScope: "internal", ProcessingStartedAt: ptrTime(now.Add(-2 * time.Hour)), UpdatedAt: now.Add(-time.Hour)}, } items := []weknora.Knowledge{ {ID: "doc-r2", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "orphan-pub"}}, {ID: "doc-r3", KnowledgeBaseID: "kb-1", Channel: "web", ParseStatus: "completed"}, {ID: "doc-r4", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", FileHash: "cccccccccccccccccccccccccccccccc", Metadata: map[string]any{"publication_id": "pub-r4", "content_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}, {ID: "doc-r5", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-r5"}}, {ID: "doc-r6", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "pub-r6"}}, {ID: "doc-r7", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "processing", Metadata: map[string]any{"publication_id": "pub-r7"}}, {ID: "doc-r8a", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "dup-pub"}}, {ID: "doc-r8b", KnowledgeBaseID: "kb-1", Channel: "governance", ParseStatus: "completed", Metadata: map[string]any{"publication_id": "dup-pub"}}, } store := &fakeReconciliationStore{ run: governance.ReconciliationRun{ID: "run-1", KBID: "kb-1", State: "running", Trigger: "manual", StartedAt: now}, ledger: ledger, removal: []governance.ReconciliationLedgerRow{{PublicationID: "pub-r6"}}, } 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) } }