fix(library): 当前生效版本改按精确查询

接管分类、基线判定、已知索引映射、同步闸口的创建判据与归档保留的保护标记,
原来都用 LibraryVersions(scope, 50/100) 这个分页窗口再在内存里筛。生效版本每
scope 只有一行、可能很久以前登记,历史一长就被挤出窗口 —— 于是"已生效"被读成
"没有生效":接管会把已经上线的目标重写一遍,基线入口会给已有权威版本的目标
再建一次基线。

现在统一走两条精确查询:LibraryCurrentVersion(kind='production_effective' AND
superseded_at IS NULL,每 scope 至多一行)与 LibraryVersionOfSnapshot(按快照
身份取回"已顶替"证据)。多行、自相矛盾、读不到一律 fail closed;同一含义只留
一份实现(knownIndexMapping 同步与恢复共用)。LibraryVersions 仍是 1..100 的
展示窗口,只用于列表。

验证:真实 PG 上先复现(窗口实现 ⇒ found=false),改后 7 条 store 契约用例与
worker 端到端判定用例全绿;本机 make verify 15 项 success(用例 1264 通过 /
0 失败 / 93 已声明可选跳过)。
This commit is contained in:
姚章浩
2026-10-30 03:09:21 +08:00
parent 67743f2285
commit 0088004cd6
15 changed files with 655 additions and 130 deletions
@@ -460,6 +460,8 @@ func scanLibraryVersions(rows pgx.Rows, capacity int) ([]governance.LibraryVersi
return result, rows.Err()
}
// LibraryVersions 是**分页展示**用的窗口列表(1..100),语义是"最近 N 条"。
// 任何"当前生效 / 本快照是否生效过"的判断都不许用它:窗口一满就会把存在读成不存在。
func (s *Store) LibraryVersions(ctx context.Context, scope string, limit int) ([]governance.LibraryVersion, error) {
if limit < 1 || limit > 100 {
return nil, errors.New("library version limit out of range")
@@ -473,6 +475,73 @@ FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`
return scanLibraryVersions(rows, limit)
}
// LibraryCurrentVersion 返回这个 scope **当前生效**(未被顶替)的生产版本。
//
// 为什么不能用窗口列表:生效版本每 scope 只有一行,但它可能很久以前就登记了;
// 之后写进来的预备份/封存记录会把它挤出任何"最近 N 条",于是接管/基线/同步闸口
// 会把"已生效"读成"没有生效"——症状是重写已经上线的内容。
// 这里按 (scope, kind, superseded_at IS NULL) 精确取,窗口大小与它无关。
//
// 唯一索引 library_versions_effective 保证每 scope 至多一行;真出现多行说明台账
// 被写坏,返回错误让调用方 fail closed,不许挑一条"看起来对"的。
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)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load current library version: %w", err)
}
items, err := scanLibraryVersions(rows, 2)
if err != nil {
return governance.LibraryVersion{}, false, err
}
if len(items) > 1 {
return governance.LibraryVersion{}, false, fmt.Errorf("%d 条未顶替的生效版本并存(scope=%s):拒绝挑选",
len(items), scope)
}
if len(items) == 1 {
return items[0], true, nil
}
return governance.LibraryVersion{}, false, nil
}
// LibraryVersionOfSnapshot 按 (scope, kind, 快照) 取这个快照**自己的**登记记录(不限作业)。
//
// 用途是"本快照曾经生效过吗/是否已被顶替":版本 id 由 (kind, scope, 快照) 决定,
// 一个快照在一种类型下只该有一行,作业归属会随恢复/重放被改写,所以不能用作业当条件。
// 命中多行同样拒绝挑选。
func (s *Store) LibraryVersionOfSnapshot(ctx context.Context, scope string,
kind governance.LibraryVersionKind, snapshotID string) (governance.LibraryVersion, bool, error) {
if scope == "" || kind == "" || snapshotID == "" {
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
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)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load library version of snapshot: %w", err)
}
found, err := scanLibraryVersions(rows, 2)
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 {
return found[0], true, nil
}
return governance.LibraryVersion{}, false, nil
}
// CreateLibraryAuthorization 记录一次生产发布授权;同一 (scope,snapshot,digest) 只保留最新有效。
func (s *Store) CreateLibraryAuthorization(ctx context.Context, item governance.LibraryReleaseAuthorization) error {
if item.ID == "" || item.Scope == "" || item.SnapshotID == "" || item.ParamsDigest == "" || item.ExpiresAt.IsZero() {
@@ -147,3 +147,105 @@ func TestLibraryVersionByRefRejectsIncompleteRef(t *testing.T) {
}
}
}
func recordEffective(t *testing.T, ctx context.Context, store *Store, scope, jobID, snapshot string, created time.Time) {
t.Helper()
if err := store.RecordLibraryVersion(ctx, governance.LibraryVersion{
ID: governance.LibraryVersionID(governance.LibraryVersionProductionEffective, scope, snapshot),
Scope: scope, Kind: governance.LibraryVersionProductionEffective, SnapshotID: snapshot,
SourceJobID: jobID, CreatedBy: "worker",
Evidence: map[string]any{"action": "sync", "job": jobID},
CreatedAt: created,
}); err != nil {
t.Fatalf("record effective %s: %v", snapshot, err)
}
}
// 当前生效版本必须按"未顶替"这个事实精确查,不能靠"最近 N 条":历史一旦超过窗口,
// 生效版本会被读成"没有",接管/基线/同步闸口就会把已经生效的目标再写一遍。
func TestLibraryCurrentVersionFindsEffectiveOutsideHistoryWindow(t *testing.T) {
store, _ := openVersionStore(t)
ctx := context.Background()
now := time.Now().UTC()
// 生效版本登记在很早的时刻,之后同 scope 又写了 300 条其它版本(真实列表上限 100)。
recordEffective(t, ctx, store, "internal", "job-cur", "snap-cur", now.Add(-72*time.Hour))
for i := 0; i < 300; i++ {
recordPrebackup(t, ctx, store, "internal", fmt.Sprintf("job-new-%03d", i), fmt.Sprintf("snap-new-%03d", i),
now.Add(-time.Duration(i)*time.Minute))
}
window, err := store.LibraryVersions(ctx, "internal", 100)
if err != nil {
t.Fatalf("list versions: %v", err)
}
for _, item := range window {
if item.SnapshotID == "snap-cur" {
t.Fatal("窗口里仍能看到生效版本:本用例证明不了窗口之外仍可精确取回(夹具失效)")
}
}
current, found, err := store.LibraryCurrentVersion(ctx, "internal")
if err != nil || !found {
t.Fatalf("窗口之外也必须取到当前生效版本:found=%v err=%v", found, err)
}
if current.SnapshotID != "snap-cur" || current.SourceJobID != "job-cur" || current.SupersededAt != nil {
t.Fatalf("取到的不是当前生效版本:%+v", current)
}
// 新版本生效后,旧快照按身份查仍然"存在但已顶替"——接管据此拒绝用旧快照覆盖。
recordEffective(t, ctx, store, "internal", "job-new", "snap-newest", now)
current, found, err = store.LibraryCurrentVersion(ctx, "internal")
if err != nil || !found || current.SnapshotID != "snap-newest" {
t.Fatalf("当前生效版本必须切到最新一份:found=%v err=%v %+v", found, err, current)
}
previous, found, err := store.LibraryVersionOfSnapshot(ctx, "internal",
governance.LibraryVersionProductionEffective, "snap-cur")
if err != nil || !found {
t.Fatalf("旧快照必须仍能按身份取回:found=%v err=%v", found, err)
}
if previous.SupersededAt == nil {
t.Fatalf("旧快照必须标成已顶替:%+v", previous)
}
}
// 没有生效版本 ≠ 查询失败:前者是"首次发布",后者必须让调用方 fail closed。
func TestLibraryCurrentVersionSeparatesMissingFromOtherKinds(t *testing.T) {
store, _ := openVersionStore(t)
ctx := context.Background()
now := time.Now().UTC()
recordPrebackup(t, ctx, store, "internal", "job-a", "snap-1", now)
if _, found, err := store.LibraryCurrentVersion(ctx, "internal"); err != nil || found {
t.Fatalf("只有预备份时不能当成有生效版本:found=%v err=%v", found, err)
}
recordEffective(t, ctx, store, "internal", "job-a", "snap-eff", now)
// 跨 scope 不许命中。
if _, found, err := store.LibraryCurrentVersion(ctx, "external"); err != nil || found {
t.Fatalf("跨 scope 不许命中:found=%v err=%v", found, err)
}
if _, found, err := store.LibraryVersionOfSnapshot(ctx, "external",
governance.LibraryVersionProductionEffective, "snap-eff"); err != nil || found {
t.Fatalf("跨 scope 的快照查询不许命中:found=%v err=%v", found, err)
}
if _, found, err := store.LibraryVersionOfSnapshot(ctx, "internal",
governance.LibraryVersionProductionEffective, "snap-missing"); err != nil || found {
t.Fatalf("未登记的快照必须 found=false 且无错误:found=%v err=%v", found, err)
}
}
// 同一快照两行(台账被写坏):按身份查必须拒绝挑选,不许挑一条"看起来对"的。
func TestLibraryVersionOfSnapshotRejectsAmbiguousRows(t *testing.T) {
store, pool := openVersionStore(t)
ctx := context.Background()
now := time.Now().UTC()
recordPrebackup(t, ctx, store, "internal", "job-a", "snap-dup", now)
if _, err := pool.Exec(ctx, `
INSERT INTO library_versions (id, scope, kind, snapshot_id, source_job_id, evidence, created_by, created_at)
VALUES ('libver-dup-current','internal','production_prebackup','snap-dup','job-b','{}'::jsonb,'worker',$1)`, now); err != nil {
t.Fatalf("insert duplicate row: %v", err)
}
if _, found, err := store.LibraryVersionOfSnapshot(ctx, "internal",
governance.LibraryVersionProductionPrebackup, "snap-dup"); err == nil || found {
t.Fatalf("同一快照多行时必须拒绝:found=%v err=%v", found, err)
} else if !strings.Contains(err.Error(), "拒绝挑选") {
t.Fatalf("错误要说清是重复身份,实际:%v", err)
}
}