From 1f8969b8098c901a46f0a3c330cecf2c49ba3e89 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:50:01 -0800 Subject: [PATCH] sw-block: snapshot-delete names its incarnation and can pin it The delete prints the incarnation it resolved (name@gen) with its request id, and the no-wait answer carries it; --gen deletes only that incarnation and is refused typed when the name holds another. Retries inside one invocation keep the id and the incarnation; a new invocation resolves the name again, and a recreated name is what it deletes. The name-only primitive (an old client's) still refuses a v1.1 HEAD. The snapshot operation commit passes the shared format guard. Co-Authored-By: Claude Opus 5.5 --- .../sw-block/catalog_snapshot_operation.go | 20 +++++-- seaweed-block/cmd/sw-block/chunk_b.go | 15 ++++-- .../snapshot_delete_legacy_refusal_test.go | 40 +++++++++----- .../layout/format_level_operation_test.go | 52 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/operator-guide.md | 10 ++++ 6 files changed, 118 insertions(+), 21 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout/format_level_operation_test.go diff --git a/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go b/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go index aa261e858e..6238d1c83d 100644 --- a/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go +++ b/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go @@ -30,12 +30,12 @@ func chunkRunCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatalog } func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef, op chunkstore.SnapshotOperation, work chunkstore.SnapshotDeleteWork, noWait bool, stderr io.Writer) (any, error) { - fmt.Fprintf(stderr, "snapshot-delete request id %s instance %s sequence %d; repeat with the same --request-id to resume\n", op.ID, op.Instance, op.Sequence) + fmt.Fprintf(stderr, "snapshot-delete %s request id %s instance %s sequence %d; repeat with the same --request-id to resume\n", snapshotIncarnation(op), op.ID, op.Instance, op.Sequence) if op.State == "refused" { return nil, &chunkstore.CatalogError{Code: op.ErrorCode, Message: op.ErrorMessage} } if noWait { - return map[string]any{"operation_id": op.ID, "volume_id": op.VolumeID.String(), "instance": op.Instance, "sequence": op.Sequence, "state": op.State}, nil + return map[string]any{"operation_id": op.ID, "volume_id": op.VolumeID.String(), "incarnation": snapshotIncarnation(op), "instance": op.Instance, "sequence": op.Sequence, "state": op.State}, nil } answer, err := cat.RunSnapshotDeleteOperation(ctx, volume, op, work) if err != nil { @@ -50,7 +50,18 @@ func chunkCatalogSnapshotDeleteAnswer(ctx context.Context, cat *chunkstore.BCata return answer.Result, nil } -func chunkAdmitCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef, id, name string, noWait bool, stderr io.Writer) (any, error) { +// snapshotIncarnation names the incarnation a delete operation captured, +// name@gen (the name alone while none is captured). +func snapshotIncarnation(op chunkstore.SnapshotOperation) string { + if op.TargetGeneration == nil || *op.TargetGeneration == 0 { + return op.Name + } + return fmt.Sprintf("%s@%d", op.Name, *op.TargetGeneration) +} + +// chunkAdmitCatalogSnapshotDelete admits a delete operation for name; a +// nonzero pin admits it only for that incarnation (name@pin). +func chunkAdmitCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef, id, name string, pin uint64, noWait bool, stderr io.Writer) (any, error) { st, err := cat.Store(volume) if err != nil { return nil, err @@ -73,6 +84,9 @@ func chunkAdmitCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatal if target.Gen == 0 { return 0, &chunkstore.CatalogError{Code: "snapshot_generation_unavailable", Message: "snapshot has no publishing generation; make the first v1.1 HEAD write with a v1.1 holder first", Retryable: true} } + if pin != 0 && target.Gen != pin { + return 0, &chunkstore.CatalogError{Code: "snapshot_generation_mismatch", Message: fmt.Sprintf("the snapshot is %s@%d, not %s@%d (--gen)", name, target.Gen, name, pin)} + } return target.Gen, nil }) if err != nil { diff --git a/seaweed-block/cmd/sw-block/chunk_b.go b/seaweed-block/cmd/sw-block/chunk_b.go index 4c32ba460f..d339398673 100644 --- a/seaweed-block/cmd/sw-block/chunk_b.go +++ b/seaweed-block/cmd/sw-block/chunk_b.go @@ -240,16 +240,21 @@ func newSnapshotDeleteRequestID() (string, error) { // v1.0's name-only delete, chosen before any operation record is written // (and as retry-unsafe as in v1.0). On a version-1 HEAD, or at level 1, it // is an operation delete: under --request-id, or else under an id made once -// for this invocation and printed for resume. Every HEAD write runs at the -// cluster's level (layout.WithFormatLevel). +// for this invocation and printed for resume, with the incarnation it +// captured (name@gen); --gen pins that incarnation and always takes the +// operation route. Retries inside one invocation keep its id and its +// incarnation; a new invocation resolves the name again. Every HEAD write +// runs at the cluster's level (layout.WithFormatLevel). func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { c := newBCommand("snapshot-delete", 30*time.Second, stdout, stderr) var vol volumeFlags var name, requestID, autoID string var noWait bool + var pin uint64 c.bindVolume(&vol, "volume", "volume") c.fs.StringVar(&name, "name", "", "snapshot name") c.fs.StringVar(&requestID, "request-id", "", "operation id for snapshot deletion; reuse on retry (made once per invocation when omitted)") + c.fs.Uint64Var(&pin, "gen", 0, "delete only this incarnation of the name (its publishing generation, shown as name@gen); refused if the name holds another") c.fs.BoolVar(&noWait, "no-wait", false, "persist the delete operation without executing it; requires --request-id") var ref chunkstore.VolumeRef return c.run(args, true, func() (err error) { @@ -270,7 +275,7 @@ func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { level := snapshotDeleteFormatLevel(ctx, c.master, stderr) ctx = layout.WithFormatLevel(ctx, level) id := requestID - if id == "" { + if id == "" && pin == 0 { st, err := cat.Store(ref) if err != nil { return nil, err @@ -285,9 +290,11 @@ func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { } return map[string]string{"volume": ref.Dir(), "name": name, "state": "absent"}, nil } + } + if id == "" { id = autoID } - return chunkAdmitCatalogSnapshotDelete(ctx, cat, ref, id, name, noWait, stderr) + return chunkAdmitCatalogSnapshotDelete(ctx, cat, ref, id, name, pin, noWait, stderr) }) } diff --git a/seaweed-block/cmd/sw-block/snapshot_delete_legacy_refusal_test.go b/seaweed-block/cmd/sw-block/snapshot_delete_legacy_refusal_test.go index 22782f08f4..b62968ef89 100644 --- a/seaweed-block/cmd/sw-block/snapshot_delete_legacy_refusal_test.go +++ b/seaweed-block/cmd/sw-block/snapshot_delete_legacy_refusal_test.go @@ -2,14 +2,24 @@ package main import ( "context" + "fmt" + "strings" + "testing" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" - "testing" ) -// The old delete succeeded but its reply was lost. The same legacy argv must -// not delete a same-name replacement after the HEAD has upgraded to v1.1. -func TestSnapshotDeleteLegacyCLIRetryCannotDeleteV11Replacement(t *testing.T) { +// The v1.0 delete by name succeeded but its reply was lost, and the name was +// recreated in a v1.1 HEAD. Running the command again is a new intent: it +// resolves the name again. Pinned to an incarnation the name no longer +// holds (--gen) it is refused typed with the HEAD unchanged; unpinned it +// deletes the replacement, which is what was asked, and names the +// incarnation it removed (name@gen). An old client's name-only call on that +// HEAD is refused (TestSnapshotDeleteOldClientNameOnlyRefusesAV1Head), and +// retries inside one invocation keep their incarnation +// (TestSnapshotDeletePublicOperationKeepsTargetAcrossRecreation). +func TestSnapshotDeleteAfterALostLegacyReplyIsANewIntent(t *testing.T) { ctx := context.Background() memory := newMemChunkStore() useMemChunkStore(t, memory) @@ -49,16 +59,20 @@ func TestSnapshotDeleteLegacyCLIRetryCannotDeleteV11Replacement(t *testing.T) { if err != nil { t.Fatal(err) } - code, out, _ := runChunk(args...) - var failure chunkErrBody - if code != 0 { - failure = chunkErrorOut(t, out) + pinned := append(append([]string(nil), args...), "--gen", "1") + code, out, _ := runChunk(pinned...) + if failure := chunkErrorOut(t, out); code == 0 || failure.Code != "snapshot_generation_mismatch" || failure.Retryable { + t.Fatalf("a delete pinned to another incarnation: exit=%d body=%s; want snapshot_generation_mismatch", code, out) } - if code != chunkExitFailed || failure.Code != "snapshot_delete_requires_operation" || failure.Retryable { - t.Errorf("legacy retry must refuse v1.1: exit=%d body=%s", code, out) + if after, _, err := st.ReadHead(ctx); err != nil || after.Gen != before.Gen || after.Snapshots["daily"].Gen != replacement.Gen { + t.Fatalf("the refused pinned delete changed the HEAD: before %+v after %+v %v", before, after, err) } - after, _, err := st.ReadHead(ctx) - if err != nil || after.Gen != before.Gen || after.Snapshots["daily"].Gen != replacement.Gen { - t.Fatalf("lost-reply retry deleted replacement: before=%+v after=%+v err=%v", before, after, err) + code, out, logs := runChunk(args...) + want := fmt.Sprintf("daily@%d", replacement.Gen) + if code != 0 || !strings.Contains(logs, want) || !strings.Contains(out, fmt.Sprintf(`"gen":%d`, replacement.Gen)) { + t.Fatalf("a new delete of the replacement: exit=%d out=%s logs=%s; want it deleted, naming %s", code, out, logs, want) + } + if after, _, err := st.ReadHead(ctx); err != nil || len(after.Snapshots) != 0 { + t.Fatalf("after the new delete: %+v %v; want no snapshot", after, err) } } diff --git a/seaweed-block/core/frontend/chunkstore/layout/format_level_operation_test.go b/seaweed-block/core/frontend/chunkstore/layout/format_level_operation_test.go new file mode 100644 index 0000000000..fea2d728fc --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout/format_level_operation_test.go @@ -0,0 +1,52 @@ +package layout + +import ( + "context" + "errors" + "testing" +) + +// guardedMemHead is a memHead whose store carries the snapshot-operation +// receipt guard (it admits every transition): the writes that bind an +// operation reach the format guard and the store as on a real store. +type guardedMemHead struct{ *memHead } + +func (guardedMemHead) GuardSnapshotOperations(context.Context, Head, Head) error { return nil } + +// The snapshot-operation writer that may raise HEAD from version 0 (a +// commit binding a create operation, the op-record mutation of the HEAD) +// passes the one shared format guard: below level 1 it is refused typed and +// writes nothing; at level 1 it lands at version 1. +func TestASnapshotOperationCommitPassesTheFormatGuard(t *testing.T) { + me := HolderID{Holder: "srv-a", Epoch: 3, ClaimID: "k-a"} + meta := SnapshotMeta{Operation: &SnapshotOperationBinding{ID: "create", Instance: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Owner: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", Sequence: 1, Fingerprint: "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"}} + for _, tc := range []struct { + ctx context.Context + want error + }{ + {context.Background(), ErrFormatLevelBelowHeadVersion}, + {WithFormatLevel(context.Background(), 0), ErrFormatLevelBelowHeadVersion}, + {WithFormatLevel(context.Background(), 1), nil}, + } { + h := idleHead() + h.State = StateLive + h.Activity = Activity{Kind: ActSnap, Session: "s"} + mem := &memHead{h: &h} + next, err := runTransition(tc.ctx, guardedMemHead{mem}, CauseCommit, func(h Head) (Head, bool, error) { + next, changed, err := h.Commit(me, "s", RootName{Hash: Sum([]byte("image"))}, h.Position+1, "daily", meta, StateLive) + if err == nil && changed { + next = next.withManifestBytes("", nil, true) + } + return next, changed, err + }) + if !errors.Is(err, tc.want) { + t.Fatalf("at level %d: %v, want %v", FormatLevelOf(tc.ctx), err, tc.want) + } + if tc.want != nil && (mem.updates != 0 || mem.h.Version != 0) { + t.Fatalf("a refused operation commit reached the store: %d updates, HEAD version %d", mem.updates, mem.h.Version) + } + if tc.want == nil && (next.Version != HeadVersion1 || next.Snapshots["daily"].Meta.Operation == nil) { + t.Fatalf("at level 1: %+v, want a version-1 HEAD binding the operation", next) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ae95b7d1d6..df00dba933 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1367,7 +1367,7 @@ Notes: | `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 and compact index wired; native qualification 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 | | `INV-SNAP-OP-CLI-001` | Snapshot observation preserves the printed operation ID across retries, polling, interruption and no-wait submission; observing an operation never admits another identity. | M9 operation observation (planned) | `chunkObserveSnapshot`, holder asynchronous create executor | `TestSnapshotOperationCLIUsesPrintedIDForAsyncObservation`, `TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID` (`cmd/sw-block/snapshot_operation_red_test.go`, `cmd/sw-block/snapshot_operation_interrupt_unix_test.go`) | SnapOps.Send/Start; rows 211–219 (server crash controls owed) | STUB | -| `INV-SNAP-DELETE-NAME-001` | Name-only snapshot deletion refuses v1.1 HEAD without a HEAD write. A lost-reply retry cannot delete a same-name replacement; a v1.1 delete needs a retained target and its durable intent. | M9 legacy delete admission | `layout.RunDeleteSnapshot`; catalog, CLI and host delete routes | `TestSnapshotDeleteLegacyCLIRetryCannotDeleteV11Replacement`, `TestSnapshotDeleteLegacyHostRetryCannotDeleteV11Replacement`, `TestSnapshotDeletePublicOperationKeepsTargetAcrossRecreation`, `TestSnapshotDeletePublicNoWaitResumesSameAdmission`, `TestSnapshotDeletePublicAbsentHeadRefuses` | SnapDelete row 242; rows 241-245 | STUB | +| `INV-SNAP-DELETE-NAME-001` | The name-only delete primitive (an old client's) refuses a v1.1 HEAD without a HEAD write. Retries in one CLI invocation keep its request id and resolved incarnation, so a lost reply never deletes a replacement; a new invocation resolves the name again (--gen pins it). | M9 legacy delete admission | `layout.RunDeleteSnapshot`; catalog, CLI and host delete routes | `TestSnapshotDeleteOldClientNameOnlyRefusesAV1Head`, `TestSnapshotDeleteAfterALostLegacyReplyIsANewIntent`, `TestSnapshotDeleteLegacyHostRetryCannotDeleteV11Replacement`, `TestSnapshotDeletePublicOperationKeepsTargetAcrossRecreation`, `TestSnapshotDeletePublicNoWaitResumesSameAdmission`, `TestSnapshotDeletePublicAbsentHeadRefuses` | SnapDelete row 242; rows 241-245 | STUB | | `INV-SNAP-DELETE-LOGICAL-001` | A delete receipt succeeds only after its retained target is proven absent. Actual unlink and its durable reclamation intent publish in one HEAD CAS; physical continuation depends on HEAD/pages, not the receipt. | M9 delete running to succeeded | `snapshotDeleteLogicalStep`, `RunDeleteSnapshotWithIntent` | `TestSnapshotDeleteLogicalCommitKeepsIndependentIntent`, `TestSnapshotDeleteLogicalCommitResumesAcrossLostAnswers`, `TestSnapshotDeleteLogicalCommitSparesReplacement` | SnapDelete rows 241-245; PageChain rows 246-253 | STUB | | `INV-SNAP-DELETE-EXECUTOR-001` | A catalog delete attempt reads its issued handle before work, takes ownership by receipt CAS, and persists uncertain work as stalled. It never infers terminal success from a callback return; terminal replay reads the same incarnation. | M9 delete attempt transport | `BCatalog.RunSnapshotDeleteOperation`; CLI execution seam | `TestSnapshotDeleteCatalogResumesDurableIntentOnAnotherExecutor`, `TestSnapshotDeleteCatalogRefusesWrongIntentBeforeWork`, `TestSnapshotDeleteCatalogCannotInferSuccessFromWorkReturn`, `TestSnapshotDeleteOfflineCLILeavesProgressInFiler` | SnapDelete retained target; SnapOps owner/state refinement; V8 completion adapter and public command activation owed | STUB | | `INV-SNAP-OP-ADMISSION-CLOSE-001` | Admission checks HEAD after receipt publication and refuses a deleting/deleted or absent volume. Closed incarnations cannot answer retained operation queries; their terminal receipt bytes are not rewritten by closing. | M9 admission and observation | `checkSnapshotOperationAdmission`, `readOperationIndex`, create/delete admission | `TestSnapshotOperationAdmissionRechecksHeadAfterPublication`, `TestSnapshotOperationClosedVolumeRefusesReceipts`, `TestSnapshotOperationTerminalReadmissionRechecksHeadAfterFlag` | SnapVolDel rows 257-260 (per-incarnation) | STUB | diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 60de54d12f..c6c60ffb16 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -404,6 +404,16 @@ then take it again. A scheduled snapshot refused this way still publishes the vo and `GET STATUS/status/durable?volume=` shows `Chunk.ScheduledSnapshot.lastFailure.code: snapshot_limit`, then `snapshot_overdue` (`TestScheduledSnapshotAtTheLimitStillPublishes`). +`ops chunk snapshot-delete --name ` deletes by name. On a v1.1 volume (and once the cluster's format level is 1) +it runs as a delete operation: it prints the incarnation it resolved (`name@gen`) and the operation's request id, and +retries inside that one run keep both, so a lost reply never deletes a same-name replacement. Running the command +again is a new delete: it resolves the name again, and if the name was recreated meanwhile it deletes the new one. +Scripts that need exactly-once pass their own `--request-id` and reuse it on retry; `--gen ` deletes only that +incarnation and is refused with `snapshot_generation_mismatch` when the name holds another. On a volume still in the +v1.0 format at format level 0 the command is v1.0's delete by name, retried as in v1.0 (a lost reply followed by a +recreate and a retry deletes the new one) (`TestSnapshotDeleteAfterALostLegacyReplyIsANewIntent`, +`TestSnapshotDeleteByNameRoutesOnTheHeadAndTheLevel`). + A snapshot can be refused with `host_slot_busy` / `no background slot` (retryable) while every host slot is held by other volumes' cuts; retry with the same request id. With many volumes on a host, a snapshot may wait for a slot: measured up to 15 s at 32 volumes with the default 3 slots.