From 425161bbe37cd0e3214936d2e8bea48886ce8063 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 20:27:44 -0800 Subject: [PATCH] volume delete: RED controls for the cut and the r3 P2s claude05's 04:08Z cut (no snapshot cascade) and codex01's r3 P2s (V:/share/rdma/codex01-block152-r3-review-20261116T0405Z/REVIEW.md). Controls failing against stubs: - the cut: a volume with a snapshot, an in-flight snapshot attempt, or a fork's snapshot is deleted (TestCatalog_DeleteVolumeRefusesWhile SnapshotsExist, TestCatalog_InFlightSnapshotRefusesTheDelete, ...Fork DuringTheDeleteMarkRefuses, ...TombstonesAndRefusesReuse); - incarnation: a claim check under generation G commits a re-marked G' (TestCatalog_DeleteCommitIsBoundToItsIncarnation); - lost CLI token: a rerun cannot release the earlier hold (TestOpsChunk_VolumeDelete, real master, restart); - CreateVolume drops workspaceMu before the create (TestMarkVolumeDeleting_CreateHoldsTheReservationLock); - the reservation directory's parent is not synced (TestDeletionReservations_ParentSyncBeforeUse). Co-Authored-By: Claude Opus 5.5 --- .../cmd/sw-block/chunk_volume_delete.go | 30 +- .../cmd/sw-block/chunk_volume_delete_test.go | 169 ++-- .../core/frontend/chunkstore/catalog.go | 11 +- .../core/frontend/chunkstore/volume_delete.go | 352 ++++----- .../frontend/chunkstore/volume_delete_test.go | 747 ++++++++---------- seaweed-block/core/host/master/services.go | 15 +- .../core/host/master/volume_deleting_test.go | 53 ++ .../core/lifecycle/deletion_reservations.go | 9 + .../lifecycle/deletion_reservations_test.go | 21 + 9 files changed, 685 insertions(+), 722 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 1c64d169ac..4283774d5f 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -2,8 +2,6 @@ package main import ( "context" - "crypto/rand" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -28,9 +26,10 @@ import ( func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { fs := chunkFlagSet("volume-delete", stderr) var ( - volumeID, filer, base, master string - timeout time.Duration + volumeID, filer, base, master, requestID string + timeout time.Duration ) + fs.StringVar(&requestID, "request-id", "", "this delete's operation id; a rerun with the same id resumes (or gives back) its earlier admission") fs.StringVar(&volumeID, "volume", "", "volume id (or the first argument)") fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") @@ -44,8 +43,8 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { } else if fs.NArg() != 0 { return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "give the volume once, as an argument or --volume", false) } - if volumeID == "" || master == "" || timeout <= 0 { - return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume and --master are required; --timeout must be positive", false) + if volumeID == "" || master == "" || requestID == "" || timeout <= 0 { + return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume, --master and --request-id are required; --timeout must be positive", false) } cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, stdout, stderr) if exit >= 0 { @@ -57,10 +56,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { return chunkResult("volume-delete", nil, err, stdout, stderr) } defer conn.Close() - admit, err := newMasterAdmission(control.NewLifecycleServiceClient(conn)) - if err != nil { - return chunkResult("volume-delete", nil, err, stdout, stderr) - } + admit := &masterAdmission{lc: control.NewLifecycleServiceClient(conn), token: requestID + "-" + fmt.Sprint(time.Now().UnixNano())} // RED: a fresh token per invocation ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() res, err := cat.DeleteVolume(ctx, volumeID, admit) @@ -70,21 +66,15 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { return chunkResult("volume-delete", res, nil, stdout, stderr) } -// masterAdmission is the delete's reservation at the blockmaster, under -// one random token per delete. +// masterAdmission is the delete's reservation at the blockmaster, held +// under the operation's request id: a rerun with the same id adopts the +// hold an earlier run left (e.g. after a lost response), so its give-back +// releases it, while another operation's hold stays. type masterAdmission struct { lc control.LifecycleServiceClient token string } -func newMasterAdmission(lc control.LifecycleServiceClient) (*masterAdmission, error) { - var b [12]byte - if _, err := rand.Read(b[:]); err != nil { - return nil, err - } - return &masterAdmission{lc: lc, token: hex.EncodeToString(b[:])}, nil -} - func (m *masterAdmission) req(vol string) *control.MarkVolumeDeletingRequest { return &control.MarkVolumeDeletingRequest{VolumeId: vol, Token: m.token} } diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go b/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go index 1378988546..535811e3a3 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete_test.go @@ -18,9 +18,40 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// volume-delete needs a volume and --master; it refuses an attached volume -// and deletes a free one (the real master runtime reports it unassigned); -// the deleted id cannot be created again. +type volumeDeleteOutput struct { + chunkstore.VolumeDeleteResult + Error *chunkErrBody `json:"error"` +} + +func lifecycleClient(t *testing.T, addr string) control.LifecycleServiceClient { + t.Helper() + c, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return control.NewLifecycleServiceClient(c) +} + +func startDeleteMaster(t *testing.T, cfg master.Config) (*master.Host, func()) { + t.Helper() + h, err := master.New(cfg) + if err != nil { + t.Fatal(err) + } + h.Start() + return h, func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = h.Close(ctx) + } +} + +// volume-delete against a real master runtime: argument checks; a held +// volume and a volume with a snapshot are refused with the admission given +// back (usable again); a lost first admission is adopted and given back by +// a rerun with the same request id (usable after a master restart); a +// completed delete is committed (never created again). func TestOpsChunk_VolumeDelete(t *testing.T) { ctx := context.Background() mem := chunkstore.NewMemFiler() @@ -32,7 +63,7 @@ func TestOpsChunk_VolumeDelete(t *testing.T) { t.Fatal(err) } geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8} - for _, vol := range []string{"v1", "v2"} { + for _, vol := range []string{"v1", "v2", "v3"} { if _, err := cat.EnsureVolume(ctx, vol, geo); err != nil { t.Fatal(err) } @@ -49,50 +80,7 @@ func TestOpsChunk_VolumeDelete(t *testing.T) { if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadActive}); err != nil { t.Fatal(err) } - - for _, args := range [][]string{ - {"volume-delete", "v1", "--chunk-filer", "f:1"}, // no --master - {"volume-delete", "--master", "m:1", "--chunk-filer", "f:1"}, // no volume - {"volume-delete", "--volume", "v1", "v2", "--master", "m:1", "--chunk-filer", "f:1"}, // two volumes - } { - if code, out, _ := runChunk(args...); code == 0 || !strings.Contains(out, codeBadRequestCLI) { - t.Fatalf("%v: %d %q; want a bad request", args, code, out) - } - } - - cfg := gcTestMasterConfig(t) - cfg.LifecycleStoreDir = t.TempDir() // MarkVolumeDeleting admits the delete - h, err := master.New(cfg) - if err != nil { - t.Fatal(err) - } - h.Start() - t.Cleanup(func() { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - _ = h.Close(ctx) - }) - // v2 is admitted by the master (it has no authority) but held in the - // catalog: refused, and the partial result says what was done. - code, out, _ := runChunk("volume-delete", "--chunk-filer", "f:1", "--master", h.Addr(), "v2") - var partial struct { - chunkstore.VolumeDeleteResult - Error *chunkErrBody `json:"error"` - } - if code == 0 || json.Unmarshal([]byte(out), &partial) != nil || partial.Error == nil || partial.Error.Code != chunkstore.CodeVolumeInUse || !partial.Admitted || !partial.AdmissionAborted || partial.HeadMarked || partial.Completed { - t.Fatalf("delete of attached v2: %d %q; want volume_in_use with the partial result, admission given back", code, out) - } - lc := lifecycleClient(t, h.Addr()) - // The given-back id is usable at the master again. - if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v2", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { - t.Fatalf("create v2 after its delete gave back: %v", err) - } - - // Integrated claim refusal: v3 has a snapshot a real, incomplete fork - // claims (VOLUME published, stopped before HEAD by its deadline). - if _, err := cat.EnsureVolume(ctx, "v3", geo); err != nil { - t.Fatal(err) - } + // v3 has a snapshot. h3, _, err := cat.ReadHead(ctx, "v3") if err != nil { t.Fatal(err) @@ -100,46 +88,71 @@ func TestOpsChunk_VolumeDelete(t *testing.T) { if _, err := cat.CreateSnapshot(ctx, "v3", chunkstore.SnapshotRequest{Name: "s", RequestID: "rs"}, h3); err != nil { t.Fatal(err) } - clock := time.Now() - cat.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) - cat.OpDeadline = time.Nanosecond - if _, err := cat.Fork(ctx, chunkstore.ForkRequest{Source: "v3", Snapshot: "s", Target: "w3", RequestID: "f"}); chunkstore.CodeOf(err) != chunkstore.CodeDeadlineExceeded { - t.Fatalf("stopped fork: %v", err) + + for _, args := range [][]string{ + {"volume-delete", "--chunk-filer", "f:1", "--request-id", "x", "v1"}, // no --master + {"volume-delete", "--chunk-filer", "f:1", "--master", "m:1", "v1"}, // no --request-id + {"volume-delete", "--master", "m:1", "--request-id", "x", "--chunk-filer", "f:1"}, // no volume + {"volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "x", "v2", "extra"}, // two volumes + } { + if code, out, _ := runChunk(args...); code == 0 || !strings.Contains(out, codeBadRequestCLI) { + t.Fatalf("%v: %d %q; want a bad request", args, code, out) + } } - cat.OpDeadline = 0 - code, out, _ = runChunk("volume-delete", "--chunk-filer", "f:1", "--master", h.Addr(), "v3") - partial.Error = nil - if code == 0 || json.Unmarshal([]byte(out), &partial) != nil || partial.Error == nil || partial.Error.Code != chunkstore.CodeSnapshotClaimed || !partial.Reverted || !partial.AdmissionAborted { - t.Fatalf("delete of claimed v3: %d %q; want snapshot_claimed, reverted, admission given back", code, out) + + cfg := gcTestMasterConfig(t) + cfg.LifecycleStoreDir = t.TempDir() // the reservation store lives here + h, stop := startDeleteMaster(t, cfg) + lc := lifecycleClient(t, h.Addr()) + run := func(vol, op string) (int, volumeDeleteOutput) { + t.Helper() + code, out, _ := runChunk("volume-delete", "--chunk-filer", "f:1", "--master", h.Addr(), "--request-id", op, vol) + var got volumeDeleteOutput + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatalf("volume-delete %s: %q", vol, out) + } + return code, got } - if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v3", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { - t.Fatalf("create v3 after the claim refusal: %v; want usable again", err) + usable := func(vol string) { + t.Helper() + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatalf("create %s: %v; want usable", vol, err) + } } + + // Held: refused, admission given back. + if code, got := run("v2", "op-v2"); code == 0 || got.Error == nil || got.Error.Code != chunkstore.CodeVolumeInUse || !got.Admitted || !got.AdmissionAborted || got.Completed { + t.Fatalf("delete of attached v2: %d %+v", code, got) + } + usable("v2") + + // A first invocation's admission landed and its reply was lost (the + // master holds op-v3); the rerun with the same request id meets the + // snapshot, gives back and so releases that hold too. + if _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v3", Token: "op-v3"}); err != nil { + t.Fatal(err) + } + if code, got := run("v3", "op-v3"); code == 0 || got.Error == nil || got.Error.Code != chunkstore.CodeVolumeHasSnapshots || !got.Reverted || !got.AdmissionAborted { + t.Fatalf("rerun of v3's delete: %d %+v; want volume_has_snapshots, reverted, given back", code, got) + } + stop() + h, stop = startDeleteMaster(t, cfg) // restart: the given-back id stays usable + defer stop() + lc = lifecycleClient(t, h.Addr()) + usable("v3") if _, err := cat.EnsureVolume(ctx, "v3", geo); err != nil { - t.Fatalf("attach v3 after the claim refusal: %v; want usable again", err) + t.Fatalf("attach v3 after the refused delete: %v", err) } - code, out, errs := runChunk("volume-delete", "--chunk-filer", "f:1", "--master", h.Addr(), "v1") - var res chunkstore.VolumeDeleteResult - if code != 0 || json.Unmarshal([]byte(out), &res) != nil || res.VolumeID != "v1" || res.Replayed || !res.Completed { - t.Fatalf("delete v1: %d %q %q", code, out, errs) + + // Completed: committed, never created again. + code, got := run("v1", "op-v1") + if code != 0 || got.VolumeID != "v1" || !got.Completed || !got.Committed { + t.Fatalf("delete v1: %d %+v", code, got) } if _, err := cat.EnsureVolume(ctx, "v1", geo); chunkstore.CodeOf(err) != chunkstore.CodeVolumeDeleted { t.Fatalf("recreate v1: %v; want volume_deleted", err) } - if !res.Committed { - t.Fatalf("delete v1: %+v; want committed", res) - } if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1 << 20, ReplicationFactor: 1}); status.Code(err) != codes.FailedPrecondition { t.Fatalf("create v1 after its committed delete: %v; want FailedPrecondition", err) } } - -func lifecycleClient(t *testing.T, addr string) control.LifecycleServiceClient { - t.Helper() - c, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { c.Close() }) - return control.NewLifecycleServiceClient(c) -} diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index d7e1dfa2ba..8c58201cf5 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -847,16 +847,13 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe if err != nil { return SnapshotInfo{}, err } - // A volume delete marks HEAD deleting before it lists the names: if - // this name was taken after that listing, this read sees the mark, and - // the attempt is given up before anything is published. + // A volume delete marks HEAD deleting before it checks for snapshot + // names: either it sees this name (and refuses), or this read sees the + // mark and nothing is published. The name stays as it is (the delete + // never touches snapshot names; DeleteSnapshot settles it). if gone, err := c.volumeGone(ctx, vol); err != nil { return SnapshotInfo{}, err } else if gone { - // Settle this name as the delete does: the attempt's tombstone or - // its winning publication is confirmed before the name is freed; - // on failure the name stays, so the delete still finds it. - _, _, _, _ = c.deleteNameForVolume(ctx, vol, root, req.Name) return SnapshotInfo{}, refuseDeleted(vol, "it cannot be snapshotted") } diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete.go b/seaweed-block/core/frontend/chunkstore/volume_delete.go index 2a2b13c73a..ef77076bce 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete.go @@ -5,6 +5,7 @@ import ( "errors" "path" "strconv" + "strings" "google.golang.org/protobuf/proto" @@ -12,8 +13,8 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// Volume delete (claude05's item, 2026-11-16 02:39Z; one linearization -// point per codex01's review of 7c43367). +// Volume delete (claude05's item, 2026-11-16 02:39Z; claude05's 04:08Z +// cut: no snapshot cascade). // // (a) Admission: the caller's Admission (the CLI's: the blockmaster's // durable deletion reservation, MarkVolumeDeleting; refused while the @@ -21,35 +22,36 @@ import ( // placement or binding is admitted and the id is not created again). // Every give-back below aborts this delete's admission (restoring the // volume's usability); the commit point commits it (permanent). -// (b) The linearization point: one conditional write of HEAD from the -// HEAD read (active or detached, NOT held: an active HEAD that names a -// holder belongs to an attached server) to state deleting, chunks -// kept. ChunkRemote.CASHead refuses to move a deleting or deleted -// HEAD, so no attach, claim or restore can revive it; EnsureVolume -// refuses it; Fork and CreateSnapshot check HEAD again after taking -// their claim or name and back out when it is deleting. -// (c) Claims are read after (b): a live fork claim reverts HEAD to its -// previous state (nothing irreversible was done) and refuses -// (snapshot_claimed). A fork claiming later sees the deleting HEAD -// and gives its claim back. -// (c') The commit point: HEAD deleting -> purging, conditioned on the -// HEAD read, then the admission is committed. A revert and a commit -// race on the same conditional write, so a delete that sampled a -// claim can never undo another delete's irreversible steps, and a -// delete whose mark was given back never starts them. -// (d) Only then the irreversible steps: every snapshot name, published or -// not (an unpublished attempt gets an aborted tombstone so its late -// publish cannot land), is marked through markDeleting (the one mark -// path) and freed; the volume's own fork claim is released. -// (e) Finally HEAD becomes deleted (no chunks: nothing it held stays a GC -// root) and VOLUME is marked deleted. GC reclaims. +// (b) One HEAD write from the HEAD read (active or detached, NOT held: an +// active HEAD that names a holder belongs to an attached server) to +// state deleting, chunks kept: a new incarnation of the delete mark +// (its generation). ChunkRemote.CASHead refuses to move a deleting, +// purging or deleted HEAD, so no attach, claim or restore can revive +// it; EnsureVolume refuses it; CreateSnapshot and Fork check the +// volume after taking their name or claim and refuse. +// (c) Under that incarnation, the volume must have no snapshot at all: no +// snapshot name record (a published snapshot, one being deleted, or an +// attempt still in flight). Any is volume_has_snapshots: HEAD is +// reverted and the admission given back. The operator deletes the +// snapshots first (DeleteSnapshot); a delete never touches snapshot +// names, attempts or their roots. (A fork claim lives on a named +// snapshot, so it is covered too.) +// (c') The commit point: HEAD deleting -> purging for that same +// incarnation only (conditioned on its generation); if HEAD moved (a +// revert and re-mark by another delete), the check is made again on +// the incarnation found. A revert is bound the same way, so no delete +// can undo another's commit, nor commit an incarnation it did not +// check. Then the admission is committed. +// (e) HEAD becomes deleted (no chunks: nothing it held stays a GC root) and +// VOLUME is marked deleted. GC reclaims. // // A call that fails reports what it did (VolumeDeleteResult) with the // error; a rerun resumes from the state it finds. const ( - CodeVolumeInUse = "volume_in_use" - CodeVolumeDeleted = "volume_deleted" + CodeVolumeInUse = "volume_in_use" + CodeVolumeDeleted = "volume_deleted" + CodeVolumeHasSnapshots = "volume_has_snapshots" // VolumeDeleted is the state of a deleted volume's VOLUME entry. VolumeDeleted = "deleted" @@ -59,7 +61,7 @@ const ( // Test seams (retainHook stages) in a DeleteVolume. hookHeadMarked = "head-marked" // after (b) - hookClaimFound = "claim-found" // (c) found a live claim, before the revert + hookBlocked = "blocked" // (c) found a snapshot, before the revert hookClaimsChecked = "claims-checked" // after (c), before the commit point ) @@ -86,15 +88,12 @@ type VolumeDeleteResult struct { // AdmissionUncertain: the admission call failed with an unknown // outcome (it may have been recorded); AdmissionAborted: this delete // gave its admission back; Committed: the admission is permanent. - AdmissionUncertain bool `json:"admissionUncertain"` - AdmissionAborted bool `json:"admissionAborted"` - Committed bool `json:"committed"` - HeadMarked bool `json:"headMarked"` // HEAD is deleting or deleted - Reverted bool `json:"reverted"` // (c) gave the HEAD mark back - SnapshotsDeleted []string `json:"snapshotsDeleted"` - AttemptsAborted []string `json:"attemptsAborted"` // unpublished attempts tombstoned - ClaimReleased bool `json:"claimReleased"` // its fork claim was confirmed removed - Completed bool `json:"completed"` // HEAD and VOLUME are deleted + AdmissionUncertain bool `json:"admissionUncertain"` + AdmissionAborted bool `json:"admissionAborted"` + Committed bool `json:"committed"` + HeadMarked bool `json:"headMarked"` // HEAD is deleting or deleted + Reverted bool `json:"reverted"` // (c) gave the HEAD mark back + Completed bool `json:"completed"` // HEAD and VOLUME are deleted // Uncertain is set when the failing call was a write whose outcome is // unknown; a rerun settles it. Uncertain bool `json:"uncertain"` @@ -103,7 +102,7 @@ type VolumeDeleteResult struct { // DeleteVolume deletes vol (see the header). admit may be nil (a catalog- // only delete, e.g. in tests): (b) still refuses a held HEAD. func (c *Catalog) DeleteVolume(ctx context.Context, vol string, admit Admission) (VolumeDeleteResult, error) { - res := VolumeDeleteResult{VolumeID: vol, SnapshotsDeleted: []string{}, AttemptsAborted: []string{}} + res := VolumeDeleteResult{VolumeID: vol} root, err := c.volRoot(vol) if err != nil { return res, err @@ -142,9 +141,15 @@ func (c *Catalog) DeleteVolume(ctx context.Context, vol string, admit Admission) } return res, cause } - // (b) - if h.State != storage.ChunkHeadPurging && h.State != storage.ChunkHeadDeleted { - u, err := c.markHeadDeleting(ctx, vol, root) + // (b), (c), (c'), each bound to one deleting incarnation (the HEAD + // generation the mark produced or joined): a claim check is only valid + // for the generation it ran under, so if HEAD moved (another delete + // reverted and re-marked it) the check is run again on the new one. + for incarnation := 0; h.State != storage.ChunkHeadPurging && h.State != storage.ChunkHeadDeleted; incarnation++ { + if incarnation == 5 { + return res, remoteErr(nil, "volume %s: the delete mark kept changing", vol) + } + gen, u, err := c.markHeadDeleting(ctx, vol, root) if err != nil { if u { res.Uncertain = true @@ -155,18 +160,23 @@ func (c *Catalog) DeleteVolume(ctx context.Context, vol string, admit Admission) res.HeadMarked = true c.hook(hookHeadMarked, vol) // (c) - live, err := c.anyLiveClaim(ctx, vol) + live, err := c.snapshotsBlock(ctx, vol, root) if err != nil { return res, err } if live != nil { - c.hook(hookClaimFound, vol) - reverted, u, rerr := c.revertHeadDeleting(ctx, vol, root) + c.hook(hookBlocked, vol) + out, u, rerr := c.revertHeadDeleting(ctx, vol, root, gen) switch { case rerr != nil: res.Uncertain = u return res, rerr - case !reverted: + case out == incarnationMoved: + if h, _, err = c.ReadHead(ctx, vol); err != nil { + return res, err + } + continue // decide again on what HEAD is now + case out == incarnationCommitted: // Another delete committed meanwhile: its irreversible steps // stand; this call neither reverts nor gives back. return res, catErr(CodeOutcomeUnknown, true, nil, "volume %s: another delete committed while this one found %v; rerun the delete", vol, live) @@ -175,16 +185,22 @@ func (c *Catalog) DeleteVolume(ctx context.Context, vol string, admit Admission) return giveBack(live) } c.hook(hookClaimsChecked, vol) - // (c') the commit point - committed, u, err := c.commitHeadPurging(ctx, vol, root) + // (c') the commit point, on the incarnation the check ran under + out, u, err := c.commitHeadPurging(ctx, vol, root, gen) if err != nil { res.Uncertain = u return res, err } - if !committed { + if out == incarnationDone { + break + } + if out == incarnationGivenBack { res.HeadMarked = false return giveBack(catErr(CodeOutcomeUnknown, true, nil, "volume %s: a concurrent delete gave the mark back; rerun the delete", vol)) } + if h, _, err = c.ReadHead(ctx, vol); err != nil { // moved: validate again + return res, err + } } res.HeadMarked = true if admit != nil { @@ -194,36 +210,6 @@ func (c *Catalog) DeleteVolume(ctx context.Context, vol string, admit Admission) } } res.Committed = true - // (d) - names, err := c.listNames(ctx, root) - if err != nil { - return res, err - } - for _, name := range names { - gone, aborted, u, err := c.deleteNameForVolume(ctx, vol, root, name) - if err != nil { - res.Uncertain = u - return res, err - } - if aborted { - res.AttemptsAborted = append(res.AttemptsAborted, name) - } else if gone { - res.SnapshotsDeleted = append(res.SnapshotsDeleted, name) - } - } - if v.Fork != nil { - req := ForkRequest{Source: v.Fork.Source, Snapshot: v.Fork.Snapshot, Target: vol, RequestID: v.Fork.RequestID} - if ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot); err != nil { - return res, err - } else if ok && ref.entry != nil { - removed, err := c.removeForkClaim(ctx, req, ref.rec.Attempt) - if err != nil { - res.Uncertain = true - return res, err - } - res.ClaimReleased = removed - } - } // (e) if u, err := c.finishHeadDeleted(ctx, vol, root); err != nil { res.Uncertain = u @@ -274,18 +260,22 @@ func lostCondition(err error) bool { // markHeadDeleting is (b): every read decides afresh whether the HEAD is // held, so an attach that landed before this read is refused, and one that -// lands after it makes the write's condition fail. -func (c *Catalog) markHeadDeleting(ctx context.Context, vol, root string) (bool, error) { +// lands after it makes the write's condition fail. gen is the generation of +// the deleting HEAD this call produced or joined (its incarnation). +func (c *Catalog) markHeadDeleting(ctx context.Context, vol, root string) (gen uint64, uncertain bool, err error) { for try := 0; try < 5; try++ { h, _, err := c.ReadHead(ctx, vol) if err != nil { - return false, err + return 0, false, err + } + if h.State == storage.ChunkHeadDeleting { + return h.Gen, false, nil // join this incarnation } if headDeletingOrDeleted(h) { - return false, nil + return h.Gen, false, nil } if headHeld(h) { - return false, catErr(CodeVolumeInUse, false, nil, "volume %s is attached: HEAD is held by %q at epoch %d; detach it first", vol, h.Holder, h.Epoch) + return 0, false, catErr(CodeVolumeInUse, false, nil, "volume %s is attached: HEAD is held by %q at epoch %d; detach it first", vol, h.Holder, h.Epoch) } next := h next.State = storage.ChunkHeadDeleting @@ -297,74 +287,82 @@ func (c *Catalog) markHeadDeleting(ctx context.Context, vol, root string) (bool, continue } if err != nil { - return true, catErr(CodeOutcomeUnknown, true, err, "mark HEAD of %s deleting: outcome unknown; rerun the delete", vol) + return 0, true, catErr(CodeOutcomeUnknown, true, err, "mark HEAD of %s deleting: outcome unknown; rerun the delete", vol) } - return false, nil + return h.Gen + 1, false, nil } - return false, remoteErr(nil, "HEAD of %s kept changing", vol) + return 0, false, remoteErr(nil, "HEAD of %s kept changing", vol) } -// revertHeadDeleting gives (b) back: deleting returns to detached when the -// HEAD carries its holder's detach record, else to active. reverted is -// false when the HEAD is no longer deleting (another delete committed, or -// already gave it back). -func (c *Catalog) revertHeadDeleting(ctx context.Context, vol, root string) (reverted, uncertain bool, err error) { - for try := 0; try < 5; try++ { - h, _, err := c.ReadHead(ctx, vol) - if err != nil { - return false, false, err - } - if h.State != storage.ChunkHeadDeleting { - return h.State == storage.ChunkHeadActive || h.State == storage.ChunkHeadDetached || h.State == "", false, nil - } - next := h - next.State = storage.ChunkHeadActive - if h.DetachedBy != nil { - next.State = storage.ChunkHeadDetached - d := *h.DetachedBy - d.Gen = h.Gen + 1 - next.DetachedBy = &d - } - err = c.writeHead(ctx, root, h, next) - if lostCondition(err) { - continue - } - if err != nil { - return false, true, catErr(CodeOutcomeUnknown, true, err, "revert the delete mark on HEAD of %s: outcome unknown; rerun the delete", vol) - } - return true, false, nil +// What a revert or commit found of the incarnation it was bound to. +type incarnationOutcome int + +const ( + incarnationDone incarnationOutcome = iota // reverted / committed by this call, or committed already + incarnationMoved // HEAD is another deleting incarnation now: validate again + incarnationCommitted // past the commit point (by another delete) + incarnationGivenBack // active or detached again (another delete reverted) +) + +// revertHeadDeleting gives (b) back for incarnation gen only: deleting +// returns to detached when the HEAD carries its holder's detach record, +// else to active. +func (c *Catalog) revertHeadDeleting(ctx context.Context, vol, root string, gen uint64) (incarnationOutcome, bool, error) { + h, _, err := c.ReadHead(ctx, vol) + if err != nil { + return 0, false, err } - return false, false, remoteErr(nil, "HEAD of %s kept changing", vol) + switch { + case h.State == storage.ChunkHeadPurging || h.State == storage.ChunkHeadDeleted: + return incarnationCommitted, false, nil + case h.State != storage.ChunkHeadDeleting: + return incarnationGivenBack, false, nil // already given back: nothing to do + case h.Gen != gen: + return incarnationMoved, false, nil + } + next := h + next.State = storage.ChunkHeadActive + if h.DetachedBy != nil { + next.State = storage.ChunkHeadDetached + d := *h.DetachedBy + d.Gen = h.Gen + 1 + next.DetachedBy = &d + } + err = c.writeHead(ctx, root, h, next) + if lostCondition(err) { + return incarnationMoved, false, nil // HEAD moved under the write: decide again + } + if err != nil { + return 0, true, catErr(CodeOutcomeUnknown, true, err, "revert the delete mark on HEAD of %s: outcome unknown; rerun the delete", vol) + } + return incarnationDone, false, nil } -// commitHeadPurging is the commit point: deleting -> purging, conditioned -// on the HEAD read. committed is false when the mark was given back (the -// HEAD is active or detached again). -func (c *Catalog) commitHeadPurging(ctx context.Context, vol, root string) (committed, uncertain bool, err error) { - for try := 0; try < 5; try++ { - h, _, err := c.ReadHead(ctx, vol) - if err != nil { - return false, false, err - } - switch h.State { - case storage.ChunkHeadPurging, storage.ChunkHeadDeleted: - return true, false, nil // committed (by this call's earlier try or another delete) - case storage.ChunkHeadDeleting: - default: - return false, false, nil - } - next := h - next.State = storage.ChunkHeadPurging - err = c.writeHead(ctx, root, h, next) - if lostCondition(err) { - continue - } - if err != nil { - return false, true, catErr(CodeOutcomeUnknown, true, err, "commit the delete of %s: outcome unknown; rerun the delete", vol) - } - return true, false, nil +// commitHeadPurging is the commit point for incarnation gen only: deleting +// -> purging, conditioned on that exact HEAD. +func (c *Catalog) commitHeadPurging(ctx context.Context, vol, root string, gen uint64) (incarnationOutcome, bool, error) { + h, _, err := c.ReadHead(ctx, vol) + if err != nil { + return 0, false, err } - return false, false, remoteErr(nil, "HEAD of %s kept changing", vol) + switch { + case h.State == storage.ChunkHeadPurging || h.State == storage.ChunkHeadDeleted: + return incarnationDone, false, nil // committed (by another delete of the same mark) + case h.State != storage.ChunkHeadDeleting: + return incarnationGivenBack, false, nil + case h.Gen != gen && false: // RED: any deleting incarnation is committed + return incarnationMoved, false, nil + } + next := h + next.State = storage.ChunkHeadPurging + err = c.writeHead(ctx, root, h, next) + if lostCondition(err) { + return incarnationMoved, false, nil + } + if err != nil { + return 0, true, catErr(CodeOutcomeUnknown, true, err, "commit the delete of %s: outcome unknown; rerun the delete", vol) + } + return incarnationDone, false, nil } // finishHeadDeleted is (e) for HEAD: deleting becomes deleted, no chunks. @@ -393,32 +391,15 @@ func (c *Catalog) finishHeadDeleted(ctx context.Context, vol, root string) (bool return false, remoteErr(nil, "HEAD of %s kept changing", vol) } -// anyLiveClaim returns snapshot_claimed for the first published snapshot of -// vol a live fork claims, or nil. -func (c *Catalog) anyLiveClaim(ctx context.Context, vol string) (error, error) { - root, err := c.volRoot(vol) - if err != nil { - return nil, err - } +// snapshotsBlock returns volume_has_snapshots when vol has any snapshot +// name record (published, being deleted, or an attempt in flight), or nil. +func (c *Catalog) snapshotsBlock(ctx context.Context, vol, root string) (error, error) { names, err := c.listNames(ctx, root) if err != nil { return nil, err } - for _, name := range names { - ref, ok, err := c.resolveSnap(ctx, vol, name) - if err != nil { - return nil, err - } - if !ok || ref.entry == nil || ref.info.State != SnapActive { - continue - } - live, err := c.liveClaims(ctx, vol, name, decodeClaims(ref.entry)) - if err != nil { - return nil, err - } - if len(live) > 0 { - return claimedErr(vol, name, live), nil - } + if len(names) > 0 && false { // RED: snapshots do not block the delete + return catErr(CodeVolumeHasSnapshots, false, nil, "volume %s has snapshots (%s); delete them first", vol, strings.Join(names, ", ")), nil } return nil, nil } @@ -448,49 +429,6 @@ func (c *Catalog) listNames(ctx context.Context, root string) ([]string, error) } } -// deleteNameForVolume is (d) for one name: a published attempt goes through -// markDeleting; an unpublished one gets an aborted tombstone at its path -// (so its late publish can never land); then the name is freed. -func (c *Catalog) deleteNameForVolume(ctx context.Context, vol, root, name string) (gone, aborted, uncertain bool, err error) { - for try := 0; try < 5; try++ { - ref, ok, err := c.resolveSnap(ctx, vol, name) - if err != nil { - return false, false, false, err - } - if !ok { - return false, false, false, nil // freed meanwhile - } - attempt := ref.rec.Attempt - if ref.entry == nil { - tomb, err := c.abortedSnapEntry(vol, name, attempt) - if err != nil { - return false, false, false, err - } - if err := c.f.CreateEntry(ctx, path.Join(root, snapsDir, name), tomb, true); err != nil && !errors.Is(err, ErrExists) { - return false, false, true, remoteErr(err, "abort the unpublished attempt of %s/%s", vol, name) - } - continue // re-read: the tombstone, or the attempt that won - } - wasAborted := ref.info.State == SnapAborted - m, live, u, err := c.markDeleting(ctx, vol, name, attempt) - if err != nil { - return false, false, u, err - } - if m == markClaimed { - // A fork claimed after (c); it backs out on the deleting HEAD. - if try < 4 { - continue - } - return false, false, false, claimedErr(vol, name, live) - } - if _, u, err := c.freeName(ctx, root, name, attempt); err != nil { - return false, false, u, err - } - return !wasAborted, wasAborted, false, nil - } - return false, false, false, remoteErr(nil, "snapshot %s/%s kept changing", vol, name) -} - // markVolumeDeleted marks vol's VOLUME entry deleted, conditioned on it not // being marked yet. func (c *Catalog) markVolumeDeleted(ctx context.Context, vol, root string) error { diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go index c064dc7191..0f851565b9 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go @@ -13,8 +13,8 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// Volume delete (claude05's item; one linearization point per codex01's -// review of 7c43367). One control per review schedule. +// Volume delete: one linearization point, no snapshot cascade (claude05, +// 04:08Z). One control per review schedule. // detachHead publishes vol's HEAD as a clean detach by its holder (what a // volume server's Detach writes). @@ -37,8 +37,7 @@ func detachHead(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) { } } -// attachEntry is the HEAD an attaching holder installs over cur (a takeover: -// new holder, next epoch). +// attachEntry is the HEAD an attaching holder installs over cur. func attachEntry(t *testing.T, cur storage.ChunkHead, holder string) *filerpb.Entry { t.Helper() att := cur @@ -50,20 +49,17 @@ func attachEntry(t *testing.T, cur storage.ChunkHead, holder string) *filerpb.En return e } +// deleteFixture: v1 with an attached HEAD (held by h1) and no snapshots; +// directory entries for v1, w2, w3 (the fake lists only what it holds). func deleteFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) { t.Helper() - f, b, c, h := catalogFixture(t) // v1 HEAD held by h1 (attached) + f, b, c, h := catalogFixture(t) ctx := context.Background() for _, vol := range []string{"v1", "w2", "w3"} { if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { t.Fatal(err) } } - for _, name := range []string{"s1", "s2"} { - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: "r-" + name}, h); err != nil { - t.Fatal(err) - } - } return f, b, c, h } @@ -76,305 +72,13 @@ func headState(t *testing.T, c *Catalog, vol string) storage.ChunkHead { return h } -// An attached volume (HEAD held), or one the admission refuses, is refused -// with volume_in_use and nothing is written. -func TestCatalog_DeleteVolumeRefusesAVolumeInUse(t *testing.T) { - f, b, c, _ := deleteFixture(t) - ctx := context.Background() - before := len(f.allWritten()) - if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeInUse { - t.Fatalf("delete of an attached volume: %v; want volume_in_use", err) - } - if got := len(f.allWritten()); got != before { - t.Fatalf("a refused delete wrote %d entries", got-before) - } - detachHead(t, f, b, "v1") - before = len(f.allWritten()) - res, err := c.DeleteVolume(ctx, "v1", (&fakeReservation{refuse: true}).admission("d1")) - var ce *CatalogError - if !errors.As(err, &ce) || ce.Code != CodeVolumeInUse || ce.Retryable || !strings.Contains(ce.Detail(), "assigned to r1") || res.Admitted || res.AdmissionUncertain { - t.Fatalf("delete the admission refuses: %+v %v; want volume_in_use naming the reason", res, err) - } - if got := len(f.allWritten()); got != before { - t.Fatalf("a refused delete wrote %d entries", got-before) - } -} - -// Schedule 1: a holder attaches after the delete's first read, before the -// HEAD mark's read. The mark reads the held HEAD and refuses; HEAD stays -// the holder's. -func TestCatalog_DeleteVolumeRefusesAnAttachBeforeTheMark(t *testing.T) { - f, b, c, _ := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - headPath := path.Join(catBase, "v1", headName) - lookups := 0 - f.afterLookup = func(p string) { - if p != headPath { - return - } - if lookups++; lookups == 1 { // the delete's first read; the mark reads next - cur, _ := decodeHead(p, f.entries[p]) - f.entries[p] = attachEntry(t, cur, "h2") - } - } - if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeInUse { - t.Fatalf("delete racing an attach: %v; want volume_in_use", err) - } - f.afterLookup = nil - if h := headState(t, c, "v1"); h.Holder != "h2" || h.State != storage.ChunkHeadActive { - t.Fatalf("HEAD after the refused delete: %+v; want h2's, active", h) - } -} - -// An attach between the mark's read and its write makes the write's -// condition fail; the re-read sees the holder and refuses. -func TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark(t *testing.T) { - f, b, c, _ := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - headPath := path.Join(catBase, "v1", headName) - lookups := 0 - f.afterLookup = func(p string) { - if p != headPath { - return - } - if lookups++; lookups == 2 { // the mark's read; the write is conditioned on it - cur, _ := decodeHead(p, f.entries[p]) - f.entries[p] = attachEntry(t, cur, "h2") - } - } - if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeInUse { - t.Fatalf("delete losing to an attach: %v; want volume_in_use", err) - } - f.afterLookup = nil - if h := headState(t, c, "v1"); h.Holder != "h2" || h.State != storage.ChunkHeadActive { - t.Fatalf("HEAD after the lost delete: %+v; want h2's", h) - } -} - -// Schedule 2: an attach that passed EnsureVolume before the mark claims -// HEAD afterwards (CASHead from the deleting or deleted HEAD it reads): the -// remote refuses, so nothing revives the volume. -func TestCatalog_DeletedHeadCannotBeRevivedByAClaim(t *testing.T) { - f, b, c, _ := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) - if err != nil { - t.Fatal(err) - } - claim := func(stage string) { - t.Helper() - h, err := r.GetHead(ctx) - if err != nil { - t.Fatal(err) - } - _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch + 1, Holder: "late", RemoteLSN: h.RemoteLSN, Chunks: h.Chunks, State: storage.ChunkHeadActive}) - if !errors.Is(err, storage.ErrChunkHeadPrecondition) || !errors.Is(err, storage.ErrChunkHeadDeleted) { - t.Fatalf("claim of a %s HEAD: %v; want a precondition failure (deleted)", stage, err) - } - if _, err := c.EnsureVolume(ctx, "v1", catGeo); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("attach of a %s volume: %v; want volume_deleted", stage, err) - } - } - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked { - claim("deleting") - } - } - res, err := c.DeleteVolume(ctx, "v1", nil) - c.retainHook = nil - if err != nil || !res.Completed { - t.Fatalf("delete: %+v %v", res, err) - } - claim("deleted") - if h := headState(t, c, "v1"); h.State != storage.ChunkHeadDeleted || h.Holder != "" || len(h.Chunks) != 0 { - t.Fatalf("HEAD after the delete: %+v; want the deleted tombstone", h) - } -} - -// A fork claim that lands before the claims are read (after the mark) -// makes the delete give the mark back: snapshot_claimed, HEAD restored, -// nothing irreversible done. -func TestCatalog_DeleteVolumeGivesBackOnALiveClaim(t *testing.T) { - f, b, c, _ := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - before := headState(t, c, "v1") - holdFirst(f, catBase+"/w3/HEAD") - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked { // the claim lands after the mark, before the read of claims - c.retainHook = nil - // Fork's own claim write is what lands here; its post-check then - // refuses on the deleting HEAD, so take only the claim. - if _, err := c.claimForkParent(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); err != nil { - t.Fatal(err) - } - // The fork published its VOLUME before the delete began. - ve, _ := volumeEntry(VolumeInfo{Format: volumeFormat, VolumeID: "w3", Geometry: catGeo, Origin: OriginFork, Parent: &Parent{VolumeID: "v1", Snapshot: "s2"}, - Fork: &ForkRecord{RequestID: "f3", Source: "v1", Snapshot: "s2"}}, "f3") - if err := f.CreateEntry(ctx, catBase+"/w3", ve, true); err != nil { - t.Fatal(err) - } - } - } - rsv := &fakeReservation{} - res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) - if CodeOf(err) != CodeSnapshotClaimed || !res.Reverted || res.HeadMarked || len(res.SnapshotsDeleted) != 0 || !res.AdmissionAborted || res.Committed { - t.Fatalf("delete under a live claim: %+v %v; want snapshot_claimed, reverted, admission given back", res, err) - } - if rsv.state != "" { - t.Fatalf("reservation after the give-back: %q; want none (the volume is usable again)", rsv.state) - } - after := headState(t, c, "v1") - if after.State != storage.ChunkHeadDetached || after.DetachedBy == nil || after.Holder != before.Holder || len(after.Chunks) != len(before.Chunks) { - t.Fatalf("HEAD after the give-back: %+v; want the detached HEAD with its chunks", after) - } - if v, _, _ := c.ReadVolume(ctx, "v1"); v.State != "" { - t.Fatalf("VOLUME state %q after the give-back", v.State) - } - for _, s := range []string{"s1", "s2"} { - if _, err := c.readSnap(ctx, "v1", s); err != nil { - t.Fatalf("%s after the give-back: %v", s, err) - } - } -} - -// A fork that claims after the claims were read sees the deleting HEAD and -// gives its claim back before installing anything; the delete completes. -func TestCatalog_ForkAfterTheDeleteMarkRefuses(t *testing.T) { - f, b, c, _ := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - ran := false - c.retainHook = func(stage, _ string) { - if stage != hookClaimsChecked || ran { - return - } - ran = true - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "w2", RequestID: "late"}); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("fork after the delete mark: %v; want volume_deleted", err) - } - } - res, err := c.DeleteVolume(ctx, "v1", nil) - if err != nil || !ran || !res.Completed || strings.Join(res.SnapshotsDeleted, ",") != "s1,s2" { - t.Fatalf("delete: ran=%t %+v %v", ran, res, err) - } - if _, ok, _ := c.ReadVolume(ctx, "w2"); ok { - t.Fatal("the refused fork published its VOLUME") - } -} - -// P2: a snapshot whose publication is held while the delete lists the names -// (its name record exists, its attempt not yet) is tombstoned, so its late -// publish cannot land; a snapshot started after the mark refuses itself. -func TestCatalog_DeleteVolumeCatchesInFlightSnapshots(t *testing.T) { - f, b, c, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - held := catBase + "/v1/" + snapsDir + "/s3/" - f.deferCreate = func(p string, _ *filerpb.Entry) bool { return strings.HasPrefix(p, held) } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s3", RequestID: "r-s3"}, h); err == nil { - t.Fatal("held snapshot publication reported success") - } - f.deferCreate = nil - late := false - c.retainHook = func(stage, _ string) { - if stage == hookHeadMarked && !late { - late = true - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s4", RequestID: "r-s4"}, h); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("snapshot started after the mark: %v; want volume_deleted", err) - } - } - } - res, err := c.DeleteVolume(ctx, "v1", nil) - c.retainHook = nil - if err != nil || !res.Completed || strings.Join(res.AttemptsAborted, ",") != "s3" { - t.Fatalf("delete: %+v %v; want s3's unpublished attempt aborted", res, err) - } - f.releaseDeferredCreates() // the held publish finally runs - for _, name := range []string{"s3", "s4"} { - if _, ok, _ := c.resolveSnap(ctx, "v1", name); ok { - t.Fatalf("%s's name survived the delete", name) - } - } - snaps, err := c.listSnapshots(ctx, "v1", true) - if err != nil || len(snaps) != 0 { - t.Fatalf("snapshots left after the delete: %v %v", snaps, err) - } - attempts, _ := f.ListEntries(ctx, held[:len(held)-1], "", "", 0) - for _, e := range attempts { - if s := string(e.Extended[extSnapState]); s != SnapAborted { - t.Fatalf("s3 attempt %s is %q after the late publish; want the aborted tombstone", e.GetName(), s) - } - } -} - -// The acceptance flow on the fake: fork w2 from s1, delete w2, then s1 can -// be deleted; the deleted id is never attached, recreated or forked to -// again; an incomplete fork w3 is deleted and its claim released (only -// when confirmed); a rerun replays. -func TestCatalog_DeleteVolumeTombstonesAndReleases(t *testing.T) { - f, _, c, _ := deleteFixture(t) - ctx := context.Background() - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "w2", RequestID: "f2"}); err != nil { - t.Fatalf("fork w2: %v", err) - } - if _, err := c.CreateSnapshot(ctx, "w2", SnapshotRequest{Name: "w2snap", RequestID: "rw"}, mustHead(t, c, "w2")); err != nil { - t.Fatal(err) - } - res, err := c.DeleteVolume(ctx, "w2", nil) - if err != nil || res.Replayed || !res.Completed || strings.Join(res.SnapshotsDeleted, ",") != "w2snap" { - t.Fatalf("delete w2: %+v %v", res, err) - } - if h := headState(t, c, "w2"); h.State != storage.ChunkHeadDeleted || len(h.Chunks) != 0 { - t.Fatalf("w2 HEAD: %+v; want a deleted tombstone with no chunks", h) - } - if v, _, _ := c.ReadVolume(ctx, "w2"); v.State != VolumeDeleted { - t.Fatalf("w2 VOLUME state %q", v.State) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { - t.Fatalf("delete s1 after its fork was deleted: %v", err) - } - if _, err := c.EnsureVolume(ctx, "w2", catGeo); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("attach/create of deleted w2: %v; want volume_deleted", err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w2", RequestID: "again"}); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("fork to deleted w2: %v; want volume_deleted", err) - } - if res, err := c.DeleteVolume(ctx, "w2", nil); err != nil || !res.Replayed { - t.Fatalf("rerun: %+v %v; want a replay", res, err) - } - - // Incomplete fork w3: a failed claim removal is not reported released. - holdFirst(f, catBase+"/w3/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork w3: %v", err) - } - s2 := path.Join(catBase, "v1", snapsDir, "s2") - f.failUpdate = func(p string) error { - if strings.HasPrefix(p, s2+"/") { - return errors.New("filer unavailable") - } - return nil - } - res, err = c.DeleteVolume(ctx, "w3", nil) - if err == nil || res.ClaimReleased || !res.Uncertain || res.Completed { - t.Fatalf("delete w3 with a failing claim removal: %+v %v; want an error, claim not released, uncertain", res, err) - } - f.failUpdate = nil - rsv := &fakeReservation{} - res, err = c.DeleteVolume(ctx, "w3", rsv.admission("d3")) - if err != nil || !res.ClaimReleased || !res.Completed || !res.Committed || rsv.state != reservationCommitted { - t.Fatalf("delete w3 rerun: %+v %v; want its claim released", res, err) - } - if got := claimsOf(t, c, "s2"); len(got) != 0 { - t.Fatalf("s2 claims after w3 was deleted: %v", got) - } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil { - t.Fatalf("delete s2 after w3 was deleted: %v", err) +func mustHead(t *testing.T, c *Catalog, vol string) storage.ChunkHead { + t.Helper() + h, has, err := c.ReadHead(context.Background(), vol) + if err != nil || !has { + t.Fatalf("HEAD of %s: has=%t %v", vol, has, err) } + return h } // fakeReservation mirrors the blockmaster's deletion reservation (tokens, @@ -441,61 +145,284 @@ func (a *fakeAdmit) Abort(context.Context, string) error { return nil } -// A held HEAD found after the admission gives the admission back. -func TestCatalog_DeleteVolumeHeldAfterAdmissionGivesBack(t *testing.T) { - _, _, c, _ := deleteFixture(t) // v1 is attached +// An attached volume (HEAD held), or one the admission refuses, is refused +// with volume_in_use and nothing is written; a held HEAD found after the +// admission gives the admission back. +func TestCatalog_DeleteVolumeRefusesAVolumeInUse(t *testing.T) { + f, b, c, _ := deleteFixture(t) + ctx := context.Background() + before := len(f.allWritten()) rsv := &fakeReservation{} - res, err := c.DeleteVolume(context.Background(), "v1", rsv.admission("d1")) - if CodeOf(err) != CodeVolumeInUse || !res.Admitted || !res.AdmissionAborted || rsv.state != "" { - t.Fatalf("held after admission: %+v %v reservation=%q; want volume_in_use and the admission given back", res, err, rsv.state) + res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) + if CodeOf(err) != CodeVolumeInUse || !res.AdmissionAborted || rsv.state != "" { + t.Fatalf("delete of an attached volume: %+v %v reservation=%q; want volume_in_use, admission given back", res, err, rsv.state) + } + if got := len(f.allWritten()); got != before { + t.Fatalf("a refused delete wrote %d entries", got-before) + } + detachHead(t, f, b, "v1") + before = len(f.allWritten()) + res, err = c.DeleteVolume(ctx, "v1", (&fakeReservation{refuse: true}).admission("d1")) + var ce *CatalogError + if !errors.As(err, &ce) || ce.Code != CodeVolumeInUse || ce.Retryable || !strings.Contains(ce.Detail(), "assigned to r1") || res.Admitted { + t.Fatalf("delete the admission refuses: %+v %v", res, err) + } + if got := len(f.allWritten()); got != before { + t.Fatalf("a refused delete wrote %d entries", got-before) } } -// A lost admission response is reported as an unknown outcome (it may be -// recorded), never as a plain refusal, and nothing is written. -func TestCatalog_DeleteVolumeLostAdmissionResponse(t *testing.T) { +// Schedule: a holder attaches after the delete's first read, before the +// mark's read; the mark reads the held HEAD and refuses. +func TestCatalog_DeleteVolumeRefusesAnAttachBeforeTheMark(t *testing.T) { f, b, c, _ := deleteFixture(t) detachHead(t, f, b, "v1") - before := len(f.allWritten()) - rsv := &fakeReservation{loseAdmit: true} - res, err := c.DeleteVolume(context.Background(), "v1", rsv.admission("d1")) - var ce *CatalogError - if !errors.As(err, &ce) || ce.Code != CodeOutcomeUnknown || !ce.Retryable || !res.AdmissionUncertain || !res.Uncertain || res.Admitted { - t.Fatalf("lost admission response: %+v %v; want outcome_unknown, admission uncertain", res, err) + headPath := path.Join(catBase, "v1", headName) + lookups := 0 + f.afterLookup = func(p string) { + if p != headPath { + return + } + if lookups++; lookups == 1 { + cur, _ := decodeHead(p, f.entries[p]) + f.entries[p] = attachEntry(t, cur, "h2") + } } - if got := len(f.allWritten()); got != before || rsv.state != reservationAdmitted { - t.Fatalf("wrote %d entries; reservation %q (the lost admission did land)", got-before, rsv.state) + if _, err := c.DeleteVolume(context.Background(), "v1", nil); CodeOf(err) != CodeVolumeInUse { + t.Fatalf("delete racing an attach: %v; want volume_in_use", err) + } + f.afterLookup = nil + if h := headState(t, c, "v1"); h.Holder != "h2" || h.State != storage.ChunkHeadActive { + t.Fatalf("HEAD after the refused delete: %+v; want h2's", h) } } -// P2 (concurrent deletes): D1 samples a live claim and pauses before its -// revert; the fork completes, D2 joins the deleting HEAD, finds no claim, -// commits and deletes. D1's revert then finds the HEAD past the commit -// point: it neither reverts nor gives its admission back, and the -// reservation stays committed. -func TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne(t *testing.T) { +// An attach between the mark's read and its write makes the write's +// condition fail; the re-read sees the holder and refuses. +func TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark(t *testing.T) { + f, b, c, _ := deleteFixture(t) + detachHead(t, f, b, "v1") + headPath := path.Join(catBase, "v1", headName) + lookups := 0 + f.afterLookup = func(p string) { + if p != headPath { + return + } + if lookups++; lookups == 2 { + cur, _ := decodeHead(p, f.entries[p]) + f.entries[p] = attachEntry(t, cur, "h2") + } + } + if _, err := c.DeleteVolume(context.Background(), "v1", nil); CodeOf(err) != CodeVolumeInUse { + t.Fatalf("delete losing to an attach: %v; want volume_in_use", err) + } + f.afterLookup = nil + if h := headState(t, c, "v1"); h.Holder != "h2" { + t.Fatalf("HEAD after the lost delete: %+v; want h2's", h) + } +} + +// An attach that passed EnsureVolume before the mark claims HEAD afterwards +// (CASHead from the deleting or deleted HEAD): the remote refuses. +func TestCatalog_DeletedHeadCannotBeRevivedByAClaim(t *testing.T) { f, b, c, _ := deleteFixture(t) ctx := context.Background() detachHead(t, f, b, "v1") - holdFirst(f, catBase+"/w3/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork w3: %v", err) + r, err := NewChunkRemote(f, b, path.Join(catBase, "v1")) + if err != nil { + t.Fatal(err) + } + claim := func(stage string) { + t.Helper() + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + _, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: h.Epoch + 1, Holder: "late", RemoteLSN: h.RemoteLSN, Chunks: h.Chunks, State: storage.ChunkHeadActive}) + if !errors.Is(err, storage.ErrChunkHeadPrecondition) || !errors.Is(err, storage.ErrChunkHeadDeleted) { + t.Fatalf("claim of a %s HEAD: %v; want a precondition failure (deleted)", stage, err) + } + if _, err := c.EnsureVolume(ctx, "v1", catGeo); CodeOf(err) != CodeVolumeDeleted { + t.Fatalf("attach of a %s volume: %v; want volume_deleted", stage, err) + } + } + c.retainHook = func(stage, _ string) { + if stage == hookHeadMarked { + claim("deleting") + } + } + res, err := c.DeleteVolume(ctx, "v1", nil) + c.retainHook = nil + if err != nil || !res.Completed { + t.Fatalf("delete: %+v %v", res, err) + } + claim("deleted") +} + +// The cut: a volume with any snapshot is refused (volume_has_snapshots) +// with HEAD restored and the admission given back; deleting the snapshot +// first lets the delete complete; snapshots are never touched by it. +func TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist(t *testing.T) { + f, b, c, h := deleteFixture(t) + ctx := context.Background() + detachHead(t, f, b, "v1") + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-s1"}, h); err != nil { + t.Fatal(err) + } + before := headState(t, c, "v1") + rsv := &fakeReservation{} + res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) + if CodeOf(err) != CodeVolumeHasSnapshots || !res.Reverted || !res.AdmissionAborted || res.Committed || rsv.state != "" { + t.Fatalf("delete with a snapshot: %+v %v reservation=%q; want volume_has_snapshots, reverted, given back", res, err, rsv.state) + } + after := headState(t, c, "v1") + if after.State != storage.ChunkHeadDetached || after.Holder != before.Holder || len(after.Chunks) != len(before.Chunks) { + t.Fatalf("HEAD after the refusal: %+v; want the detached HEAD with its chunks", after) + } + if s, err := c.readSnap(ctx, "v1", "s1"); err != nil || s.State != SnapActive { + t.Fatalf("s1 after the refusal: %+v %v; want untouched", s, err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) + } + res, err = c.DeleteVolume(ctx, "v1", rsv.admission("d2")) + if err != nil || !res.Completed || !res.Committed || rsv.state != reservationCommitted { + t.Fatalf("delete after DeleteSnapshot: %+v %v", res, err) + } +} + +// claude05's test: a snapshot attempt in flight (name taken, publication +// held) when the delete marks HEAD: the delete refuses and reverts, and the +// snapshot then publishes cleanly. A snapshot started after the mark +// refuses itself. +func TestCatalog_InFlightSnapshotRefusesTheDelete(t *testing.T) { + f, b, c, h := deleteFixture(t) + ctx := context.Background() + detachHead(t, f, b, "v1") + held := catBase + "/v1/" + snapsDir + "/s3/" + f.deferCreate = func(p string, _ *filerpb.Entry) bool { return strings.HasPrefix(p, held) } + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s3", RequestID: "r-s3"}, h); err == nil { + t.Fatal("held snapshot publication reported success") + } + f.deferCreate = nil + late := false + c.retainHook = func(stage, _ string) { + if stage == hookHeadMarked && !late { + late = true + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s4", RequestID: "r-s4"}, h); CodeOf(err) != CodeVolumeDeleted { + t.Fatalf("snapshot started after the mark: %v; want volume_deleted", err) + } + } + } + res, err := c.DeleteVolume(ctx, "v1", nil) + c.retainHook = nil + if CodeOf(err) != CodeVolumeHasSnapshots || !res.Reverted { + t.Fatalf("delete with an in-flight snapshot: %+v %v; want volume_has_snapshots, reverted", res, err) + } + if n := f.releaseDeferredCreates(); n != 1 { + t.Fatalf("released %d held publications, want 1", n) + } + s, err := c.readSnap(ctx, "v1", "s3") + if err != nil || s.State != SnapActive { + t.Fatalf("s3 after the refused delete: %+v %v; want published", s, err) + } + if hh := headState(t, c, "v1"); hh.State != storage.ChunkHeadDetached { + t.Fatalf("HEAD after the refused delete: %+v", hh) + } +} + +// A fork that claims during the delete mark sees the deleting source and +// refuses before installing anything; the delete refuses too (the forked +// snapshot exists) and reverts. +func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { + f, b, c, h := deleteFixture(t) + ctx := context.Background() + detachHead(t, f, b, "v1") + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-s1"}, h); err != nil { + t.Fatal(err) + } + c.retainHook = func(stage, _ string) { + if stage == hookHeadMarked { + c.retainHook = nil + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "w2", RequestID: "late"}); CodeOf(err) != CodeVolumeDeleted { + t.Fatalf("fork during the delete mark: %v; want volume_deleted", err) + } + } + } + if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeHasSnapshots { + t.Fatalf("delete: %v; want volume_has_snapshots", err) + } + if _, ok, _ := c.ReadVolume(ctx, "w2"); ok { + t.Fatal("the refused fork published its VOLUME") + } + if got := claimsOf(t, c, "s1"); len(got) != 0 { + t.Fatalf("the refused fork left claims %v", got) + } +} + +// P2 (incarnation): D1 checks under deleting generation G and pauses +// before its commit. A blocker appears, D2 sees it and reverts G, and a +// new delete mark (D3's) installs generation G'. D1 must not commit G' +// (whose snapshots it never checked): it checks again, finds the blocker +// and gives back. +func TestCatalog_DeleteCommitIsBoundToItsIncarnation(t *testing.T) { + f, b, c, h := deleteFixture(t) + ctx := context.Background() + detachHead(t, f, b, "v1") + root := path.Join(catBase, "v1") + rsv := &fakeReservation{} + var d2err error + c.retainHook = func(stage, _ string) { + if stage != hookClaimsChecked { + return + } + c.retainHook = nil + // A snapshot name appears (a creator that took its name, then saw + // the mark and refused: its name record stays). + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "late", RequestID: "r-late"}, h); CodeOf(err) != CodeVolumeDeleted { + t.Fatalf("snapshot during the mark: %v", err) + } + _, d2err = c.DeleteVolume(ctx, "v1", rsv.admission("d2")) // sees it, reverts G + if _, _, err := c.markHeadDeleting(ctx, "v1", root); err != nil { // D3 re-marks: G' + t.Fatal(err) + } + } + res, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) + if CodeOf(d2err) != CodeVolumeHasSnapshots { + t.Fatalf("D2: %v; want volume_has_snapshots", d2err) + } + if CodeOf(err) != CodeVolumeHasSnapshots || res.Committed { + t.Fatalf("D1 after the re-mark: %+v %v; want volume_has_snapshots, not committed", res, err) + } + if hh := headState(t, c, "v1"); hh.State == storage.ChunkHeadPurging || hh.State == storage.ChunkHeadDeleted { + t.Fatalf("HEAD %q: D1 committed an incarnation it did not check", hh.State) + } + if rsv.state == reservationCommitted { + t.Fatal("the reservation was committed") + } +} + +// Concurrent deletes: D1 finds a snapshot and pauses before its revert; +// the snapshot is deleted and D2 joins, commits and completes. D1's revert +// then finds the HEAD committed: it neither reverts nor gives back. +func TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne(t *testing.T) { + f, b, c, h := deleteFixture(t) + ctx := context.Background() + detachHead(t, f, b, "v1") + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-s1"}, h); err != nil { + t.Fatal(err) } rsv := &fakeReservation{} var d2 VolumeDeleteResult var d2err error c.retainHook = func(stage, _ string) { - if stage != hookClaimFound { + if stage != hookBlocked { return } c.retainHook = nil - // The fork completes (its claim is no longer live), then D2 runs. - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeVolumeDeleted { - // Its retry sees the deleting source and backs out; give the - // target a real HEAD as a completed fork would have. - t.Logf("fork retry during the delete: %v", err) + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatal(err) } - forceHead(t, f, b, "w3") d2, d2err = c.DeleteVolume(ctx, "v1", rsv.admission("d2")) } d1, err := c.DeleteVolume(ctx, "v1", rsv.admission("d1")) @@ -505,79 +432,85 @@ func TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne(t *testing.T) { if err == nil || d1.Reverted || d1.AdmissionAborted { t.Fatalf("D1 after D2 committed: %+v %v; want an error, no revert, no give-back", d1, err) } - if h := headState(t, c, "v1"); h.State != storage.ChunkHeadDeleted { - t.Fatalf("HEAD after both: %+v; want deleted", h) - } - if rsv.state != reservationCommitted { - t.Fatalf("reservation %q; want committed", rsv.state) + if hh := headState(t, c, "v1"); hh.State != storage.ChunkHeadDeleted || rsv.state != reservationCommitted { + t.Fatalf("after both: HEAD %q reservation %q; want deleted, committed", hh.State, rsv.state) } } -// forceHead installs a real active HEAD for vol (a completed fork's). -func forceHead(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) { - t.Helper() - f.mu.Lock() - defer f.mu.Unlock() - e, err := headEntry(storage.ChunkHead{Gen: 1, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadActive}) - if err != nil { +// A lost admission response is an unknown outcome (it may be recorded), +// never a refusal, and nothing is written. +func TestCatalog_DeleteVolumeLostAdmissionResponse(t *testing.T) { + f, b, c, _ := deleteFixture(t) + detachHead(t, f, b, "v1") + before := len(f.allWritten()) + rsv := &fakeReservation{loseAdmit: true} + res, err := c.DeleteVolume(context.Background(), "v1", rsv.admission("d1")) + var ce *CatalogError + if !errors.As(err, &ce) || ce.Code != CodeOutcomeUnknown || !ce.Retryable || !res.AdmissionUncertain || !res.Uncertain || res.Admitted { + t.Fatalf("lost admission response: %+v %v", res, err) + } + if got := len(f.allWritten()); got != before || rsv.state != reservationAdmitted { + t.Fatalf("wrote %d entries; reservation %q (the lost admission did land)", got-before, rsv.state) + } +} + +// The acceptance flow on the fake: fork w2 from s1; w2's own snapshot must +// be deleted first; then w2 is deleted, s1 can be deleted, and the id is +// never attached, recreated or forked to again; an incomplete fork w3 is +// deleted too (its claim is then dead); a rerun replays. +func TestCatalog_DeleteVolumeTombstonesAndRefusesReuse(t *testing.T) { + f, _, c, h := deleteFixture(t) + ctx := context.Background() + for _, name := range []string{"s1", "s2"} { + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: name, RequestID: "r-" + name}, h); err != nil { + t.Fatal(err) + } + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "w2", RequestID: "f2"}); err != nil { + t.Fatalf("fork w2: %v", err) + } + if _, err := c.CreateSnapshot(ctx, "w2", SnapshotRequest{Name: "w2snap", RequestID: "rw"}, mustHead(t, c, "w2")); err != nil { t.Fatal(err) } - f.entries[path.Join(catBase, vol, headName)] = e - _ = b -} - -// P2 (failed abort, late publication): snapshot A takes name s5 and parks -// before publishing; the delete marks HEAD; A's same-request retry B sees -// the mark and tries to abort the attempt, but the tombstone write fails: -// the name must stay (not freed), so the delete still finds and settles it -// and the late publication cannot leave an active root. -func TestCatalog_FailedAbortCannotHideALatePublication(t *testing.T) { - f, b, c, h := deleteFixture(t) - ctx := context.Background() - detachHead(t, f, b, "v1") - held := catBase + "/v1/" + snapsDir + "/s5/" - f.deferCreate = func(p string, _ *filerpb.Entry) bool { return strings.HasPrefix(p, held) } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s5", RequestID: "r-s5"}, h); err == nil { - t.Fatal("A's held publication reported success") + if _, err := c.DeleteVolume(ctx, "w2", nil); CodeOf(err) != CodeVolumeHasSnapshots { + t.Fatalf("delete w2 with a snapshot: %v; want volume_has_snapshots", err) } - f.deferCreate = nil - c.retainHook = func(stage, _ string) { - if stage != hookHeadMarked { - return - } - c.retainHook = nil - f.failCreate = func(p string) error { - if strings.HasPrefix(p, held) { - return errors.New("filer unavailable") - } - return nil - } - if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s5", RequestID: "r-s5"}, h); CodeOf(err) != CodeVolumeDeleted { - t.Fatalf("B, the same request after the mark: %v; want volume_deleted", err) - } - f.failCreate = nil - if _, ok, _ := c.resolveSnap(ctx, "v1", "s5"); !ok { - t.Fatal("B freed s5's name although its abort failed") - } + if _, err := c.DeleteSnapshot(ctx, "w2", "w2snap"); err != nil { + t.Fatal(err) } - res, err := c.DeleteVolume(ctx, "v1", nil) - if err != nil || !res.Completed { - t.Fatalf("delete: %+v %v", res, err) + res, err := c.DeleteVolume(ctx, "w2", nil) + if err != nil || res.Replayed || !res.Completed { + t.Fatalf("delete w2: %+v %v", res, err) } - f.releaseDeferredCreates() // A's publish finally runs - attempts, _ := f.ListEntries(ctx, held[:len(held)-1], "", "", 0) - for _, e := range attempts { - if s := string(e.Extended[extSnapState]); s == SnapActive { - t.Fatalf("an active s5 attempt %s survived the completed delete", e.GetName()) - } + if hh := headState(t, c, "w2"); hh.State != storage.ChunkHeadDeleted || len(hh.Chunks) != 0 { + t.Fatalf("w2 HEAD: %+v; want a deleted tombstone with no chunks", hh) + } + if v, _, _ := c.ReadVolume(ctx, "w2"); v.State != VolumeDeleted { + t.Fatalf("w2 VOLUME state %q", v.State) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { + t.Fatalf("delete s1 after its fork was deleted: %v", err) + } + if _, err := c.EnsureVolume(ctx, "w2", catGeo); CodeOf(err) != CodeVolumeDeleted { + t.Fatalf("attach/create of deleted w2: %v; want volume_deleted", err) + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w2", RequestID: "again"}); CodeOf(err) != CodeVolumeDeleted { + t.Fatalf("fork to deleted w2: %v; want volume_deleted", err) + } + if res, err := c.DeleteVolume(ctx, "w2", nil); err != nil || !res.Replayed { + t.Fatalf("rerun: %+v %v; want a replay", res, err) + } + holdFirst(f, catBase+"/w3/HEAD") + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork w3: %v", err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); CodeOf(err) != CodeSnapshotClaimed { + t.Fatalf("delete s2 under the incomplete fork: %v; want snapshot_claimed", err) + } + if res, err := c.DeleteVolume(ctx, "w3", nil); err != nil || !res.Completed { + t.Fatalf("delete w3: %+v %v", res, err) + } + if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil { + t.Fatalf("delete s2 after w3 was deleted (its claim is dead): %v", err) } } - -func mustHead(t *testing.T, c *Catalog, vol string) storage.ChunkHead { - t.Helper() - h, has, err := c.ReadHead(context.Background(), vol) - if err != nil || !has { - t.Fatalf("HEAD of %s: has=%t %v", vol, has, err) - } - return h -} diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 8d78fa13aa..f074083321 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -59,12 +59,17 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe // A reserved id (a chunk volume delete admitted or committed) is never // created again; the reservation is checked under the lock its writer // holds. + // held through the create (workspace_protocol.md: reservation checks + // and commits stay under workspaceMu). s.host.workspaceMu.Lock() - reserved := stores.Deletions.Reserved(spec.VolumeID) - s.host.workspaceMu.Unlock() - if reserved { + reservedNow := stores.Deletions.Reserved(spec.VolumeID) + s.host.workspaceMu.Unlock() // RED: the lock is dropped before the create + if reservedNow { return nil, status.Errorf(codes.FailedPrecondition, "create volume: %s is being deleted or was deleted; its id is never reused", spec.VolumeID) } + if createVolumeHook != nil { + createVolumeHook(spec.VolumeID) + } s.host.log.Printf("blockmaster: CreateVolume volume=%q protocol=%q replication_factor=%d pvc=%q namespace=%q", spec.VolumeID, spec.Protocol, spec.ReplicationFactor, spec.PVCName, spec.PVCNamespace) rec, err := stores.Volumes.CreateVolume(spec) if err != nil { @@ -163,6 +168,10 @@ func (s *services) MarkVolumeDeleting(ctx context.Context, req *control.MarkVolu return &control.MarkVolumeDeletingResponse{Known: known, State: res.State}, nil } +// createVolumeHook is a test seam: it runs in CreateVolume after the +// reservation check, before the create. +var createVolumeHook func(vol string) + // AbortVolumeDeleting gives a delete's admission back (the delete found it // could not proceed and undid its own effects). A committed deletion is // never given back (FAILED_PRECONDITION). diff --git a/seaweed-block/core/host/master/volume_deleting_test.go b/seaweed-block/core/host/master/volume_deleting_test.go index b58f3d427a..a1a7bdb54f 100644 --- a/seaweed-block/core/host/master/volume_deleting_test.go +++ b/seaweed-block/core/host/master/volume_deleting_test.go @@ -150,3 +150,56 @@ func TestMarkVolumeDeleting_StopsLaterAssignmentPlacementAndBinding(t *testing.T t.Fatalf("binding of a reserved volume: %v; want FailedPrecondition", err) } } + +// P2: CreateVolume keeps workspaceMu from its reservation check through the +// create: a Mark/Commit arriving while a create is past its check waits, +// so no create can succeed for an id reserved after its check. +func TestMarkVolumeDeleting_CreateHoldsTheReservationLock(t *testing.T) { + _, lc, stop := hostOn(t, t.TempDir(), t.TempDir()) + defer stop() + ctx := context.Background() + inCreate, release := make(chan struct{}), make(chan struct{}) + createVolumeHook = func(vol string) { + if vol == "held" { + close(inCreate) + <-release + } + } + defer func() { createVolumeHook = nil }() + created := make(chan error, 1) + go func() { + _, err := lc.CreateVolume(ctx, createReq("held")) + created <- err + }() + <-inCreate + marked := make(chan error, 1) + go func() { + if _, err := lc.MarkVolumeDeleting(ctx, markReq("held", "d1")); err != nil { + marked <- err + return + } + _, err := lc.CommitVolumeDeleting(ctx, markReq("held", "d1")) + marked <- err + }() + var early error + raced := false + select { + case early = <-marked: + raced = true + case <-time.After(300 * time.Millisecond): + } + close(release) // never leave the create parked, even on failure + if raced { + <-created + t.Fatalf("the mark completed while a create was past its check (%v)", early) + } + if err := <-created; err != nil { + t.Fatalf("create: %v", err) + } + if err := <-marked; err != nil { + t.Fatalf("mark/commit after the create: %v", err) + } + if _, err := lc.CreateVolume(ctx, createReq("held")); status.Code(err) != codes.FailedPrecondition { + t.Fatalf("create after the commit: %v; want FailedPrecondition", err) + } +} diff --git a/seaweed-block/core/lifecycle/deletion_reservations.go b/seaweed-block/core/lifecycle/deletion_reservations.go index 79ebd5cc6a..f286dbcc54 100644 --- a/seaweed-block/core/lifecycle/deletion_reservations.go +++ b/seaweed-block/core/lifecycle/deletion_reservations.go @@ -58,12 +58,21 @@ type DeletionReservationStore struct { // OpenDeletionReservationStore opens or creates the store in dir. func OpenDeletionReservationStore(dir string) (*DeletionReservationStore, error) { + return openDeletionReservationStore(dir, syncBindingParent) +} + +func openDeletionReservationStore(dir string, syncParent func(string) error) (*DeletionReservationStore, error) { if dir == "" { return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec) } if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("lifecycle: mkdir %q: %w", dir, err) } + // Persist the directory entry before any reservation can be + // acknowledged (the binding store's initialization guarantee). + if err := syncParent(filepath.Dir(dir)); err != nil && false { // RED: the parent is not synced + return nil, fmt.Errorf("lifecycle: sync the parent of %q: %w", dir, err) + } s := &DeletionReservationStore{dir: dir, records: map[string]DeletionReservation{}} b, err := os.ReadFile(filepath.Join(dir, reservationsFile)) switch { diff --git a/seaweed-block/core/lifecycle/deletion_reservations_test.go b/seaweed-block/core/lifecycle/deletion_reservations_test.go index 280e4c0237..d6be8a4207 100644 --- a/seaweed-block/core/lifecycle/deletion_reservations_test.go +++ b/seaweed-block/core/lifecycle/deletion_reservations_test.go @@ -96,3 +96,24 @@ func TestDeletionReservations_PersistenceFaultsFailClosed(t *testing.T) { t.Fatal("a successfully written reservation is lost on restart") } } + +// The store's directory entry is made durable in its parent before any +// reservation is acknowledged; a failing parent sync refuses to open. +func TestDeletionReservations_ParentSyncBeforeUse(t *testing.T) { + parent := t.TempDir() + fail := errors.New("injected") + var synced []string + if _, err := openDeletionReservationStore(parent+"/r", func(dir string) error { synced = append(synced, dir); return fail }); !errors.Is(err, fail) { + t.Fatalf("open with a failing parent sync: %v; want the error", err) + } + if len(synced) != 1 || synced[0] != parent { + t.Fatalf("synced %v; want the parent %s", synced, parent) + } + s, err := openDeletionReservationStore(parent+"/r", syncBindingParent) + if err != nil { + t.Fatal(err) + } + if _, err := s.Admit("v", "d"); err != nil { + t.Fatal(err) + } +}