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
+9 -9
View File
@@ -52,18 +52,18 @@ func libraryBaselineEnqueue(w http.ResponseWriter, r *http.Request, config Confi
"error": "版本登记存储不可用"})
return
}
versions, err := store.LibraryVersions(r.Context(), request.Scope, 50)
// 建基线的前提是"这个目标还没有生效版本"。这是创建判据,必须精确查当前生效版本:
// 用"最近 N 条"会在窗口满时把已生效读成没有,放行一次会覆盖他人版本的基线捕获。
current, hasCurrent, err := store.LibraryCurrentVersion(r.Context(), request.Scope)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"})
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read current library version"})
return
}
for _, item := range versions {
if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_baseline_exists",
"error": "该目标已有生效版本,不需要再建基线;换版本请走同步或恢复",
"snapshot_id": item.SnapshotID})
return
}
if hasCurrent {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_baseline_exists",
"error": "该目标已有生效版本,不需要再建基线;换版本请走同步或恢复",
"snapshot_id": current.SnapshotID})
return
}
// 目标必须真的读得到:读不到就不是"非空无权威版本",而是另一个问题,
// 不允许用建基线去掩盖连接/配置故障。
+30
View File
@@ -3,6 +3,7 @@ package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
@@ -160,3 +161,32 @@ func TestLibraryMaintenanceCapabilityReportsWiringInsteadOfOneVagueSentence(t *t
t.Fatalf("missing=%v", broken["missing"])
}
}
// 建基线的存在性判断同样不能靠展示窗口:生效版本可能在"最近 N 条"之外。
// 读不到(而不是"没有")时也必须 fail closed,不许当成可以建基线。
func TestLibraryBaselineUsesExactCurrentVersionBeyondWindow(t *testing.T) {
store := &fakeLibraryStore{current: &governance.LibraryVersion{ID: "libver-1", Scope: "internal",
Kind: governance.LibraryVersionProductionEffective, SnapshotID: "snap-effective",
CreatedAt: time.Now().UTC().Add(-96 * time.Hour)}}
recorder := httptest.NewRecorder()
libraryBaselineEnqueue(recorder, baselineRequest(`{"scope":"internal"}`, roleAdmin, "admin"), Config{Store: store})
if recorder.Code != http.StatusConflict {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
if body := decodeBody(t, recorder); body["code"] != "library_baseline_exists" || body["snapshot_id"] != "snap-effective" {
t.Fatalf("body=%v", body)
}
if store.createN != 0 {
t.Fatal("must not create a baseline job when an effective version exists")
}
failing := &fakeLibraryStore{currentErr: errors.New("version storage down")}
recorder = httptest.NewRecorder()
libraryBaselineEnqueue(recorder, baselineRequest(`{"scope":"internal"}`, roleAdmin, "admin"), Config{Store: failing})
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
if failing.createN != 0 {
t.Fatal("must not create a baseline job while the current version is unreadable")
}
}
+29 -7
View File
@@ -342,6 +342,11 @@ type libraryJobStore interface {
ListLibraryJobs(ctx context.Context, scope string, limit int) ([]governance.LibraryJob, error)
RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error
LibraryVersions(ctx context.Context, scope string, limit int) ([]governance.LibraryVersion, error)
// 当前生效版本与"某快照自己的登记"必须是精确查询:LibraryVersions 是分页展示窗口,
// 窗口一满就会把"已生效"读成"没有",同步闸口/基线入口就会放行一次不必要的重写。
LibraryCurrentVersion(ctx context.Context, scope string) (governance.LibraryVersion, bool, error)
LibraryVersionOfSnapshot(ctx context.Context, scope string, kind governance.LibraryVersionKind,
snapshotID string) (governance.LibraryVersion, bool, error)
UpdateLibraryStage(ctx context.Context, jobID, stage, state string, total, completed, bytesTotal, bytesDone *int64, detail string, now time.Time) error
AdvanceLibraryJob(ctx context.Context, jobID string, state governance.LibraryJobState, stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) error
AttachLibraryQueueJob(ctx context.Context, jobID, queueJobID string, now time.Time) error
@@ -678,16 +683,27 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
}
// 生产生效 / 预备份 / 作业来自持久登记。
// 历史列表仍是分页展示(窗口),但"当前生效版本"必须精确查:窗口一满,
// 生效版本会掉出列表,页面就会显示成"没有生效版本",与真实状态不符。
versions, err := store.LibraryVersions(r.Context(), scope, 50)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"})
return
}
current, hasCurrent, currentErr := store.LibraryCurrentVersion(r.Context(), scope)
if currentErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read current library version"})
return
}
if archiveReadable {
overview.TestSealed, overview.TestSealedReason = testSealedOf(versions, byID)
}
overview.Production = libraryKnownView{State: "unknown", Reason: "还没有生产验证通过的生效版本记录"}
overview.Prebackup = libraryKnownView{State: "unknown", Reason: "这个范围还没有任何生产预备份"}
if hasCurrent {
view := libraryVersionViewOf(current)
overview.Production = libraryKnownView{State: "known", Version: &view}
}
target := ""
if overview.TestSealed != nil {
target = overview.TestSealed.SnapshotID
@@ -701,9 +717,7 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
})
switch item.Kind {
case governance.LibraryVersionProductionEffective:
if item.SupersededAt == nil {
overview.Production = libraryKnownView{State: "known", Version: &view}
}
// 生效状态只认上面那条精确查询;这里只负责把历史行放进列表。
case governance.LibraryVersionProductionPrebackup:
// 页面要显示"最近一次生产写入前的备份",不是"与拟发布快照同内容的那一份":
// 恢复作业登记的是**恢复前**的备份,它和测试封存快照本来就不同;
@@ -833,12 +847,24 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
return
}
overview := libraryOverview{Scope: request.Scope}
// 闸口依赖"生产是否已有生效版本":这是**创建**判据,必须精确查。
// 用窗口列表会把它读成"没有",于是把一次不必要的覆盖当成合法首发;
// 查询失败同样拒绝(fail closed),不猜。
current, hasCurrent, currentErr := store.LibraryCurrentVersion(r.Context(), request.Scope)
if currentErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read current library version"})
return
}
versions, err := store.LibraryVersions(r.Context(), request.Scope, 50)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read library versions"})
return
}
overview.Production = libraryKnownView{State: "unknown"}
if hasCurrent {
view := libraryVersionViewOf(current)
overview.Production = libraryKnownView{State: "known", Version: &view}
}
overview.Prebackup = libraryKnownView{State: "unknown"}
if empty, probeErr := productionScopeEmpty(r.Context(), config, request.Scope); probeErr == nil && empty {
overview.Production = libraryKnownView{State: "unknown", EmptyBaseline: true,
@@ -846,10 +872,6 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
}
for index := range versions {
item := versions[index]
if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil {
view := libraryVersionViewOf(item)
overview.Production = libraryKnownView{State: "known", Version: &view}
}
if item.Kind == governance.LibraryVersionProductionPrebackup && request.Target != "" && item.SnapshotID == request.Target {
view := libraryVersionViewOf(item)
overview.Prebackup = libraryKnownView{State: "known", Version: &view}
+91
View File
@@ -3,6 +3,7 @@ package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
@@ -24,6 +25,10 @@ type fakeLibraryStore struct {
createN int
lastJob governance.LibraryJob
lastState governance.LibraryJobState
// current 让用例表达"窗口列表里看不到、但精确查询能查到当前生效版本"这一现场形状;
// currentErr 表达"读不到"(调用方必须 fail closed,不许当成没有生效版本)。
current *governance.LibraryVersion
currentErr error
}
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
@@ -61,6 +66,33 @@ func (f *fakeLibraryStore) LibraryVersions(_ context.Context, scope string, _ in
return result, nil
}
// 当前生效版本是精确查询:这里刻意只按 (scope, kind, 未顶替) 过滤,不模拟分页窗口,
// 与真实 Store 的契约一致(窗口只用于展示列表)。
func (f *fakeLibraryStore) LibraryCurrentVersion(_ context.Context, scope string) (governance.LibraryVersion, bool, error) {
if f.currentErr != nil {
return governance.LibraryVersion{}, false, f.currentErr
}
if f.current != nil {
return *f.current, true, nil
}
for _, version := range f.versions {
if version.Scope == scope && version.Kind == governance.LibraryVersionProductionEffective && version.SupersededAt == nil {
return version, true, nil
}
}
return governance.LibraryVersion{}, false, nil
}
func (f *fakeLibraryStore) LibraryVersionOfSnapshot(_ context.Context, scope string, kind governance.LibraryVersionKind,
snapshotID string) (governance.LibraryVersion, bool, error) {
for _, version := range f.versions {
if version.Scope == scope && version.Kind == kind && version.SnapshotID == snapshotID {
return version, true, nil
}
}
return governance.LibraryVersion{}, false, nil
}
func (f *fakeLibraryStore) UpdateLibraryStage(_ context.Context, _, _, _ string, _, _, _, _ *int64, _ string, _ time.Time) error {
return nil
}
@@ -414,3 +446,62 @@ func TestLibraryOverviewKeepsVersionKindsSeparate(t *testing.T) {
t.Fatal("gate must stay closed")
}
}
// 现场形状:历史把生效版本挤出了展示窗口(LibraryVersions 返回空),但"当前生效版本"
// 精确查询仍读得到它。同步闸口必须据此认为生产已有权威版本:
// 读成"没有"会把一次不必要的覆盖放行,并把人推向"重新建基线"。
func TestLibrarySyncEnqueueUsesExactCurrentVersionBeyondWindow(t *testing.T) {
target := "snap-1"
digest, err := librarySyncParamsDigest("internal", target)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
store := &fakeLibraryStore{
// 窗口:故意什么都不返回(模拟生效版本掉出"最近 N 条")。
versions: []governance.LibraryVersion{},
current: &governance.LibraryVersion{ID: "ver-prod", Scope: "internal",
Kind: governance.LibraryVersionProductionEffective, SnapshotID: "prod-snap",
VersionLabel: "prod-2026.10", CreatedAt: now.Add(-72 * time.Hour)},
}
store.enqueueEchoRequestedID = true
store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target,
ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(30 * time.Minute), CreatedAt: now}
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
if recorder.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s(窗口外读到生效版本时闸口不该拒绝)", recorder.Code, recorder.Body.String())
}
if store.createN != 1 {
t.Fatalf("created=%d, want 1", store.createN)
}
}
// 读不到当前生效版本时不许猜:fail closed(500)且不创建作业。
func TestLibrarySyncEnqueueFailsClosedWhenCurrentVersionUnreadable(t *testing.T) {
target := "snap-1"
digest, err := librarySyncParamsDigest("internal", target)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
store := &fakeLibraryStore{currentErr: errors.New("version storage down")}
store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target,
ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(30 * time.Minute), CreatedAt: now}
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs",
strings.NewReader(`{"scope":"internal","target_snapshot_id":"`+target+`"}`)), config)
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
if store.createN != 0 {
t.Fatalf("created %d jobs while the current version was unreadable", store.createN)
}
}
+19 -3
View File
@@ -103,14 +103,19 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config
if listErr == nil {
for _, item := range versions {
kinds[item.SnapshotID] = item
if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil {
protectedBy[item.SnapshotID] = append(protectedBy[item.SnapshotID], "生产生效版本")
}
if item.Kind == governance.LibraryVersionProductionPrebackup {
protectedBy[item.SnapshotID] = append(protectedBy[item.SnapshotID], "生产预备份")
}
}
}
// 生产生效版本 = 唯一一条未顶替的记录,必须精确查:它可能早已掉出上面的
// 展示窗口,靠列表判"是否受保护"会让当前生效的那份被当成普通版本清掉。
if current, found, currentErr := store.LibraryCurrentVersion(r.Context(), scope); currentErr == nil && found {
if _, seen := kinds[current.SnapshotID]; !seen {
kinds[current.SnapshotID] = current
}
protectedBy[current.SnapshotID] = appendUnique(protectedBy[current.SnapshotID], "生产生效版本")
}
jobs, jobErr := store.ListLibraryJobs(r.Context(), scope, 20)
if jobErr == nil {
for _, job := range jobs {
@@ -205,3 +210,14 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config
response.Capacity = libraryretention.CheckCapacity(total.ContentBytes, requiredBytes, config.LibraryCapacityBudgetBytes)
writeJSON(w, http.StatusOK, response)
}
// appendUnique 只追加还没出现过的标签:同一条版本可能同时被展示窗口与精确查询命中,
// 重复标签会让"保护依据"看起来像两条不同理由。
func appendUnique(labels []string, value string) []string {
for _, item := range labels {
if item == value {
return labels
}
}
return append(labels, value)
}