fix(library): 统一执行身份、终态收尾、准入与数据身份
build / build (push) Failing after 24s

why:审计 19 项(12 P1 / 7 P2)来自同一批根因,逐点试错会把协议撕成十几份:
  · 意图与执行混为一谈(F01/F15):`library.sync:<scope>:<快照>` 是终身幂等键,
    A→B→A 的第三次发布拿到第一次的历史成功作业,什么都不做;
  · 版本行既是实体又是事件(F02/F09):主键只由 (kind,scope,快照) 决定、写入是
    upsert,第二个作业覆盖 `source_job_id`/`evidence`/`created_at`;
  · 接管没有代次(F13):两个 worker 都能认领同一 pending 作业,失租的旧执行还能
    写业务状态、释放别人的维护锁;
  · 早退与终态没有统一政策(F03/F04/F05/F06):半写窗口的前置检查失败会重新开门、
    服务起不来也照样开入口、journal 终态后收尾不可重建、恢复成功不回写 current;
  · 数据身份与准入各写一套(F07/F08/F14/F17):接管丢了复用语义、全库搬运不改
    location_hash、通用入口可造 library.* 作业、目标模型从没被问过;
  · 存储/容量/UI/CI 判据各自为政(F10/F11/F12/F16/F18/F19)。

what:按批准的一套协议集中实施(详见 handoffs/release-consolidated-implementation/
current-contract.md):
  · operation(一次明确意图)/ attempt(epoch 代次)/ 不可变版本事件 / current 指针;
    治理库迁移 76,只动治理库,不碰 WeKnora Schema/源码/镜像;
  · 所有业务状态、阶段、版本事件、维护锁写入带 epoch 守卫(失租代次写不进去);
    心跳失租立刻取消 handler;
  · 半写窗口早退保持关闭;服务未全部健康绝不开入口;journal 终态可从持久事实重建
    收尾;恢复成功登记 recovery 事件并推进 current;
  · worker 在动维护前核对业务行/kind/scope/队列关联;通用入口拒绝 library.*;
  · 全库搬运重算 location_hash 并与文档级导入共用实现;接管消费写集合的复用决定;
    发布前核目标实时模型契约、容量门禁前置;
  · 存储保护闭包改为全量依赖、类型只认显式登记、保护未知则不出可删候选;
  · 页面核 HTTP 状态与结构、恢复纳入轮询、Wiki 差异覆盖标题/摘要/父级。

