fix(library): 守卫按行取作业身份、同作业多代次、原作业续作与执行域准入
build / build (push) Successful in 1m27s

R1 维护/发布守卫硬编码 j.id=$1:维护类入口的 $1 是 scope/instance,作业号在 $2,
导致 update/release/ingress 六个入口正常路径全部匹配不到作业。改为按被更新行自己的
owner_job_id 生成条件,并同时要求该代次在 library_attempts 里仍活跃。

R2 认领只改 jobs.attempt_epoch 不改 attempts.epoch,第二次接管即错位;唯一索引
(job_id) 与"每次接管新 attempt 且历史不可变"矛盾。改为同作业多代次:锁作业行与
operation 行、同 owner 幂等续租、活跃未过期者让路、过期/本作业旧代次标 abandoned、
新代次 epoch=max+1,并清同 operation 其它作业行租约。迟到 write/renew/finish 一律
ErrLibraryEpochStale(finish 补了"只能在活跃态进来一次")。

R3 续作不再新建 -resume 作业:PrepareLibraryJobResume 让原业务作业回 pending 并显式
结束上一代,维护窗口/journal/预备份/写集合仍按原作业 id 归属,代次由 worker 起手递增。

R4 执行域准入改为注册 handler 前读事实:目标实况(KB/租户/schema/索引)、旧 release
路由绑定的 KB、未释放维护窗口持有者;未知或重叠即拒绝执行(不做维护动作、不停既有服务)。

同时自纠 5 项设计偏离:current 次序键取意图创建时间(旧意图迟到事实被拒)、首次锚点
改事务 FOR UPDATE + 回读且 NULL≠0、版本事件冲突只做加法且 xmax=0 才算新事实、
恢复作为新 kind=recover 意图推进 current、隔离测试加测试库护栏并清理残留 schema。

