fix(library): 按目标身份隔离版本授权与执行历史
build / build (push) Successful in 1m47s

This commit is contained in:
姚章浩
2026-10-31 02:15:15 +08:00
parent 323f9ae502
commit 7ab2eb1ccf
15 changed files with 473 additions and 72 deletions
+69 -52
View File
@@ -30,12 +30,12 @@ func (s *Store) CreateLibraryJob(ctx context.Context, job governance.LibraryJob,
var id string
err = s.db.QueryRow(ctx, `
INSERT INTO library_jobs (id, scope, kind, state, stage, idempotency_key, request_digest, request,
queue_job_id, snapshot_id, target_snapshot_id, actor, error, recovery, operation_id, created_at, updated_at)
VALUES ($1,$2,$3,'pending','',$4,$5,$6,$7,$8,$9,$10,'','',$11,$12,$12)
queue_job_id, snapshot_id, target_snapshot_id, actor, error, recovery, operation_id, created_at, updated_at, target_id)
VALUES ($1,$2,$3,'pending','',$4,$5,$6,$7,$8,$9,$10,'','',$11,$12,$12,$13)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id`,
job.ID, job.Scope, string(job.Kind), job.IdempotencyKey, request, rawRequest,
job.QueueJobID, job.SnapshotID, job.TargetSnapshotID, job.Actor, job.OperationID, now.UTC()).Scan(&id)
job.QueueJobID, job.SnapshotID, job.TargetSnapshotID, job.Actor, job.OperationID, now.UTC(), s.libraryTargetID).Scan(&id)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
@@ -87,7 +87,7 @@ func (s *Store) LibraryJob(ctx context.Context, id string) (governance.LibraryJo
if err := s.db.QueryRow(ctx, `
SELECT id, scope, kind, state, stage, idempotency_key, request_digest, queue_job_id, snapshot_id,
target_snapshot_id, actor, error, recovery, operation_id, attempt_epoch, created_at, updated_at, finished_at
FROM library_jobs WHERE id=$1`, id).Scan(&job.ID, &job.Scope, &kind, &state, &job.Stage, &job.IdempotencyKey,
FROM library_jobs WHERE id=$1 AND (kind='seal' OR target_id=$2)`, id, s.libraryTargetID).Scan(&job.ID, &job.Scope, &kind, &state, &job.Stage, &job.IdempotencyKey,
&job.RequestDigest, &job.QueueJobID, &job.SnapshotID, &job.TargetSnapshotID, &job.Actor, &job.Error,
&job.Recovery, &job.OperationID, &job.AttemptEpoch, &job.CreatedAt, &job.UpdatedAt, &finished); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -123,16 +123,16 @@ func (s *Store) LibraryReuseSources(ctx context.Context, scope string, limit int
rows, err := s.db.Query(ctx, `
SELECT j.id, j.target_snapshot_id, 'sync', coalesce(j.finished_at, j.updated_at)
FROM library_jobs j
WHERE j.scope=$1 AND j.kind='sync' AND j.state='succeeded' AND coalesce(j.target_snapshot_id,'')<>''
WHERE j.scope=$1 AND j.target_id=$3 AND j.kind='sync' AND j.state='succeeded' AND coalesce(j.target_snapshot_id,'')<>''
AND EXISTS (SELECT 1 FROM library_versions v
WHERE v.scope=j.scope AND v.kind='production_effective'
WHERE v.scope=j.scope AND v.target_id=j.target_id AND v.kind='production_effective'
AND v.snapshot_id=j.target_snapshot_id AND v.source_job_id=j.id)
UNION ALL
SELECT coalesce(v.source_job_id,''), v.snapshot_id, 'prebackup', v.created_at
FROM library_versions v
WHERE v.scope=$1 AND v.kind='production_prebackup' AND coalesce(v.snapshot_id,'')<>''
WHERE v.scope=$1 AND v.target_id=$3 AND v.kind='production_prebackup' AND coalesce(v.snapshot_id,'')<>''
ORDER BY 4 DESC
LIMIT $2`, scope, limit)
LIMIT $2`, scope, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("load library reuse sources: %w", err)
}
@@ -173,7 +173,7 @@ func (s *Store) ListLibraryJobs(ctx context.Context, scope string, limit int) ([
if limit < 1 || limit > 50 {
return nil, errors.New("library job list limit out of range")
}
rows, err := s.db.Query(ctx, `SELECT id FROM library_jobs WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
rows, err := s.db.Query(ctx, `SELECT id FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$3) ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list library jobs: %w", err)
}
@@ -273,6 +273,10 @@ WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, target
// 更早登记的事实不能把指针拉回历史,旧 epoch 在写边界就被守卫拒绝(见 guard)。
// - 生效/恢复事件才动指针;预备份/封存只追加事件。
func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error {
targetID := s.libraryTargetID
if version.Kind == governance.LibraryVersionTestSealed {
targetID = ""
}
evidence, err := json.Marshal(version.Evidence)
if err != nil {
return fmt.Errorf("encode library version evidence: %w", err)
@@ -301,17 +305,25 @@ func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.Lib
var inserted bool
err = tx.QueryRow(ctx, `
INSERT INTO library_versions (id, scope, kind, snapshot_id, version_label, source_job_id,
operation_id, attempt_epoch, evidence, created_by, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
operation_id, attempt_epoch, evidence, created_by, created_at, target_id)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
ON CONFLICT (id) DO UPDATE
SET evidence = EXCLUDED.evidence || library_versions.evidence
WHERE library_versions.source_job_id = EXCLUDED.source_job_id
AND library_versions.operation_id = EXCLUDED.operation_id
AND library_versions.target_id = EXCLUDED.target_id
RETURNING (xmax = 0)`,
version.ID, version.Scope, string(version.Kind), version.SnapshotID, version.VersionLabel,
version.SourceJobID, version.OperationID, version.AttemptEpoch, evidence, version.CreatedBy,
version.CreatedAt.UTC()).Scan(&inserted)
version.CreatedAt.UTC(), targetID).Scan(&inserted)
if errors.Is(err, pgx.ErrNoRows) {
var existingTarget string
if loadErr := tx.QueryRow(ctx, `SELECT target_id FROM library_versions WHERE id=$1`, version.ID).Scan(&existingTarget); loadErr != nil {
return loadErr
}
if existingTarget != targetID {
return errors.New("library version identity belongs to another target")
}
// 同一身份已经存在、但归属是别的执行者/别的意图:不覆盖、不报错,也不推进 current。
inserted = false
err = nil
@@ -321,7 +333,7 @@ RETURNING (xmax = 0)`,
}
if version.Kind == governance.LibraryVersionProductionEffective || version.Kind == governance.LibraryVersionRecoveryVerified {
if err := advanceLibraryCurrent(ctx, tx, version, inserted); err != nil {
if err := advanceLibraryCurrent(ctx, tx, version, inserted, targetID); err != nil {
return err
}
}
@@ -338,7 +350,7 @@ RETURNING (xmax = 0)`,
// 恢复要不要能把 current 指回更早的**内容**?要,但它是通过**新的意图**(kind=recover,
// 创建于恢复时刻)做到的:内容更旧、意图更新,两者不矛盾。旧代次能不能写由 epoch
// 守卫回答(见 libraryFence),不由时间回答。
func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.LibraryVersion, inserted bool) error {
func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.LibraryVersion, inserted bool, targetID string) error {
orderAt := version.CreatedAt
if version.OperationID != "" {
var created *time.Time
@@ -358,8 +370,8 @@ func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.Li
if !inserted {
// 重放:事件已经在台账里。确认指针没有被别的更晚事实覆盖,否则只确认自己的历史。
var currentID string
err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1 FOR UPDATE`,
version.Scope).Scan(&currentID)
err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1 AND target_id=$2 FOR UPDATE`,
version.Scope, targetID).Scan(&currentID)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
@@ -369,21 +381,21 @@ func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.Li
return nil
}
tag, err := tx.Exec(ctx, `
INSERT INTO library_current_versions (scope, version_id, snapshot_id, operation_id, attempt_epoch, order_key, updated_at)
VALUES ($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT (scope) DO UPDATE SET
INSERT INTO library_current_versions (scope, version_id, snapshot_id, operation_id, attempt_epoch, order_key, updated_at, target_id)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
ON CONFLICT (scope, target_id) DO UPDATE SET
version_id=EXCLUDED.version_id, snapshot_id=EXCLUDED.snapshot_id,
operation_id=EXCLUDED.operation_id, attempt_epoch=EXCLUDED.attempt_epoch,
order_key=EXCLUDED.order_key, updated_at=EXCLUDED.updated_at
WHERE EXCLUDED.order_key > library_current_versions.order_key`,
version.Scope, version.ID, version.SnapshotID, version.OperationID, version.AttemptEpoch, orderKey,
version.CreatedAt.UTC())
version.CreatedAt.UTC(), targetID)
if err != nil {
return fmt.Errorf("advance library current pointer: %w", err)
}
var currentID string
if err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1`,
version.Scope).Scan(&currentID); err != nil {
if err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1 AND target_id=$2`,
version.Scope, targetID).Scan(&currentID); err != nil {
return fmt.Errorf("read back library current pointer: %w", err)
}
if tag.RowsAffected() == 0 && currentID != version.ID {
@@ -394,8 +406,8 @@ WHERE EXCLUDED.order_key > library_current_versions.order_key`,
// 它跟着指针走:指针指向谁,谁就是未顶替的那一行。
if _, err := tx.Exec(ctx, `
UPDATE library_versions SET superseded_at = CASE WHEN id=$2 THEN NULL ELSE COALESCE(superseded_at, $3) END
WHERE scope=$1 AND kind IN ('production_effective','recovery_verified')`, version.Scope, currentID,
version.CreatedAt.UTC()); err != nil {
WHERE scope=$1 AND target_id=$4 AND kind IN ('production_effective','recovery_verified')`, version.Scope, currentID,
version.CreatedAt.UTC(), targetID); err != nil {
return fmt.Errorf("refresh library version supersede metadata: %w", err)
}
return nil
@@ -417,7 +429,8 @@ WHERE lj.kind IN ('sync','restore','baseline')
-- 业务作业已被前一轮接管置为 pending,但队列作业的租约也没了(worker 又死了)
OR (lj.state='pending' AND j.state='running' AND j.lease_until IS NOT NULL AND j.lease_until < now())
)
ORDER BY lj.created_at`)
AND lj.target_id=$1
ORDER BY lj.created_at`, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list interrupted library jobs: %w", err)
}
@@ -454,6 +467,9 @@ ORDER BY lj.created_at`)
// 条件更新:只有 failed/cancelled 才允许置回 pending;终态时间与错误清零,
// 旧 attempt 行保留(历史不可变)。代次由 BeginLibraryAttempt 在 worker 起手时递增。
func (s *Store) PrepareLibraryJobResume(ctx context.Context, jobID string, now time.Time) (governance.LibraryJob, bool, error) {
if _, err := s.LibraryJob(ctx, jobID); err != nil {
return governance.LibraryJob{}, false, err
}
tx, err := s.db.Begin(ctx)
if err != nil {
return governance.LibraryJob{}, false, fmt.Errorf("prepare library job resume: %w", err)
@@ -512,8 +528,8 @@ WHERE id=$1 AND state IN ('running','retry','failed','pending')
// 然后各自跑一遍同一个窗口(F13)。租约仍有效时直接失败,让调用方跳过。
func (s *Store) ClaimLibraryJobForResume(ctx context.Context, jobID string, now time.Time) (bool, error) {
tag, err := s.db.Exec(ctx, `UPDATE library_jobs SET state='pending', updated_at=$2
WHERE id=$1 AND state IN ('running','pending')
AND (lease_owner='' OR lease_until IS NULL OR lease_until < $2)`, jobID, now.UTC())
WHERE id=$1 AND target_id=$3 AND state IN ('running','pending')
AND (lease_owner='' OR lease_until IS NULL OR lease_until < $2)`, jobID, now.UTC(), s.libraryTargetID)
if err != nil {
return false, fmt.Errorf("claim interrupted library job: %w", err)
}
@@ -540,19 +556,20 @@ SET state='failed', error='队列中已无对应作业,业务作业未收到
updated_at=$1, finished_at=$1
WHERE lj.state IN ('pending','running')
AND lj.kind = ANY($2)
AND (lj.kind='seal' OR lj.target_id=$3)
AND lj.queue_job_id <> ''
AND NOT EXISTS (
SELECT 1 FROM jobs AS j
WHERE j.id = lj.queue_job_id AND j.state IN ('pending','running','retry')
)`, now.UTC(), kinds); err != nil {
)`, now.UTC(), kinds, s.libraryTargetID); err != nil {
return 0, fmt.Errorf("reconcile library jobs: %w", err)
}
// 建了业务作业但队列投递没完成(queue_job_id 为空)超过 5 分钟,也是孤儿。
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs
SET state='failed', error='队列投递未完成,作业从未开始', recovery='无需恢复来源;可直接重发', updated_at=$1, finished_at=$1
WHERE state IN ('pending','running') AND queue_job_id='' AND kind = ANY($3) AND created_at < $2`,
now.UTC(), now.Add(-5*time.Minute).UTC(), kinds)
WHERE state IN ('pending','running') AND queue_job_id='' AND kind = ANY($3) AND (kind='seal' OR target_id=$4) AND created_at < $2`,
now.UTC(), now.Add(-5*time.Minute).UTC(), kinds, s.libraryTargetID)
if err != nil {
return 0, fmt.Errorf("reconcile unattached library jobs: %w", err)
}
@@ -577,8 +594,8 @@ func (s *Store) LibraryVersionByRef(ctx context.Context, scope string, kind gove
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=$2 AND source_job_id=$3 AND snapshot_id=$4
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), sourceJobID, snapshotID)
WHERE scope=$1 AND kind=$2 AND source_job_id=$3 AND snapshot_id=$4 AND (kind='test_sealed' OR target_id=$5)
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), sourceJobID, snapshotID, s.libraryTargetID)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load library version by ref: %w", err)
}
@@ -597,8 +614,8 @@ ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), sourceJobID, sn
// 当成"没有记录"就会允许调用方覆盖别人的台账。
var owner string
err = s.db.QueryRow(ctx, `
SELECT source_job_id FROM library_versions WHERE scope=$1 AND kind=$2 AND snapshot_id=$3
ORDER BY created_at DESC LIMIT 1`, scope, string(kind), snapshotID).Scan(&owner)
SELECT source_job_id FROM library_versions WHERE scope=$1 AND kind=$2 AND snapshot_id=$3 AND (kind='test_sealed' OR target_id=$4)
ORDER BY created_at DESC LIMIT 1`, scope, string(kind), snapshotID, s.libraryTargetID).Scan(&owner)
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryVersion{}, false, nil
}
@@ -639,7 +656,7 @@ func (s *Store) LibraryVersions(ctx context.Context, scope string, limit int) ([
}
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 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
FROM library_versions WHERE scope=$1 AND (kind='test_sealed' OR target_id=$3) ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list library versions: %w", err)
}
@@ -654,7 +671,7 @@ FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`
// 任何"最近 N 条",接管/基线/闸口就会把"已生效"读成"没有生效"。
// · 不能靠扫 library_versions.kind='production_effective' 挑未顶替行——事件不可变,
// "谁是当前"是指针的事实,不是事件行的可变字段(F02)。
// · 指针每 scope 至多一行(主键),所以这里不需要"挑一条看起来对的"。
// · 指针每 (scope, target_id) 至多一行,历史归属不明的空身份不归新目标。
//
// 指针可能指向 production_effective,也可能指向 recovery_verified(按预备份恢复后
// 的当前内容身份)——调用方只能用它回答"当前是什么内容",不能假设它是一次成功发布。
@@ -666,7 +683,7 @@ func (s *Store) LibraryCurrentVersion(ctx context.Context, scope string) (govern
SELECT v.id, v.scope, v.kind, v.snapshot_id, v.version_label, v.source_job_id, v.operation_id, v.attempt_epoch,
v.evidence, v.created_by, v.created_at, v.superseded_at
FROM library_current_versions c JOIN library_versions v ON v.id = c.version_id
WHERE c.scope=$1`, scope)
WHERE c.scope=$1 AND c.target_id=$2 AND v.target_id=c.target_id`, scope, s.libraryTargetID)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load current library version: %w", err)
}
@@ -697,8 +714,8 @@ func (s *Store) LibraryVersionOfSnapshot(ctx context.Context, scope string,
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=$2 AND snapshot_id=$3
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), snapshotID)
WHERE scope=$1 AND kind=$2 AND snapshot_id=$3 AND (kind='test_sealed' OR target_id=$4)
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), snapshotID, s.libraryTargetID)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load library version of snapshot: %w", err)
}
@@ -732,9 +749,9 @@ func (s *Store) CreateLibraryAuthorization(ctx context.Context, item governance.
return errors.New("invalid library release authorization")
}
_, err := s.db.Exec(ctx, `
INSERT INTO library_release_authorizations (id, scope, snapshot_id, params_digest, authorized_by, expires_at, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
item.ID, item.Scope, item.SnapshotID, item.ParamsDigest, item.AuthorizedBy, item.ExpiresAt.UTC(), item.CreatedAt.UTC())
INSERT INTO library_release_authorizations (id, scope, snapshot_id, params_digest, authorized_by, expires_at, created_at, target_id)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
item.ID, item.Scope, item.SnapshotID, item.ParamsDigest, item.AuthorizedBy, item.ExpiresAt.UTC(), item.CreatedAt.UTC(), s.libraryTargetID)
if err != nil {
return fmt.Errorf("create library release authorization: %w", err)
}
@@ -748,9 +765,9 @@ func (s *Store) ActiveLibraryAuthorization(ctx context.Context, scope, snapshotI
err := s.db.QueryRow(ctx, `
SELECT id, scope, snapshot_id, params_digest, authorized_by, expires_at, revoked_at, created_at
FROM library_release_authorizations
WHERE scope=$1 AND snapshot_id=$2 AND params_digest=$3 AND revoked_at IS NULL AND expires_at > $4
WHERE scope=$1 AND snapshot_id=$2 AND params_digest=$3 AND target_id=$5 AND revoked_at IS NULL AND expires_at > $4
ORDER BY expires_at DESC, created_at DESC
LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC()).Scan(&item.ID, &item.Scope, &item.SnapshotID,
LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC(), s.libraryTargetID).Scan(&item.ID, &item.Scope, &item.SnapshotID,
&item.ParamsDigest, &item.AuthorizedBy, &item.ExpiresAt, &item.RevokedAt, &item.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryReleaseAuthorization{}, false, nil
@@ -762,7 +779,7 @@ LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC()).Scan(&item.ID, &item.Scope
}
func (s *Store) RevokeLibraryAuthorization(ctx context.Context, id string, now time.Time) error {
tag, err := s.db.Exec(ctx, `UPDATE library_release_authorizations SET revoked_at=$2 WHERE id=$1 AND revoked_at IS NULL`, id, now.UTC())
tag, err := s.db.Exec(ctx, `UPDATE library_release_authorizations SET revoked_at=$2 WHERE id=$1 AND target_id=$3 AND revoked_at IS NULL`, id, now.UTC(), s.libraryTargetID)
if err != nil {
return fmt.Errorf("revoke library authorization: %w", err)
}
@@ -778,7 +795,7 @@ func (s *Store) LibraryAuthorizations(ctx context.Context, scope string, limit i
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, snapshot_id, params_digest, authorized_by, expires_at, revoked_at, created_at
FROM library_release_authorizations WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
FROM library_release_authorizations WHERE scope=$1 AND target_id=$3 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list library authorizations: %w", err)
}
@@ -806,7 +823,7 @@ func (s *Store) LibraryVersionsBySnapshot(ctx context.Context, scope, snapshotID
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, source_job_id, COALESCE(evidence, '{}'::jsonb), created_at
FROM library_versions WHERE scope=$1 AND snapshot_id=$2 ORDER BY created_at`, scope, snapshotID)
FROM library_versions WHERE scope=$1 AND snapshot_id=$2 AND (kind='test_sealed' OR target_id=$3) ORDER BY created_at`, scope, snapshotID, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("read snapshot versions: %w", err)
}
@@ -859,7 +876,7 @@ func (s *Store) LibrarySnapshotKinds(ctx context.Context, scope, snapshotID stri
if scope == "" || snapshotID == "" {
return nil, errors.New("snapshot kinds requires scope and snapshot")
}
rows, err := s.db.Query(ctx, `SELECT DISTINCT kind FROM library_versions WHERE scope=$1 AND snapshot_id=$2`, scope, snapshotID)
rows, err := s.db.Query(ctx, `SELECT DISTINCT kind FROM library_versions WHERE scope=$1 AND snapshot_id=$2 AND (kind='test_sealed' OR target_id=$3)`, scope, snapshotID, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("read snapshot provenance: %w", err)
}
@@ -903,11 +920,11 @@ func (s *Store) LibrarySnapshotCandidates(ctx context.Context, scope string, aft
}
rows, err := s.db.Query(ctx, `
WITH referenced AS (
SELECT snapshot_id, created_at FROM library_versions WHERE scope=$1 AND snapshot_id <> ''
SELECT snapshot_id, created_at FROM library_versions WHERE scope=$1 AND (kind='test_sealed' OR target_id=$5) AND snapshot_id <> ''
UNION ALL
SELECT snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND snapshot_id <> ''
SELECT snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$5) AND snapshot_id <> ''
UNION ALL
SELECT target_snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND target_snapshot_id <> ''
SELECT target_snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$5) AND target_snapshot_id <> ''
), grouped AS (
SELECT snapshot_id, MAX(created_at) AS created_at FROM referenced GROUP BY snapshot_id
)
@@ -916,7 +933,7 @@ WHERE $2::timestamptz IS NULL
OR created_at < $2::timestamptz
OR (created_at = $2::timestamptz AND snapshot_id < $3)
ORDER BY created_at DESC, snapshot_id DESC
LIMIT $4`, scope, cursor, afterID, limit)
LIMIT $4`, scope, cursor, afterID, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list snapshot candidates: %w", err)
}
@@ -31,11 +31,11 @@ func (s *Store) EnsureLibraryOperation(ctx context.Context, op governance.Librar
}
var id string
err := s.db.QueryRow(ctx, `
INSERT INTO library_operations (id, scope, kind, target_snapshot_id, request_digest, operation_key, actor, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
INSERT INTO library_operations (id, scope, kind, target_snapshot_id, request_digest, operation_key, actor, created_at, target_id)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
ON CONFLICT (scope, kind, operation_key) DO NOTHING
RETURNING id`, op.ID, op.Scope, string(op.Kind), op.TargetSnapshotID, op.RequestDigest,
op.OperationKey, op.Actor, op.CreatedAt.UTC()).Scan(&id)
op.OperationKey, op.Actor, op.CreatedAt.UTC(), s.libraryTargetID).Scan(&id)
if err == nil {
return op, true, nil
}
@@ -70,7 +70,7 @@ func (s *Store) LibraryOperation(ctx context.Context, id string) (governance.Lib
var kind string
err := s.db.QueryRow(ctx, `
SELECT id, scope, kind, target_snapshot_id, request_digest, operation_key, actor, created_at
FROM library_operations WHERE id=$1`, id).Scan(&op.ID, &op.Scope, &kind, &op.TargetSnapshotID,
FROM library_operations WHERE id=$1 AND (kind='seal' OR target_id=$2)`, id, s.libraryTargetID).Scan(&op.ID, &op.Scope, &kind, &op.TargetSnapshotID,
&op.RequestDigest, &op.OperationKey, &op.Actor, &op.CreatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -0,0 +1,166 @@
package postgres
import (
"context"
"testing"
"time"
"knowledge-governance/internal/governance"
)
// Exercise the existing SQL against a real disposable PostgreSQL schema.
// Keep the unbound legacy namespace available to prove history survives
// while configured targets cannot adopt it.
func targetTestStore(s *Store, target string) *Store {
return s.WithLibraryTarget(target)
}
func TestLibraryTargetRejectsForeignEvidenceJobsAndGrants(t *testing.T) {
legacy, _ := openVersionStore(t)
a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b")
ctx := context.Background()
now := time.Now().UTC()
recordPrebackup(t, ctx, a, "internal", "backup-job", "backup", now)
if err := a.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: "source-seal", Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: "source", SourceJobID: "seal-job", CreatedAt: now}); err != nil {
t.Fatal(err)
}
checks := []struct {
name string
run func() bool
}{
{"version list", func() bool {
rows, err := b.LibraryVersions(ctx, "internal", 100)
return err == nil && len(rows) == 1 && rows[0].Kind == governance.LibraryVersionTestSealed
}},
{"exact backup", func() bool {
_, found, err := b.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionPrebackup, "backup-job", "backup")
return err == nil && !found
}},
{"snapshot version", func() bool {
_, found, err := b.LibraryVersionOfSnapshot(ctx, "internal", governance.LibraryVersionProductionPrebackup, "backup")
return err == nil && !found
}},
{"provenance", func() bool {
rows, err := b.LibraryVersionsBySnapshot(ctx, "internal", "backup")
return err == nil && len(rows) == 0
}},
{"snapshot kinds", func() bool {
rows, err := b.LibrarySnapshotKinds(ctx, "internal", "backup")
return err == nil && len(rows) == 0
}},
{"reuse sources", func() bool {
rows, err := b.LibraryReuseSources(ctx, "internal", 100)
return err == nil && len(rows) == 0
}},
{"handoff candidates", func() bool {
rows, err := b.LibrarySnapshotCandidates(ctx, "internal", time.Time{}, "", 100)
return err == nil && len(rows) == 1 && rows[0].SnapshotID == "source"
}},
}
for _, check := range checks {
t.Run(check.name, func(t *testing.T) {
if !check.run() {
t.Fatal("foreign target evidence was accepted or source seal was hidden")
}
})
}
job, _, err := a.CreateLibraryJob(ctx, governance.LibraryJob{ID: "target-a-job", Scope: "internal", Kind: governance.LibraryJobSync, IdempotencyKey: "target-a-job", RequestDigest: "digest", TargetSnapshotID: "source"}, governance.SyncStages(), now)
if err != nil {
t.Fatal(err)
}
if _, err := b.LibraryJob(ctx, job.ID); err == nil {
t.Error("new executor admitted old target job")
}
if _, _, err := b.PrepareLibraryJobResume(ctx, job.ID, now); err == nil {
t.Error("new target resumed old target job")
}
grant := governance.LibraryReleaseAuthorization{ID: "grant-a", Scope: "internal", SnapshotID: "source", ParamsDigest: "same-input", AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now}
if err := a.CreateLibraryAuthorization(ctx, grant); err != nil {
t.Fatal(err)
}
if _, found, err := b.ActiveLibraryAuthorization(ctx, "internal", "source", "same-input", now); err != nil || found {
t.Errorf("foreign grant accepted: found=%v err=%v", found, err)
}
if rows, err := b.LibraryAuthorizations(ctx, "internal", 100); err != nil || len(rows) != 0 {
t.Errorf("foreign grant listed: rows=%v err=%v", rows, err)
}
if err := b.RevokeLibraryAuthorization(ctx, grant.ID, now); err == nil {
t.Error("foreign grant revoked")
}
if _, found, err := a.ActiveLibraryAuthorization(ctx, "internal", "source", "same-input", now); err != nil || !found {
t.Errorf("original grant must remain valid: found=%v err=%v", found, err)
}
}
func TestLibraryTargetRejectsForeignOperationReplay(t *testing.T) {
legacy, _ := openVersionStore(t)
a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b")
ctx := context.Background()
op := governance.LibraryOperation{ID: "operation", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: "snapshot", RequestDigest: "digest", OperationKey: "same-key", CreatedAt: time.Now(), Actor: "admin"}
if _, _, err := a.EnsureLibraryOperation(ctx, op); err != nil {
t.Fatal(err)
}
if _, _, err := b.EnsureLibraryOperation(ctx, op); err == nil {
t.Error("new target replayed foreign operation")
}
if _, err := b.LibraryOperation(ctx, op.ID); err == nil {
t.Error("new target read foreign operation as its own")
}
}
func TestLibraryTargetRejectsEventIdentityCollision(t *testing.T) {
legacy, _ := openVersionStore(t)
a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b")
ctx := context.Background()
event := governance.LibraryVersion{ID: "same-event", Scope: "internal", Kind: governance.LibraryVersionProductionEffective, SnapshotID: "snapshot", SourceJobID: "job", CreatedAt: time.Now()}
if err := a.RecordLibraryVersion(ctx, event); err != nil {
t.Fatal(err)
}
if err := b.RecordLibraryVersion(ctx, event); err == nil {
t.Fatal("foreign event collision was silently accepted")
}
event.ID = "seal"
event.Kind = governance.LibraryVersionTestSealed
if err := a.RecordLibraryVersion(ctx, event); err != nil {
t.Fatal(err)
}
if err := b.RecordLibraryVersion(ctx, event); err != nil {
t.Fatalf("source seal replay must remain independent: %v", err)
}
}
func TestLibraryTargetSeparatesCurrentAndPreservesLegacy(t *testing.T) {
legacy, pool := openVersionStore(t)
a := targetTestStore(legacy, "target-a")
b := targetTestStore(legacy, "target-b")
ctx := context.Background()
now := time.Now().UTC()
record := func(s *Store, id string, at time.Time) {
t.Helper()
if err := s.RecordLibraryVersion(ctx, governance.LibraryVersion{
ID: id, Scope: "internal", Kind: governance.LibraryVersionProductionEffective,
SnapshotID: "snapshot-" + id, SourceJobID: "job-" + id, Evidence: map[string]any{"verified": true}, CreatedAt: at,
}); err != nil {
t.Fatal(err)
}
}
record(legacy, "legacy", now)
if _, found, err := b.LibraryCurrentVersion(ctx, "internal"); err != nil || found {
t.Fatalf("new target inherited legacy current: found=%v err=%v", found, err)
}
record(a, "a", now.Add(time.Second))
record(b, "b", now.Add(2*time.Second))
for _, tc := range []struct {
s *Store
want string
}{{legacy, "legacy"}, {a, "a"}, {b, "b"}} {
got, found, err := tc.s.LibraryCurrentVersion(ctx, "internal")
if err != nil || !found || got.ID != tc.want || got.SupersededAt != nil {
t.Fatalf("target current must remain independent: want=%s got=%+v found=%v err=%v", tc.want, got, found, err)
}
}
var count int
if err := pool.QueryRow(ctx, "SELECT count(*) FROM library_versions").Scan(&count); err != nil || count != 3 {
t.Fatalf("history changed: count=%d err=%v", count, err)
}
}
@@ -0,0 +1,17 @@
-- 已产生目标绑定证据时不可降级为 scope-only,否则会把不同目标历史混为一谈。
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM library_versions WHERE target_id <> '')
OR EXISTS (SELECT 1 FROM library_operations WHERE target_id <> '')
OR EXISTS (SELECT 1 FROM library_jobs WHERE target_id <> '')
OR EXISTS (SELECT 1 FROM library_release_authorizations WHERE target_id <> '') THEN
RAISE EXCEPTION 'target-bound release evidence exists; restore the verified control-plane backup instead of downgrading';
END IF;
END $$;
ALTER TABLE library_current_versions DROP CONSTRAINT library_current_versions_pkey;
ALTER TABLE library_current_versions DROP COLUMN target_id;
ALTER TABLE library_current_versions ADD PRIMARY KEY (scope);
DROP INDEX library_versions_target;
ALTER TABLE library_versions DROP COLUMN target_id;
ALTER TABLE library_operations DROP COLUMN target_id;
ALTER TABLE library_jobs DROP COLUMN target_id;
ALTER TABLE library_release_authorizations DROP COLUMN target_id;
@@ -0,0 +1,9 @@
-- 旧记录无法证明属于新配置目标;保留在空身份的历史空间,不猜测回填。
ALTER TABLE library_operations ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_jobs ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_release_authorizations ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_versions ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_current_versions ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_current_versions DROP CONSTRAINT library_current_versions_pkey;
ALTER TABLE library_current_versions ADD PRIMARY KEY (scope, target_id);
CREATE INDEX library_versions_target ON library_versions (target_id, scope, kind, created_at DESC);
+16 -13
View File
@@ -11,59 +11,62 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 76 {
t.Fatalf("migration count = %d, want 76", len(migrations))
if len(migrations) != 77 {
t.Fatalf("migration count = %d, want 77", len(migrations))
}
if target := migrations[76]; target.Version != 77 || !strings.Contains(target.UpSQL, "PRIMARY KEY (scope, target_id)") {
t.Fatalf("migration 77 = %#v", target)
}
// 76 是发布执行身份:operation / attempt(epoch) / 不可变事件 + current 指针。
// 它只动治理库,不碰 WeKnora Schema。
if identity := migrations[len(migrations)-1]; identity.Version != 76 ||
if identity := migrations[75]; identity.Version != 76 ||
!strings.Contains(identity.UpSQL, "library_operations") ||
!strings.Contains(identity.UpSQL, "library_attempts") ||
!strings.Contains(identity.UpSQL, "library_current_versions") {
t.Fatalf("migration 76 = %#v", identity)
}
// 75 允许"建立目标权威基线"作为独立业务作业,并与 sync/restore 共用写互斥。
if baseline := migrations[len(migrations)-2]; baseline.Version != 75 ||
if baseline := migrations[74]; baseline.Version != 75 ||
!strings.Contains(baseline.UpSQL, "library_jobs_write_target") ||
!strings.Contains(baseline.UpSQL, "'baseline'") {
t.Fatalf("migration 75 = %#v", baseline)
}
// 74 记录封存执行器的运行时状态:页面可用性来自真实观测,不来自配置字符串。
if executor := migrations[len(migrations)-3]; executor.Version != 74 ||
if executor := migrations[73]; executor.Version != 74 ||
!strings.Contains(executor.UpSQL, "library_executor_status") {
t.Fatalf("migration 74 = %#v", executor)
}
// 73 记录死信精确解除:保留上游行,只绑定指纹、重放引用与观测摘要。
if release := migrations[len(migrations)-4]; release.Version != 73 ||
if release := migrations[72]; release.Version != 73 ||
!strings.Contains(release.UpSQL, "library_dead_letter_releases") {
t.Fatalf("migration 73 = %#v", release)
}
// 72 让维护占用按实例互斥(internal/external 不再各有各的锁)。
if instance := migrations[len(migrations)-5]; instance.Version != 72 ||
if instance := migrations[71]; instance.Version != 72 ||
!strings.Contains(instance.UpSQL, "library_instance_maintenance") {
t.Fatalf("migration 72 = %#v", instance)
}
// 71 让维护记录能区分实例级维护与仅治理库互斥。
if level := migrations[len(migrations)-6]; level.Version != 71 ||
if level := migrations[70]; level.Version != 71 ||
!strings.Contains(level.UpSQL, "level") || !strings.Contains(level.UpSQL, "ingress_state") {
t.Fatalf("migration 71 = %#v", level)
}
if maint := migrations[len(migrations)-7]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
if maint := migrations[69]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
t.Fatalf("migration 70 = %#v", maint)
}
if tail := migrations[len(migrations)-8]; tail.Version != 69 ||
if tail := migrations[68]; tail.Version != 69 ||
!strings.Contains(tail.UpSQL, "library_jobs_write_target") {
t.Fatalf("migration 69 = %#v", tail)
}
if restore := migrations[len(migrations)-9]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
if restore := migrations[67]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
t.Fatalf("migration 68 = %#v", restore)
}
if last := migrations[len(migrations)-10]; last.Version != 67 ||
if last := migrations[66]; last.Version != 67 ||
!strings.Contains(last.UpSQL, "library_release_authorizations") ||
!strings.Contains(last.UpSQL, "params_digest") {
t.Fatalf("migration 67 = %#v", last)
}
if flow := migrations[len(migrations)-11]; flow.Version != 66 ||
if flow := migrations[65]; flow.Version != 66 ||
!strings.Contains(flow.UpSQL, "CREATE TABLE library_versions") ||
!strings.Contains(flow.UpSQL, "library_jobs_active") {
t.Fatalf("migration 66 = %#v", flow)
+11 -1
View File
@@ -23,7 +23,17 @@ type database interface {
}
type Store struct {
db database
db database
libraryTargetID string
}
// WithLibraryTarget isolates release facts without mutating a shared Store.
// The empty namespace retains legacy evidence; live API/workers bind a nonempty
// identity before exposing library operations. Source seals remain independent.
func (s *Store) WithLibraryTarget(id string) *Store {
copy := *s
copy.libraryTargetID = id
return &copy
}
func NewStore(db database) *Store {