B1/B2:演练在同一维护切点做两次真实捕获(写前镜像与来源身份), 写集合在写第一笔之前落盘并登记;恢复走限定范围的 RestoreDrill, 复用同一份 DS01 身份合同与 Apply 原语整段回放,不再让同快照必被拒绝。 worker 接治理维护生命周期(实例+scope 行、真实入口状态、成功才释放), held 保留行并由同 job 的 library.recover 收口(kind 过滤贯通 verify)。 B3:证据优先,failed/invalid 与读取错误即使 env=true 也拒绝。 B4/B5:GET 投影在飞作业,子面板回调父页面轮询;观测绑定 scope 与代次, 刷新失败明确过期,不再显示旧的"已验证"。 迁移 79 不自动 down;未部署、未调用业务目标。
This commit is contained in:
@@ -3,37 +3,60 @@ package libraryverify
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
)
|
||||
|
||||
func TestCanaryPersistsRecoveryEvidenceBeforeWrite(t *testing.T) {
|
||||
func drillLedger() libraryrelease.WriteSet {
|
||||
return libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb",
|
||||
BackupSnapshotID: "backup", TargetSnapshotID: "source", CreatedAt: time.Now().UTC(),
|
||||
Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
}
|
||||
|
||||
// 写集合必须先落盘并登记,再标记内容风险,最后才写目标:
|
||||
// 顺序颠倒会让恢复入口在"已经写过"时读不到 ledger。
|
||||
func TestCanaryPersistsAndRegistersEvidenceBeforeWrite(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
marked := false
|
||||
written := false
|
||||
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", func(context.Context) error { marked = true; return nil }, func(context.Context) error {
|
||||
if !marked {
|
||||
t.Fatal("write preceded risk marker")
|
||||
}
|
||||
if len(ledger.CreatedIDs("knowledge_tags")) != 1 {
|
||||
t.Fatal("canary absent from write set")
|
||||
}
|
||||
matches, e := filepath.Glob(filepath.Join(root, "writesets", "*.json"))
|
||||
if e != nil || len(matches) != 1 {
|
||||
t.Fatalf("durable ledger missing: %v %v", matches, e)
|
||||
}
|
||||
if _, e := os.Stat(matches[0]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
written = true
|
||||
return nil
|
||||
})
|
||||
if err != nil || !written {
|
||||
t.Fatalf("err=%v written=%v", err, written)
|
||||
ledger := drillLedger()
|
||||
registered, marked, written := false, false, false
|
||||
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id",
|
||||
func(context.Context) error {
|
||||
if !registered {
|
||||
t.Fatal("risk marker preceded durable registration")
|
||||
}
|
||||
marked = true
|
||||
return nil
|
||||
},
|
||||
func(_ context.Context) error {
|
||||
if len(ledger.CreatedIDs("knowledge_tags")) != 1 {
|
||||
t.Fatal("canary absent from write set")
|
||||
}
|
||||
if ledger.Digest == "" {
|
||||
t.Fatal("write set was not sealed before registration")
|
||||
}
|
||||
matches, e := filepath.Glob(filepath.Join(root, "writesets", "*.json"))
|
||||
if e != nil || len(matches) != 1 {
|
||||
t.Fatalf("durable ledger missing: %v %v", matches, e)
|
||||
}
|
||||
if _, e := os.Stat(matches[0]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
registered = true
|
||||
return nil
|
||||
},
|
||||
func(context.Context) error {
|
||||
if !registered || !marked {
|
||||
t.Fatal("write preceded registration/risk marker")
|
||||
}
|
||||
written = true
|
||||
return nil
|
||||
})
|
||||
if err != nil || !written || !registered {
|
||||
t.Fatalf("err=%v written=%v registered=%v", err, written, registered)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,18 +65,37 @@ func TestCanaryNeverWritesWithoutDurableLedger(t *testing.T) {
|
||||
if err := os.WriteFile(root, []byte("not a directory"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
ledger := drillLedger()
|
||||
marked, written := false, false
|
||||
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id", func(context.Context) error { marked = true; return nil }, func(context.Context) error { written = true; return nil })
|
||||
err := writeDrillCanary(context.Background(), root, &ledger, "canary-id",
|
||||
func(context.Context) error { marked = true; return nil },
|
||||
func(context.Context) error { marked = true; return nil },
|
||||
func(context.Context) error { written = true; return nil })
|
||||
if err == nil || marked || written {
|
||||
t.Fatalf("err=%v marked=%v written=%v", err, marked, written)
|
||||
}
|
||||
}
|
||||
|
||||
// 登记失败 = 恢复入口读不到写集合:此时一笔都不许写。
|
||||
func TestCanaryNeverWritesWhenRegistrationFails(t *testing.T) {
|
||||
ledger := drillLedger()
|
||||
marked, written := false, false
|
||||
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id",
|
||||
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 })
|
||||
if err == nil || marked || written {
|
||||
t.Fatalf("err=%v marked=%v written=%v", err, marked, written)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanaryNeverWritesWhenRiskMarkerFails(t *testing.T) {
|
||||
ledger := libraryrelease.WriteSet{Version: 1, JobID: "drill", Target: "internal", TenantID: 10000, KnowledgeBaseID: "kb", BackupSnapshotID: "backup", TargetSnapshotID: "backup", CreatedAt: time.Now().UTC(), Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
ledger := drillLedger()
|
||||
written := false
|
||||
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id", func(context.Context) error { return errors.New("journal unavailable") }, func(context.Context) error { written = true; return nil })
|
||||
err := writeDrillCanary(context.Background(), t.TempDir(), &ledger, "canary-id",
|
||||
func(context.Context) error { return errors.New("journal unavailable") },
|
||||
func(context.Context) error { return nil },
|
||||
func(context.Context) error { written = true; return nil })
|
||||
if err == nil || written {
|
||||
t.Fatalf("err=%v written=%v", err, written)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package libraryverify
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"knowledge-governance/internal/libraryrelease"
|
||||
v071 "knowledge-governance/internal/releaseadapter/v071"
|
||||
)
|
||||
|
||||
// B1 的定向回归:共享 Run 用 PlanWrite 产出的写前/来源身份与写集合,
|
||||
// 必须通过真实恢复入口调用的**同一份**身份合同;用同一份快照冒充两个身份
|
||||
// 的旧形状必须被拒绝。这里不连接任何业务目标(隔离 fixture)。
|
||||
func TestSharedDrillPlanPassesRealRestoreIdentityContract(t *testing.T) {
|
||||
preimage := libraryrelease.BackupRef{SnapshotID: strings.Repeat("a", 64),
|
||||
Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
source := libraryrelease.BackupRef{SnapshotID: strings.Repeat("b", 64),
|
||||
Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
|
||||
set, err := PlanWrite("libverify-internal-fixture", "internal", 10000, "fixture-kb", preimage, source)
|
||||
if err != nil {
|
||||
t.Fatalf("shared plan rejected: %v", err)
|
||||
}
|
||||
if err := set.Seal(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// ProductionLibraryTarget.Restore 与 RestoreDrill 都在写之前调用这一判定。
|
||||
if err := set.ValidateRestoreBinding(preimage.SnapshotID, 10000, "fixture-kb"); err != nil {
|
||||
t.Fatalf("real restore identity contract rejected the shared plan: %v", err)
|
||||
}
|
||||
// 演练恢复入口的写集合守卫(只允许可归因的 canary 行)也必须接受它。
|
||||
canary := set
|
||||
canary.Rows = append(canary.Rows, libraryrelease.WriteSetRow{Table: "knowledge_tags", ID: "canary-1"})
|
||||
if err := canary.Seal(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := v071.ValidateDrillWriteSet(canary); err != nil {
|
||||
t.Fatalf("drill write set guard rejected the shared plan: %v", err)
|
||||
}
|
||||
|
||||
// 旧缺陷形状:来源快照 = 写前镜像。同一判定必须拒绝。
|
||||
legacy := set
|
||||
legacy.TargetSnapshotID = preimage.SnapshotID
|
||||
legacy.Digest = ""
|
||||
if err := legacy.Seal(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = legacy.ValidateRestoreBinding(preimage.SnapshotID, 10000, "fixture-kb")
|
||||
if err == nil || !strings.Contains(err.Error(), "同一份快照") {
|
||||
t.Fatalf("legacy same-snapshot plan must be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedPlanRejectsSameSnapshotIdentity(t *testing.T) {
|
||||
preimage := libraryrelease.BackupRef{SnapshotID: strings.Repeat("c", 64),
|
||||
Universe: map[string]libraryrelease.TableFingerprint{"knowledge_tags": {Count: 0, Digest: "empty"}}}
|
||||
if _, err := PlanWrite("job", "internal", 10000, "kb", preimage, preimage); err == nil {
|
||||
t.Fatal("plan must refuse to use one snapshot as both source and pre-image")
|
||||
}
|
||||
if _, err := PlanWrite("job", "internal", 10000, "kb", preimage, libraryrelease.BackupRef{}); err == nil {
|
||||
t.Fatal("plan must refuse a missing source identity")
|
||||
}
|
||||
}
|
||||
|
||||
// 演练恢复入口只回放"本次写的隔离 canary 行";任何其它行都不是演练产物。
|
||||
func TestDrillWriteSetGuardRejectsForeignRows(t *testing.T) {
|
||||
set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, Rows: []libraryrelease.WriteSetRow{
|
||||
{Table: "knowledges", ID: "doc-1"},
|
||||
}}
|
||||
if err := v071.ValidateDrillWriteSet(set); err == nil {
|
||||
t.Fatal("drill guard must reject non-canary rows")
|
||||
}
|
||||
set.Rows = []libraryrelease.WriteSetRow{{Table: "knowledge_tags", ID: "tag-1", Existing: true}}
|
||||
if err := v071.ValidateDrillWriteSet(set); err == nil {
|
||||
t.Fatal("drill guard must reject rows that existed before the write")
|
||||
}
|
||||
}
|
||||
@@ -37,21 +37,24 @@ type Verification struct {
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
Status string `json:"status"` // passed | failed | maintenance_held
|
||||
Scope string `json:"scope"`
|
||||
Target string `json:"target"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Project string `json:"project"`
|
||||
Counts map[string]int64 `json:"counts"`
|
||||
BaselineCheck *Verification `json:"baseline_check"`
|
||||
DriftCheck *Verification `json:"drift_check"` // 必须失败:证明确实能发现差异
|
||||
RestoreCheck *Verification `json:"restore_check"`
|
||||
Canary string `json:"canary"`
|
||||
Failure string `json:"failure,omitempty"`
|
||||
Stage string `json:"stage,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt time.Time `json:"finished_at"`
|
||||
Until map[string]string `json:"until,omitempty"`
|
||||
Status string `json:"status"` // passed | failed | maintenance_held
|
||||
Scope string `json:"scope"`
|
||||
Target string `json:"target"`
|
||||
SnapshotID string `json:"snapshot_id"` // 写前镜像:恢复实际回放的那份预备份
|
||||
SourceSnapshot string `json:"source_snapshot_id,omitempty"`
|
||||
WriteSetDigest string `json:"writeset_digest,omitempty"`
|
||||
WindowState string `json:"window_state,omitempty"`
|
||||
Project string `json:"project"`
|
||||
Counts map[string]int64 `json:"counts"`
|
||||
BaselineCheck *Verification `json:"baseline_check"`
|
||||
DriftCheck *Verification `json:"drift_check"` // 必须失败:证明确实能发现差异
|
||||
RestoreCheck *Verification `json:"restore_check"`
|
||||
Canary string `json:"canary"`
|
||||
Failure string `json:"failure,omitempty"`
|
||||
Stage string `json:"stage,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt time.Time `json:"finished_at"`
|
||||
Until map[string]string `json:"until,omitempty"`
|
||||
}
|
||||
|
||||
// Progress 把演练的阶段推进交给调用方(worker 写 library_job_stages,CLI 打日志)。
|
||||
@@ -63,12 +66,46 @@ func (p Progress) report(stage, state, detail string) {
|
||||
}
|
||||
}
|
||||
|
||||
// TargetIdentity 是治理侧维护记录必须钉住的目标事实(与 librarymaintenance.Target 同源)。
|
||||
type TargetIdentity struct {
|
||||
Instance string
|
||||
Fingerprint string
|
||||
Writers []string
|
||||
}
|
||||
|
||||
// Governance 是演练必须持有的**治理侧**维护生命周期:实例/scope 占用、入口真实状态、
|
||||
// 释放。为什么不能让调用方只写磁盘 journal:页面与恢复入口读的是治理行,只写 journal
|
||||
// 时"正在维护"不会出现在 UI,失败后也没有同 job 的恢复锚点(2026-11 审核 B2)。
|
||||
type Governance interface {
|
||||
Acquire(ctx context.Context, jobID, scope string, target TargetIdentity, originalServiceState string) error
|
||||
Ingress(ctx context.Context, jobID, scope, state, note string) error
|
||||
State(ctx context.Context, jobID, scope, state, note string) error
|
||||
Release(ctx context.Context, jobID, scope, note string) error
|
||||
}
|
||||
|
||||
// Ledger 把预备份身份与写集合摘要持久化到**同一个作业**(worker 直接传
|
||||
// libraryStageRecorder:它已经是 BackupObserver + WriteSetObserver)。
|
||||
// 恢复入口按 (scope, job, 写前镜像) 精确读这条记录,所以两件事必须发生在写第一笔之前。
|
||||
type Ledger interface {
|
||||
BackupPrepared(ctx context.Context, backup libraryrelease.BackupRef) error
|
||||
WriteSetPlanned(ctx context.Context, set libraryrelease.WriteSet) error
|
||||
}
|
||||
|
||||
// Options 是演练的可选接线。Governance/Ledger 为 nil 只允许主机侧 CLI 使用:
|
||||
// 页面发起的作业必须两者都在,否则演练结论不会出现在治理记录里。
|
||||
type Options struct {
|
||||
Progress Progress
|
||||
Governance Governance
|
||||
Ledger Ledger
|
||||
}
|
||||
|
||||
// Run 执行一次演练。jobID 同时是维护窗口的持有者标识,必须与业务作业 id 一致,
|
||||
// 否则崩溃恢复时窗口与作业对不上。
|
||||
func Run(ctx context.Context, config appconfig.Config, scope, jobID string, progress Progress) (*Report, error) {
|
||||
func Run(ctx context.Context, config appconfig.Config, scope, jobID string, opts Options) (*Report, error) {
|
||||
if scope != "internal" && scope != "external" {
|
||||
return nil, errors.New("scope must be internal or external")
|
||||
}
|
||||
progress := opts.Progress
|
||||
report := &Report{Status: "failed", Scope: scope, Project: config.LibraryTargetProject,
|
||||
Target: config.LibraryTargetInstance, StartedAt: time.Now().UTC()}
|
||||
fail := func(stage string, cause error, held bool) (*Report, error) {
|
||||
@@ -96,8 +133,25 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
if err := manager.VerifyTopology(ctx); err != nil {
|
||||
return fail("capture", err, false)
|
||||
}
|
||||
originalState, err := manager.OriginalState(ctx)
|
||||
if err != nil {
|
||||
return fail("capture", errors.New("读不到目标写入者的原运行状态,不能开维护窗口:"+err.Error()), false)
|
||||
}
|
||||
identity := manager.Target()
|
||||
// 治理占用必须在任何目标动作之前:拿不到就没有"入口已关/写入者已停"的权威记录,
|
||||
// 失败后也没有可恢复的同 job 锚点。
|
||||
if opts.Governance != nil {
|
||||
targetIdentity := TargetIdentity{Instance: identity.Instance, Fingerprint: identity.Fingerprint, Writers: identity.Writers}
|
||||
if err := opts.Governance.Acquire(ctx, jobID, scope, targetIdentity, originalState); err != nil {
|
||||
return fail("capture", errors.New("目标实例正在维护中或无法登记维护占用:"+err.Error()), false)
|
||||
}
|
||||
}
|
||||
coordinator, control, err := manager.Open(config.LibraryTargetJournalRoot)
|
||||
if err != nil {
|
||||
if opts.Governance != nil {
|
||||
// 还没进窗口、目标未被停用:释放占用是诚实的;释放失败就报告出来。
|
||||
_ = opts.Governance.Release(ctx, jobID, scope, "维护协调器不可用,未进入窗口")
|
||||
}
|
||||
return fail("capture", err, false)
|
||||
}
|
||||
defer control.Close()
|
||||
@@ -105,6 +159,8 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
|
||||
var (
|
||||
snapshotID string
|
||||
sourceID string
|
||||
writesetDigest string
|
||||
counts map[string]int64
|
||||
canary string
|
||||
contentTouched bool
|
||||
@@ -114,13 +170,21 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
)
|
||||
work := func(ctx context.Context, window *libraryfreeze.Window) (string, error) {
|
||||
start := time.Now()
|
||||
// 窗口已关入口、已停写入者并证明排空:此时才敢把 UI 的入口状态写成 closed。
|
||||
if opts.Governance != nil {
|
||||
if err := opts.Governance.Ingress(ctx, jobID, scope, "closed",
|
||||
"恢复验证已关闭目标入口并停止写入者"); err != nil {
|
||||
return "", errors.New("登记入口关闭失败:" + err.Error())
|
||||
}
|
||||
}
|
||||
current, err := target.Current(ctx)
|
||||
if err != nil {
|
||||
return "", errors.New("读取目标当前整库状态失败:" + err.Error())
|
||||
}
|
||||
counts = current.Counts
|
||||
report.Counts = counts
|
||||
// 1) 真预备份(落归档、内容寻址、导出后复核内容未变)。
|
||||
// 1) 写前镜像:真预备份(落归档、内容寻址、导出后复核内容未变)。
|
||||
// 它是恢复阶段实际回放的唯一内容来源。
|
||||
backup, err := backups.Prepare(ctx, "", current)
|
||||
if err != nil {
|
||||
return "", errors.New("捕获目标整库失败:" + err.Error())
|
||||
@@ -130,11 +194,32 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
if err := window.SetBackupSnapshot(ctx, snapshotID); err != nil {
|
||||
return "", errors.New("记录预备份身份失败:" + err.Error())
|
||||
}
|
||||
// 2) 来源身份:DS01 合同要求"来源快照 ≠ 写前镜像",演练不能用同一份快照冒充
|
||||
// 两个身份(真实 Restore 会在任何写之前拒绝)。这里再做一次**真实的**独立捕获,
|
||||
// 只作为这次写入的来源身份;两次捕获都在同一维护切点内、由同一备份存储密封,
|
||||
// 不伪造快照、也不放宽 Restore 的校验。
|
||||
source, err := backups.Prepare(ctx, "", current)
|
||||
if err != nil {
|
||||
return "", errors.New("捕获来源身份失败:" + err.Error())
|
||||
}
|
||||
if source.SnapshotID == "" || source.SnapshotID == snapshotID {
|
||||
return "", errors.New("来源身份与写前镜像相同:拒绝用一份快照冒充两个恢复身份")
|
||||
}
|
||||
sourceID = source.SnapshotID
|
||||
report.SourceSnapshot = sourceID
|
||||
// 预备份引用必须在任何写入之前落进同一个作业:恢复入口按它取写前镜像。
|
||||
if opts.Ledger != nil {
|
||||
if err := opts.Ledger.BackupPrepared(ctx, backup); err != nil {
|
||||
return "", errors.New("预备份身份无法持久化,未对目标执行任何写入:" + err.Error())
|
||||
}
|
||||
}
|
||||
progress.report("capture", "succeeded",
|
||||
fmt.Sprintf("已捕获目标整库快照 %s(%d 字节,用时 %s)", snapshotID, backup.Bytes, time.Since(start).Round(time.Second)))
|
||||
log.Printf("verify: snapshot captured snapshot=%s bytes=%d in=%s", snapshotID, backup.Bytes, time.Since(start))
|
||||
fmt.Sprintf("已捕获写前镜像 %s 与来源身份 %s(%d 字节,用时 %s)",
|
||||
short(snapshotID), short(sourceID), backup.Bytes, time.Since(start).Round(time.Second)))
|
||||
log.Printf("verify: snapshot captured preimage=%s source=%s bytes=%d in=%s",
|
||||
snapshotID, sourceID, backup.Bytes, time.Since(start))
|
||||
|
||||
// 2) 基线校验:预备份必须与目标完全一致。
|
||||
// 3) 基线校验:预备份必须与目标完全一致。
|
||||
progress.report("verify", "running", "逐表/索引/资源比对目标与预备份")
|
||||
baseline = Verification{SnapshotID: snapshotID, At: time.Now().UTC()}
|
||||
if err := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); err != nil {
|
||||
@@ -160,10 +245,10 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
if exists {
|
||||
return "", errors.New("canary identity collision; no write attempted")
|
||||
}
|
||||
ledger := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: jobID, Target: scope,
|
||||
TenantID: identityValue.TenantID, KnowledgeBaseID: identityValue.KnowledgeBaseID,
|
||||
BackupSnapshotID: snapshotID, TargetSnapshotID: snapshotID,
|
||||
CreatedAt: time.Now().UTC(), Universe: backup.Universe}
|
||||
ledger, planErr := PlanWrite(jobID, scope, identityValue.TenantID, identityValue.KnowledgeBaseID, backup, source)
|
||||
if planErr != nil {
|
||||
return "", planErr
|
||||
}
|
||||
report.Canary = canary
|
||||
progress.report("canary", "running", "写入一个隔离 canary,验证校验能发现差异")
|
||||
if err := writeDrillCanary(ctx, config.LibraryArchiveRoot, &ledger, canary,
|
||||
@@ -173,12 +258,21 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
}
|
||||
contentTouched = true
|
||||
return nil
|
||||
}, func(ctx context.Context) error {
|
||||
if opts.Ledger == nil {
|
||||
return nil
|
||||
}
|
||||
// 写集合摘要必须在第一笔写入之前登记到同一个作业的预备份证据里:
|
||||
// 恢复入口按 (scope, job, 写前镜像) 精确读它,读不到就保持维护。
|
||||
return opts.Ledger.WriteSetPlanned(ctx, *ledgerClone(&ledger))
|
||||
}, func(ctx context.Context) error {
|
||||
_, err := target.Pool().Exec(ctx, `INSERT INTO knowledge_tags(id,tenant_id,knowledge_base_id,name) VALUES($1,$2,$3,$4)`, canary, identityValue.TenantID, identityValue.KnowledgeBaseID, "drill-canary-"+canary)
|
||||
return err
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("canary preparation/write failed: %w", err)
|
||||
}
|
||||
writesetDigest = ledger.Digest
|
||||
report.WriteSetDigest = writesetDigest
|
||||
drift = Verification{SnapshotID: snapshotID, At: time.Now().UTC()}
|
||||
if verifyErr := target.Verify(ctx, libraryrelease.Expectation{SnapshotID: snapshotID}); verifyErr == nil {
|
||||
drift.Error = "写入 canary 后校验仍然通过:校验没有真正比对内容"
|
||||
@@ -191,9 +285,12 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
progress.report("canary", "succeeded", "校验按预期发现了 canary 差异")
|
||||
log.Printf("verify: drift detected as expected (%s)", drift.Error)
|
||||
|
||||
// 4) 按预备份恢复。恢复只删掉持久写集合里那个新 canary 身份。
|
||||
// 4) 按写前镜像恢复:四个阶段整段回放(与真实恢复同一批 Apply 原语),
|
||||
// 而不是只删 canary。发布计划形态的 Restore 不能接受"只写过一行 canary"的
|
||||
// 写集合(v2 执行计划合同),所以演练走限定的安全恢复入口;它复用同一份
|
||||
// DS01 身份合同与整实例指纹校验。
|
||||
progress.report("restore", "running", "按预备份恢复目标整库")
|
||||
if err := target.Restore(ctx, libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID,
|
||||
if err := target.RestoreDrill(ctx, libraryrelease.BackupRef{ID: "backup-" + snapshotID, SnapshotID: snapshotID,
|
||||
WriteSet: &ledger}); err != nil {
|
||||
return "", errors.New("按预备份恢复失败:" + err.Error())
|
||||
}
|
||||
@@ -218,15 +315,42 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
func(error) bool { return !contentTouched || restored.Verified })
|
||||
|
||||
report.Until = map[string]string{"job": jobID, "window_state": window.State}
|
||||
report.WindowState = window.State
|
||||
// 服务真的回来、入口验证过(succeeded / 未写内容的安全失败)才释放治理占用;
|
||||
// held 时保留行,页面才能显示真实入口状态并从同一 job 走恢复入口。
|
||||
released := false
|
||||
if opts.Governance != nil {
|
||||
switch {
|
||||
case window.State == "succeeded" || (window.State == "failed" && !contentTouched):
|
||||
if err := opts.Governance.Ingress(ctx, jobID, scope, "open",
|
||||
"维护窗口已按原运行状态恢复,入口已验证可用"); err != nil {
|
||||
return fail("finalize", errors.New("恢复后登记入口状态失败:"+err.Error()), false)
|
||||
}
|
||||
if err := opts.Governance.Release(ctx, jobID, scope,
|
||||
"恢复验证结束,服务与入口已按原状态恢复"); err != nil {
|
||||
return fail("finalize", errors.New("恢复验证结束但维护占用释放失败:"+err.Error()), false)
|
||||
}
|
||||
released = true
|
||||
default:
|
||||
cause := "维护窗口保持关闭"
|
||||
if windowErr != nil {
|
||||
cause = windowErr.Error()
|
||||
}
|
||||
_ = opts.Governance.Ingress(ctx, jobID, scope, "closed", "目标内容状态未验证,入口保持关闭")
|
||||
_ = opts.Governance.State(ctx, jobID, scope, "needs_restore",
|
||||
"恢复验证失败且目标内容未验证:"+cause)
|
||||
}
|
||||
}
|
||||
if windowErr != nil || window.State != "succeeded" {
|
||||
cause := windowErr
|
||||
if cause == nil {
|
||||
cause = fmt.Errorf("维护窗口状态 %s(未成功)", window.State)
|
||||
}
|
||||
if window.State == "held" {
|
||||
return fail("finalize", cause, true)
|
||||
held := window.State == "held"
|
||||
if held && released {
|
||||
held = false
|
||||
}
|
||||
return fail("finalize", cause, false)
|
||||
return fail("finalize", cause, held)
|
||||
}
|
||||
report.Status = "passed"
|
||||
report.FinishedAt = time.Now().UTC()
|
||||
@@ -234,7 +358,46 @@ func Run(ctx context.Context, config appconfig.Config, scope, jobID string, prog
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func writeDrillCanary(ctx context.Context, root string, ledger *libraryrelease.WriteSet, id string, mark func(context.Context) error, write func(context.Context) error) error {
|
||||
// PlanWrite 构造演练的写前镜像/来源身份与写集合。Run 与定向回归共用这一份:
|
||||
// 只有来源身份 ≠ 写前镜像、且两者都是同一次维护切点里密封的真实捕获时,
|
||||
// 恢复入口(同一份 DS01 身份合同)才接受这次演练。
|
||||
func PlanWrite(jobID, scope string, tenantID uint64, knowledgeBaseID string,
|
||||
preimage, source libraryrelease.BackupRef) (libraryrelease.WriteSet, error) {
|
||||
if preimage.SnapshotID == "" || source.SnapshotID == "" {
|
||||
return libraryrelease.WriteSet{}, errors.New("演练缺少写前镜像或来源身份快照")
|
||||
}
|
||||
if preimage.SnapshotID == source.SnapshotID {
|
||||
return libraryrelease.WriteSet{}, errors.New("来源身份与写前镜像相同:拒绝用一份快照冒充两个恢复身份")
|
||||
}
|
||||
set := libraryrelease.WriteSet{Version: libraryrelease.WriteSetVersion, JobID: jobID, Target: scope,
|
||||
TenantID: tenantID, KnowledgeBaseID: knowledgeBaseID,
|
||||
BackupSnapshotID: preimage.SnapshotID, TargetSnapshotID: source.SnapshotID,
|
||||
CreatedAt: time.Now().UTC(), Universe: preimage.Universe}
|
||||
if err := set.ValidateRestoreBinding(preimage.SnapshotID, tenantID, knowledgeBaseID); err != nil {
|
||||
return libraryrelease.WriteSet{}, err
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
func short(id string) string {
|
||||
if len(id) <= 12 {
|
||||
return id
|
||||
}
|
||||
return id[:12]
|
||||
}
|
||||
|
||||
// ledgerClone 只用于把台账交给登记方:Seal 会重排 Rows,调用方随后还要用同一份
|
||||
// 内容去恢复,不能让登记方持有可变的同一指针。
|
||||
func ledgerClone(set *libraryrelease.WriteSet) *libraryrelease.WriteSet {
|
||||
copy := *set
|
||||
copy.Rows = append([]libraryrelease.WriteSetRow(nil), set.Rows...)
|
||||
return ©
|
||||
}
|
||||
|
||||
// writeDrillCanary 是"写入前先留痕"的唯一实现:seal → 落盘 → 登记 → 标风险 → 写。
|
||||
// 任何一步失败都不写目标;登记在标风险之前,恢复入口才拿得到这份写集合。
|
||||
func writeDrillCanary(ctx context.Context, root string, ledger *libraryrelease.WriteSet, id string,
|
||||
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 err := ledger.Seal(); err != nil {
|
||||
return err
|
||||
@@ -242,6 +405,11 @@ func writeDrillCanary(ctx context.Context, root string, ledger *libraryrelease.W
|
||||
if _, err := v071.PersistWriteSet(root, ledger); err != nil {
|
||||
return err
|
||||
}
|
||||
if record != nil {
|
||||
if err := record(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := mark(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user