From bfa09d4e256f3cb3a515674570a2a38f489c1c06 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:59:04 -0800 Subject: [PATCH] feat: couple snapshot delete receipts to durable intent --- .../sw-block/catalog_snapshot_operation.go | 5 +- .../catalog_snapshot_operation_test.go | 51 +++ .../catalog_snapshot_delete_intent.go | 161 +++++++ .../catalog_snapshot_delete_intent_test.go | 417 ++++++++++++++++++ .../chunkstore/catalog_snapshot_operation.go | 4 +- .../frontend/chunkstore/head_readers_test.go | 2 + .../snapshot_operation_terminal_guard_test.go | 18 +- seaweed-block/docs/design/invariants.md | 10 +- .../docs/design/snapshot-operation-index.md | 59 ++- 9 files changed, 698 insertions(+), 29 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_snapshot_delete_intent.go create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_snapshot_delete_intent_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 954bad14c3..96cb614dee 100644 --- a/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go +++ b/seaweed-block/cmd/sw-block/catalog_snapshot_operation.go @@ -10,8 +10,9 @@ import ( ) // chunkRunCatalogSnapshotDelete is the CLI-owned execution/observation seam. -// Admission and the V8 durable-work adapter must be supplied by the shared -// writer integration. No background server or process-local progress is added. +// Admission supplies the retained identity. A nil work override uses the +// catalog's shared atomic unlink/intent adapter. No background server or +// process-local progress is added. func chunkRunCatalogSnapshotDelete(ctx context.Context, cat *chunkstore.BCatalog, volume chunkstore.VolumeRef, op chunkstore.SnapshotOperation, work chunkstore.SnapshotDeleteWork, noWait bool, stdout, stderr io.Writer) int { 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) if noWait { diff --git a/seaweed-block/cmd/sw-block/catalog_snapshot_operation_test.go b/seaweed-block/cmd/sw-block/catalog_snapshot_operation_test.go index 7b1d9f7b5b..025ba0fa80 100644 --- a/seaweed-block/cmd/sw-block/catalog_snapshot_operation_test.go +++ b/seaweed-block/cmd/sw-block/catalog_snapshot_operation_test.go @@ -80,3 +80,54 @@ func TestSnapshotDeleteOfflineCLILeavesProgressInFiler(t *testing.T) { t.Fatalf("resume result: code=%d out=%q", code, out.String()) } } + +func TestSnapshotDeleteOfflineCLIUsesAtomicLogicalStep(t *testing.T) { + ctx := context.Background() + mem := newMemChunkStore() + cat, err := chunkstore.NewBCatalog(mem, mem, "/blocks") + if err != nil { + t.Fatal(err) + } + id, err := layout.ParseVolumeID("00000000000000000000000000000001") + if err != nil { + t.Fatal(err) + } + v := chunkstore.VolumeRef{Name: "v1", ID: id} + if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(v) + if err != nil { + t.Fatal(err) + } + root, segments, err := layout.Build(map[uint64]layout.Ref{}) + if err != nil { + t.Fatal(err) + } + rn, err := layout.PrepareRoot(ctx, st, root, segments, "seed") + if err != nil { + t.Fatal(err) + } + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + h.Version = layout.HeadVersion1 + h.Snapshots = map[string]layout.Snapshot{"daily": {Root: rn, Gen: 2}} + if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseSnapshotUnchanged); err != nil { + t.Fatal(err) + } + op, err := st.AdmitSnapshotDeleteOperation(ctx, "cli-real", "daily", func(context.Context) (uint64, error) { return 2, nil }) + if err != nil { + t.Fatal(err) + } + var out, logs bytes.Buffer + code := chunkRunCatalogSnapshotDelete(ctx, cat, v, op, nil, false, &out, &logs) + if code != 0 || out.String() != `{"volume_id":"00000000000000000000000000000001","name":"daily","gen":2}` { + t.Fatalf("real logical answer: code=%d out=%s logs=%s", code, &out, &logs) + } + h, _, err = st.ReadHead(ctx) + if err != nil || h.Gen != 3 || h.List == nil || len(h.Snapshots) != 0 { + t.Fatalf("CLI did not use atomic unlink/intent: %+v %v", h, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_snapshot_delete_intent.go b/seaweed-block/core/frontend/chunkstore/catalog_snapshot_delete_intent.go new file mode 100644 index 0000000000..c807a33716 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_snapshot_delete_intent.go @@ -0,0 +1,161 @@ +package chunkstore + +import ( + "context" + "encoding/json" + "fmt" + "sort" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +// SnapshotDeleteResult identifies the retained incarnation proven absent by +// the logical step. It says nothing about physical reclamation or bytes freed. +type SnapshotDeleteResult struct { + VolumeID string `json:"volume_id"` + Name string `json:"name"` + Gen uint64 `json:"gen"` +} + +// snapshotDeleteLogicalStep delegates the only HEAD write to the shared kernel +// transition: unlink and durable reclamation intent are one CAS. An already +// absent/replaced target needs no HEAD write, and never resolves to a new one. +func (c *BCatalog) snapshotDeleteLogicalStep(ctx context.Context, v VolumeRef, st *LayoutStore, op SnapshotOperation) error { + h, found, err := st.ReadHead(ctx) + if err != nil { + return snapshotOperationHeadError(err) + } + if !found { + return layout.ErrHeadAbsent + } + target := layout.SnapshotTarget{Name: op.Name, Gen: *op.TargetGeneration} + _, changed, err := h.DeleteSnapshotAt(target.Name, target.Gen) + if err != nil { + return err + } + if changed { + if h.List != nil { + return layout.ErrBusy + } + cursor, err := c.stageSnapshotDeleteIntent(ctx, v, st, op, h, target) + if err != nil { + return err + } + // A stale queued/paused worker checks its captured owner before publication. + // The kernel CAS and immutable target carry delete safety, not this read. + current, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence) + if err != nil { + return err + } + if current.Revision != op.Revision || current.Owner != op.Owner || current.State != "running" { + return ErrSnapshotOperationOwner + } + h, err = layout.RunDeleteSnapshotWithIntent(ctx, st, h.Gen, cursor) + if err != nil { + return err + } + } + // This also validates state and identity for the no-op/lost-answer case. + if _, remaining, err := h.DeleteSnapshotAt(target.Name, target.Gen); err != nil { + return err + } else if remaining { + return layout.ErrPrecondition + } + raw, err := json.Marshal(SnapshotDeleteResult{VolumeID: v.ID.String(), Name: target.Name, Gen: target.Gen}) + if err != nil { + return err + } + _, err = st.AdvanceSnapshotOperation(ctx, op, "succeeded", raw, "") + return err +} + +// stageSnapshotDeleteIntent streams candidates in bounded pages. A page's +// identity uses the immutable operation instance/sequence, not HEAD's CAS base +// or the worker owner, so retry after unrelated metadata changes reuses bytes. +func (c *BCatalog) stageSnapshotDeleteIntent(ctx context.Context, v VolumeRef, st *LayoutStore, op SnapshotOperation, h layout.Head, target layout.SnapshotTarget) (layout.ListCursor, error) { + reader, err := layout.NewReader(c.base, v.Dir(), st.Fetch) + if err != nil { + return layout.ListCursor{}, err + } + snapshot := h.Snapshots[target.Name] + image, err := reader.Open(ctx, snapshot.Root) + if err != nil { + return layout.ListCursor{}, err + } + var tail *layout.ListRef + entries := make([]string, 0, layout.MaxListPageEntries) + flush := func() error { + if len(entries) == 0 { + return nil + } + sort.Strings(entries) + unique := entries[:0] + for _, rel := range entries { + if len(unique) == 0 || rel != unique[len(unique)-1] { + unique = append(unique, rel) + } + } + pages := uint32(1) + if tail != nil { + pages = tail.Pages + 1 + } + if pages > layout.MaxListPages { + return fmt.Errorf("%w: snapshot-delete intent exceeds page limit", layout.ErrMalformed) + } + page := layout.ListPage{VolumeID: v.ID, Kind: layout.ListSnapshotDeleteIntent, Producer: op.Instance, Generation: op.Sequence, Pages: pages, Next: tail, Target: &target, Entries: unique} + ref, err := layout.StageSnapshotDeletePage(ctx, st, h.Gen, page) + if err != nil { + return err + } + tail = &ref + entries = entries[:0] + return nil + } + add := func(rel string) error { + if err := ctx.Err(); err != nil { + return err + } + entries = append(entries, rel) + if len(entries) == layout.MaxListPageEntries { + return flush() + } + return nil + } + if err := add(snapshot.Root.Path()); err != nil { + return layout.ListCursor{}, err + } + root := image.Root() + for _, shard := range image.Shards() { + if err := add(root.Segments[shard].Path()); err != nil { + return layout.ListCursor{}, err + } + segment, found, err := image.Segment(ctx, shard) + if err != nil { + return layout.ListCursor{}, err + } + if !found { + return layout.ListCursor{}, layout.ErrMissing + } + indices := make([]uint64, 0, len(segment.Chunks)) + for index := range segment.Chunks { + indices = append(indices, index) + } + sort.Slice(indices, func(i, j int) bool { return indices[i] < indices[j] }) + for _, index := range indices { + ref := segment.Chunks[index] + if ref.OwnerID != v.ID { + continue + } // Foreign pool entries are never this volume's candidates. + if ref.Owner != v.Name { + return layout.ListCursor{}, layout.ErrIdentity + } + if err := add(ref.Chunk.Path()); err != nil { + return layout.ListCursor{}, err + } + } + } + if err := flush(); err != nil { + return layout.ListCursor{}, err + } + return layout.ListCursor{Ref: *tail, Kind: layout.ListSnapshotDeleteIntent, Producer: op.Instance, Generation: op.Sequence, Target: &target}, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_snapshot_delete_intent_test.go b/seaweed-block/core/frontend/chunkstore/catalog_snapshot_delete_intent_test.go new file mode 100644 index 0000000000..b660500a01 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_snapshot_delete_intent_test.go @@ -0,0 +1,417 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "path" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) + +func catalogDeleteIntentFixture(t *testing.T) (*BCatalog, VolumeRef, *LayoutStore, SnapshotOperation, layout.Head) { + t.Helper() + ctx := context.Background() + cat, volume, st, _ := cleanFixture(t) + h, found, err := st.ReadHead(ctx) + if err != nil || !found { + t.Fatalf("fixture HEAD: %v %v", found, err) + } + stamped, _, err := h.StampSnapshotGenerations() + if err != nil { + t.Fatal(err) + } + // Test fixture only: emulate the holder's first v1.1 publication. The + // catalog admission below reads persisted identity; it never stamps HEAD. + if err := st.UpdateHead(ctx, h.Gen, stamped, layout.CauseSnapshotUnchanged); err != nil { + t.Fatal(err) + } + h, _, err = st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + op, err := st.AdmitSnapshotDeleteOperation(ctx, "delete-issued", "s", func(context.Context) (uint64, error) { return h.Snapshots["s"].Gen, nil }) + if err != nil { + t.Fatal(err) + } + return cat, volume, st, op, h +} + +func TestSnapshotDeleteLogicalCommitKeepsIndependentIntent(t *testing.T) { + ctx := context.Background() + cat, volume, st, op, before := catalogDeleteIntentFixture(t) + done, err := cat.RunSnapshotDeleteOperation(ctx, volume, op, nil) + if err != nil || done.State != "succeeded" { + t.Fatalf("real logical delete did not settle: %+v %v", done, err) + } + h, found, err := st.ReadHead(ctx) + if err != nil || !found || h.Gen != before.Gen+1 || len(h.Snapshots) != 0 || h.List == nil { + t.Fatalf("unlink and intent were not one HEAD CAS: before=%+v after=%+v err=%v", before, h, err) + } + if h.List.Kind != layout.ListSnapshotDeleteIntent || h.List.Target == nil || h.List.Target.Name != op.Name || h.List.Target.Gen != *op.TargetGeneration { + t.Fatalf("intent changed admitted target: %+v", h.List) + } + var result struct { + VolumeID string `json:"volume_id"` + Name string `json:"name"` + Gen uint64 `json:"gen"` + } + if err := json.Unmarshal(done.Result, &result); err != nil || result.VolumeID != volume.ID.String() || result.Name != op.Name || result.Gen != *op.TargetGeneration { + t.Fatalf("result lost identity: %s %v", done.Result, err) + } + // Receipt retirement cannot strand physical work. Simulate unavailable + // operation metadata, then construct a fresh executor from HEAD/pages only. + if err := st.f.DeleteEntry(ctx, st.operationDirectory(), operationReceiptName(done.Sequence), nil); err != nil { + t.Fatal(err) + } + if err := st.f.DeleteEntry(ctx, st.operationDirectory(), operationIndexName, nil); err != nil { + t.Fatal(err) + } + reopened, err := NewLayoutStore(st.f, st.b, st.root, st.id) + if err != nil { + t.Fatal(err) + } + reader, err := layout.NewReader(cat.base, volume.Dir(), reopened.Fetch) + if err != nil { + t.Fatal(err) + } + for i := 0; h.List != nil && i < layout.MaxListPages; i++ { + h, err = layout.RunConsumeSnapshotDeleteIntent(ctx, reopened, reader) + if err != nil { + t.Fatal(err) + } + } + if h.List != nil || h.Epoch != before.Epoch || h.Holder != before.Holder { + t.Fatalf("physical resume incomplete or claimed holder: %+v", h) + } + if h.Current == nil || *h.Current != *before.Current { + t.Fatal("intent cleanup changed live image") + } + if _, err := reader.Open(ctx, *h.Current); err != nil { + t.Fatalf("intent cleanup removed live root: %v", err) + } +} + +type catalogDeleteFaultFiler struct { + afterRunning func() + Filer + beforeHead bool + lostHead bool + failSuccess bool + headWrites int + afterPage func() + fault error +} + +func (f *catalogDeleteFaultFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + logical := e.Name == layout.HeadName && bytes.Contains(e.Content, []byte(`"kind":"snapshot-delete-intent"`)) + if logical && f.beforeHead { + f.beforeHead = false + return f.fault + } + if string(e.Extended[layoutKind]) == "snapshot-operation" && f.failSuccess { + var op SnapshotOperation + if err := json.Unmarshal(e.Content, &op); err != nil { + return err + } + if op.State == "succeeded" { + f.failSuccess = false + return f.fault + } + } + if err := f.Filer.UpdateEntry(ctx, dir, e, expected); err != nil { + return err + } + if string(e.Extended[layoutKind]) == "snapshot-operation" && f.afterRunning != nil { + var op SnapshotOperation + if err := json.Unmarshal(e.Content, &op); err != nil { + return err + } + if op.State == "running" { + hook := f.afterRunning + f.afterRunning = nil + hook() + } + } + if logical { + f.headWrites++ + if f.lostHead { + f.lostHead = false + return f.fault + } + } + return nil +} +func (f *catalogDeleteFaultFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, exclusive bool) error { + if err := f.Filer.CreateEntry(ctx, dir, e, exclusive); err != nil { + return err + } + if path.Base(dir) == layout.ListDir && f.afterPage != nil { + hook := f.afterPage + f.afterPage = nil + hook() + } + return nil +} + +func TestSnapshotDeleteLogicalCommitResumesAcrossLostAnswers(t *testing.T) { + for _, phase := range []string{"before-publication", "after-publication-before-settle"} { + t.Run(phase, func(t *testing.T) { + ctx := context.Background() + cat, v, st, op, before := catalogDeleteIntentFixture(t) + injected := errors.New("executor interrupted") + faults := &catalogDeleteFaultFiler{Filer: st.f, fault: injected, beforeHead: phase == "before-publication", lostHead: phase != "before-publication", failSuccess: phase != "before-publication"} + executor, err := NewBCatalog(faults, st.b, cat.base) + if err != nil { + t.Fatal(err) + } + stalled, err := executor.RunSnapshotDeleteOperation(ctx, v, op, nil) + if !errors.Is(err, injected) || stalled.State != "stalled" { + t.Fatalf("uncertain step became terminal: %+v %v", stalled, err) + } + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + _, present := h.Snapshots[op.Name] + if phase == "before-publication" { + if !present || h.List != nil || h.Gen != before.Gen { + t.Fatalf("failed CAS changed HEAD: %+v", h) + } + } else if present || h.List == nil || h.Gen != before.Gen+1 { + t.Fatalf("lost reply lost its intent: %+v", h) + } + other, err := NewBCatalog(faults, st.b, cat.base) + if err != nil { + t.Fatal(err) + } + done, err := other.RunSnapshotDeleteOperation(ctx, v, stalled, nil) + if err != nil || done.State != "succeeded" || done.Instance != op.Instance { + t.Fatalf("restart did not settle target: %+v %v", done, err) + } + h, _, err = st.ReadHead(ctx) + if err != nil || h.Gen != before.Gen+1 || h.List == nil || faults.headWrites != 1 { + t.Fatalf("resume did another HEAD write: %+v writes=%d err=%v", h, faults.headWrites, err) + } + replay, err := other.RunSnapshotDeleteOperation(ctx, v, op, nil) + if err != nil || !bytes.Equal(done.Result, replay.Result) || faults.headWrites != 1 { + t.Fatalf("replay changed outcome: %+v %v", replay, err) + } + }) + } +} + +func TestSnapshotDeleteLogicalCommitSparesReplacement(t *testing.T) { + ctx := context.Background() + cat, v, st, op, h := catalogDeleteIntentFixture(t) + replacement := h.Snapshots[op.Name] + replacement.Gen = h.Gen + 1 + h.Snapshots[op.Name] = replacement + if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseSnapshotUnchanged); err != nil { + t.Fatal(err) + } + before, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + done, err := cat.RunSnapshotDeleteOperation(ctx, v, op, nil) + after, _, readErr := st.ReadHead(ctx) + if err != nil || readErr != nil || done.State != "succeeded" || after.Gen != before.Gen || after.Snapshots[op.Name].Gen != replacement.Gen || after.List != nil { + t.Fatalf("old target removed replacement: %+v %+v %v %v", done, after, err, readErr) + } +} + +func TestSnapshotDeleteLogicalCommitChecksOwnerAfterStaging(t *testing.T) { + ctx := context.Background() + cat, v, st, op, before := catalogDeleteIntentFixture(t) + faults := &catalogDeleteFaultFiler{Filer: st.f} + faults.afterPage = func() { + current, err := st.ReadSnapshotOperationHandle(ctx, op.ID, op.Verb, op.Instance, op.Sequence) + if err != nil { + t.Fatal(err) + } + if _, err := st.AdvanceSnapshotOperation(ctx, current, "running", nil, ""); err != nil { + t.Fatal(err) + } + } + executor, err := NewBCatalog(faults, st.b, cat.base) + if err != nil { + t.Fatal(err) + } + _, err = executor.RunSnapshotDeleteOperation(ctx, v, op, nil) + if !errors.Is(err, ErrSnapshotOperationOwner) { + t.Fatalf("stale owner published: %v", err) + } + h, _, err := st.ReadHead(ctx) + if err != nil || h.Gen != before.Gen || h.List != nil || h.Snapshots[op.Name].Gen != *op.TargetGeneration { + t.Fatalf("stale owner changed HEAD: %+v %v", h, err) + } +} + +func TestSnapshotDeleteLogicalCommitAbsentHeadRefuses(t *testing.T) { + ctx := context.Background() + cat, v, st, op, _ := catalogDeleteIntentFixture(t) + faults := &catalogDeleteFaultFiler{Filer: st.f} + faults.afterRunning = func() { + if err := st.f.DeleteEntry(ctx, st.root, layout.HeadName, nil); err != nil { + t.Fatal(err) + } + } + executor, err := NewBCatalog(faults, st.b, cat.base) + if err != nil { + t.Fatal(err) + } + _, err = executor.RunSnapshotDeleteOperation(ctx, v, op, nil) + if !errors.Is(err, layout.ErrHeadAbsent) { + t.Fatalf("missing HEAD answered success: %v", err) + } + if _, err := st.f.LookupEntry(ctx, st.root, layout.HeadName); !errors.Is(err, ErrNotFound) { + t.Fatalf("HEAD recreated: %v", err) + } + pages, err := st.f.ListEntries(ctx, path.Join(st.root, layout.ListDir), "", "", 128) + if err != nil || len(pages) != 0 { + t.Fatalf("absent HEAD published intent: %d %v", len(pages), err) + } + entry, err := st.f.LookupEntry(ctx, st.operationDirectory(), operationReceiptName(op.Sequence)) + if err != nil { + t.Fatal(err) + } + var retained SnapshotOperation + if err := json.Unmarshal(entry.Content, &retained); err != nil { + t.Fatal(err) + } + if retained.State == "succeeded" || retained.State == "refused" { + t.Fatalf("absent HEAD made terminal receipt: %+v", retained) + } +} + +func TestSnapshotDeleteLogicalCommitStagesBoundedCompletePages(t *testing.T) { + ctx := context.Background() + filer, blobs := NewMemFiler(), newFakeBlobs() + cat, err := NewBCatalog(filer, blobs, "/blocks") + if err != nil { + t.Fatal(err) + } + v := newRef(t, "many") + n := layout.MaxListPageEntries + 3 + if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: uint64(n+1) * 16384, BlockSize: 4096, ChunkBytes: 16384}); err != nil { + t.Fatal(err) + } + st, err := cat.Store(v) + if err != nil { + t.Fatal(err) + } + refs := make(map[uint64]layout.Ref, n) + for i := 0; i < n; i++ { + raw := bytes.Repeat([]byte{byte(i)}, 4096) + name := layout.NameChunk(uint64(i), raw) + if err := st.Create(ctx, name.Path(), raw, "seed"); err != nil { + t.Fatal(err) + } + refs[uint64(i)] = layout.Ref{Owner: v.Name, OwnerID: v.ID, Chunk: name} + } + root, segments, err := layout.Build(refs) + if err != nil { + t.Fatal(err) + } + rn, err := layout.PrepareRoot(ctx, st, root, segments, "seed") + if err != nil { + t.Fatal(err) + } + h, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + h.Version = layout.HeadVersion1 + h.Snapshots = map[string]layout.Snapshot{"s": {Root: rn, Gen: h.Gen + 1}} + if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseSnapshotUnchanged); err != nil { + t.Fatal(err) + } + op, err := st.AdmitSnapshotDeleteOperation(ctx, "many-delete", "s", func(context.Context) (uint64, error) { return h.Snapshots["s"].Gen, nil }) + if err != nil { + t.Fatal(err) + } + if done, err := cat.RunSnapshotDeleteOperation(ctx, v, op, nil); err != nil || done.State != "succeeded" { + t.Fatalf("many-target logical commit: %+v %v", done, err) + } + h, _, err = st.ReadHead(ctx) + if err != nil || h.List == nil { + t.Fatalf("missing pages: %+v %v", h, err) + } + seen := map[string]bool{} + pages := 0 + err = layout.ReadListChain(ctx, st, v.ID, *h.List, func(_ layout.ListRef, p layout.ListPage) error { + pages++ + if len(p.Entries) > layout.MaxListPageEntries || p.Producer != op.Instance || p.Generation != op.Sequence || p.Target.Gen != *op.TargetGeneration { + t.Fatalf("page identity/bound: %+v", p) + } + for _, rel := range p.Entries { + seen[rel] = true + } + return nil + }) + if err != nil || pages < 2 || len(seen) != n+len(segments)+1 { + t.Fatalf("plan omitted candidates: pages=%d entries=%d want=%d err=%v", pages, len(seen), n+len(segments)+1, err) + } + for _, ref := range refs { + if !seen[ref.Chunk.Path()] { + t.Fatalf("missing chunk candidate %s", ref.Chunk.Path()) + } + } + for sn := range segments { + if !seen[sn.Path()] { + t.Fatalf("missing segment candidate %s", sn.Path()) + } + } + if !seen[rn.Path()] { + t.Fatal("missing root candidate") + } +} + +func TestSnapshotDeleteLogicalCommitSettlesCreateWithoutChangingItsOutcome(t *testing.T) { + ctx := context.Background() + cat, v, st, _, h := catalogDeleteIntentFixture(t) + create, _, err := st.CreateSnapshotOperation(ctx, "original-create", "create", "s", strings.Repeat("a", 64)) + if err != nil { + t.Fatal(err) + } + create, err = st.AdvanceSnapshotOperation(ctx, create, "running", nil, "") + if err != nil { + t.Fatal(err) + } + snapshot := h.Snapshots["s"] + snapshot.Gen = h.Gen + 1 + snapshot.Meta.Operation = &layout.SnapshotOperationBinding{ID: create.ID, Sequence: create.Sequence, Instance: create.Instance, Owner: create.Owner, Fingerprint: create.Fingerprint, Generation: h.Gen + 1, Epoch: h.Epoch} + h.Snapshots["s"] = snapshot + if err := st.UpdateHead(ctx, h.Gen, h, layout.CauseSnapshotUnchanged); err != nil { + t.Fatal(err) + } + published, _, err := st.ReadHead(ctx) + if err != nil { + t.Fatal(err) + } + original, err := json.Marshal(SnapshotInfoFromHead(v.Name, "s", published)) + if err != nil { + t.Fatal(err) + } + deletion, err := st.AdmitSnapshotDeleteOperation(ctx, "bound-delete", "s", func(context.Context) (uint64, error) { return snapshot.Gen, nil }) + if err != nil { + t.Fatal(err) + } + done, err := cat.RunSnapshotDeleteOperation(ctx, v, deletion, nil) + if err != nil || done.State != "succeeded" { + t.Fatalf("delete did not settle: %+v %v", done, err) + } + retained, err := st.ReadSnapshotOperationHandle(ctx, create.ID, create.Verb, create.Instance, create.Sequence) + if err != nil || retained.State != "succeeded" || !bytes.Equal(retained.Result, original) { + t.Fatalf("unlink did not preserve unsettled create outcome: %+v want=%s err=%v", retained, original, err) + } + replay, created, err := st.CreateSnapshotOperation(ctx, create.ID, create.Verb, create.Name, create.Fingerprint) + if err != nil || created || !bytes.Equal(replay.Result, original) { + t.Fatalf("create replay changed after delete: %+v %v", replay, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_snapshot_operation.go b/seaweed-block/core/frontend/chunkstore/catalog_snapshot_operation.go index 104d7eee89..c6ea439723 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_snapshot_operation.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_snapshot_operation.go @@ -39,7 +39,9 @@ func (c *BCatalog) RunSnapshotDeleteOperation(ctx context.Context, v VolumeRef, return op, nil } if work == nil { - return op, errors.New("chunkstore: snapshot delete needs its durable work executor") + work = func(ctx context.Context, st *LayoutStore, running SnapshotOperation) error { + return c.snapshotDeleteLogicalStep(ctx, v, st, running) + } } if op.Revision != expected.Revision || op.Owner != expected.Owner { return SnapshotOperation{}, ErrSnapshotOperationOwner diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 4e4d702016..6e42130916 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -24,6 +24,8 @@ import ( // pins it. "GAP" marks a reader that takes an absent HEAD for an empty // one; a change that treats an absent HEAD as unknown flips those probes. var headReaders = map[string]string{ + "core/frontend/chunkstore/catalog_snapshot_delete_intent.go snapshotDeleteLogicalStep -> ReadHead": "absent HEAD refuses without unlink, pages or terminal receipt (TestSnapshotDeleteLogicalCommitAbsentHeadRefuses)", + "core/frontend/chunkstore/snapshot_operation_index.go readOperationIndex -> ReadHead": "missing HEAD gives an empty query only without INDEX; existing INDEX without HEAD refuses; deleting/deleted refuses before dead-incarnation lookup (TestSnapshotOperationDeleteFencesPausedPublications, TestSnapshotOperationCleanupRequiresDeletedHead)", "core/frontend/chunkstore/snapshot_operation.go checkSnapshotOperationAdmission -> ReadHead": "absent HEAD refuses admission; deleting/deleted refuses after INDEX and receipt publication (TestSnapshotOperationAdmissionRechecksHeadAfterPublication, TestSnapshotOperationCleanupRequiresDeletedHead)", "core/frontend/chunkstore/snapshot_operation_index.go writeOperationIndex -> ReadHead": "absent HEAD refuses first-index publication; deleting/deleted refuses sequence reset after namespace cleanup (TestSnapshotOperationCleanupRequiresDeletedHead, TestSnapshotOperationVolumeDeleteEndsNamespace)", 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 index 62266504c5..01252afa3c 100644 --- a/seaweed-block/core/host/volume/snapshot_operation_terminal_guard_test.go +++ b/seaweed-block/core/host/volume/snapshot_operation_terminal_guard_test.go @@ -43,13 +43,19 @@ func TestSnapshotOperationTerminalWriterEnumeration(t *testing.T) { if !ok || fn.Body == nil { continue } - var execution token.Pos + var execution, deleteCommit, deleteProof 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 == "RunDeleteSnapshotWithIntent" { + deleteCommit = call.Pos() + } + if ok && sel.Sel.Name == "DeleteSnapshotAt" { + deleteProof = call.Pos() + } if ok && sel.Sel.Name == "SnapshotVolume" { execution = call.Pos() } @@ -86,6 +92,14 @@ func TestSnapshotOperationTerminalWriterEnumeration(t *testing.T) { seen[key]++ switch key { case "core/frontend/chunkstore/snapshot_operation_guard.go:SettleSnapshotOperationFromHead:succeeded": + case "core/frontend/chunkstore/catalog_snapshot_delete_intent.go:snapshotDeleteLogicalStep:succeeded": + if deleteCommit == token.NoPos || deleteProof == token.NoPos || deleteCommit >= deleteProof || deleteProof >= call.Pos() { + t.Errorf("%s: delete success must follow shared logical commit and fixed-target absence proof", fset.Position(call.Pos())) + } + // Fixed-target absence is proved by the shared atomic + // unlink+intent CAS (or its already-absent HEAD fact). + // Real catalog controls cover lost publication/settle + // replies and spare a replacement incarnation. case "core/frontend/chunkstore/snapshot_delete_operation.go:refuseInitiallyAbsentDelete:refused": code, ok := call.Args[4].(*ast.BasicLit) if !ok || code.Value != `"not_found"` { @@ -114,7 +128,7 @@ func TestSnapshotOperationTerminalWriterEnumeration(t *testing.T) { t.Fatal(err) } } - for _, key := range []string{"core/frontend/chunkstore/snapshot_operation_guard.go:SettleSnapshotOperationFromHead:succeeded", "core/host/volume/chunk_control.go:snapshotOperationAttempt:refused", "core/frontend/chunkstore/snapshot_delete_operation.go:refuseInitiallyAbsentDelete:refused"} { + for _, key := range []string{"core/frontend/chunkstore/catalog_snapshot_delete_intent.go:snapshotDeleteLogicalStep:succeeded", "core/frontend/chunkstore/snapshot_operation_guard.go:SettleSnapshotOperationFromHead:succeeded", "core/host/volume/chunk_control.go:snapshotOperationAttempt:refused", "core/frontend/chunkstore/snapshot_delete_operation.go:refuseInitiallyAbsentDelete: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 90e244f07e..1d98019805 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -631,7 +631,7 @@ stateDiagram-v2 running --> stalled: interrupted or retryable attempt stalled --> running: conditional readmission, fresh owner accepted --> succeeded: reconcile existing HEAD binding - running --> succeeded: settle published binding + running --> succeeded: settle published binding or logical delete stalled --> succeeded: removal/readmission settles binding accepted --> refused: definite refusal running --> refused: definite refusal @@ -661,6 +661,13 @@ After ordered volume deletion, GC conditionally removes receipts before INDEX; interrupted or late garbage is collected by a later pass. HEAD and VOLUME stay. No elapsed-time window or absence of bytes after GC returns grants safety. +The CLI-owned delete attempt stages immutable candidate pages and delegates to +`RunDeleteSnapshotWithIntent`: removing the retained `(name, gen)` and naming +its durable reclamation intent are one HEAD CAS. Only then, or after proving +the retained target already absent/replaced, does the receipt settle. Physical +intent consumption needs HEAD/pages, never the receipt; receipt retirement +cannot strand it. Lost publication or settlement replies resume the same target. + ## Part B. Invariant ledger @@ -1335,6 +1342,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-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` | SnapVolDel rows 257-260 (per-incarnation) | STUB | | `INV-SNAP-OP-END-001` | Operation metadata is scoped to full VolumeID and creation generation. Late writes in a closed incarnation grant no authority. Dead-incarnation GC is idempotent and cannot affect a replacement; it does not promise no later writes. | M9 live incarnation to dead and GC | `operationDirectory`, `readOperationIndex`, `deleteSnapshotOperations` | `TestSnapshotOperationDeleteFencesPausedPublications`, `TestSnapshotOperationVolumeDeleteCleanupReruns`, `TestSnapshotOperationVolumeDeleteSparesForeignReceipt`, `TestSnapshotOperationDeadGCSparesUnobservedIncarnation` | SnapVolDel rows 257-260 (per-incarnation) | STUB | diff --git a/seaweed-block/docs/design/snapshot-operation-index.md b/seaweed-block/docs/design/snapshot-operation-index.md index 962cba87e3..60d09039e7 100644 --- a/seaweed-block/docs/design/snapshot-operation-index.md +++ b/seaweed-block/docs/design/snapshot-operation-index.md @@ -145,30 +145,43 @@ NoOrphanAfterEnd is not its target. GC visits only the incarnation whose own HEAD was observed deleted, never every child of the operations parent; a sibling without that death observation stays untouched. Whole-unit and native qualification remain separate. -## CLI-owned catalog attempt boundary +## CLI-owned catalog logical delete `BCatalog.RunSnapshotDeleteOperation` accepts an already admitted receipt. It -reads that exact volume/instance/sequence, checks the intent and owner/revision, -then takes the existing running transition. It never resolves a snapshot name -or admits another request. A work error becomes a resumable stalled receipt; -a lost cleanup CAS rereads only the captured incarnation. Terminal results -come from the durable receipt, not from a callback return or process memory. -A nil callback error without a durable terminal receipt remains nonterminal. +reads that exact volume/instance/sequence, checks intent and owner/revision, +then takes the existing running transition. It never resolves the name or +admits a new request. An interrupted attempt persists stalled state; cleanup +rereads only the captured incarnation, and another CLI host can resume it. -The CLI execution seam returns an admitted handle without launching work for -no-wait; default execution runs in the CLI process. A later catalog/CLI instance -reads the same filer receipt and continues with its fixed target. No daemon is -introduced. These are transport/ownership boundaries, not an implementation of -V8 cleanup or a new terminal writer. The production work adapter and public -snapshot-delete flag wiring remain inactive until the common producer and -atomic logical-commit adapter are integrated. Callback controls do not qualify a real HEAD -unlink, legacy stamp, physical list cleanup or power loss. +Without a work override the catalog uses the shared snapshot-delete intent +transition. It reads the retained `(name, gen)`, stages its root, segment and +locally owned chunk candidates as immutable pages, then calls +`RunDeleteSnapshotWithIntent`. That ONE HEAD CAS removes only the retained +incarnation and publishes the durable intent. The catalog adds no HEAD writer +and does not claim a holder or change its epoch. A currently absent/replaced +target needs no HEAD write. The final fixed-target absence proof precedes the +receipt's conditional terminal write. No provider error alone becomes refusal. -The delete is its own operation and receipt. It targets the incarnation the -create bound, never the display name alone; the create receipt/result stays -immutable. Delete success follows the logical HEAD transition removing the -entry and durably recording the V8 deleting identity and intent in that same -step. Physical reclamation follows that intent independently; retirement of -the delete receipt must neither strand nor control it. The work adapter must -prove that logical commit before settling this request. A bare RunDeleteSnapshotAt -that only removes a row is not that combined commit. +The typed success result is `{volume_id, name, gen}`: the incarnation confirmed +absent, not a count of reclaimed bytes. The create receipt/result never changes. +Receipt retirement cannot strand physical reclamation: a later executor calls +`RunConsumeSnapshotDeleteIntent` from HEAD/pages alone with the ordinary +reachability, activity and conditional mark/delete guards. It does not require +the delete receipt or the original process. Metadata reply loss settles by +rereading the fixed target, and settlement failure leaves the same operation +resumable without another unlink. + +Page identity uses the immutable operation instance and sequence, independent +of a changing HEAD CAS base or owner token. Enumeration holds the decoded root +and its shard order plus one segment and one at-most-4096-entry page; it does +not accumulate a volume-wide candidate list. Each page is at most 1 MiB and the +chain at most 4096 pages. Sorting is per segment/page. Total planning work still +scales with the removed root's references; root-read progress windows remain +unit-2 work. Foreign pool objects are not this volume's removal candidates. + +The CLI execution seam returns an admitted handle without work for no-wait and +uses this catalog adapter for normal execution; a custom work callback cannot +fabricate success merely by returning nil. Public snapshot-delete flag parsing +and admission still need activation against the shared stamped-generation +producer. Local controls qualify the logical HEAD/receipt coupling and offline +intent resume, not the entire public procedure or native power-loss path.