how:`make verify` rc=0(16 项必需检查全绿,含 go test 全量与前端 485 例);
`go vet ./...` rc=0;`npx tsc -p tsconfig.json --noEmit` rc=0;逐项负例见各包测试
(F03/F04/F08/F12/F13/F14/F16/F18/F19 都有先红后绿记录)。
未执行:治理库迁移到任何已有库、真实 PG/ES/S3/WeKnora 集成、故障注入、部署。
This commit is contained in:
姚章浩
2026-10-30 16:14:54 +08:00
parent 4f0852a94d
commit 98294b9583
52 changed files with 2821 additions and 198 deletions
+128 -54
View File
@@ -28,12 +28,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, created_at, updated_at)
VALUES ($1,$2,$3,'pending','',$4,$5,$6,$7,$8,$9,$10,'','',$11,$11)
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)
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, now.UTC()).Scan(&id)
job.QueueJobID, job.SnapshotID, job.TargetSnapshotID, job.Actor, job.OperationID, now.UTC()).Scan(&id)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
@@ -84,10 +84,10 @@ func (s *Store) LibraryJob(ctx context.Context, id string) (governance.LibraryJo
var finished *time.Time
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, created_at, updated_at, finished_at
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,
&job.RequestDigest, &job.QueueJobID, &job.SnapshotID, &job.TargetSnapshotID, &job.Actor, &job.Error,
&job.Recovery, &job.CreatedAt, &job.UpdatedAt, &finished); err != nil {
&job.Recovery, &job.OperationID, &job.AttemptEpoch, &job.CreatedAt, &job.UpdatedAt, &finished); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryJob{}, err
}
@@ -261,8 +261,15 @@ WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, target
return nil
}
// RecordLibraryVersion 写入一个版本记录。生产生效版本必须先把旧的 supersede 掉,
// 否则唯一索引会拒绝——这正是"不许两个生效版本并存"的保证。
// RecordLibraryVersion 写入一条**不可变版本事件**,并在需要时推进 current 指针。
//
// 与旧实现的区别(F02/F09 的根因):
// - 事件 ID 含 operation:不同 operation 引用同一快照是两条事件,`source_job_id`/
// `evidence`/`created_at` 谁也不覆盖谁(旧实现是 `ON CONFLICT DO UPDATE` 整份替换)。
// - 同一 operation 重放是幂等:`ON CONFLICT (id) DO NOTHING`,已存行原样返回。
// - "谁当前生效"由 `library_current_versions` 表达,用单调次序做条件更新;
// 更早登记的事实不能把指针拉回历史,旧 epoch 在写边界就被守卫拒绝(见 guard)。
// - 生效/恢复事件才动指针;预备份/封存只追加事件。
func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error {
evidence, err := json.Marshal(version.Evidence)
if err != nil {
@@ -273,35 +280,87 @@ func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.Lib
return fmt.Errorf("begin library version: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if version.Kind == governance.LibraryVersionProductionEffective {
if _, err := tx.Exec(ctx, `
UPDATE library_versions SET superseded_at=$2
WHERE scope=$1 AND kind='production_effective' AND superseded_at IS NULL`, version.Scope, version.CreatedAt.UTC()); err != nil {
return fmt.Errorf("supersede library version: %w", err)
// 执行代次守卫:写事件的人必须还是当前代次(失租旧执行器不能登记"我成功了")。
if version.SourceJobID != "" && version.AttemptEpoch > 0 {
if err := guardLibraryJobEpoch(ctx, tx, version.SourceJobID, version.AttemptEpoch, version.AttemptOwner); err != nil {
return err
}
}
if _, err := tx.Exec(ctx, `
INSERT INTO library_versions (id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
ON CONFLICT (id) DO UPDATE SET
-- 恢复/重放同一个快照时必须把它重新"激活":否则它还是被 supersede 的旧行,
-- 页面会显示"生产当前版本未知",而实际生产已经恢复到这个快照。
superseded_at = NULL,
source_job_id = EXCLUDED.source_job_id,
evidence = EXCLUDED.evidence,
-- 预备份版本行的 created_at 是"这份基线什么时候拍的",只能早、不能晚:
-- 崩溃接管会复用同一份预备份,重写登记时间会把"复用"洗成"重做了备份",
-- 事后无法证明基线没被半写状态覆盖过。
created_at = CASE WHEN library_versions.kind='production_prebackup'
THEN LEAST(library_versions.created_at, EXCLUDED.created_at)
ELSE EXCLUDED.created_at END`,
tag, err := tx.Exec(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)
ON CONFLICT (id) DO NOTHING`,
version.ID, version.Scope, string(version.Kind), version.SnapshotID, version.VersionLabel,
version.SourceJobID, evidence, version.CreatedBy, version.CreatedAt.UTC()); err != nil {
return fmt.Errorf("record library version: %w", err)
version.SourceJobID, version.OperationID, version.AttemptEpoch, evidence, version.CreatedBy,
version.CreatedAt.UTC())
if err != nil {
return fmt.Errorf("record library version event: %w", err)
}
inserted := tag.RowsAffected() == 1
if version.Kind == governance.LibraryVersionProductionEffective || version.Kind == governance.LibraryVersionRecoveryVerified {
if err := advanceLibraryCurrent(ctx, tx, version, inserted); err != nil {
return err
}
}
return tx.Commit(ctx)
}
// advanceLibraryCurrent 用单调次序条件推进 current 指针。
//
// 次序键 = (事件登记时间|operation|epoch)。它只回答"哪一条事实更晚被登记",
// 不回答"哪个意图更重要";旧代次能不能写由 epoch 守卫回答,两件事分开才不会互相冒充。
func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.LibraryVersion, inserted bool) error {
orderKey := governance.CurrentOrderKey(version.CreatedAt, version.OperationID, version.AttemptEpoch)
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)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return fmt.Errorf("load library current pointer: %w", err)
}
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
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())
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 {
return fmt.Errorf("read back library current pointer: %w", err)
}
if tag.RowsAffected() == 0 && currentID != version.ID {
return fmt.Errorf("%w(scope=%s:当前 %s,本条 %s)", governance.ErrLibraryCurrentStale,
version.Scope, currentID, version.ID)
}
// superseded_at 只是展示元数据("这条已被顶替"),不改任何证据字段。
// 它跟着指针走:指针指向谁,谁就是未顶替的那一行。
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 {
return fmt.Errorf("refresh library version supersede metadata: %w", err)
}
return nil
}
// InterruptedLibraryJobs 找出"业务作业 running、但队列里已没有活跃作业"的作业:
// worker 被杀/重启后它们需要被接管,而不是被当成失败丢掉已完成的预备份。
func (s *Store) InterruptedLibraryJobs(ctx context.Context) ([]governance.LibraryJob, error) {
@@ -347,20 +406,33 @@ ORDER BY lj.created_at`)
// ResetQueueJobForResume 把中断/失败过的队列作业重新排队:attempt 必须归零,
// 否则 attempt<max_attempts 永远不成立,作业再也不会被任何 worker 领取。
//
// 但**不能清掉仍然有效的租约**:那等于把正在执行的那一代直接踢掉,而它可能已经在写目标
// (F13 的原始形态)。只有租约为空或已过期才允许重置。
func (s *Store) ResetQueueJobForResume(ctx context.Context, queueJobID string, now time.Time) error {
if _, err := s.db.Exec(ctx, `UPDATE jobs
tag, err := s.db.Exec(ctx, `UPDATE jobs
SET state='pending', attempt=0, lease_owner=NULL, lease_until=NULL, available_at=$2, updated_at=$2
WHERE id=$1 AND state IN ('running','retry','failed','pending')`, queueJobID, now); err != nil {
WHERE id=$1 AND state IN ('running','retry','failed','pending')
AND (lease_until IS NULL OR lease_until < $2)`, queueJobID, now.UTC())
if err != nil {
return fmt.Errorf("reset queue job for resume: %w", err)
}
if tag.RowsAffected() == 0 {
// 有活跃租约:另一个执行者正在跑,本次接管必须让路(调用方跳过即可)。
return ErrLibraryAttemptHeld
}
return nil
}
// ClaimLibraryJobForResume 用一次条件更新把中断作业抢过来:只有把 running 改成 pending
// 的那一个 worker 拿到 true,多个 worker 同时重启也只会有一个执行(fencing)。
//
// 条件里必须看租约:pending→pending 的无条件认领会让两个 worker 都"认领成功",
// 然后各自跑一遍同一个窗口(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')`, jobID, now)
WHERE id=$1 AND state IN ('running','pending')
AND (lease_owner='' OR lease_until IS NULL OR lease_until < $2)`, jobID, now.UTC())
if err != nil {
return false, fmt.Errorf("claim interrupted library job: %w", err)
}
@@ -409,7 +481,7 @@ func (s *Store) LibraryVersionByRef(ctx context.Context, scope string, kind gove
return governance.LibraryVersion{}, false, errors.New("library version ref requires scope, kind, job and snapshot")
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at, superseded_at
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)
@@ -453,7 +525,7 @@ func scanLibraryVersions(rows pgx.Rows, capacity int) ([]governance.LibraryVersi
var kind string
var evidence []byte
if err := rows.Scan(&item.ID, &item.Scope, &kind, &item.SnapshotID, &item.VersionLabel, &item.SourceJobID,
&evidence, &item.CreatedBy, &item.CreatedAt, &item.SupersededAt); err != nil {
&item.OperationID, &item.AttemptEpoch, &evidence, &item.CreatedBy, &item.CreatedAt, &item.SupersededAt); err != nil {
return nil, fmt.Errorf("scan library version: %w", err)
}
item.Kind = governance.LibraryVersionKind(kind)
@@ -472,7 +544,7 @@ func (s *Store) LibraryVersions(ctx context.Context, scope string, limit int) ([
return nil, errors.New("library version limit out of range")
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at, superseded_at
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)
if err != nil {
return nil, fmt.Errorf("list library versions: %w", err)
@@ -480,24 +552,27 @@ FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`
return scanLibraryVersions(rows, limit)
}
// LibraryCurrentVersion 返回这个 scope **当前生效**(未被顶替)的生产版本。
// LibraryCurrentVersion 返回这个 scope **当前生效**的事实(由指针表回答)。
//
// 为什么不能用窗口列表:生效版本每 scope 只有一行,但它可能很久以前就登记了;
// 之后写进来的预备份/封存记录会把它挤出任何"最近 N 条",于是接管/基线/同步闸口
// 会把"已生效"读成"没有生效"——症状是重写已经上线的内容。
// 这里按 (scope, kind, superseded_at IS NULL) 精确取,窗口大小与它无关。
// 三个理由必须一起满足:
//
// 唯一索引 library_versions_effective 保证每 scope 至多一行;真出现多行说明台账
// 被写坏,返回错误让调用方 fail closed,不许挑一条"看起来对"的。
// · 不能用窗口列表——生效事实可能很久以前登记,之后写进来的预备份/封存会把它挤出
// 任何"最近 N 条",接管/基线/闸口就会把"已生效"读成"没有生效"。
// · 不能靠扫 library_versions.kind='production_effective' 挑未顶替行——事件不可变,
// "谁是当前"是指针的事实,不是事件行的可变字段(F02)。
// · 指针每 scope 至多一行(主键),所以这里不需要"挑一条看起来对的"。
//
// 指针可能指向 production_effective,也可能指向 recovery_verified(按预备份恢复后
// 的当前内容身份)——调用方只能用它回答"当前是什么内容",不能假设它是一次成功发布。
func (s *Store) LibraryCurrentVersion(ctx context.Context, scope string) (governance.LibraryVersion, bool, error) {
if scope == "" {
return governance.LibraryVersion{}, false, errors.New("library current version requires scope")
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at, superseded_at
FROM library_versions
WHERE scope=$1 AND kind='production_effective' AND superseded_at IS NULL
ORDER BY created_at DESC, id DESC LIMIT 2`, scope)
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)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load current library version: %w", err)
}
@@ -506,8 +581,8 @@ ORDER BY created_at DESC, id DESC LIMIT 2`, scope)
return governance.LibraryVersion{}, false, err
}
if len(items) > 1 {
return governance.LibraryVersion{}, false, fmt.Errorf("%d 条未顶替的生效版本并存(scope=%s):拒绝挑选",
len(items), scope)
return governance.LibraryVersion{}, false, fmt.Errorf("scope=%s 的当前指针指向 %d 行事件:台账被写坏,拒绝挑选",
scope, len(items))
}
if len(items) == 1 {
return items[0], true, nil
@@ -526,7 +601,7 @@ func (s *Store) LibraryVersionOfSnapshot(ctx context.Context, scope string,
return governance.LibraryVersion{}, false, errors.New("library version snapshot requires scope, kind and snapshot")
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at, superseded_at
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)
@@ -537,11 +612,10 @@ ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), snapshotID)
if err != nil {
return governance.LibraryVersion{}, false, err
}
if len(found) > 1 {
return governance.LibraryVersion{}, false, fmt.Errorf("同一快照存在 %d 条 %s 版本记录(%s):拒绝挑选",
len(found), kind, snapshotID)
}
if len(found) == 1 {
// 同一快照被多次意图引用时会有多条事件(每次 operation 一条),这是**正常历史**,
// 不是台账损坏:按登记时间取最新一条回答"这个快照最近一次登记成什么"。
// 谁当前生效不在这里判断,那是 current 指针的事实。
if len(found) >= 1 {
return found[0], true, nil
}
return governance.LibraryVersion{}, false, nil
@@ -0,0 +1,320 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/governance"
)
// 发布执行身份:operation / attempt(epoch)的持久化。
//
// 一条铁律写在这里,别处不再重复实现:**谁写业务状态,就必须证明自己是当前代次**。
// epoch 守卫读 library_jobs.attempt_epoch/lease_owner,与 BeginLibraryAttempt 的激活
// 是同一把锁;失租代次的所有治理写入都会被拒绝,而不是靠调用方自觉。
// ErrLibraryAttemptHeld:同一作业还有未过期的租约。第二个执行者必须放弃,
// 不能"再认领一次"——那正是 F13 的双 claim。
var ErrLibraryAttemptHeld = errors.New("library job lease is held by another attempt")
// EnsureLibraryOperation 幂等创建/读取一次意图。
// 同一个 (scope,kind,operation_key) + 同一个 request_digest ⇒ 同一次意图(重放);
// 摘要不一致 ⇒ 冲突,绝不把新意图塞进旧 operation。
func (s *Store) EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error) {
if err := governance.ValidateLibraryOperation(op); err != nil {
return governance.LibraryOperation{}, false, err
}
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)
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)
if err == nil {
return op, true, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryOperation{}, false, fmt.Errorf("create library operation: %w", err)
}
existing, loadErr := s.libraryOperationByKey(ctx, op.Scope, op.Kind, op.OperationKey)
if loadErr != nil {
return governance.LibraryOperation{}, false, loadErr
}
if existing.RequestDigest != op.RequestDigest {
return existing, false, governance.ErrLibraryOperationConflict
}
return existing, false, nil
}
func (s *Store) libraryOperationByKey(ctx context.Context, scope string, kind governance.LibraryJobKind, key string) (governance.LibraryOperation, error) {
var id string
if err := s.db.QueryRow(ctx, `
SELECT id FROM library_operations WHERE scope=$1 AND kind=$2 AND operation_key=$3`,
scope, string(kind), key).Scan(&id); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryOperation{}, errors.New("library operation not found")
}
return governance.LibraryOperation{}, fmt.Errorf("load library operation: %w", err)
}
return s.LibraryOperation(ctx, id)
}
func (s *Store) LibraryOperation(ctx context.Context, id string) (governance.LibraryOperation, error) {
var op governance.LibraryOperation
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,
&op.RequestDigest, &op.OperationKey, &op.Actor, &op.CreatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryOperation{}, err
}
return governance.LibraryOperation{}, fmt.Errorf("load library operation: %w", err)
}
op.Kind = governance.LibraryJobKind(kind)
return op, nil
}
// OperationAnchors 读不可变首次锚点。
func (s *Store) OperationAnchors(ctx context.Context, operationID string) (governance.LibraryAnchors, bool, error) {
var a governance.LibraryAnchors
err := s.db.QueryRow(ctx, `
SELECT first_backup_snapshot_id, first_backup_bytes, first_backup_at, writeset_digest, writeset_rows,
target_fingerprint, anchors_at
FROM library_operations WHERE id=$1`, operationID).Scan(&a.FirstBackupSnapshotID, &a.FirstBackupBytes,
&a.FirstBackupAt, &a.WriteSetDigest, &a.WriteSetRows, &a.TargetFingerprint, &a.RecordedAt)
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryAnchors{}, false, nil
}
if err != nil {
return governance.LibraryAnchors{}, false, fmt.Errorf("load library operation anchors: %w", err)
}
return a, a.RecordedAt != nil, nil
}
// RecordOperationAnchors 只**填空**,不改已存在的锚点。
// 接管/重放会用同一份锚点重复调用;如果新值想覆盖旧值,那说明"首次"被重拍了,
// 直接报错让调用方停下来(把半写状态当新基线等于毁掉唯一可回滚的那份)。
func (s *Store) RecordOperationAnchors(ctx context.Context, operationID string, anchors governance.LibraryAnchors, now time.Time) error {
if operationID == "" {
return errors.New("record operation anchors requires an operation")
}
existing, found, err := s.OperationAnchors(ctx, operationID)
if err != nil {
return err
}
if found {
if existing.FirstBackupSnapshotID != "" && anchors.FirstBackupSnapshotID != "" &&
existing.FirstBackupSnapshotID != anchors.FirstBackupSnapshotID {
return fmt.Errorf("operation %s 的首次预备份是 %s,不能用 %s 覆盖",
operationID, existing.FirstBackupSnapshotID, anchors.FirstBackupSnapshotID)
}
if existing.WriteSetDigest != "" && anchors.WriteSetDigest != "" &&
existing.WriteSetDigest != anchors.WriteSetDigest {
return fmt.Errorf("operation %s 的首次写集合是 %s,不能用 %s 覆盖",
operationID, existing.WriteSetDigest, anchors.WriteSetDigest)
}
}
_, err = s.db.Exec(ctx, `
UPDATE library_operations SET
first_backup_snapshot_id = COALESCE(first_backup_snapshot_id, $2),
first_backup_bytes = COALESCE(first_backup_bytes, $3),
first_backup_at = COALESCE(first_backup_at, $4),
writeset_digest = COALESCE(writeset_digest, $5),
writeset_rows = COALESCE(writeset_rows, $6),
target_fingerprint = COALESCE(target_fingerprint, $7),
anchors_at = COALESCE(anchors_at, $8)
WHERE id=$1`, operationID, nullIfEmpty(anchors.FirstBackupSnapshotID), anchors.FirstBackupBytes,
anchors.FirstBackupAt, nullIfEmpty(anchors.WriteSetDigest), anchors.WriteSetRows,
nullIfEmpty(anchors.TargetFingerprint), now.UTC())
if err != nil {
return fmt.Errorf("record library operation anchors: %w", err)
}
return nil
}
// BeginLibraryAttempt 取得这个作业的执行权并激活一个新代次。
//
// 三件事必须在同一个事务里:判租约(谁能执行)→ 递增 epoch(谁是当前代次)→
// 写作业行的租约(守卫读它)。分成三步就会出现"两个 worker 都认为自己是当前代次"。
func (s *Store) BeginLibraryAttempt(ctx context.Context, jobID, owner string, lease time.Duration, now time.Time) (governance.LibraryAttempt, error) {
if jobID == "" || owner == "" {
return governance.LibraryAttempt{}, errors.New("begin library attempt requires job and owner")
}
if lease <= 0 {
lease = 2 * time.Minute
}
tx, err := s.db.Begin(ctx)
if err != nil {
return governance.LibraryAttempt{}, fmt.Errorf("begin library attempt: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
var operationID, leaseOwner, queueJobID string
var epoch int
var leaseUntil *time.Time
err = tx.QueryRow(ctx, `
SELECT operation_id, attempt_epoch, lease_owner, lease_until, queue_job_id
FROM library_jobs WHERE id=$1 FOR UPDATE`, jobID).Scan(&operationID, &epoch, &leaseOwner, &leaseUntil, &queueJobID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryAttempt{}, fmt.Errorf("library job %s not found", jobID)
}
return governance.LibraryAttempt{}, fmt.Errorf("load library job for attempt: %w", err)
}
// 同一 owner 重入是幂等(重试/队列重投);别人持有未过期租约就必须让路。
if leaseOwner != "" && leaseOwner != owner && leaseUntil != nil && leaseUntil.After(now.UTC()) {
return governance.LibraryAttempt{}, ErrLibraryAttemptHeld
}
nextEpoch := epoch + 1
if nextEpoch < 1 {
nextEpoch = 1
}
// 代次必须按 operation 单调递增,而不是按作业行:同一个意图的重试/接管会**新开作业行**,
// 若按作业行各自从 1 数起,旧代次(1)与新代次(1)就分不出先后,fencing 失效。
if operationID != "" {
var maxEpoch *int
if err := tx.QueryRow(ctx, `SELECT MAX(epoch) FROM library_attempts WHERE operation_id=$1`,
operationID).Scan(&maxEpoch); err != nil {
return governance.LibraryAttempt{}, fmt.Errorf("load library attempt epoch: %w", err)
}
next := 1
if maxEpoch != nil && *maxEpoch >= next {
next = *maxEpoch + 1
}
if nextEpoch < next {
nextEpoch = next
}
}
attempt := governance.LibraryAttempt{
OperationID: operationID, Epoch: nextEpoch, JobID: jobID, QueueJobID: queueJobID,
Owner: owner, State: governance.LibraryAttemptRunning, StartedAt: now.UTC(),
}
until := now.Add(lease).UTC()
attempt.LeaseUntil = &until
if operationID != "" {
// 一个代次只对应一个作业行:重复 Begin(同 job)不再新增谱系。
if _, err := tx.Exec(ctx, `
INSERT INTO library_attempts (operation_id, epoch, job_id, queue_job_id, owner, state, started_at, heartbeat_at, lease_until)
VALUES ($1,$2,$3,$4,$5,'running',$6,$6,$7)
ON CONFLICT (job_id) DO UPDATE SET
owner=EXCLUDED.owner, state='running', lease_until=EXCLUDED.lease_until, heartbeat_at=EXCLUDED.heartbeat_at`,
operationID, nextEpoch, jobID, queueJobID, owner, now.UTC(), until); err != nil {
return governance.LibraryAttempt{}, fmt.Errorf("record library attempt: %w", err)
}
}
if _, err := tx.Exec(ctx, `
UPDATE library_jobs SET attempt_epoch=$2, lease_owner=$3, lease_until=$4, updated_at=$5 WHERE id=$1`,
jobID, nextEpoch, owner, until, now.UTC()); err != nil {
return governance.LibraryAttempt{}, fmt.Errorf("activate library attempt: %w", err)
}
if err := tx.Commit(ctx); err != nil {
return governance.LibraryAttempt{}, fmt.Errorf("commit library attempt: %w", err)
}
return attempt, nil
}
// FinishLibraryAttempt 落本次代次的终态。旧代次不能结束别人的代次:
// 只有 (operation, epoch) 与 owner 都匹配才写。
func (s *Store) FinishLibraryAttempt(ctx context.Context, attempt governance.LibraryAttempt, state governance.LibraryAttemptState, outcome string, now time.Time) error {
if attempt.OperationID == "" {
return nil // 旧作业没有 operation:没有代次可结
}
tag, err := s.db.Exec(ctx, `
UPDATE library_attempts SET state=$4, finished_at=$5, outcome=$6, lease_until=NULL
WHERE operation_id=$1 AND epoch=$2 AND owner=$3`,
attempt.OperationID, attempt.Epoch, attempt.Owner, string(state), now.UTC(), outcome)
if err != nil {
return fmt.Errorf("finish library attempt: %w", err)
}
if tag.RowsAffected() != 1 {
return governance.ErrLibraryEpochStale
}
return nil
}
// LibraryAttempts 返回一次 operation 的执行谱系(按代次升序):接管/恢复排查读它。
func (s *Store) LibraryAttempts(ctx context.Context, operationID string) ([]governance.LibraryAttempt, error) {
rows, err := s.db.Query(ctx, `
SELECT operation_id, epoch, job_id, queue_job_id, owner, state, started_at, heartbeat_at, lease_until, finished_at, outcome
FROM library_attempts WHERE operation_id=$1 ORDER BY epoch`, operationID)
if err != nil {
return nil, fmt.Errorf("list library attempts: %w", err)
}
defer rows.Close()
items := make([]governance.LibraryAttempt, 0, 4)
for rows.Next() {
var item governance.LibraryAttempt
var state string
if err := rows.Scan(&item.OperationID, &item.Epoch, &item.JobID, &item.QueueJobID, &item.Owner, &state,
&item.StartedAt, &item.HeartbeatAt, &item.LeaseUntil, &item.FinishedAt, &item.Outcome); err != nil {
return nil, fmt.Errorf("scan library attempt: %w", err)
}
item.State = governance.LibraryAttemptState(state)
items = append(items, item)
}
return items, rows.Err()
}
// LatestLibraryAttempt 取当前代次(无则 false)。
func (s *Store) LatestLibraryAttempt(ctx context.Context, operationID string) (governance.LibraryAttempt, bool, error) {
items, err := s.LibraryAttempts(ctx, operationID)
if err != nil || len(items) == 0 {
return governance.LibraryAttempt{}, false, err
}
return items[len(items)-1], true, nil
}
// RenewLibraryAttempt 续租:失租(0 行)即返回 ErrLibraryEpochStale,调用方必须停手。
func (s *Store) RenewLibraryAttempt(ctx context.Context, attempt governance.LibraryAttempt, lease time.Duration, now time.Time) error {
until := now.Add(lease).UTC()
tag, err := s.db.Exec(ctx, `
UPDATE library_attempts SET heartbeat_at=$4, lease_until=$5
WHERE operation_id=$1 AND epoch=$2 AND owner=$3 AND state='running'`,
attempt.OperationID, attempt.Epoch, attempt.Owner, now.UTC(), until)
if err != nil {
return fmt.Errorf("renew library attempt: %w", err)
}
if tag.RowsAffected() != 1 {
return governance.ErrLibraryEpochStale
}
if _, err := s.db.Exec(ctx, `
UPDATE library_jobs SET lease_until=$4 WHERE id=$1 AND attempt_epoch=$2 AND lease_owner=$3`,
attempt.JobID, attempt.Epoch, attempt.Owner, until); err != nil {
return fmt.Errorf("renew library job lease: %w", err)
}
return nil
}
// guardLibraryJobEpoch 在事务内核"这次写入来自当前代次"。守卫失败一律返回
// ErrLibraryEpochStale,调用方不许把它当成"重试一下就好"。
func guardLibraryJobEpoch(ctx context.Context, tx pgx.Tx, jobID string, epoch int, owner string) error {
var currentEpoch int
var currentOwner string
err := tx.QueryRow(ctx, `
SELECT attempt_epoch, lease_owner FROM library_jobs WHERE id=$1 FOR UPDATE`, jobID).Scan(&currentEpoch, &currentOwner)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("library job %s not found", jobID)
}
return fmt.Errorf("load library job for epoch guard: %w", err)
}
if currentEpoch != epoch || (owner != "" && currentOwner != owner) {
return fmt.Errorf("%w(作业 %s:本代次 %d/%s,当前 %d/%s)", governance.ErrLibraryEpochStale,
jobID, epoch, owner, currentEpoch, currentOwner)
}
return nil
}
func nullIfEmpty(value string) any {
if value == "" {
return nil
}
return value
}
@@ -0,0 +1,142 @@
package postgres
import (
"context"
"fmt"
)
// LibraryProtection 回答"这些快照现在为什么不能删"。
//
// 关键点(F10):保护依据必须来自**全量依赖**,不能来自"最近 100 个版本 / 20 个作业"的
// 展示窗口。历史上一份需要恢复的旧预备份、一个 failed 但仍持有维护锁的作业,都完全
// 可能掉出任何窗口——按窗口判断就会把它显示成"可删除候选"。
//
// 任何一条查询失败都返回错误:调用方必须显示"保护未知"并拒绝生成可删候选,
// 不允许因为"读不到"就当成"没被引用"。
func (s *Store) LibraryProtection(ctx context.Context) (map[string][]string, error) {
protected := map[string][]string{}
add := func(snapshotID, reason string) {
if snapshotID == "" {
return
}
for _, existing := range protected[snapshotID] {
if existing == reason {
return
}
}
protected[snapshotID] = append(protected[snapshotID], reason)
}
// 1) 当前生效事实(指针):每个 scope 一条,与历史长度无关。
rows, err := s.db.Query(ctx, `SELECT snapshot_id FROM library_current_versions`)
if err != nil {
return nil, fmt.Errorf("读取当前生效版本失败:%w", err)
}
for rows.Next() {
var snapshot string
if err := rows.Scan(&snapshot); err != nil {
rows.Close()
return nil, fmt.Errorf("扫描当前生效版本失败:%w", err)
}
add(snapshot, "生产生效版本")
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("读取当前生效版本失败:%w", err)
}
// 2) 全部生产预备份:任何一份都是某个窗口唯一的可回滚基线,没有窗口限制。
rows, err = s.db.Query(ctx, `SELECT DISTINCT snapshot_id FROM library_versions WHERE kind='production_prebackup'`)
if err != nil {
return nil, fmt.Errorf("读取生产预备份失败:%w", err)
}
for rows.Next() {
var snapshot string
if err := rows.Scan(&snapshot); err != nil {
rows.Close()
return nil, fmt.Errorf("扫描生产预备份失败:%w", err)
}
add(snapshot, "生产预备份")
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("读取生产预备份失败:%w", err)
}
// 3) 每个 scope 最近一次测试封存(最新可发布版本),精确取而不是窗口里挑。
rows, err = s.db.Query(ctx, `
SELECT DISTINCT ON (scope) scope, snapshot_id FROM library_versions
WHERE kind='test_sealed' ORDER BY scope, created_at DESC`)
if err != nil {
return nil, fmt.Errorf("读取最近测试封存失败:%w", err)
}
for rows.Next() {
var scope, snapshot string
if err := rows.Scan(&scope, &snapshot); err != nil {
rows.Close()
return nil, fmt.Errorf("扫描最近测试封存失败:%w", err)
}
add(snapshot, "最近测试封存("+scope+")")
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("读取最近测试封存失败:%w", err)
}
// 4) 未释放的维护窗口:窗口持有者的预备份与目标快照都要留住——
// 否则"删除候选"会把正在等待恢复的那一份清掉。
var owners []string
rows, err = s.db.Query(ctx, `
SELECT owner_job_id FROM library_maintenance WHERE released_at IS NULL
UNION
SELECT owner_job_id FROM library_instance_maintenance WHERE released_at IS NULL`)
if err != nil {
return nil, fmt.Errorf("读取未释放维护窗口失败:%w", err)
}
for rows.Next() {
var owner string
if err := rows.Scan(&owner); err != nil {
rows.Close()
return nil, fmt.Errorf("扫描未释放维护窗口失败:%w", err)
}
owners = append(owners, owner)
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("读取未释放维护窗口失败:%w", err)
}
// 5) 在飞作业与"失败但仍持有窗口"的作业。
rows, err = s.db.Query(ctx, `
SELECT coalesce(snapshot_id,''), coalesce(target_snapshot_id,'')
FROM library_jobs WHERE state IN ('pending','running')`)
if err != nil {
return nil, fmt.Errorf("读取在飞作业失败:%w", err)
}
for rows.Next() {
var snapshot, target string
if err := rows.Scan(&snapshot, &target); err != nil {
rows.Close()
return nil, fmt.Errorf("扫描在飞作业失败:%w", err)
}
add(snapshot, "在飞作业引用")
add(target, "在飞作业引用")
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("读取在飞作业失败:%w", err)
}
for _, owner := range owners {
var snapshot, target string
err := s.db.QueryRow(ctx, `
SELECT coalesce(snapshot_id,''), coalesce(target_snapshot_id,'') FROM library_jobs WHERE id=$1`, owner).
Scan(&snapshot, &target)
if err != nil {
return nil, fmt.Errorf("读取维护窗口持有作业 %s 失败:%w", owner, err)
}
add(snapshot, "未释放维护窗口的预备份")
add(target, "未释放维护窗口的目标快照")
}
return protected, nil
}
@@ -0,0 +1,212 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/governance"
)
// 写入栅栏:所有"业务状态 / 维护锁"的写都必须证明调用方仍是当前执行代次。
//
// 为什么单独放一份:F13 的根因不是某一条 SQL 写错了,而是"同一个 job_id 被两个代次
// 同时使用"这件事本身没有被表达出来。只要有一处更新不带代次条件,失租的旧执行就能
// 用同一个 job_id 写业务终态、释放别人刚拿到的维护锁。所以这里给每个可变入口配一个
// 带守卫的版本,worker 只准走这些版本;不带守卫的旧方法留给 API(它代表"当前意图",
// 没有执行代次)。
const epochFence = `EXISTS (SELECT 1 FROM library_jobs j WHERE j.id=$1 AND j.attempt_epoch=$%d AND j.lease_owner=$%d)`
// AdvanceLibraryJobGuarded 只在调用方仍是该作业当前代次时写业务状态。
func (s *Store) AdvanceLibraryJobGuarded(ctx context.Context, attempt governance.LibraryAttempt,
state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error {
finished := any(nil)
if state == governance.LibraryJobSucceeded || state == governance.LibraryJobFailed || state == governance.LibraryJobCancelled {
finished = now.UTC()
}
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,
updated_at=$8,
finished_at=COALESCE($9, finished_at)
WHERE id=$1 AND attempt_epoch=$10 AND lease_owner=$11`,
attempt.JobID, string(state), stage, message, recovery, snapshotID, targetSnapshotID, now.UTC(), finished,
attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("advance library job (guarded): %w", err)
}
if tag.RowsAffected() != 1 {
return s.fencedWriteError(ctx, attempt, "advance library job")
}
return nil
}
// UpdateLibraryStageGuarded 是阶段进度的守卫版:失租代次不能再写"我这一阶段成功了"。
func (s *Store) UpdateLibraryStageGuarded(ctx context.Context, attempt governance.LibraryAttempt,
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,
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,
updated_at = $9
WHERE job_id=$1 AND stage=$2
AND EXISTS (SELECT 1 FROM library_jobs j WHERE j.id=$1 AND j.attempt_epoch=$10 AND j.lease_owner=$11)`,
attempt.JobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC(),
attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("update library stage (guarded): %w", err)
}
if tag.RowsAffected() != 1 {
return s.fencedWriteError(ctx, attempt, "update library stage")
}
return nil
}
// ReleaseLibraryMaintenanceGuarded 释放 scope 维护锁,但只认当前代次。
func (s *Store) ReleaseLibraryMaintenanceGuarded(ctx context.Context, scope, ownerJobID string,
attempt governance.LibraryAttempt, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_maintenance SET state='released', released_at=$3, updated_at=$3
WHERE scope=$1 AND owner_job_id=$2 AND released_at IS NULL
AND `+fmt.Sprintf(epochFence, 4, 5), scope, ownerJobID, now.UTC(), attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("release library maintenance (guarded): %w", err)
}
if tag.RowsAffected() == 0 {
if s.releasedByThisJob(ctx, "library_maintenance", "scope", scope, ownerJobID) {
return ErrMaintenanceReleased
}
return s.fencedWriteError(ctx, attempt, "release library maintenance")
}
return nil
}
// ReleaseInstanceMaintenanceGuarded 释放实例维护锁,但只认当前代次。
func (s *Store) ReleaseInstanceMaintenanceGuarded(ctx context.Context, instance, ownerJobID string,
attempt governance.LibraryAttempt, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_instance_maintenance SET state='released', released_at=$3, updated_at=$3
WHERE instance=$1 AND owner_job_id=$2 AND released_at IS NULL
AND `+fmt.Sprintf(epochFence, 4, 5), instance, ownerJobID, now.UTC(), attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("release instance maintenance (guarded): %w", err)
}
if tag.RowsAffected() == 0 {
if s.releasedByThisJob(ctx, "library_instance_maintenance", "instance", instance, ownerJobID) {
return ErrMaintenanceReleased
}
return s.fencedWriteError(ctx, attempt, "release instance maintenance")
}
return nil
}
// UpdateLibraryMaintenanceStateGuarded / UpdateInstanceMaintenanceStateGuarded 同理:
// 失租代次不能把窗口改成 needs_restore / verified 去影响当前代次的判断。
func (s *Store) UpdateLibraryMaintenanceStateGuarded(ctx context.Context, scope, ownerJobID, state, note string,
attempt governance.LibraryAttempt, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_maintenance SET state=$3, note=$4, updated_at=$5
WHERE scope=$1 AND owner_job_id=$2 AND released_at IS NULL
AND `+fmt.Sprintf(epochFence, 6, 7), scope, ownerJobID, state, note, now.UTC(), attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("update library maintenance (guarded): %w", err)
}
if tag.RowsAffected() == 0 {
if s.releasedByThisJob(ctx, "library_maintenance", "scope", scope, ownerJobID) {
return ErrMaintenanceReleased
}
return s.fencedWriteError(ctx, attempt, "update library maintenance")
}
return nil
}
func (s *Store) UpdateInstanceMaintenanceStateGuarded(ctx context.Context, instance, ownerJobID, state, note string,
attempt governance.LibraryAttempt, now time.Time) error {
tag, err := s.db.Exec(ctx, `
UPDATE library_instance_maintenance SET state=$3, note=$4, updated_at=$5
WHERE instance=$1 AND owner_job_id=$2 AND released_at IS NULL
AND `+fmt.Sprintf(epochFence, 6, 7), instance, ownerJobID, state, note, now.UTC(), attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("update instance maintenance (guarded): %w", err)
}
if tag.RowsAffected() == 0 {
if s.releasedByThisJob(ctx, "library_instance_maintenance", "instance", instance, ownerJobID) {
return ErrMaintenanceReleased
}
return s.fencedWriteError(ctx, attempt, "update instance maintenance")
}
return nil
}
// fencedWriteError 区分"作业不存在"与"代次已过期":两者都要停下,但文案不能误导运维。
func (s *Store) fencedWriteError(ctx context.Context, attempt governance.LibraryAttempt, action string) error {
var epoch int
var owner string
err := s.db.QueryRow(ctx, `SELECT attempt_epoch, lease_owner FROM library_jobs WHERE id=$1`,
attempt.JobID).Scan(&epoch, &owner)
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s:作业 %s 不存在", action, attempt.JobID)
}
if err != nil {
return fmt.Errorf("%s:读不到作业代次:%w", action, err)
}
return fmt.Errorf("%w(%s:本代次 %d/%s,当前 %d/%s)", governance.ErrLibraryEpochStale,
action, attempt.Epoch, attempt.Owner, epoch, owner)
}
func (s *Store) SetInstanceMaintenanceIngressGuarded(ctx context.Context, instance, ownerJobID, state, note string,
attempt governance.LibraryAttempt, now time.Time) error {
if state != "closed" && state != "open" {
return errors.New("invalid ingress state")
}
tag, err := s.db.Exec(ctx, `
UPDATE library_instance_maintenance SET ingress_state=$3, note=$4, updated_at=$5
WHERE instance=$1 AND owner_job_id=$2 AND released_at IS NULL
AND `+fmt.Sprintf(epochFence, 6, 7), instance, ownerJobID, state, note, now.UTC(), attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("update instance maintenance ingress (guarded): %w", err)
}
if tag.RowsAffected() == 0 {
if s.releasedByThisJob(ctx, "library_instance_maintenance", "instance", instance, ownerJobID) {
return ErrMaintenanceReleased
}
return s.fencedWriteError(ctx, attempt, "update instance maintenance ingress")
}
return nil
}
// SetLibraryMaintenanceIngressGuarded 记录入口状态也需要代次守卫:
// "入口已关"是隔离证据,失租代次写它等于伪造证据。
func (s *Store) SetLibraryMaintenanceIngressGuarded(ctx context.Context, scope, ownerJobID, state, note string,
attempt governance.LibraryAttempt, now time.Time) error {
if state != "closed" && state != "open" {
return errors.New("invalid ingress state")
}
tag, err := s.db.Exec(ctx, `
UPDATE library_maintenance SET ingress_state=$3, note=$4, updated_at=$5
WHERE scope=$1 AND owner_job_id=$2 AND released_at IS NULL
AND `+fmt.Sprintf(epochFence, 6, 7), scope, ownerJobID, state, note, now.UTC(), attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("update library maintenance ingress (guarded): %w", err)
}
if tag.RowsAffected() == 0 {
if s.releasedByThisJob(ctx, "library_maintenance", "scope", scope, ownerJobID) {
return ErrMaintenanceReleased
}
return s.fencedWriteError(ctx, attempt, "update library maintenance ingress")
}
return nil
}
@@ -0,0 +1,29 @@
-- 回滚:只撤掉 identity/指针这一层。**不删任何版本事件、作业或证据**(历史不可回填)。
-- 回滚后 library_versions 仍是完整台账;current 重新由 superseded_at 表达。
DROP TABLE IF EXISTS library_current_versions;
UPDATE library_versions SET superseded_at = NULL
WHERE id IN (
SELECT id FROM (
SELECT id, row_number() OVER (PARTITION BY scope ORDER BY created_at DESC, id DESC) AS rn
FROM library_versions
WHERE kind = 'production_effective'
) ranked WHERE rn = 1
);
ALTER TABLE library_versions DROP CONSTRAINT IF EXISTS library_versions_kind_check;
DELETE FROM library_versions WHERE kind = 'recovery_verified';
ALTER TABLE library_versions ADD CONSTRAINT library_versions_kind_check
CHECK (kind IN ('test_sealed','production_effective','production_prebackup'));
ALTER TABLE library_versions DROP COLUMN IF EXISTS attempt_epoch;
ALTER TABLE library_versions DROP COLUMN IF EXISTS operation_id;
CREATE UNIQUE INDEX IF NOT EXISTS library_versions_effective ON library_versions(scope)
WHERE kind = 'production_effective' AND superseded_at IS NULL;
ALTER TABLE library_jobs DROP COLUMN IF EXISTS lease_until;
ALTER TABLE library_jobs DROP COLUMN IF EXISTS lease_owner;
ALTER TABLE library_jobs DROP COLUMN IF EXISTS attempt_epoch;
ALTER TABLE library_jobs DROP COLUMN IF EXISTS operation_id;
DROP TABLE IF EXISTS library_attempts;
DROP TABLE IF EXISTS library_operations;
@@ -0,0 +1,108 @@
-- 发布执行身份:operation(一次意图)/ attempt(执行代次)/ 不可变版本事件 / current 指针。
--
-- 为什么现在加、且只加在治理库:
-- · 旧实现把"用户的一次意图"等同于"某个快照的终身幂等键",于是 A→B→A 的第三次请求
-- 拿到的是第一次的历史成功,什么也不做(F01);版本行主键只由 (kind,scope,快照) 决定,
-- 第二次登记直接覆盖 source_job_id/evidence/created_at(F02/F09)。
-- · 接管没有代次:两个 worker 可以把同一 pending 作业都认领走,失租的旧执行还能继续
-- 写业务状态、释放别人的维护锁(F13)。
--
-- 这里不修改 WeKnora 的 Schema/源码/镜像,也不声称数据库 CAS 能拦住已经发出去的
-- S3/ES 请求:跨系统原子性不存在,物理执行域隔离另由部署准入负责。
-- ── operation:一次明确意图(不可变)────────────────────────────────────
CREATE TABLE IF NOT EXISTS library_operations (
id VARCHAR(64) PRIMARY KEY,
scope VARCHAR(16) NOT NULL CHECK (scope IN ('internal','external')),
kind VARCHAR(16) NOT NULL,
target_snapshot_id VARCHAR(64) NOT NULL DEFAULT '',
request_digest VARCHAR(64) NOT NULL,
-- 客户端可重放的意图键:同一个键 + 同一个摘要 ⇒ 同一次意图(重放幂等);
-- 换一个键 ⇒ 新意图,即使目标快照与历史成功完全相同。
operation_key VARCHAR(255) NOT NULL,
actor VARCHAR(128) NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL,
-- 不可变首次锚点:由第一次成功拍下预备份/写集合的执行写入,之后只读。
first_backup_snapshot_id VARCHAR(64),
first_backup_bytes BIGINT,
first_backup_at TIMESTAMPTZ,
writeset_digest VARCHAR(64),
writeset_rows BIGINT,
target_fingerprint VARCHAR(128),
anchors_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX IF NOT EXISTS library_operations_key
ON library_operations(scope, kind, operation_key);
-- ── attempt:执行代次(epoch),同一 operation 只允许一个活跃代次 ─────────
CREATE TABLE IF NOT EXISTS library_attempts (
operation_id VARCHAR(64) NOT NULL REFERENCES library_operations(id),
epoch INTEGER NOT NULL CHECK (epoch >= 1),
job_id VARCHAR(64) NOT NULL,
queue_job_id VARCHAR(64) NOT NULL DEFAULT '',
owner VARCHAR(128) NOT NULL DEFAULT '',
state VARCHAR(16) NOT NULL CHECK (state IN ('claimed','running','completed','failed','abandoned')),
started_at TIMESTAMPTZ NOT NULL,
heartbeat_at TIMESTAMPTZ,
lease_until TIMESTAMPTZ,
finished_at TIMESTAMPTZ,
outcome TEXT NOT NULL DEFAULT '',
PRIMARY KEY (operation_id, epoch)
);
-- 一个作业行只对应一个代次:重复 Begin 不新增谱系。
CREATE UNIQUE INDEX IF NOT EXISTS library_attempts_job ON library_attempts(job_id);
-- 同一 operation 同时只能有一个活跃代次:第二个 resumer 的失败不能释放另一个代次的锁。
CREATE UNIQUE INDEX IF NOT EXISTS library_attempts_active
ON library_attempts(operation_id) WHERE state IN ('claimed','running');
-- ── 作业行继承 operation/代次与租约(写入守卫读这里)─────────────────────
ALTER TABLE library_jobs ADD COLUMN IF NOT EXISTS operation_id VARCHAR(64) NOT NULL DEFAULT '';
ALTER TABLE library_jobs ADD COLUMN IF NOT EXISTS attempt_epoch INTEGER NOT NULL DEFAULT 0;
ALTER TABLE library_jobs ADD COLUMN IF NOT EXISTS lease_owner VARCHAR(128) NOT NULL DEFAULT '';
ALTER TABLE library_jobs ADD COLUMN IF NOT EXISTS lease_until TIMESTAMPTZ;
-- ── 版本行:不可变事件 + 执行身份;允许 recovery_verified ────────────────
ALTER TABLE library_versions ADD COLUMN IF NOT EXISTS operation_id VARCHAR(64) NOT NULL DEFAULT '';
ALTER TABLE library_versions ADD COLUMN IF NOT EXISTS attempt_epoch INTEGER NOT NULL DEFAULT 0;
ALTER TABLE library_versions DROP CONSTRAINT IF EXISTS library_versions_kind_check;
ALTER TABLE library_versions ADD CONSTRAINT library_versions_kind_check
CHECK (kind IN ('test_sealed','production_effective','production_prebackup','recovery_verified'));
-- 旧唯一索引禁止同一 scope 出现第二条未顶替的生效行——那是"用 UPDATE 顶替"的实现细节。
-- 现在"谁是当前"由指针表表达,事件本身不再被改写;索引留着反而会逼写入方去 UPDATE 历史。
DROP INDEX IF EXISTS library_versions_effective;
-- ── current 指针:单调次序 + 条件更新,不覆盖事件 ───────────────────────
CREATE TABLE IF NOT EXISTS library_current_versions (
scope VARCHAR(16) PRIMARY KEY CHECK (scope IN ('internal','external')),
version_id VARCHAR(64) NOT NULL REFERENCES library_versions(id),
snapshot_id VARCHAR(64) NOT NULL,
operation_id VARCHAR(64) NOT NULL DEFAULT '',
attempt_epoch INTEGER NOT NULL DEFAULT 0,
-- 排序键 = (事件登记时间|operation|epoch),见 governance.CurrentOrderKey。
-- 只有更大的键才能推进指针:更早的事实不能把当前状态拉回历史。
order_key VARCHAR(255) NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
-- 回填:只搬运"已登记且未被顶替"的既有生效版本(不新造版本行、不改旧证据)。
INSERT INTO library_current_versions(scope, version_id, snapshot_id, operation_id, attempt_epoch, order_key, updated_at)
SELECT v.scope, v.id, v.snapshot_id, v.operation_id, v.attempt_epoch,
lpad((extract(epoch from v.created_at) * 1000000)::bigint::text, 20, '0') || '|' || v.operation_id || '|' || lpad(v.attempt_epoch::text, 9, '0'),
v.created_at
FROM library_versions v
WHERE v.kind = 'production_effective' AND v.superseded_at IS NULL
ON CONFLICT (scope) DO NOTHING;
-- 历史行不再靠 superseded_at 表达"当前":把指针指向的那一行标成未顶替,其余保持原值。
-- 这里只补元数据、不改任何证据字段(source_job_id/evidence/created_at 原样)。
UPDATE library_versions v
SET superseded_at = NULL
WHERE v.id IN (SELECT version_id FROM library_current_versions)
AND v.superseded_at IS NOT NULL;
UPDATE library_versions v
SET superseded_at = coalesce(v.superseded_at, now())
WHERE v.kind = 'production_effective'
AND v.superseded_at IS NULL
AND NOT EXISTS (SELECT 1 FROM library_current_versions c WHERE c.version_id = v.id);
+20 -12
View File
@@ -11,51 +11,59 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 75 {
t.Fatalf("migration count = %d, want 75", len(migrations))
if len(migrations) != 76 {
t.Fatalf("migration count = %d, want 76", len(migrations))
}
// 76 是发布执行身份:operation / attempt(epoch) / 不可变事件 + current 指针。
// 它只动治理库,不碰 WeKnora Schema。
if identity := migrations[len(migrations)-1]; 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)-1]; baseline.Version != 75 ||
if baseline := migrations[len(migrations)-2]; 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)-2]; executor.Version != 74 ||
if executor := migrations[len(migrations)-3]; executor.Version != 74 ||
!strings.Contains(executor.UpSQL, "library_executor_status") {
t.Fatalf("migration 74 = %#v", executor)
}
// 73 记录死信精确解除:保留上游行,只绑定指纹、重放引用与观测摘要。
if release := migrations[len(migrations)-3]; release.Version != 73 ||
if release := migrations[len(migrations)-4]; 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)-4]; instance.Version != 72 ||
if instance := migrations[len(migrations)-5]; instance.Version != 72 ||
!strings.Contains(instance.UpSQL, "library_instance_maintenance") {
t.Fatalf("migration 72 = %#v", instance)
}
// 71 让维护记录能区分实例级维护与仅治理库互斥。
if level := migrations[len(migrations)-5]; level.Version != 71 ||
if level := migrations[len(migrations)-6]; 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)-6]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
if maint := migrations[len(migrations)-7]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
t.Fatalf("migration 70 = %#v", maint)
}
if tail := migrations[len(migrations)-7]; tail.Version != 69 ||
if tail := migrations[len(migrations)-8]; tail.Version != 69 ||
!strings.Contains(tail.UpSQL, "library_jobs_write_target") {
t.Fatalf("migration 69 = %#v", tail)
}
if restore := migrations[len(migrations)-8]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
if restore := migrations[len(migrations)-9]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
t.Fatalf("migration 68 = %#v", restore)
}
if last := migrations[len(migrations)-9]; last.Version != 67 ||
if last := migrations[len(migrations)-10]; 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)-10]; flow.Version != 66 ||
if flow := migrations[len(migrations)-11]; flow.Version != 66 ||
!strings.Contains(flow.UpSQL, "CREATE TABLE library_versions") ||
!strings.Contains(flow.UpSQL, "library_jobs_active") {
t.Fatalf("migration 66 = %#v", flow)