fix(library): 修复封存终态回写并增加精确核对
build / build (push) Successful in 2m9s

修复 varchar 状态参数在 AdvanceLibraryJob 的 42P08;worker 开始/终态写入失败
不再吞掉。新增管理员核对路由,仅在 completed capture queue、export succeeded、
精确 test_sealed 版本、来源身份和归档复核一致时,以条件更新修复仍为
pending/running 的同一作业;已有不同快照或并发失败/取消行拒绝覆盖。保留
第一因与历史记录,不重新封存、不产生快照、不写源或目标知识。

验证:真实 varchar DDL PG 路径、handler 负例/幂等、worker 注入、web 组件;
umask022 与真实隔离 kg_library_test_* 下 Go 全量与 make verify 17 项通过。
This commit is contained in:
姚章浩
2026-11-06 10:04:19 +08:00
parent 77bbc3ac6b
commit 146ac832a2
18 changed files with 1082 additions and 39 deletions
@@ -0,0 +1,97 @@
package postgres
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// This exercises the exact SQL used by the admin capture reconcile path with
// the real varchar/jsonb/timestamptz column shapes from the migration. Fake
// stores cannot catch parameter-type mistakes, as the 42P08 incident showed.
func TestCaptureReconcileExactPostgresPath(t *testing.T) {
dsn := os.Getenv("KG_LIBRARY_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires explicitly isolated kg_library_test_ PostgreSQL database")
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil || !strings.HasPrefix(cfg.ConnConfig.Database, "kg_library_test_") || os.Getenv("KG_LIBRARY_TEST_ISOLATED") != "1" {
t.Fatal("isolated database required")
}
cfg.MaxConns = 1
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_temp"
ctx := context.Background()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if _, err := pool.Exec(ctx, `
CREATE TEMP TABLE library_jobs(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(16) NOT NULL,
state varchar(16) NOT NULL, queue_job_id varchar(64) NOT NULL DEFAULT '',
stage varchar(32) NOT NULL DEFAULT '', snapshot_id varchar(64) NOT NULL DEFAULT '',
error text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, finished_at timestamptz);
CREATE TEMP TABLE library_job_stages(
job_id varchar(64) NOT NULL, stage varchar(32) NOT NULL, state varchar(16) NOT NULL,
detail text NOT NULL DEFAULT '', updated_at timestamptz NOT NULL, PRIMARY KEY(job_id,stage));
CREATE TEMP TABLE library_versions(
id varchar(64) PRIMARY KEY, scope varchar(16) NOT NULL, kind varchar(24) NOT NULL,
snapshot_id varchar(64) NOT NULL DEFAULT '', version_label varchar(64) NOT NULL DEFAULT '',
source_job_id varchar(64) NOT NULL DEFAULT '', operation_id varchar(64) NOT NULL DEFAULT '',
attempt_epoch integer NOT NULL DEFAULT 0, evidence jsonb NOT NULL DEFAULT '{}'::jsonb,
created_by varchar(128) NOT NULL DEFAULT '', created_at timestamptz NOT NULL,
superseded_at timestamptz);
INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,updated_at)
VALUES('libseal-cap-1','internal','seal','pending','libcap-1',now());
INSERT INTO library_job_stages(job_id,stage,state,updated_at)
VALUES('libseal-cap-1','export','succeeded',now());
INSERT INTO library_versions(id,scope,kind,snapshot_id,source_job_id,created_at)
VALUES('libver-1','internal','test_sealed','snap-1','libseal-cap-1',now());`); err != nil {
t.Fatal(err)
}
store := NewStore(pool)
state, _, err := store.LibraryCaptureExportEvidence(ctx, "libseal-cap-1")
if err != nil || state != "succeeded" {
t.Fatalf("export evidence state=%q err=%v", state, err)
}
version, found, err := store.LibraryTestSealedVersionForJob(ctx, "internal", "libseal-cap-1")
if err != nil || !found || version.SnapshotID != "snap-1" {
t.Fatalf("version found=%v snapshot=%q err=%v", found, version.SnapshotID, err)
}
now := time.Now().UTC()
updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-cap-1", "internal", "libcap-1", "snap-1", now)
if err != nil || !updated {
t.Fatalf("conditional repair updated=%v err=%v", updated, err)
}
var gotState, gotScope, gotSnapshot string
var finished bool
if err := pool.QueryRow(ctx, `SELECT state, scope, snapshot_id, finished_at IS NOT NULL FROM library_jobs WHERE id='libseal-cap-1'`).
Scan(&gotState, &gotScope, &gotSnapshot, &finished); err != nil {
t.Fatal(err)
}
if gotState != "succeeded" || gotScope != "internal" || gotSnapshot != "snap-1" || !finished {
t.Fatalf("terminal state=%q scope=%q snapshot=%q finished=%v", gotState, gotScope, gotSnapshot, finished)
}
if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-cap-1", "internal", "libcap-1", "snap-1", now.Add(time.Second)); err != nil || updated {
t.Fatalf("second repair must be idempotent/false: updated=%v err=%v", updated, err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,updated_at)
VALUES('libseal-failed','internal','seal','failed','libcap-2',now())`); err != nil {
t.Fatal(err)
}
if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-failed", "internal", "libcap-2", "snap-2", now); err != nil || updated {
t.Fatalf("failed row must not be repaired: updated=%v err=%v", updated, err)
}
if _, err := pool.Exec(ctx, `INSERT INTO library_jobs(id,scope,kind,state,queue_job_id,snapshot_id,updated_at)
VALUES('libseal-other','internal','seal','running','libcap-3','other',now())`); err != nil {
t.Fatal(err)
}
if updated, err := store.ReconcileLibraryCaptureTerminal(ctx, "libseal-other", "internal", "libcap-3", "snap-3", now); err != nil || updated {
t.Fatalf("different existing snapshot must not be overwritten: updated=%v err=%v", updated, err)
}
}
+88 -12
View File
@@ -205,12 +205,12 @@ func (s *Store) ListLibraryJobs(ctx context.Context, scope string, limit int) ([
func (s *Store) UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_job_stages SET
state = CASE WHEN $3='' THEN state ELSE $3 END,
state = CASE WHEN $3::text='' THEN state ELSE $3::text END,
total = COALESCE($4, total),
completed = COALESCE($5, completed),
bytes_total = COALESCE($6, bytes_total),
bytes_done = COALESCE($7, bytes_done),
detail = CASE WHEN $8='' THEN detail ELSE $8 END,
detail = CASE WHEN $8::text='' THEN detail ELSE $8::text END,
updated_at = $9
WHERE job_id=$1 AND stage=$2`, jobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC())
if err != nil {
@@ -245,19 +245,20 @@ func (s *Store) AdvanceLibraryJob(ctx context.Context, jobID string, state gover
}
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs SET
state=$2,
stage = CASE WHEN $3='' THEN stage ELSE $3 END,
state=$2::text,
stage = CASE WHEN $3::text='' THEN stage ELSE $3::text END,
-- 失败重试不得把第一因覆盖成第二次“already exists”;成功时清除旧错误,
-- 但新的 failed 状态保留已记录的第一条失败原因。
-- 但新的 failed 状态保留已记录的第一条失败原因。显式 ::text 让所有对 $2
-- 的引用推导为同一类型;否则 varchar 列赋值与 CASE 文本比较会触发 42P08。
error = CASE
WHEN $2='succeeded' THEN ''
WHEN $4='' THEN error
WHEN $2='failed' AND error<>'' THEN error
ELSE $4
WHEN $2::text='succeeded' THEN ''
WHEN $4::text='' THEN error
WHEN $2::text='failed' AND error<>'' THEN error
ELSE $4::text
END,
recovery = CASE WHEN $5='' THEN recovery ELSE $5 END,
snapshot_id = CASE WHEN $6='' THEN snapshot_id ELSE $6 END,
target_snapshot_id = CASE WHEN $7='' THEN target_snapshot_id ELSE $7 END,
recovery = CASE WHEN $5::text='' THEN recovery ELSE $5::text END,
snapshot_id = CASE WHEN $6::text='' THEN snapshot_id ELSE $6::text END,
target_snapshot_id = CASE WHEN $7::text='' THEN target_snapshot_id ELSE $7::text END,
updated_at=$8,
finished_at=COALESCE($9, finished_at)
WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, targetSnapshotID, now.UTC(), finished)
@@ -270,6 +271,81 @@ WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, target
return nil
}
// LibraryCaptureExportEvidence is the exact export-stage evidence used by the
// admin capture reconciliation gate. It is a named method so callers do not
// drift into a "latest stage" or generic list query.
func (s *Store) LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error) {
return s.LibraryJobStage(ctx, jobID, "export")
}
// LibraryJobStage reads one exact stage row. The customer-visible job row is
// authoritative for state; this is the export-stage evidence used by the
// capture reconciliation gate.
func (s *Store) LibraryJobStage(ctx context.Context, jobID, stage string) (string, string, error) {
if jobID == "" || stage == "" {
return "", "", errors.New("library stage requires job and stage")
}
var state, detail string
err := s.db.QueryRow(ctx, `SELECT state, detail FROM library_job_stages WHERE job_id=$1 AND stage=$2`, jobID, stage).Scan(&state, &detail)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", errors.New("library stage not found")
}
if err != nil {
return "", "", fmt.Errorf("read library stage: %w", err)
}
return state, detail, nil
}
// LibraryTestSealedVersionForJob finds the immutable test-sealed version by
// exact (scope, source_job_id), never by "latest N". More than one row means
// the ledger is ambiguous and must be rejected instead of picking one.
func (s *Store) LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) {
if scope == "" || jobID == "" {
return governance.LibraryVersion{}, false, errors.New("test sealed version requires scope and job")
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch,
evidence, created_by, created_at, superseded_at
FROM library_versions
WHERE scope=$1 AND kind='test_sealed' AND source_job_id=$2
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, jobID)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("read test sealed version for job: %w", err)
}
items, err := scanLibraryVersions(rows, 2)
if err != nil {
return governance.LibraryVersion{}, false, err
}
if len(items) > 1 {
return governance.LibraryVersion{}, false, fmt.Errorf("job %s has %d test-sealed rows; refuse to pick one", jobID, len(items))
}
if len(items) == 1 {
return items[0], true, nil
}
return governance.LibraryVersion{}, false, nil
}
// ReconcileLibraryCaptureTerminal is the only write allowed to repair a seal
// terminal during admin reconciliation. It is conditional on the exact job,
// scope, kind, queue/capture identity and an in-flight state; a concurrent
// failed/cancelled row or a different snapshot is never overwritten.
func (s *Store) ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error) {
if jobID == "" || scope == "" || queueJobID == "" || snapshotID == "" {
return false, errors.New("reconcile capture terminal requires job/scope/queue/snapshot")
}
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs
SET state='succeeded', stage='export', error='', snapshot_id=$4,
updated_at=$5, finished_at=$5
WHERE id=$1 AND scope=$2 AND kind='seal' AND queue_job_id=$3
AND state IN ('pending','running')
AND (snapshot_id='' OR snapshot_id=$4)`, jobID, scope, queueJobID, snapshotID, now.UTC())
if err != nil {
return false, fmt.Errorf("reconcile capture terminal: %w", err)
}
return tag.RowsAffected() == 1, nil
}
// RecordLibraryVersion 写入一条**不可变版本事件**,并在需要时推进 current 指针。
//
// 与旧实现的区别(F02/F09 的根因):
@@ -33,13 +33,36 @@ func TestAdvanceLibraryJobPreservesFirstFailure(t *testing.T) {
defer pool.Close()
if _, err := pool.Exec(ctx, `
CREATE TEMP TABLE library_jobs(
id text primary key, state text, stage text, error text, recovery text,
snapshot_id text, target_snapshot_id text, updated_at timestamptz, finished_at timestamptz);
INSERT INTO library_jobs(id,state,stage,error) VALUES('libseal-retry','running','export','');`); err != nil {
id text primary key, state varchar(16) NOT NULL CHECK (state IN ('pending','running','succeeded','failed','cancelled')),
stage varchar(32) NOT NULL DEFAULT '', error text NOT NULL DEFAULT '', recovery varchar(255) NOT NULL DEFAULT '',
snapshot_id varchar(64) NOT NULL DEFAULT '', target_snapshot_id varchar(64) NOT NULL DEFAULT '',
updated_at timestamptz NOT NULL, finished_at timestamptz);
INSERT INTO library_jobs(id,state,stage,error,updated_at) VALUES('libseal-retry','pending','','',now());
CREATE TEMP TABLE library_job_stages(
job_id text, stage varchar(32), state varchar(16), total bigint, completed bigint,
bytes_total bigint, bytes_done bigint, detail text, updated_at timestamptz, primary key(job_id,stage));
INSERT INTO library_job_stages(job_id,stage,state,updated_at) VALUES('libseal-retry','export','pending',now());`); err != nil {
t.Fatal(err)
}
store := NewStore(pool)
now := time.Now().UTC()
if err := store.UpdateLibraryStage(ctx, "libseal-retry", "export", "running", nil, nil, nil, nil, "started", now); err != nil {
t.Fatalf("update stage with real varchar types: %v", err)
}
if stageState, _, err := store.LibraryJobStage(ctx, "libseal-retry", "export"); err != nil || stageState != "running" {
t.Fatalf("read stage state=%q err=%v", stageState, err)
}
if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobRunning, "export", "", "", "", "", now); err != nil {
t.Fatal(err)
}
var state, stage string
var finished bool
if err := pool.QueryRow(ctx, `SELECT state, stage, finished_at IS NULL FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &stage, &finished); err != nil {
t.Fatal(err)
}
if state != "running" || stage != "export" || !finished {
t.Fatalf("running transition not persisted: state=%q stage=%q finished_null=%v", state, stage, finished)
}
if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobFailed, "export", "first validation failure", "", "", "", now); err != nil {
t.Fatal(err)
}
@@ -47,18 +70,25 @@ INSERT INTO library_jobs(id,state,stage,error) VALUES('libseal-retry','running',
t.Fatal(err)
}
var got string
if err := pool.QueryRow(ctx, `SELECT error FROM library_jobs WHERE id='libseal-retry'`).Scan(&got); err != nil {
var snap string
if err := pool.QueryRow(ctx, `SELECT state, error, finished_at IS NOT NULL, snapshot_id FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &got, &finished, &snap); err != nil {
t.Fatal(err)
}
if state != "failed" || !finished || snap != "" {
t.Fatalf("failed transition not persisted: state=%q finished=%v snapshot=%q", state, finished, snap)
}
if got != "first validation failure" {
t.Fatalf("first failure overwritten: %q", got)
}
if err := store.AdvanceLibraryJob(ctx, "libseal-retry", governance.LibraryJobSucceeded, "export", "", "", "snap-ok", "", now.Add(2*time.Second)); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx, `SELECT error FROM library_jobs WHERE id='libseal-retry'`).Scan(&got); err != nil {
if err := pool.QueryRow(ctx, `SELECT state, error, snapshot_id, finished_at IS NOT NULL FROM library_jobs WHERE id='libseal-retry'`).Scan(&state, &got, &snap, &finished); err != nil {
t.Fatal(err)
}
if state != "succeeded" || !finished || snap != "snap-ok" {
t.Fatalf("succeeded transition not persisted: state=%q finished=%v snapshot=%q", state, finished, snap)
}
if got != "" {
t.Fatalf("success must clear old error, got %q", got)
}
@@ -57,12 +57,12 @@ func (s *Store) AdvanceLibraryJobGuarded(ctx context.Context, attempt governance
}
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs SET
state=$2,
stage = CASE WHEN $3='' THEN stage ELSE $3 END,
error = CASE WHEN $4='' THEN error ELSE $4 END,
recovery = CASE WHEN $5='' THEN recovery ELSE $5 END,
snapshot_id = CASE WHEN $6='' THEN snapshot_id ELSE $6 END,
target_snapshot_id = CASE WHEN $7='' THEN target_snapshot_id ELSE $7 END,
state=$2::text,
stage = CASE WHEN $3::text='' THEN stage ELSE $3::text END,
error = CASE WHEN $4::text='' THEN error ELSE $4::text END,
recovery = CASE WHEN $5::text='' THEN recovery ELSE $5::text END,
snapshot_id = CASE WHEN $6::text='' THEN snapshot_id ELSE $6::text END,
target_snapshot_id = CASE WHEN $7::text='' THEN target_snapshot_id ELSE $7::text END,
updated_at=$8,
finished_at=COALESCE($9, finished_at)
WHERE id=$1 AND `+libraryFence("$1", 10, 11),
@@ -82,12 +82,12 @@ func (s *Store) UpdateLibraryStageGuarded(ctx context.Context, attempt governanc
stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_job_stages SET
state = CASE WHEN $3='' THEN state ELSE $3 END,
state = CASE WHEN $3::text='' THEN state ELSE $3::text END,
total = COALESCE($4, total),
completed = COALESCE($5, completed),
bytes_total = COALESCE($6, bytes_total),
bytes_done = COALESCE($7, bytes_done),
detail = CASE WHEN $8='' THEN detail ELSE $8 END,
detail = CASE WHEN $8::text='' THEN detail ELSE $8::text END,
updated_at = $9
WHERE job_id=$1 AND stage=$2 AND `+libraryFence("$1", 10, 11),
attempt.JobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC(),
+8
View File
@@ -134,6 +134,14 @@ SELECT id FROM updated
// One job type, newest first: a caller which needs "the recent jobs of MY type"
// must not page the global queue (other traffic would hide its own rows).
const jobByIDSQL = `
SELECT id, type, payload, state, priority, available_at,
lease_owner, lease_until, attempt, max_attempts,
last_error, idempotency_key, created_at, updated_at
FROM jobs
WHERE id = $1
`
const listJobsByTypeSQL = `
SELECT id, type, payload, state, priority, available_at,
lease_owner, lease_until, attempt, max_attempts,
+15
View File
@@ -101,6 +101,21 @@ func (s *Store) Claim(ctx context.Context, workerID string, allowedTypes []strin
// ListByType lists only the requested job type, so a busy queue cannot hide the
// caller's own recent jobs behind unrelated traffic.
// QueueJob reads one queue row by exact id (no window / no type filter).
func (s *Store) QueueJob(ctx context.Context, id string) (jobs.Job, bool, error) {
if strings.TrimSpace(id) == "" {
return jobs.Job{}, false, errors.New("queue job id required")
}
job, err := scanJob(s.db.QueryRow(ctx, jobByIDSQL, id))
if errors.Is(err, pgx.ErrNoRows) {
return jobs.Job{}, false, nil
}
if err != nil {
return jobs.Job{}, false, fmt.Errorf("read queue job: %w", err)
}
return *job, true, nil
}
func (s *Store) ListByType(ctx context.Context, jobType string, limit int) ([]jobs.Job, error) {
if strings.TrimSpace(jobType) == "" || limit < 1 || limit > 200 {
return nil, errors.New("list jobs by type requires a type and a bounded limit")