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
+26 -6
View File
@@ -338,6 +338,9 @@ type libraryVersionRef struct {
type libraryJobStore interface {
CreateLibraryJob(ctx context.Context, job governance.LibraryJob, stages []string, now time.Time) (governance.LibraryJob, bool, error)
// EnsureLibraryOperation 幂等登记"一次明确意图":同键+同摘要 ⇒ 同一次意图(客户端重放),
// 换键 ⇒ 新意图。作业是意图的执行代次,不能反过来用"历史成功作业"回答新意图(F01)。
EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error)
LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error)
ListLibraryJobs(ctx context.Context, scope string, limit int) ([]governance.LibraryJob, error)
RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error
@@ -837,6 +840,9 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
var request struct {
Scope string `json:"scope"`
Target string `json:"target_snapshot_id"`
// OperationKey 是客户端重放键:同一次意图重发要命中同一个 operation。
// 不传就是一次新意图(同一个快照再发布一次也必须真的执行)。
OperationKey string `json:"operation_key"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
@@ -917,9 +923,22 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
}
now := time.Now().UTC()
jobID := fmt.Sprintf("libsync-%s-%d", request.Scope, now.UnixNano())
// 意图身份:同一个 operation 的重复请求复用作业;新意图即使目标快照与历史成功相同
// 也会建新作业并真的执行(F01)。
intent, intentErr := ensureLibraryIntent(r.Context(), store, request.Scope, governance.LibraryJobSync,
request.Target, digest, actor, request.OperationKey, now)
if intentErr != nil {
if isIntentConflict(intentErr) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_intent_conflict",
"error": "同一 operation_key 对应了不同的请求内容:换一个键表示新意图"})
return
}
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register library intent"})
return
}
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobSync,
IdempotencyKey: "library.sync:" + request.Scope + ":" + request.Target, RequestDigest: digest,
IdempotencyKey: intent.JobKey, RequestDigest: digest, OperationID: intent.Operation.ID,
TargetSnapshotID: request.Target, Actor: actor,
}, governance.SyncStages(), now)
if errors.Is(err, governance.ErrLibraryJobActive) {
@@ -935,14 +954,15 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library sync job"})
return
}
// 上一次同参数请求失败/被取消后,幂等键不能再把新请求塞回那个死作业里:
// 换一个"重试代次"键重新建作业,旧作业保留为审计记录。
// 上一次同意图请求失败/被取消后,幂等键不能再把新请求塞回那个死作业里:
// 在**同一个 operation** 下开一个新的执行作业(重试代次),旧作业保留为审计记录。
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: fmt.Sprintf("libsync-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope,
ID: fmt.Sprintf("libsync-%s-%d", request.Scope, time.Now().UTC().UnixNano()), Scope: request.Scope,
Kind: governance.LibraryJobSync,
IdempotencyKey: "library.sync:" + request.Scope + ":" + request.Target + ":retry:" + now.Format("20060102T150405.000000000"),
RequestDigest: digest, TargetSnapshotID: request.Target, Actor: actor,
IdempotencyKey: intent.JobKey + ":retry:" + now.Format("20060102T150405.000000000"),
RequestDigest: digest, OperationID: intent.Operation.ID,
TargetSnapshotID: request.Target, Actor: actor,
}, governance.SyncStages(), now)
if err != nil || reused {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_retry_conflict",
+20
View File
@@ -29,6 +29,9 @@ type fakeLibraryStore struct {
// currentErr 表达"读不到"(调用方必须 fail closed,不许当成没有生效版本)。
current *governance.LibraryVersion
currentErr error
// operations/lastOperation 记录"意图身份":重放与换键的差别在这里表达(F01)。
operations map[string]governance.LibraryOperation
lastOperation governance.LibraryOperation
}
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
@@ -37,6 +40,23 @@ func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.Li
return job, false, nil
}
// EnsureLibraryOperation 在 fake 里就是"同键同摘要 ⇒ 同一条意图":测试用例靠它表达
// "重放命中同意图 / 换键是新意图"(F01),不需要真实库。
func (f *fakeLibraryStore) EnsureLibraryOperation(_ context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error) {
if f.operations == nil {
f.operations = map[string]governance.LibraryOperation{}
}
if existing, ok := f.operations[op.OperationKey]; ok {
if existing.RequestDigest != op.RequestDigest {
return existing, false, governance.ErrLibraryOperationConflict
}
return existing, false, nil
}
f.operations[op.OperationKey] = op
f.lastOperation = op
return op, true, nil
}
func (f *fakeLibraryStore) LibraryJob(_ context.Context, id string) (governance.LibraryJob, error) {
return governance.LibraryJob{ID: id}, nil
}
+63
View File
@@ -0,0 +1,63 @@
package httpapi
import (
"context"
"errors"
"strconv"
"strings"
"time"
"knowledge-governance/internal/governance"
)
// libraryIntent 是"用户这一次明确意图"的不可变身份。
//
// 为什么不能再拿 `library.sync:<scope>:<snapshot>` 当终身幂等键:那是把**意图**和
// **目标状态**混成一体。成功同步 B 之后改成 A、再要求同步 B 时,第二次 B 拿到的是第一次
// 的历史成功作业,什么都不做——用户要的状态没实现,页面还显示成功(F01)。
//
// 现在:客户端可以用 `operation_key` 重放同一次意图(双击/网络重试 ⇒ 同一个 operation ⇒
// 同一个作业);不带或换一个键 ⇒ 新意图 ⇒ 新 operation ⇒ 真的执行一遍,并留下自己的
// 事件与 current 变更。
type libraryIntent struct {
Operation governance.LibraryOperation
// JobKey 是作业幂等键:同一意图重放得到同一个作业行(不会重复建)。
JobKey string
}
// intentCacheKey 把"目标快照 + 客户端意图键"拼成 operation 键:
// 快照参与是因为 operation 的身份必须绑定它发布的是什么;客户端键参与是因为
// 同一次重放要命中同一条意图。
func intentCacheKey(snapshotID, clientKey string, now time.Time) string {
base := strings.TrimSpace(snapshotID)
if client := strings.TrimSpace(clientKey); client != "" {
return base + "#" + client
}
// 没有客户端键:每次请求都是一次新意图。用纳秒而不是随机数,便于从日志里回溯。
return base + "#" + strconv.FormatInt(now.UnixNano(), 10)
}
// ensureLibraryIntent 幂等登记意图。摘要不一致 ⇒ 冲突(同一个键不许换内容)。
func ensureLibraryIntent(ctx context.Context, store libraryJobStore, scope string, kind governance.LibraryJobKind,
snapshotID, digest, actor, clientKey string, now time.Time) (libraryIntent, error) {
key := intentCacheKey(snapshotID, clientKey, now)
op, _, err := store.EnsureLibraryOperation(ctx, governance.LibraryOperation{
ID: governance.LibraryOperationID(scope, kind, key), Scope: scope, Kind: kind,
TargetSnapshotID: snapshotID, RequestDigest: digest, OperationKey: key, Actor: actor, CreatedAt: now.UTC(),
})
if err != nil {
return libraryIntent{}, err
}
return libraryIntent{Operation: op, JobKey: "library.job:" + op.ID}, nil
}
// isIntentConflict 区分"同一个意图键换了内容"(409,调用方应换键)与内部错误。
func isIntentConflict(err error) bool {
return errors.Is(err, governance.ErrLibraryOperationConflict)
}
// libraryOperationView 是响应里给前端的意图身份(可复用于重放)。
func libraryOperationView(intent libraryIntent) map[string]any {
return map[string]any{"operation_id": intent.Operation.ID, "operation_key": intent.Operation.OperationKey,
"target_snapshot_id": intent.Operation.TargetSnapshotID, "kind": string(intent.Operation.Kind)}
}
+125
View File
@@ -0,0 +1,125 @@
package httpapi
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
// F01:同一个目标快照的**新意图**必须真的执行,不能被"这个快照曾经成功过"吞掉。
//
// 现场形状:同步 B 成功 → 恢复 A → 再次同步 B。第三次请求是一次合法意图,
// 旧实现返回第一次的成功作业(202, 不再并入队),用户要的状态没实现。
//
// 判据:换 operation_key ⇒ 新 operation(ID 不同、作业幂等键不同);
// 同一个 operation_key ⇒ 同一 operation(重放)。
func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
target := "snap-1"
digest, err := librarySyncParamsDigest("internal", target)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
newStore := func() *fakeLibraryStore {
store := &fakeLibraryStore{
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}
return store
}
config := func(store *fakeLibraryStore) Config {
return Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
}
post := func(store *fakeLibraryStore, body string) *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs",
strings.NewReader(body)), config(store))
return recorder
}
withKey := `{"scope":"internal","target_snapshot_id":"` + target + `","operation_key":"%s"}`
// 第一次意图:建作业。
first := newStore()
if recorder := post(first, strings.Replace(withKey, "%s", "intent-1", 1)); recorder.Code != http.StatusAccepted {
t.Fatalf("首次发布会话 status=%d body=%s", recorder.Code, recorder.Body.String())
}
firstOperation := first.lastOperation.ID
if firstOperation == "" || first.lastJob.OperationID != firstOperation {
t.Fatalf("作业必须挂在意图上:job.operation=%q intent=%q", first.lastJob.OperationID, firstOperation)
}
// 同一次意图重放(双击/超时重发):同一个 operation,不产生第二条意图。
replay := newStore()
if recorder := post(replay, strings.Replace(withKey, "%s", "intent-1", 1)); recorder.Code != http.StatusAccepted {
t.Fatalf("重放 status=%d body=%s", recorder.Code, recorder.Body.String())
}
if replay.lastOperation.ID != firstOperation {
t.Fatalf("同一意图键得到了不同 operation:%q vs %q", replay.lastOperation.ID, firstOperation)
}
// 新意图(同一快照、不同键):必须是新 operation ⇒ 新作业幂等键 ⇒ 真的执行。
second := newStore()
if recorder := post(second, strings.Replace(withKey, "%s", "intent-2", 1)); recorder.Code != http.StatusAccepted {
t.Fatalf("新意图 status=%d body=%s", recorder.Code, recorder.Body.String())
}
if second.lastOperation.ID == firstOperation {
t.Fatal("同一快照的新意图必须得到新 operation:否则历史成功会吞掉本次请求(F01)")
}
if second.lastJob.IdempotencyKey == first.lastJob.IdempotencyKey {
t.Fatal("新意图的作业幂等键与历史作业相同:CreateLibraryJob 会返回旧作业,什么也不执行")
}
if second.createN != 1 {
t.Fatalf("新意图必须建作业并执行,created=%d", second.createN)
}
}
// 同一个意图键配上不同快照 = 冲突,不能悄悄共享谱系。
func TestLibrarySyncIntentKeyReusedWithAnotherSnapshotConflicts(t *testing.T) {
target := "snap-1"
digest, _ := librarySyncParamsDigest("internal", target)
now := time.Now().UTC()
store := &fakeLibraryStore{current: &governance.LibraryVersion{ID: "ver-prod", Scope: "internal",
Kind: governance.LibraryVersionProductionEffective, SnapshotID: "prod-snap", CreatedAt: now.Add(-time.Hour)}}
store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target,
ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now}
// 预先登记一条"同键但不同快照"的意图。
if _, _, err := store.EnsureLibraryOperation(nil, governance.LibraryOperation{
ID: "libop-x", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: "other-snap",
RequestDigest: "different", OperationKey: target + "#intent-1", CreatedAt: now}); err != nil {
t.Fatal(err)
}
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 + `","operation_key":"intent-1"}`
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
if recorder.Code != http.StatusConflict {
t.Fatalf("同键不同内容必须 409,status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
// F14:通用 queue 入口不许创建整库保留类型——那里的角色检查替代不了发布准入。
func TestCreateJobRejectsReservedLibraryTypes(t *testing.T) {
store := &fakeJobStore{}
config := Config{Store: store}
body := `{"type":"library.baseline","payload":{"scope":"internal"},"idempotency_key":"k-1"}`
recorder := httptest.NewRecorder()
createJob(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/jobs", strings.NewReader(body)), config)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("保留类型必须被通用入口拒绝:status=%d body=%s", recorder.Code, recorder.Body.String())
}
if !strings.Contains(recorder.Body.String(), "发布管理专用入口") {
t.Fatalf("拒绝原因必须指向专用入口:%s", recorder.Body.String())
}
}
+37 -6
View File
@@ -25,6 +25,8 @@ func libraryRestoreParamsDigest(scope, snapshotID string) (string, error) {
type libraryRestoreRequest struct {
Scope string `json:"scope"`
SnapshotID string `json:"snapshot_id"`
// OperationKey 是客户端重放键;不传就是一次新意图(同一快照再恢复一次也要真的执行)。
OperationKey string `json:"operation_key"`
}
func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
@@ -91,10 +93,22 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
// [A-Za-z0-9_-]:带 "." 的时间戳会让恢复在开窗口时被拒(真跑报 invalid freeze request),
// 所以用纳秒整数,和同步作业保持一致。
jobID := "librestore-" + request.Scope + "-" + strconv.FormatInt(now.UnixNano(), 10)
intent, intentErr := ensureLibraryIntent(r.Context(), store, request.Scope, governance.LibraryJobRestore,
request.SnapshotID, digest, identity.Username, request.OperationKey, now)
if intentErr != nil {
if isIntentConflict(intentErr) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_intent_conflict",
"error": "同一 operation_key 对应了不同的请求内容:换一个键表示新意图"})
return
}
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register restore intent"})
return
}
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: jobID, Scope: request.Scope, Kind: governance.LibraryJobRestore,
IdempotencyKey: "library.restore:" + request.Scope + ":" + request.SnapshotID,
RequestDigest: digest, TargetSnapshotID: request.SnapshotID, Actor: identity.Username,
IdempotencyKey: intent.JobKey,
RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.SnapshotID,
Actor: identity.Username,
}, governance.SyncStages(), now)
if errors.Is(err, governance.ErrLibraryJobActive) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_active", "error": "该目标已有在飞作业"})
@@ -111,8 +125,9 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: jobID + "-retry", Scope: request.Scope, Kind: governance.LibraryJobRestore,
IdempotencyKey: "library.restore:" + request.Scope + ":" + request.SnapshotID + ":retry:" + strconv.FormatInt(now.UnixNano(), 10),
RequestDigest: digest, TargetSnapshotID: request.SnapshotID, Actor: identity.Username,
IdempotencyKey: intent.JobKey + ":retry:" + strconv.FormatInt(now.UnixNano(), 10),
RequestDigest: digest, OperationID: intent.Operation.ID, TargetSnapshotID: request.SnapshotID,
Actor: identity.Username,
}, governance.SyncStages(), now)
if err != nil || reused {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_retry_conflict", "error": "无法为重试创建新作业"})
@@ -273,10 +288,26 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusConflict, map[string]any{"error": "封存作业由封存入口重发,不走续作"})
return
}
// F15:续作是**同一个意图的新执行代次**,不是新意图。沿用原作业的 operation,
// 维护窗口、预备份、写集合的谱系都还挂在同一条意图上;新作业行只是这次执行的载体,
// worker 起手会为它开一个更大的 epoch(旧代次从此不能写)。
operationID := source.OperationID
if operationID == "" {
// 迁移前的老作业没有 operation:按原作业身份补一条(同键同摘要 ⇒ 幂等,
// 不会因为点了两次续作而造出两条意图)。
intent, intentErr := ensureLibraryIntent(r.Context(), store, source.Scope, kind,
source.TargetSnapshotID, digest, identity.Username, "resume:"+sourceID, now)
if intentErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot register resume intent"})
return
}
operationID = intent.Operation.ID
}
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: jobID, Scope: source.Scope, Kind: kind,
IdempotencyKey: "library.resume:" + sourceID,
RequestDigest: digest, TargetSnapshotID: source.TargetSnapshotID, Actor: identity.Username,
IdempotencyKey: "library.job:" + operationID + ":resume",
RequestDigest: digest, OperationID: operationID,
TargetSnapshotID: source.TargetSnapshotID, Actor: identity.Username,
}, governance.SyncStages(), now)
if errors.Is(err, governance.ErrLibraryJobActive) {
writeJSON(w, http.StatusConflict, map[string]any{"error": "该目标已有在飞作业"})
+40 -28
View File
@@ -1,6 +1,7 @@
package httpapi
import (
"context"
"net/http"
"sort"
"strings"
@@ -96,41 +97,47 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config
// 版本类型与保护依据来自持久登记与在飞作业,不靠文件时间猜。
kinds := map[string]governance.LibraryVersion{}
protectedBy := map[string][]string{}
protectionUnknown := false
store, storeOK := libraryStore(config)
if storeOK {
// 类型与保护依据只认**持久登记**的精确查询:分页窗口(最近 100 个版本/20 个作业)
// 一旦被历史挤满,需要恢复的旧预备份与 failed-but-held 作业就会被读成"可删除候选"(F10)。
for _, scope := range []string{"internal", "external"} {
versions, listErr := store.LibraryVersions(r.Context(), scope, 100)
if listErr == nil {
for _, item := range versions {
kinds[item.SnapshotID] = item
if item.Kind == governance.LibraryVersionProductionPrebackup {
protectedBy[item.SnapshotID] = append(protectedBy[item.SnapshotID], "生产预备份")
}
}
if listErr != nil {
protectionUnknown = true
continue
}
for _, item := range versions {
kinds[item.SnapshotID] = item
}
// 生产生效版本 = 唯一一条未顶替的记录,必须精确查:它可能早已掉出上面的
// 展示窗口,靠列表判"是否受保护"会让当前生效的那份被当成普通版本清掉。
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 {
if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning {
continue
}
for _, id := range []string{job.SnapshotID, job.TargetSnapshotID} {
if id != "" {
protectedBy[id] = append(protectedBy[id], "在飞作业引用")
}
}
}
} else if currentErr != nil {
protectionUnknown = true
}
}
if protector, ok := config.Store.(interface {
LibraryProtection(ctx context.Context) (map[string][]string, error)
}); ok {
if reasons, protectErr := protector.LibraryProtection(r.Context()); protectErr == nil {
for snapshot, items := range reasons {
for _, reason := range items {
protectedBy[snapshot] = appendUnique(protectedBy[snapshot], reason)
}
}
} else {
protectionUnknown = true
response.Notes = append(response.Notes, "保护依据读取失败("+protectErr.Error()+"):本次不生成可删除候选")
}
} else {
protectionUnknown = true
response.Notes = append(response.Notes, "存储不支持全量保护查询:本次不生成可删除候选")
}
} else {
protectionUnknown = true
response.Notes = append(response.Notes, "版本登记存储不可用:只按归档文件统计,无法识别受保护版本")
}
@@ -148,11 +155,11 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config
}
for index, id := range ids {
manifest := manifests[index]
// 备份类型只能来自显式登记:非空 ValidationPolicy 也被生产预备份使用,
// 拿它猜类型会把生产预备份显示成测试封存(F10)。
kind := "unregistered"
if record, ok := kinds[id]; ok {
kind = string(record.Kind)
} else if manifest.ValidationPolicy != "" {
kind = "test_sealed"
}
if kind == "test_sealed" {
// 每库最近一次封存受保护:它是最新可发布的测试版本。
@@ -170,14 +177,19 @@ func libraryStorageHandler(w http.ResponseWriter, r *http.Request, config Config
// 用与上面相同的清单再定位一次最新测试封存,避免把时间映射回 ID 时出错。
for index, id := range ids {
manifest := manifests[index]
if kindOf := kinds[id].Kind; kindOf == governance.LibraryVersionTestSealed ||
(kindOf == "" && manifest.ValidationPolicy != "") {
if kindOf := kinds[id].Kind; kindOf == governance.LibraryVersionTestSealed {
if manifest.CreatedAt.Equal(latestSealed[manifest.Scope]) {
protectedBy[id] = append(protectedBy[id], "最近测试封存("+manifest.Scope+")")
protectedBy[id] = appendUnique(protectedBy[id], "最近测试封存("+manifest.Scope+")")
}
}
}
if protectionUnknown {
// 保护依据未知 ⇒ 不许产出"可删除候选":不确定的东西不能按可删处理(fail closed)。
for index := range versions {
protectedBy[versions[index].ID] = appendUnique(protectedBy[versions[index].ID], "保护依据未知(拒绝生成可删候选)")
}
}
for index := range versions {
if reasons := protectedBy[versions[index].ID]; len(reasons) > 0 {
versions[index].Protected = true
+9
View File
@@ -776,6 +776,15 @@ func createJob(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "通讯录同步任务只能从问答运营的管理员入口创建"})
return
}
// 保留类型:`library.*` 的准入条件(闸口、精确授权、维护互斥、目标身份)只在专用
// 入口里判断。通用入口只做通用 engineer 角色检查,让它在队列里造一个 library.*
// 作业就等于绕过全部准入——worker 拿到没有业务行的作业仍会去取维护锁(F14)。
// 这里按前缀整类拒绝,而不是逐个类型列举:新增 library 作业类型时不会漏。
if governance.IsReservedLibraryJobType(input.Type) {
writeJSON(w, http.StatusBadRequest, map[string]string{
"error": "整库发布相关作业只能从发布管理专用入口创建"})
return
}
if strings.TrimSpace(input.Type) == "" || len(input.Type) > 100 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "type is required and must not exceed 100 characters"})
return