测试:真实 PG(kg-pgtest-writeset,一用例一 schema)新增 8 条集成用例覆盖上述正负例;
go test ./... 全绿(50 包)、go vet/build rc=0、web tsc + vitest 485 通过、make verify 16 项通过。
This commit is contained in:
姚章浩
2026-10-30 17:20:40 +08:00
parent afe9affc2a
commit a7d643635a
26 changed files with 1551 additions and 215 deletions
@@ -11,15 +11,40 @@ import (
"knowledge-governance/internal/governance"
)
// 写入栅栏:所有"业务状态 / 维护锁"的写都必须证明调用方仍是当前执行代次。
// 写入栅栏:所有"业务状态 / 维护锁"的写都必须证明调用方仍是**当前活跃代次**。
//
// 为什么单独放一份:F13 的根因不是某一条 SQL 写错了,而是"同一个 job_id 被两个代次
// 同时使用"这件事本身没有被表达出来。只要有一处更新不带代次条件,失租的旧执行就能
// 用同一个 job_id 写业务终态、释放别人刚拿到的维护锁。所以这里给每个可变入口配一个
// 带守卫的版本,worker 只准走这些版本;不带守卫的旧方法留给 API(它代表"当前意图",
// 没有执行代次)。
// 两条条件缺一不可:
// 1. 作业行上的 (attempt_epoch, lease_owner) 就是这次的 (epoch, owner);
// 2. library_attempts 里那一代次仍是 active(claimed/running)。
//
// 为什么第 2 条不能省(R2):接管/续跑会激活新一代次,而**旧作业行上的 epoch/owner
// 字段仍原样保留**。只比较旧作业行,旧执行器的守卫会继续通过——它就能继续写业务状态、
// 释放别人刚拿到的锁。把"该代次仍活跃"作为条件后,旧代次被结束的那一刻起,
// 它的所有守卫写都会失败。
//
// 参数契约(R1):作业 id 取自**被更新行自己的列**(`library_maintenance.owner_job_id`
// 等),不写死 `$1`——维护类更新的 `$1` 是 scope/instance,写死 `$1` 会让守卫永远匹配
// 不到作业,正常写与释放全部失败。列表达式由调用方传入,序号漂移不可能再发生。
const epochFence = `EXISTS (SELECT 1 FROM library_jobs j WHERE j.id=$1 AND j.attempt_epoch=$%d AND j.lease_owner=$%d)`
// libraryFence 生成"调用方仍是当前活跃代次"的谓词。jobIDExpr 是**列表达式**。
func libraryFence(jobIDExpr string, epochParam, ownerParam int) string {
return fmt.Sprintf(`EXISTS (
SELECT 1 FROM library_jobs j
WHERE j.id = %s
AND j.attempt_epoch = $%d
AND j.lease_owner = $%d
AND (
j.operation_id = ''
OR EXISTS (
SELECT 1 FROM library_attempts a
WHERE a.operation_id = j.operation_id
AND a.epoch = j.attempt_epoch
AND a.owner = j.lease_owner
AND a.state IN ('claimed','running')
)
)
)`, jobIDExpr, epochParam, ownerParam)
}
// AdvanceLibraryJobGuarded 只在调用方仍是该作业当前代次时写业务状态。
func (s *Store) AdvanceLibraryJobGuarded(ctx context.Context, attempt governance.LibraryAttempt,
@@ -38,7 +63,7 @@ UPDATE library_jobs SET
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`,
WHERE id=$1 AND `+libraryFence("$1", 10, 11),
attempt.JobID, string(state), stage, message, recovery, snapshotID, targetSnapshotID, now.UTC(), finished,
attempt.Epoch, attempt.Owner)
if err != nil {
@@ -62,8 +87,7 @@ UPDATE library_job_stages SET
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)`,
WHERE job_id=$1 AND stage=$2 AND `+libraryFence("$1", 10, 11),
attempt.JobID, stage, state, total, completed, bytesTotal, bytesDone, detail, now.UTC(),
attempt.Epoch, attempt.Owner)
if err != nil {
@@ -81,7 +105,8 @@ func (s *Store) ReleaseLibraryMaintenanceGuarded(ctx context.Context, scope, own
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)
AND `+libraryFence("library_maintenance.owner_job_id", 4, 5), scope, ownerJobID, now.UTC(),
attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("release library maintenance (guarded): %w", err)
}
@@ -100,7 +125,8 @@ func (s *Store) ReleaseInstanceMaintenanceGuarded(ctx context.Context, instance,
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)
AND `+libraryFence("library_instance_maintenance.owner_job_id", 4, 5), instance, ownerJobID, now.UTC(),
attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("release instance maintenance (guarded): %w", err)
}
@@ -120,7 +146,8 @@ func (s *Store) UpdateLibraryMaintenanceStateGuarded(ctx context.Context, scope,
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)
AND `+libraryFence("library_maintenance.owner_job_id", 6, 7), scope, ownerJobID, state, note, now.UTC(),
attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("update library maintenance (guarded): %w", err)
}
@@ -138,7 +165,8 @@ func (s *Store) UpdateInstanceMaintenanceStateGuarded(ctx context.Context, insta
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)
AND `+libraryFence("library_instance_maintenance.owner_job_id", 6, 7), instance, ownerJobID, state, note,
now.UTC(), attempt.Epoch, attempt.Owner)
if err != nil {
return fmt.Errorf("update instance maintenance (guarded): %w", err)
}
@@ -154,17 +182,22 @@ WHERE instance=$1 AND owner_job_id=$2 AND released_at IS NULL
// 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)
var owner, operation string
err := s.db.QueryRow(ctx, `SELECT attempt_epoch, lease_owner, operation_id FROM library_jobs WHERE id=$1`,
attempt.JobID).Scan(&epoch, &owner, &operation)
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)
var state string
if operation != "" {
_ = s.db.QueryRow(ctx, `SELECT state FROM library_attempts WHERE operation_id=$1 AND epoch=$2`,
operation, attempt.Epoch).Scan(&state)
}
return fmt.Errorf("%w(%s:本代次 %d/%s,作业行 %d/%s,代次状态 %q)", governance.ErrLibraryEpochStale,
action, attempt.Epoch, attempt.Owner, epoch, owner, state)
}
func (s *Store) SetInstanceMaintenanceIngressGuarded(ctx context.Context, instance, ownerJobID, state, note string,
@@ -175,7 +208,8 @@ func (s *Store) SetInstanceMaintenanceIngressGuarded(ctx context.Context, instan
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)
AND `+libraryFence("library_instance_maintenance.owner_job_id", 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)
}
@@ -198,7 +232,8 @@ func (s *Store) SetLibraryMaintenanceIngressGuarded(ctx context.Context, scope,
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)
AND `+libraryFence("library_maintenance.owner_job_id", 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)
}