diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_operation_guard.go b/seaweed-block/core/frontend/chunkstore/snapshot_operation_guard.go index 4de20fc2dd..fb01284041 100644 --- a/seaweed-block/core/frontend/chunkstore/snapshot_operation_guard.go +++ b/seaweed-block/core/frontend/chunkstore/snapshot_operation_guard.go @@ -51,6 +51,9 @@ func (s *LayoutStore) SettleSnapshotOperationFromHead(ctx context.Context, h lay // GuardSnapshotOperations is shared by every kernel transition, including // direct catalog delete and retention. The HEAD read precedes the receipt // read and the subsequent HEAD CAS uses that observed generation. +// A nonterminal receipt owner change need not revoke an already-checked CAS: +// its single binding is settled by the successor before any second publish. +// Terminal refusals must remain HEAD facts that also exclude that publication. func (s *LayoutStore) GuardSnapshotOperations(ctx context.Context, old, next layout.Head) error { for name, sn := range old.Snapshots { if sn.Meta.Operation == nil { diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_operation_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_operation_test.go index 3a778814ba..3a1aa16172 100644 --- a/seaweed-block/core/frontend/chunkstore/snapshot_operation_test.go +++ b/seaweed-block/core/frontend/chunkstore/snapshot_operation_test.go @@ -82,8 +82,9 @@ func TestSnapshotOperationStallReadmissionFencesOldOwner(t *testing.T) { } // This deterministic seam witness pauses publication after its receipt guard. -// Advancing the receipt's owner must invalidate that already-checked HEAD CAS. -func TestSnapshotOperationReadmissionInvalidatesCheckedPublication(t *testing.T) { +// A nonterminal owner change need not invalidate the CAS: the successor must +// settle that one binding, never publish a second binding for the instance. +func TestSnapshotOperationSplitPublishReadmissionSettlesOneBinding(t *testing.T) { for _, readmit := range []bool{false, true} { t.Run(map[bool]string{false: "unchanged-owner-control", true: "readmitted-owner"}[readmit], func(t *testing.T) { ctx := context.Background() @@ -115,6 +116,7 @@ func TestSnapshotOperationReadmissionInvalidatesCheckedPublication(t *testing.T) if err := st.GuardSnapshotOperations(ctx, h, next); err != nil { t.Fatal(err) } + current := op if readmit { stalled, err := st.AdvanceSnapshotOperation(ctx, op, "stalled", nil, "") if err != nil { @@ -127,13 +129,46 @@ func TestSnapshotOperationReadmissionInvalidatesCheckedPublication(t *testing.T) if fresh.Owner == op.Owner { t.Fatal("fixture failed to change owner") } + current = fresh } err = st.UpdateHead(ctx, h.Gen, next, layout.CauseCommit) - if !readmit && err != nil { - t.Fatalf("unchanged owner failed publication: %v", err) + if err != nil { + t.Fatalf("checked publication failed: %v", err) } - if readmit && err == nil { - t.Fatal("revoked owner published after readmission acknowledged a new owner") + published, found, err := st.ReadHead(ctx) + if err != nil || !found || published.Gen != h.Gen+1 { + t.Fatalf("publication missing: %+v %v", published, err) + } + if readmit { + if _, err := st.SettleSnapshotOperationFromHead(ctx, published, "s", op.Owner); !errors.Is(err, ErrSnapshotOperationOwner) { + t.Fatalf("stale worker settled successor receipt: %v", err) + } + } + done, err := st.SettleSnapshotOperationFromHead(ctx, published, "s", current.Owner) + if err != nil || done.State != "succeeded" || done.Instance != op.Instance { + t.Fatalf("successor did not settle original instance: %+v %v", done, err) + } + var outcome SnapshotInfo + if err := json.Unmarshal(done.Result, &outcome); err != nil || outcome.HeadGen != h.Gen+1 { + t.Fatalf("original outcome changed: %+v %v", outcome, err) + } + proposed := next + proposed.Snapshots = map[string]layout.Snapshot{} + for name, sn := range published.Snapshots { + proposed.Snapshots[name] = sn + } + sn = proposed.Snapshots["s"] + b := *sn.Meta.Operation + b.Owner = current.Owner + b.Generation = published.Gen + 1 + sn.Meta.Operation = &b + proposed.Snapshots["s"] = sn + if err := st.GuardSnapshotOperations(ctx, published, proposed); !errors.Is(err, ErrSnapshotOperationTerminal) { + t.Fatalf("second binding permitted: %v", err) + } + after, _, err := st.ReadHead(ctx) + if err != nil || !reflect.DeepEqual(published, after) { + t.Fatalf("second publication changed HEAD: %v", err) } }) } diff --git a/seaweed-block/core/host/volume/snapshot_operation_terminal_guard_test.go b/seaweed-block/core/host/volume/snapshot_operation_terminal_guard_test.go new file mode 100644 index 0000000000..22f62c663d --- /dev/null +++ b/seaweed-block/core/host/volume/snapshot_operation_terminal_guard_test.go @@ -0,0 +1,117 @@ +package volume + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" +) + +// Split publication permits nonterminal owner changes between guard and CAS. +// Its refinement therefore depends on a closed census of terminal writers: +// success settles a HEAD binding; refusal is a HEAD fact before execution. +func TestSnapshotOperationTerminalWriterEnumeration(t *testing.T) { + _, file, _, _ := runtime.Caller(0) + root := filepath.Clean(filepath.Join(filepath.Dir(file), "../../..")) + seen := map[string]int{} + for _, dir := range []string{"."} { + err := filepath.WalkDir(filepath.Join(root, dir), func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() && (d.Name() == ".git" || d.Name() == "vendor") { + return filepath.SkipDir + } + if d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + rel = filepath.ToSlash(rel) + classified := map[token.Pos]bool{} + for _, decl := range f.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + var execution token.Pos + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if ok && sel.Sel.Name == "SnapshotVolume" { + execution = call.Pos() + } + return true + }) + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "AdvanceSnapshotOperation" { + return true + } + classified[sel.Pos()] = true + if len(call.Args) < 5 { + t.Errorf("%s: unclassified operation transition", fset.Position(call.Pos())) + return true + } + lit, ok := call.Args[2].(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + t.Errorf("%s: dynamic operation state bypasses terminal census", fset.Position(call.Pos())) + return true + } + state, err := strconv.Unquote(lit.Value) + if err != nil { + t.Error(err) + return true + } + if state != "succeeded" && state != "refused" { + return true + } + key := rel + ":" + fn.Name.Name + ":" + state + seen[key]++ + switch key { + case "core/frontend/chunkstore/snapshot_operation_guard.go:SettleSnapshotOperationFromHead:succeeded": + case "core/host/volume/chunk_control.go:snapshotOperationAttempt:refused": + code, ok := call.Args[4].(*ast.BasicLit) + if !ok || code.Value != `"snapshot_exists"` || execution == token.NoPos || call.Pos() >= execution { + t.Errorf("%s: refusal must precede provider execution and name the observed HEAD conflict", fset.Position(call.Pos())) + } + default: + t.Errorf("%s: terminal writer needs a HEAD-coupling proof: %s", fset.Position(call.Pos()), key) + } + return true + }) + } + ast.Inspect(f, func(n ast.Node) bool { + if sel, ok := n.(*ast.SelectorExpr); ok && sel.Sel.Name == "AdvanceSnapshotOperation" && !classified[sel.Pos()] { + t.Errorf("%s: operation transition alias or initializer bypasses terminal census", fset.Position(sel.Pos())) + } + return true + }) + return nil + }) + if err != nil { + t.Fatal(err) + } + } + for _, key := range []string{"core/frontend/chunkstore/snapshot_operation_guard.go:SettleSnapshotOperationFromHead:succeeded", "core/host/volume/chunk_control.go:snapshotOperationAttempt:refused"} { + if seen[key] != 1 { + t.Fatalf("terminal writer census changed: %s count=%d", key, seen[key]) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index aac4c3ccc4..49a19aab1b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1288,7 +1288,8 @@ Notes: | `INV-SNAPK-CREATE-001` | A new volume or restore target gets VOLUME then an unclaimed HEAD (epoch 0, no holder, no claim id, idle), each created exclusively; only createVolume and the operator's tombstone create a HEAD; the first Start claims it from a fresh root. | M9 absent → idle | `core/frontend/chunkstore/layout` `create.go` `CreateVolume`, `CreateTarget` | `TestCreateVolume`, `TestCreateVolume_InterruptAtEveryStep`, `TestUnclaimedHead_Shape`, `TestStart_ClaimsAnUnclaimedHeadFromAFreshRoot`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-RESTORE-ORDER-001` | Master checks the source HEAD and named snapshot and refuses RF>1 before persisting. The target binds source layout id, snapshot, request id and VOLUME geometry as not-ready; then AddDependent, copy root/segments, create VOLUME and unclaimed HEAD, and mark ready. A retry keeps the binding. | M9 source HEAD, dependents | `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`; `core/frontend/chunkstore/layout/create.go` `CreateTarget`; `cmd/sw-block/chunk_b.go` `chunkRestore` | `TestRestoreRequestBindsTargetName`, `TestRestoreCreateVolumePersistsRequestBeforeTargetAndHealsRetry`, `TestOpsChunkRestoreUsesOnlyMasterCreate`, `TestCreateTarget`, `TestRunAddDependent_RefusesAForeignSource` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-SNAP-DELETE-001` | A named snapshot leaves HEAD by one conditional update, refused while it has dependents; the automatic delete (retention) also refuses a snapshot pinned at its time. | M9 idle → idle | `core/frontend/chunkstore/layout` `snapshots.go` `Head.DeleteSnapshot`, `Head.RetireSnapshot` | `TestDeleteSnapshot_Closure`, `TestRetireSnapshot_Closure`, `TestRunRetireSnapshot_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | -| `INV-SNAP-OP-RECEIPT-001` | A snapshot operation receipt survives reopening its volume store; changed intent is refused, terminal outcomes are immutable, and a stale owner or revision cannot advance the receipt. | M9 operation receipt | `LayoutStore.CreateSnapshotOperation`, `AdvanceSnapshotOperation` (create coupling and process-owned executor wired; retirement pending) | `TestSnapshotOperationReceiptSurvivesReopenAndRejectsChangedIntent`, `TestSnapshotOperationStallReadmissionFencesOldOwner` | SnapOps run3 rows 211–219; shared HEAD guard wired; retirement/concurrent-owner controls owed | STUB | +| `INV-SNAP-OP-RECEIPT-001` | A snapshot operation receipt survives reopening its volume store; changed intent is refused, terminal outcomes are immutable, and a stale owner or revision cannot advance the receipt. | M9 operation receipt | `LayoutStore.CreateSnapshotOperation`, `AdvanceSnapshotOperation` (create coupling and process-owned executor wired; retirement pending) | `TestSnapshotOperationReceiptSurvivesReopenAndRejectsChangedIntent`, `TestSnapshotOperationStallReadmissionFencesOldOwner`, `TestSnapshotOperationSplitPublishReadmissionSettlesOneBinding` | SnapOps run3 rows 211–219; split-publication model result and retirement owed | STUB | +| `INV-SNAP-OP-TERMINAL-WRITERS-001` | Snapshot operation success settles a HEAD binding. A terminal refusal is a HEAD conflict checked before provider execution; a provider error can only stall or leave the receipt unchanged. | M9 operation terminal outcome | `LayoutStore.SettleSnapshotOperationFromHead`, `chunkControl.snapshotOperationAttempt` | `TestSnapshotOperationTerminalWriterEnumeration`, `TestSnapshotOperationAppliedAnswerFailureNeverBecomesRefused`, `TestSnapshotOperationFencedFailurePreservesPublishedBinding` | SnapOps run3 row 218; split-publication refinement pending | STUB | | `INV-SNAP-OP-ORIGINAL-001` | Within the retained operation window, retrying a snapshot create returns its original outcome after control, catalog or retention removal, and after name reuse; it performs no new cut or HEAD write. | M9 operation replay (planned) | `chunkControl.Snapshot`, shared HEAD/receipt guard and process-owned executor; retirement pending | `TestSnapshotOperationRetryAfterRemovalKeepsOriginalOutcome`, `TestSnapshotOperationOldIDDoesNotAliasReusedName` (`core/host/volume/snapshot_operation_red_test.go`) | SnapOps.Send/Publish/Delete; rows 211–219 (first red tranche only) | STUB | | `INV-SNAP-OP-FINGERPRINT-001` | A retained operation ID reused with changed snapshot intent refuses before any cut or HEAD write. | M9 operation admission (planned) | `CreateSnapshotOperation` canonical fingerprint; create executor wired; delete executor pending | `TestSnapshotOperationSameIDChangedIntentRefusesBeforeWrite` (`core/host/volume/snapshot_operation_red_test.go`) | SnapOps.Send; rows 211–219 | STUB | | `INV-SNAP-OP-READMIT-001` | A create whose HEAD publication applied before its answer was lost reconciles that original outcome on re-admission; later removal cannot cause another execution under its retained operation ID. | M9 operation re-admission (planned) | `SnapshotOperationBinding`, `LayoutStore.GuardSnapshotOperations`; create executor wired; retirement pending | `TestSnapshotOperationLostPublishAnswerReadmitDeleteCannotRepublish`, `TestSnapshotOperationRemovalBeforeReadmitKeepsPublishedOutcome` (`core/host/volume/snapshot_operation_red_test.go`) | SnapOps.Send/Publish/Settle/Delete; rows 211–219 (persisted-stall removal controls included; concurrent-owner controls pending) | STUB |