feat(reconciliation): 实现导入对账后端

为什么: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/零写/失败整批/动作/运行时/密钥权限测试。
This commit is contained in:
Zhero & Rin
2026-12-01 12:19:54 +08:00
committed by 姚章浩
parent 580695ca2e
commit 4528a55e6a
43 changed files with 3661 additions and 122 deletions
@@ -0,0 +1,5 @@
DROP VIEW IF EXISTS removal_candidates;
DROP TABLE IF EXISTS reconciliation_finding_actions;
DROP TABLE IF EXISTS reconciliation_findings;
DROP TABLE IF EXISTS reconciliation_runs;
ALTER TABLE test_publications DROP COLUMN IF EXISTS upload_md5;
@@ -0,0 +1,119 @@
-- T6 一期导入对账:批次、差异、处置审计与上传 MD5。
-- 只新增,不改台账既有状态语义;findings 可按 run 整批清理,actions 永久保留。
ALTER TABLE test_publications
ADD COLUMN IF NOT EXISTS upload_md5 CHAR(32) NOT NULL DEFAULT ''
CHECK (upload_md5 = '' OR upload_md5 ~ '^[0-9a-f]{32}$');
CREATE TABLE IF NOT EXISTS reconciliation_runs (
id VARCHAR(36) PRIMARY KEY,
test_kb_id VARCHAR(255) NOT NULL,
state VARCHAR(16) NOT NULL DEFAULT 'running'
CHECK (state IN ('running', 'succeeded', 'failed')),
trigger VARCHAR(16) NOT NULL
CHECK (trigger IN ('schedule', 'manual')),
started_at TIMESTAMPTZ NOT NULL,
finished_at TIMESTAMPTZ,
ledger_count INTEGER NOT NULL DEFAULT 0 CHECK (ledger_count >= 0),
kb_count INTEGER NOT NULL DEFAULT 0 CHECK (kb_count >= 0),
counts JSONB NOT NULL DEFAULT '{}'::jsonb
CHECK (jsonb_typeof(counts) = 'object'),
previous_counts JSONB
CHECK (previous_counts IS NULL OR jsonb_typeof(previous_counts) = 'object'),
window_overlapped BOOLEAN NOT NULL DEFAULT FALSE,
error_code VARCHAR(64) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- One running batch per test knowledge base. The application 409 is only a
-- friendly hint; this index is the real concurrency guard.
CREATE UNIQUE INDEX IF NOT EXISTS reconciliation_runs_one_running
ON reconciliation_runs (test_kb_id) WHERE state = 'running';
CREATE INDEX IF NOT EXISTS idx_reconciliation_runs_started
ON reconciliation_runs (started_at DESC, id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_runs_kb_started
ON reconciliation_runs (test_kb_id, started_at DESC);
CREATE TABLE IF NOT EXISTS reconciliation_findings (
id VARCHAR(36) PRIMARY KEY,
run_id VARCHAR(36) NOT NULL
REFERENCES reconciliation_runs(id) ON DELETE CASCADE,
finding_type VARCHAR(2) NOT NULL
CHECK (finding_type IN ('R1','R2','R3','R4','R5','R6','R7','R8')),
publication_id VARCHAR(36) NOT NULL DEFAULT '',
knowledge_id VARCHAR(255) NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
path TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL DEFAULT '',
target_scope VARCHAR(16) NOT NULL DEFAULT '',
ledger_state VARCHAR(20) NOT NULL DEFAULT '',
weknora_parse_status VARCHAR(32) NOT NULL DEFAULT '',
normalized_state VARCHAR(32) NOT NULL DEFAULT '',
ledger_sha256 CHAR(64) NOT NULL DEFAULT '',
declared_sha256 CHAR(64) NOT NULL DEFAULT '',
weknora_file_md5 CHAR(32) NOT NULL DEFAULT '',
evidence_level VARCHAR(16) NOT NULL DEFAULT 'none'
CHECK (evidence_level IN ('independent','declared_only','none')),
confirmation_state VARCHAR(16) NOT NULL DEFAULT 'confirmed'
CHECK (confirmation_state IN ('confirmed','pending')),
detail TEXT NOT NULL DEFAULT '',
suggested_action VARCHAR(32) NOT NULL DEFAULT 'none'
CHECK (suggested_action IN ('requeue_upload','remove_from_test','writeback_state','enter_removal','none')),
action_state VARCHAR(16) NOT NULL DEFAULT 'open'
CHECK (action_state IN ('open','done')),
weknora_url TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (run_id, finding_type, publication_id, knowledge_id)
);
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_run
ON reconciliation_findings (run_id, finding_type, id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_publication
ON reconciliation_findings (publication_id);
CREATE INDEX IF NOT EXISTS idx_reconciliation_findings_knowledge
ON reconciliation_findings (knowledge_id);
-- Durable action audit. Deliberedly not FK-bound to findings: findings are
-- deleted by retention, the audit is not.
CREATE TABLE IF NOT EXISTS reconciliation_finding_actions (
id VARCHAR(36) PRIMARY KEY,
finding_id VARCHAR(36) NOT NULL,
run_id VARCHAR(36) NOT NULL,
publication_id VARCHAR(36) NOT NULL DEFAULT '',
knowledge_id VARCHAR(255) NOT NULL DEFAULT '',
action VARCHAR(32) NOT NULL
CHECK (action IN ('writeback','requeue','remove')),
actor_ref VARCHAR(128) NOT NULL DEFAULT '',
outcome VARCHAR(32) NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_reconciliation_actions_finding
ON reconciliation_finding_actions (finding_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_reconciliation_actions_publication
ON reconciliation_finding_actions (publication_id, created_at DESC);
-- R6 and /monitor/overview must never disagree about "需下架": both read this
-- view. The 2026-10-10 acceptance found the old lane permanently zero because
-- two different predicates were maintained by hand.
CREATE OR REPLACE VIEW removal_candidates AS
SELECT publication.id AS publication_id,
publication.test_kb_id,
publication.knowledge_id,
publication.target_scope,
version.id AS source_item_version_id,
version.source_item_id,
item.title,
item.normalized_path,
item.source_connection_id,
connection.name AS source_name
FROM test_publications publication
JOIN source_item_versions version ON version.id = publication.source_item_version_id
JOIN source_items item ON item.id = version.source_item_id
JOIN source_connections connection ON connection.id = item.source_connection_id
WHERE publication.superseded_at IS NULL
AND publication.knowledge_id <> ''
AND publication.processing_state = 'completed'
AND publication.retrieval_state NOT IN ('disabling', 'disabled')
AND item.policy_state = 'blocked';
+10 -2
View File
@@ -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 ||
@@ -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, &currentExists, &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
}
@@ -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)
}
}
@@ -246,14 +246,15 @@ const recordUploadAndSchedulePollSQL = `
WITH updated AS (
UPDATE test_publications
SET knowledge_id = $2,
upload_md5 = $3,
ingest_state = 'uploaded',
processing_state = 'pending',
poll_sequence = 1,
last_remote_status = 'pending',
processing_started_at = COALESCE(processing_started_at, $3),
last_observed_at = $3,
processing_started_at = COALESCE(processing_started_at, $4),
last_observed_at = $4,
last_error = '',
updated_at = $3
updated_at = $4
WHERE id = $1
AND processing_state = 'pending'
AND (
@@ -622,7 +623,7 @@ func (s *Store) MarkUploading(ctx context.Context, publicationID, instanceURL st
return nil
}
func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID, knowledgeID string, now, nextAt time.Time) (int, error) {
func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID, knowledgeID, uploadMD5 string, now, nextAt time.Time) (int, error) {
payload, err := json.Marshal(struct {
PublicationID string `json:"publication_id"`
Sequence int `json:"sequence"`
@@ -636,6 +637,7 @@ func (s *Store) RecordUploadAndSchedulePoll(ctx context.Context, publicationID,
recordUploadAndSchedulePollSQL,
publicationID,
knowledgeID,
strings.ToLower(strings.TrimSpace(uploadMD5)),
now,
payload,
0,
@@ -67,13 +67,13 @@ func TestPublicationOrchestrationIsAtomicAndRejectsStaleTransitions(t *testing.T
if err := store.MarkUploading(ctx, "publication-1", "", 0, now); err != nil {
t.Fatal(err)
}
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", "", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
t.Fatalf("record upload = %d, %v", sequence, err)
}
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", "", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
t.Fatalf("replay upload = %d, %v", sequence, err)
}
if _, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-conflict", now, now.Add(10*time.Second)); !errors.Is(err, ErrPublicationStateConflict) {
if _, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-conflict", "", now, now.Add(10*time.Second)); !errors.Is(err, ErrPublicationStateConflict) {
t.Fatalf("conflicting knowledge error = %v", err)
}
@@ -52,7 +52,7 @@ func TestRecordUploadAndSchedulePollIsAtomicAndIdempotent(t *testing.T) {
db := &recordingDB{row: sequenceRow{sequence: 1}}
now := time.Date(2026, time.September, 4, 2, 5, 0, 0, time.UTC)
nextAt := now.Add(10 * time.Second)
sequence, err := NewStore(db).RecordUploadAndSchedulePoll(context.Background(), "publication-1", "knowledge-1", now, nextAt)
sequence, err := NewStore(db).RecordUploadAndSchedulePoll(context.Background(), "publication-1", "knowledge-1", "", now, nextAt)
if err != nil {
t.Fatalf("RecordUploadAndSchedulePoll() error = %v", err)
}
@@ -64,14 +64,14 @@ func TestRecordUploadAndSchedulePollIsAtomicAndIdempotent(t *testing.T) {
if updateAt < 0 || insertAt < 0 || updateAt >= insertAt {
t.Fatalf("atomic SQL missing ordered update/insert: %q", recordUploadAndSchedulePollSQL)
}
if db.queryRowSQL != recordUploadAndSchedulePollSQL || len(db.queryRowArgs) != 7 {
if db.queryRowSQL != recordUploadAndSchedulePollSQL || len(db.queryRowArgs) != 8 {
t.Fatalf("query = %q %#v", db.queryRowSQL, db.queryRowArgs)
}
if !strings.Contains(recordUploadAndSchedulePollSQL, "'test-poll:' || $1 || ':' || updated.retry_count || ':1'") {
t.Fatalf("poll schedule key must carry the retry round: %q", recordUploadAndSchedulePollSQL)
}
var payload map[string]any
if err := json.Unmarshal(db.queryRowArgs[3].([]byte), &payload); err != nil {
if err := json.Unmarshal(db.queryRowArgs[4].([]byte), &payload); err != nil {
t.Fatal(err)
}
if len(payload) != 2 || payload["publication_id"] != "publication-1" || payload["sequence"] != float64(1) {