fix(library): 收口 B1-R1/B2-R1/B5-R1 并让恢复链经过正式队列终态

B1-R1: 演练写集改为受限 restore-drill(V2 信封/contract 1/schema 摘要,零对象、零索引、零本地映射,来源身份必填)。B2-R1: verify 作业先建不可变 operation 并携带 operation_id,同 job recover 的网关 claim 同时携带原 operation 与 recovery 身份。B5-R1: 前端按 scope 世代与动作序号丢弃迟到响应,不污染新 scope 或父级旧回调。harness 的 recovery 改由生产 jobs.Worker.RunOnce 消费并读回 jobs 终态;原失败窗口作业保持 failed,不改写历史。
This commit is contained in:
姚章浩
2026-11-03 13:02:42 +08:00
parent f9457fab52
commit b4add6c9b0
12 changed files with 1515 additions and 18 deletions
+15
View File
@@ -1,5 +1,20 @@
# Changelog
## 开发快照(B1-R1 / B2-R1 / B5-R1 真实链收口)
### Fixed
- **B1-R1 受限演练恢复计划**:写集合新增 `restore-drill` 种类——共享 V2 信封、contract 1 与 schema 摘要,
对象/索引/本地 ID 映射必须为空,来源 tenant/KB 必填;任一项非空即拒绝,旧执行器不能把它当发布计划
接管。恢复演练入口 `RestoreDrill` 与对象网关签发的零对象计划使用同一 attempt/写前镜像身份。
- **B2-R1 verify 作业的不可变 operation**:`POST /api/v1/library/verifications` 在创建作业前先建
operation(`ensureLibraryIntent`),作业携带 `operation_id` 与稳定幂等键;同一幂等键对应不同请求返回
409。worker owned attempt 与同 job recover 的网关 claim 都按原 operation + recovery job/operation
核验,缺 operation 的 verify 作业在真实恢复中 fail closed。
- **B5-R1 迟到响应不得污染新 scope**:恢复验证面板按 scope 世代 + 动作序号判定在飞动作;切 scope 即作废
旧 POST/回调,迟到响应不能改写新 scope 观测、不能触发父级旧 job 回调、不能清掉新动作的 pending。
新增真实挂载反例用例覆盖旧 internal POST 晚到的场景。
## 开发快照(GPT-6 正常 UI 发布审核 B1–B5 修复)
### Fixed
File diff suppressed because it is too large Load Diff
+16 -2
View File
@@ -97,11 +97,25 @@ func libraryVerifyEnqueue(w http.ResponseWriter, r *http.Request, config Config)
return
}
now := time.Now().UTC()
// 验证作业必须有和同步/恢复同一套不可变 operation:worker 的 owned attempt 从
// job.operation_id 取身份,恢复派发闸口和对象网关都按它核验。没有 operation 的
// verify 作业在真实恢复时会被 fail closed(审核 B2-R1)。
intent, intentErr := ensureLibraryIntent(r.Context(), store, request.Scope, governance.LibraryJobVerify,
"", digest, identity.Username, "", now)
if intentErr != nil {
if isIntentConflict(intentErr) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_verify_conflict",
"error": "同一幂等键对应了不同的请求"})
return
}
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library verify operation"})
return
}
job, reused, err := store.CreateLibraryDispatch(r.Context(), governance.LibraryJob{
ID: fmt.Sprintf("libverify-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope,
Kind: governance.LibraryJobVerify,
IdempotencyKey: "library.verify:" + request.Scope + ":" + now.Format("20060102T150405.000000000"),
RequestDigest: digest, Actor: identity.Username,
IdempotencyKey: intent.JobKey,
RequestDigest: digest, OperationID: intent.Operation.ID, Actor: identity.Username,
}, governance.VerifyStages(), false, now)
if errors.Is(err, governance.ErrLibraryJobActive) {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_write_active",
+8
View File
@@ -99,6 +99,14 @@ func TestLibraryVerifyEnqueuesVerifyJobWithCanaryStages(t *testing.T) {
if !strings.HasPrefix(store.lastJob.ID, "libverify-internal-") {
t.Fatalf("job id=%q", store.lastJob.ID)
}
// B2-R1:verify 作业必须带不可变 operation,worker 的 owned attempt / 恢复派发
// 身份都从它取;没有 operation 的作业在真实恢复时会被 fail closed。
if store.lastJob.OperationID == "" || store.lastJob.OperationID != store.lastOperation.ID {
t.Fatalf("verify job must carry its operation: job=%#v op=%#v", store.lastJob, store.lastOperation)
}
if store.lastOperation.Kind != governance.LibraryJobVerify || store.lastOperation.Scope != "internal" {
t.Fatalf("verify operation identity=%#v", store.lastOperation)
}
// 阶段必须包含 canary:没有"写 canary 证明校验有效"这一步,验证就只是自证。
want := governance.VerifyStages()
if len(want) != 5 || want[2] != "canary" || want[3] != "restore" || want[4] != "finalize" {
+29
View File
@@ -19,6 +19,12 @@ const WriteSetVersion = 1
// MigrationWriteSetVersion rejects reinterpretation by old V1 executors.
const MigrationWriteSetVersion = 2
// WriteSetKindRestoreDrill marks a write set that authorizes only a recovery
// drill: canary rows plus a zero-object/zero-index execution plan. It shares
// the V2 envelope so the object gateway controller can verify it, but it is
// never a publish plan and must not be adopted as one.
const WriteSetKindRestoreDrill = "restore-drill"
// WriteSetRow 是台账里的一行:本次发布明确要写的精确身份 + 写前状态。
//
// 为什么需要"写前状态":恢复不能在目标里按"没人引用"推断残渣。历史孤儿资源、
@@ -89,6 +95,10 @@ type LocalIDMapping struct {
}
type WriteSet struct {
// Kind 区分发布执行计划与受限演练恢复计划。空值 = 历史发布计划。
// 演练计划必须显式为 restore-drill:它只授权 canary 回放,不含对象/索引
// 写项,读取方不能把它当发布计划接管。
Kind string `json:"kind,omitempty"`
Index []IndexWrite `json:"index,omitempty"`
Objects []ObjectWrite `json:"objects,omitempty"`
SchemaDigest string `json:"schema_digest,omitempty"`
@@ -218,6 +228,22 @@ func (w *WriteSet) Verify() error {
if w.Version != WriteSetVersion && w.Version != MigrationWriteSetVersion {
return fmt.Errorf("写集合记录版本 %d 不受支持(当前 %d)", w.Version, WriteSetVersion)
}
if w.Kind != "" && w.Kind != WriteSetKindRestoreDrill {
return fmt.Errorf("写集合记录种类 %q 不受支持", w.Kind)
}
if w.Kind == WriteSetKindRestoreDrill {
// 演练恢复计划只回放写前镜像:不新建对象、不按发布计划改索引、不做本地 ID 映射。
// 任何一项非空都说明它被当成发布计划构造/改写过,拒绝。
if w.Version != MigrationWriteSetVersion || w.ContractVersion != 1 || len(w.SchemaDigest) != 64 {
return errors.New("演练恢复计划缺少可执行契约(V2 + contract 1 + schema 摘要)")
}
if len(w.Objects) != 0 || len(w.Index) != 0 || len(w.LocalIDs) != 0 {
return errors.New("演练恢复计划不得包含对象/索引/本地映射写项")
}
if w.SourceTenantID == 0 || w.SourceKnowledgeBaseID == "" {
return errors.New("演练恢复计划缺少来源身份")
}
}
if w.JobID == "" || w.BackupSnapshotID == "" || w.TargetSnapshotID == "" {
return errors.New("写集合记录缺少作业/预备份/快照绑定")
}
@@ -248,6 +274,9 @@ func (w *WriteSet) Verify() error {
return nil
}
// IsRestoreDrill 表示这是一份受限演练恢复计划,而不是发布执行计划。
func (w WriteSet) IsRestoreDrill() bool { return w.Kind == WriteSetKindRestoreDrill }
// CreatedIDs 返回"本次新建"的精确身份(写前不存在的行)。恢复只允许删这些。
func (w WriteSet) CreatedIDs(table string) []string {
ids := make([]string, 0, 8)
+4 -4
View File
@@ -23,7 +23,7 @@ func TestCanaryPersistsAndRegistersEvidenceBeforeWrite(t *testing.T) {
root := t.TempDir()
ledger := drillLedger()
registered, marked, written := false, false, false
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id",
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", nil,
func(context.Context) error {
if !registered {
t.Fatal("risk marker preceded durable registration")
@@ -67,7 +67,7 @@ func TestCanaryNeverWritesWithoutDurableLedger(t *testing.T) {
}
ledger := drillLedger()
marked, written := false, false
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id",
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", nil,
func(context.Context) error { marked = true; return nil },
func(context.Context) error { marked = true; return nil },
func(context.Context) error { written = true; return nil })
@@ -80,7 +80,7 @@ func TestCanaryNeverWritesWithoutDurableLedger(t *testing.T) {
func TestCanaryNeverWritesWhenRegistrationFails(t *testing.T) {
ledger := drillLedger()
marked, written := false, false
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id",
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id", nil,
func(context.Context) error { marked = true; return nil },
func(context.Context) error { return errors.New("governance registration unavailable") },
func(context.Context) error { written = true; return nil })
@@ -92,7 +92,7 @@ func TestCanaryNeverWritesWhenRegistrationFails(t *testing.T) {
func TestCanaryNeverWritesWhenRiskMarkerFails(t *testing.T) {
ledger := drillLedger()
written := false
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id",
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id", nil,
func(context.Context) error { return errors.New("journal unavailable") },
func(context.Context) error { return nil },
func(context.Context) error { written = true; return nil })
+11
View File
@@ -252,6 +252,11 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, opts
report.Canary = canary
progress.report("canary", "running", "写入一个隔离 canary,验证校验能发现差异")
if err := writeDrillCanary(ctx, config.LibraryArchiveRoot, &ledger, canary,
func(set *libraryrelease.WriteSet) error {
// 计划必须在 Seal/落盘/登记之前定型:对象网关控制器按登记摘要加载,
// 这里补 V2 信封、目标 schema、来源身份与当前 owned attempt 绑定。
return target.PrepareDrillPlan(ctx, set)
},
func(ctx context.Context) error {
if err := window.MarkContentRisk(ctx); err != nil {
return err
@@ -397,8 +402,14 @@ func ledgerClone(set *libraryrelease.WriteSet) *libraryrelease.WriteSet {
// writeDrillCanary 是"写入前先留痕"的唯一实现:seal → 落盘 → 登记 → 标风险 → 写。
// 任何一步失败都不写目标;登记在标风险之前,恢复入口才拿得到这份写集合。
func writeDrillCanary(ctx context.Context, root string, ledger *libraryrelease.WriteSet, id string,
prepare func(*libraryrelease.WriteSet) error,
mark func(context.Context) error, record func(context.Context) error, write func(context.Context) error) error {
ledger.Rows = append(ledger.Rows, libraryrelease.WriteSetRow{Table: "knowledge_tags", ID: id, Existing: false})
if prepare != nil {
if err := prepare(ledger); err != nil {
return err
}
}
if err := ledger.Seal(); err != nil {
return err
}
@@ -53,6 +53,12 @@ func ObjectGatewayPlan(set libraryrelease.WriteSet) (objectgateway.Plan, error)
func gatewayCreateOperation(plan, owner string) string {
return objectgateway.Digest([]byte(plan + "\x00" + owner + "\x00create"))
}
// OwnedAttemptClaim 暴露本装配冻结的 attempt claim:受限演练计划/回放必须与它一致。
func (s *GatewayObjectStore) OwnedAttemptClaim() (objectgateway.Claim, bool) {
return s.Claim, s.Automatic
}
func (s *GatewayObjectStore) BindObjectPlan(set libraryrelease.WriteSet) error {
if !validLowerSHA256(set.Digest) || set.JobID == "" {
return errors.New("gateway frozen plan identity missing")
@@ -19,6 +19,7 @@ import (
"knowledge-governance/internal/libraryrelease"
"knowledge-governance/internal/librarysnapshot"
"knowledge-governance/internal/objectgateway"
"knowledge-governance/internal/testbarrier"
)
@@ -116,6 +117,9 @@ type ProductionLibraryTarget struct {
preserveChunkSequence bool
activePlan *libraryrelease.WriteSet
activeSnapshot string
// drillRestore 表示 activePlan 是受限演练恢复计划:索引按写前镜像重建,
// 对象只做只读字节核对(计划本身零对象写项)。发布恢复永不为 true。
drillRestore bool
// restoreScope / restoreSourceSnapshot / restoreBackupSnapshot 在 Restore 进入时
// 从**原持久锚点**冻结:scope 来自真实装配,来源快照与写前镜像来自本次 WriteSet
// 与原 backup 引用。它们不能由调用方在恢复中途改写,也不允许同一个快照既当
@@ -681,7 +685,7 @@ WHERE tenant_id=$1 AND id = ANY($2::text[])`, t.scope.TenantID, ids)
}
func (t *ProductionLibraryTarget) importIndex(ctx context.Context, archive *librarysnapshot.Archive, manifest librarysnapshot.Manifest) error {
if t.activePlan != nil {
if t.activePlan != nil && !t.drillRestore {
if t.preserveChunkSequence {
return t.restorePlannedIndex(ctx)
}
@@ -927,6 +931,10 @@ func (t *ProductionLibraryTarget) AdoptWriteSet(set libraryrelease.WriteSet) err
if err := set.Verify(); err != nil {
return fmt.Errorf("写集合记录校验失败:%w", err)
}
if set.IsRestoreDrill() {
// 演练计划只描述 canary 回放,不是发布执行计划;发布恢复入口不得消费它。
return errors.New("演练恢复计划不能作为发布执行计划接管")
}
if set.TenantID != t.scope.TenantID || set.KnowledgeBaseID != t.scope.KnowledgeBaseID {
return fmt.Errorf("写集合绑定的是 %d/%s,与目标 %d/%s 不一致",
set.TenantID, set.KnowledgeBaseID, t.scope.TenantID, t.scope.KnowledgeBaseID)
@@ -983,6 +991,89 @@ func ValidateDrillWriteSet(set libraryrelease.WriteSet) error {
return nil
}
// PrepareDrillPlan 把演练台账升级为**受限可执行计划**:V2 执行信封 + 目标 schema
// 摘要 + 真实来源身份 + 当前 owned attempt 绑定,但对象/索引/本地映射写项必须为空。
//
// 为什么必须在这里而不是在 Apply 里临时补:对象网关控制器只认治理库里
// production_prebackup 证据登记的 writeset_digest;计划必须在 Seal/落盘/登记之前
// 定型,否则控制器加载到的摘要是另一份形状。它只增加受限语义,不放宽任何发布校验。
func (t *ProductionLibraryTarget) PrepareDrillPlan(ctx context.Context, set *libraryrelease.WriteSet) error {
if set == nil || set.JobID == "" {
return errors.New("演练恢复计划缺少作业身份")
}
if set.TenantID != t.scope.TenantID || set.KnowledgeBaseID != t.scope.KnowledgeBaseID {
return fmt.Errorf("演练恢复计划绑定的是 %d/%s,与目标 %d/%s 不一致",
set.TenantID, set.KnowledgeBaseID, t.scope.TenantID, t.scope.KnowledgeBaseID)
}
if err := set.ValidateRestoreBinding(set.BackupSnapshotID, t.scope.TenantID, t.scope.KnowledgeBaseID); err != nil {
return err
}
archive, err := librarysnapshot.Open(t.config.ArchiveRoot, 256*1024*1024)
if err != nil {
return errors.New("归档不可用")
}
source, err := archive.Load(set.TargetSnapshotID)
archive.Close()
if err != nil {
return errors.New("演练来源快照不可读")
}
if source.TenantID != t.scope.TenantID || source.KnowledgeBaseID != t.scope.KnowledgeBaseID {
return errors.New("演练来源快照不属于当前目标范围")
}
_, schemaDigest, err := t.migrationCatalog(ctx)
if err != nil {
return err
}
// 先清空任何发布写项:演练计划只允许 canary 行。
set.Kind = libraryrelease.WriteSetKindRestoreDrill
set.Version = libraryrelease.MigrationWriteSetVersion
set.ContractVersion = migrationIdentityContractVersion
set.SourceTenantID, set.SourceKnowledgeBaseID = source.TenantID, source.KnowledgeBaseID
set.SchemaDigest = schemaDigest
set.Index, set.Objects, set.LocalIDs = nil, nil, nil
// 自动对象网关没有静态 grant:计划签发必须绑定当前 owned attempt,
// 网关控制器会再按治理库核一次(不靠调用方自证)。
if claim, automatic := t.ownedAttempt(); automatic {
return validateDrillAttempt(claim, set.JobID)
}
return nil
}
// ownedAttempt 返回本目标装配时冻结的对象网关 claim。只有 Automatic 网关需要它。
func (t *ProductionLibraryTarget) ownedAttempt() (objectgateway.Claim, bool) {
if provider, ok := t.config.Objects.(interface {
OwnedAttemptClaim() (objectgateway.Claim, bool)
}); ok {
return provider.OwnedAttemptClaim()
}
return objectgateway.Claim{}, false
}
// validateDrillAttempt 要求计划/回放绑定一个真实的作业代次,而不是调用方编造的身份。
func validateDrillAttempt(claim objectgateway.Claim, jobID string) error {
if claim.JobID == "" || claim.JobID != jobID || claim.OperationID == "" || claim.Owner == "" || claim.AttemptEpoch < 1 {
return errors.New("演练恢复缺少当前 owned attempt 身份(job/operation/owner/epoch)")
}
return nil
}
// validateDrillDispatch 证明这次演练的派发身份来自原窗口的真实 attempt 与恢复投递,
// 不是把 gate 置 nil 绕过 DS01。
func (t *ProductionLibraryTarget) validateDrillDispatch(claim objectgateway.Claim, automatic bool) error {
config := t.config
if config.RestoreTargetIdentity == "" || config.RestoreScope == "" || config.RestoreInstance == "" ||
config.RestoreOperationID == "" || config.RestoreWindowJobID == "" || config.RestoreAttemptOwner == "" ||
config.RestoreAttemptEpoch < 1 || config.RestoreRecoveryJobID == "" || config.RestoreRecoveryOperationID == "" {
return errors.New("演练恢复缺少完整的派发身份(目标/scope/实例/原 operation/窗口/attempt/恢复作业)")
}
if automatic && (claim.JobID != config.RestoreWindowJobID || claim.OperationID != config.RestoreOperationID ||
claim.Owner != config.RestoreAttemptOwner || claim.AttemptEpoch != config.RestoreAttemptEpoch ||
claim.RecoveryJobID != config.RestoreRecoveryJobID || claim.RecoveryOperationID != config.RestoreRecoveryOperationID) {
return errors.New("演练恢复的派发身份与当前 owned attempt 不一致")
}
return nil
}
// RestoreDrill 是恢复演练**限定范围**的安全恢复入口。
//
// 为什么不是直接调用 Restore:Restore 的写集合是"发布执行计划"(v2 合同 + 索引/对象/
@@ -990,7 +1081,10 @@ func ValidateDrillWriteSet(set libraryrelease.WriteSet) error {
// 一份从未发生过的发布。这里保留同一份 DS01 身份合同(来源快照 ≠ 写前镜像、同一作业/
// 目标/预备份)与同一批 Apply 原语:四个阶段都按写前镜像**整段回放**(先清 scope 再
// 插入归档行),不是"只删 canary";回放后再用整实例指纹证明目标与预备份一致。
// 有派发闸口的目标不走这条入口:那条路径必须有过派发证据的恢复计划。
//
// 自动对象网关保持启用:演练计划显式零对象写项,仍由控制器按当前 attempt/job/目标/
// 写前镜像签发零写入许可;对象阶段只做只读字节核对,任何创建/删除都会被网关拒绝。
// 有派发闸口的目标也不再把 gate 置 nil:必须携带原窗口 attempt + 恢复投递身份。
func (t *ProductionLibraryTarget) RestoreDrill(ctx context.Context, backup libraryrelease.BackupRef) error {
if backup.SnapshotID == "" {
return errors.New("恢复需要绑定的预备份快照")
@@ -1007,8 +1101,43 @@ func (t *ProductionLibraryTarget) RestoreDrill(ctx context.Context, backup libra
if err := ValidateDrillWriteSet(*backup.WriteSet); err != nil {
return err
}
if !backup.WriteSet.IsRestoreDrill() {
return errors.New("演练恢复只接受受限恢复计划(restore-drill),拒绝发布执行计划")
}
claim, automatic := t.ownedAttempt()
if automatic {
if err := validateDrillAttempt(claim, backup.WriteSet.JobID); err != nil {
return err
}
}
if t.config.RestoreDispatch != nil {
return errors.New("目标配置了恢复派发闸口:演练不能用绕过派发证据的回放入口")
if backup.WriteSet.Target != t.config.RestoreScope {
return fmt.Errorf("演练恢复计划 scope=%s,与派发身份 scope=%s 不一致",
backup.WriteSet.Target, t.config.RestoreScope)
}
if err := t.validateDrillDispatch(claim, automatic); err != nil {
return err
}
}
// 对象网关:冻结零对象计划。控制器仍按治理库核 attempt/job/目标/写前镜像;
// 没有冻结计划时 EnsureObjectGrant 会继续 fail closed。
if binder, ok := t.config.Objects.(interface {
BindObjectPlan(libraryrelease.WriteSet) error
}); ok {
if err := binder.BindObjectPlan(*backup.WriteSet); err != nil {
return err
}
}
adopted := *backup.WriteSet
adopted.Rows = append([]libraryrelease.WriteSetRow(nil), backup.WriteSet.Rows...)
t.activePlan = &adopted
t.drillRestore = true
// DS01 准入必须在任何 PG/对象/索引写之前:原窗口若还有未决派发记录,
// 即使计划是零对象也要 held。
if t.config.RestoreDispatch != nil {
if err := t.admitRestorePlan(ctx); err != nil {
return err
}
}
// 幂等:恢复收尾可能重放(上次恢复到一半崩溃)。这里不要求"目标当前仍与镜像不同"——
// "写确实发生"由发起方在写入后的 drift 校验证明,而不是由重放入口猜。
@@ -1020,6 +1149,16 @@ func (t *ProductionLibraryTarget) RestoreDrill(ctx context.Context, backup libra
return fmt.Errorf("演练恢复阶段 %s 失败: %w", stage, err)
}
}
// canary 是这次演练唯一新建的行:回放后必须精确消失(不是"整库看起来差不多")。
for _, id := range backup.WriteSet.CreatedIDs("knowledge_tags") {
var exists bool
if err := t.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM knowledge_tags WHERE id=$1)`, id).Scan(&exists); err != nil {
return fmt.Errorf("读取演练 canary 残留失败: %w", err)
}
if exists {
return fmt.Errorf("演练恢复后 canary %s 仍在目标中", id)
}
}
after, err := universeFingerprint(ctx, t.pool)
if err != nil {
return fmt.Errorf("演练恢复后读取整库指纹失败: %w", err)
@@ -1045,6 +1184,9 @@ func (t *ProductionLibraryTarget) Restore(ctx context.Context, backup libraryrel
if err := backup.WriteSet.Verify(); err != nil {
return fmt.Errorf("写集合记录校验失败,拒绝恢复:%w", err)
}
if backup.WriteSet.IsRestoreDrill() {
return errors.New("演练恢复计划不能走发布恢复入口:请使用同作业的恢复演练路径")
}
// 身份合同与演练共用同一份判定(libraryrelease.WriteSet.ValidateRestoreBinding):
// 来源快照 ≠ 写前镜像、同一预备份、同一 tenant/KB,缺一不可。
if err := backup.WriteSet.ValidateRestoreBinding(backup.SnapshotID, t.scope.TenantID, t.scope.KnowledgeBaseID); err != nil {
+2 -1
View File
@@ -430,6 +430,7 @@
"reason": "真实隔离PG/ES/MinIO;验证mapping哈希不变和成功后无暂态marker,默认CI无这些服务"
},
{"package":"knowledge-governance/internal/releaseadapter/v071","test":"TestCandidateEmptyTargetFixture","reason":"需显式一次性本机PG/ES/MinIO与运行器注入的隔离库/归档根:为候选页面装配并封存独立 fullshape 测试来源、证空目标、登记 test_sealed;普通CI跳过不是通过"},
{"package":"knowledge-governance/internal/releaseadapter/v071","test":"TestCandidateAttestation","reason":"需运行器注入一次性 ed25519 种子与四份真实证据摘要:续签 object-gateway 审计(有效期上限1h);普通CI没有注入,跳过不是通过"}
{"package":"knowledge-governance/internal/releaseadapter/v071","test":"TestCandidateAttestation","reason":"需运行器注入一次性 ed25519 种子与四份真实证据摘要:续签 object-gateway 审计(有效期上限1h);普通CI没有注入,跳过不是通过"},
{"package":"knowledge-governance/cmd/worker","test":"TestThreeBlockersVerifyChain","reason":"需外置 runner 创建的一次性隔离 PG/ES/MinIO 加真实入口/网关容器与 Automatic+DS01 授权:完整 verify 与同 job recover 纵向链;普通CI没有这些资源,跳过不是通过"}
]
}
@@ -158,6 +158,47 @@ describe('RestoreVerificationSection mounted (offline fixtures)', () => {
expect(onComplete).toHaveBeenCalledWith('libverify-internal-1')
})
it('切 scope 后迟到的旧 POST 不能污染新目标或触发父级旧作业回调', async () => {
const onAccepted = vi.fn()
const onComplete = vi.fn()
let resolvePost: ((value: unknown) => void) | null = null
vi.stubGlobal('fetch', async (url: string, init?: { method?: string }) => {
if (init?.method === 'POST') {
return new Promise((resolve) => {
resolvePost = resolve
})
}
return jsonResponse(String(url).includes('scope=external') ? externalView : internalView)
})
await act(async () => {
root.render(
<RestoreVerificationSection scope="internal" isAdmin onAccepted={onAccepted} onComplete={onComplete} />
)
})
// 旧 internal POST 挂起时切到 external:external 的真实观测已经完成。
await act(async () => {
;[...container.querySelectorAll('button')].find((item) => item.textContent?.includes('跑一次恢复验证'))!.click()
})
await act(async () => {
root.render(
<RestoreVerificationSection scope="external" isAdmin onAccepted={onAccepted} onComplete={onComplete} />
)
})
expect(container.textContent).toContain('fixture-external')
expect(container.textContent).not.toContain('已验证(当前目标)')
expect(container.textContent).not.toContain('old-internal-job')
// 放行旧 internal POST:它的 then/onAccepted/reload 必须全部失效。
await act(async () => {
resolvePost?.(jsonResponse({ job: { id: 'verify-internal-new', scope: 'internal' }, reused: false }, 202))
})
expect(container.textContent).toContain('fixture-external')
expect(container.textContent).not.toContain('已验证(当前目标)')
expect(container.textContent).not.toContain('old-internal-job')
expect(container.textContent).not.toContain('verify-internal-new')
expect(onAccepted).not.toHaveBeenCalled()
expect(onComplete).not.toHaveBeenCalled()
})
it('HTTP 失败按失败显示,不把响应当通过证据', async () => {
vi.stubGlobal('fetch', async () =>
jsonResponse({ scope: 'internal', verified: true, reason: '证据读取失败', target, history: [] }, 503)
+36 -8
View File
@@ -112,8 +112,15 @@ export function RestoreVerificationSection({
const mounted = useRef(true)
const generation = useRef(0)
const viewScopeRef = useRef('')
// scopeRef 是"当前渲染的 scope":异步回调必须同时核对 scope 与世代,
// 只比 GET generation 会被迟到的旧 POST 重新递增而失效(审核 B5-R1)。
const scopeRef = useRef(scope)
const scopeEpoch = useRef(0)
const actionSeq = useRef(0)
const acceptedJob = useRef('')
const sawRunning = useRef(false)
const onAcceptedRef = useRef(onAccepted)
onAcceptedRef.current = onAccepted
const onCompleteRef = useRef(onComplete)
onCompleteRef.current = onComplete
@@ -122,7 +129,7 @@ export function RestoreVerificationSection({
return fetchLibraryVerification(targetScope, signal)
.then((next) => {
// 晚到的旧 scope/旧代次响应一律丢弃:它不能改写当前 scope 的观测。
if (!mounted.current || request !== generation.current) return
if (!mounted.current || request !== generation.current || targetScope !== scopeRef.current) return
setView(next)
viewScopeRef.current = next.scope
setStale(false)
@@ -141,7 +148,7 @@ export function RestoreVerificationSection({
}
})
.catch((err: unknown) => {
if (!mounted.current || request !== generation.current) return
if (!mounted.current || request !== generation.current || targetScope !== scopeRef.current) return
if ((err as Error)?.name === 'AbortError') return
// 刷新失败:同 scope 的旧结果保留但明确标成过期;别的 scope 的旧结果直接丢掉。
setStale(true)
@@ -152,6 +159,11 @@ export function RestoreVerificationSection({
useEffect(() => {
mounted.current = true
scopeRef.current = scope
// 切 scope 使所有在飞动作失效:旧 scope 的 POST/回调不能写回新目标。
scopeEpoch.current += 1
actionSeq.current = 0
setPending(false)
// 切 scope:旧 scope 的证据不能继续显示为"当前目标已验证"。
setView(null)
viewScopeRef.current = ''
@@ -173,21 +185,37 @@ export function RestoreVerificationSection({
}, [scope])
const onRun = useCallback(() => {
const actionScope = scope
const actionEpoch = scopeEpoch.current
const action = ++actionSeq.current
// 动作仍然有效 = 组件挂着 + 还是同一个 scope 世代 + 仍是最新一次点击。
const current = () =>
mounted.current &&
scopeEpoch.current === actionEpoch &&
scopeRef.current === actionScope &&
actionSeq.current === action
setPending(true)
setError(null)
setNotice('')
enqueueLibraryVerification(scope)
enqueueLibraryVerification(actionScope)
.then((accepted) => {
if (!current() || accepted.scope !== actionScope) return
acceptedJob.current = accepted.job_id
sawRunning.current = false
setNotice(`已投递恢复验证作业 ${accepted.job_id};页面会自动刷新进度与终态,父级作业/维护/闸口同步更新。`)
// 父页面必须立刻知道"有一个验证在跑":否则它不会轮询 overview/维护。
onAccepted?.(accepted.job_id)
void reload(scope)
onAcceptedRef.current?.(accepted.job_id)
void reload(actionScope)
})
.catch((err: unknown) => setError(err instanceof Error ? err.message : '投递恢复验证失败'))
.finally(() => setPending(false))
}, [scope, reload, onAccepted])
.catch((err: unknown) => {
if (!current()) return
setError(err instanceof Error ? err.message : '投递恢复验证失败')
})
.finally(() => {
// 旧动作的 finally 不能清掉新 scope 新动作的 pending。
if (current()) setPending(false)
})
}, [scope, reload])
return (
<RestoreVerificationView