From 26426dd50efb8c01d8ee269837db743fcba29118 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:12:57 -0800 Subject: [PATCH 1/4] durable: a failed detach never leaves the guest frozen (MIGRATION E4) DetachVolume stopped guest I/O, then ran the whole final cut; on any error I/O stayed stopped for the process, even when nothing was published, and the only bound was the caller's context (up to 5 min). Now: - The freeze (drain + final cut) is bounded by DetachFreezeTimeout (default 20 s, below the host's 30 s I/O timeout); a freeze past the 5 s target is logged as an ALARM. - A detach that provably did not publish (the drain or the cut failed before its CAS, the CAS was refused, or an unresolved detach CAS was cancelled) resumes serving: periodic cuts restart, the stop is lifted, and ErrDetachAborted (HTTP detach_aborted, 409, retryable) is returned. The dirty set stays dirty, so the next cut publishes it. - The new ChunkLayer.SettleDetach decides an unresolved detach CAS: if HEAD is still that CAS's base, a CAS at the same base to the non-detached base image (this holder, this epoch) cancels it, so the detach can never land afterwards; HEAD carrying the detach means it applied (the detached result is returned, I/O stays stopped); a newer holder means fenced (stays stopped); HEAD unreadable leaves it undecided: ErrDetachOutcomeUnknown, I/O stays stopped. Never resume on top of a possibly detached HEAD. Tests: failed upload, refused CAS, lost unapplied CAS (cancelled, HEAD one generation on, not detached) resume and the next cut publishes the dirty blocks; an applied CAS whose reply was lost (found by the cut's re-read or only by the settle) stays detached; undecidable and fenced stay stopped; a hung CAS ends at the freeze bound, is settled and resumes; the old drain-timeout test flips (it asserted I/O stays stopped). Six declared mutants each turn exactly their declared tests red. Known limit: after an abort whose drain is still pending (an admitted I/O stuck), new I/O queues behind that admitted I/O (the drain holds a pending ioMu.Lock); serving resumes once it completes, not instantly. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 13 + .../core/frontend/durable/provider_chunk.go | 92 ++++-- .../provider_chunk_detach_abort_test.go | 272 ++++++++++++++++++ .../provider_chunk_detach_stop_test.go | 34 ++- .../core/host/volume/chunk_control.go | 4 + .../core/host/volume/chunk_control_test.go | 2 + seaweed-block/core/storage/chunk_layer.go | 69 +++++ seaweed-block/core/storage/chunk_public.go | 8 + seaweed-block/core/storage/chunk_seam.go | 17 ++ 9 files changed, 482 insertions(+), 29 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 1b9f8e565f..d115bc07af 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -81,6 +81,14 @@ var ErrImplKindMismatch = errors.New("durable: impl kind mismatch between select // volumeID has not been Open'd. var ErrVolumeNotOpen = errors.New("durable: volume not opened") +// ErrDetachAborted: the detach did not happen (its final cut provably did not +// publish), so the volume resumed serving on this host (MIGRATION E4). +var ErrDetachAborted = errors.New("durable: detach aborted; the volume keeps serving on this host") + +// ErrDetachOutcomeUnknown: whether the detach landed cannot be decided yet; +// I/O stays stopped (never resumed on a possibly detached HEAD). +var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O stays stopped") + // ProviderConfig configures a DurableProvider. type ProviderConfig struct { // Impl selects which LogicalStorage implementation to open or @@ -157,6 +165,11 @@ type ProviderConfig struct { // passed since the volume's last successful cut (of any kind). Zero // disables the timer. ChunkCaptureInterval time.Duration + // DetachFreezeTimeout bounds how long DetachVolume keeps guest I/O + // stopped for its drain and final cut (the caller's context can only + // shorten it). Zero: 20 s, below the host's 30 s I/O timeout; a freeze + // past the 5 s target is logged as an alarm. + DetachFreezeTimeout time.Duration // ChunkDirtyThreshold is the bound on one cut's barrier copy, in // chunks. It never triggers a cut: the remote holds snapshots, and // cuts are published only by CaptureVolume, MakeVolumeRemoteDurable diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 7b4da71e7d..95add9aadc 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -262,15 +262,22 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v h.backend.mu.Lock() h.backend.chunkFenced = layer.Fenced h.backend.mu.Unlock() - if p.cfg.ChunkCaptureInterval > 0 { - loopCtx, cancel := context.WithCancel(context.Background()) - h.chunkStop, h.chunkDone = cancel, make(chan struct{}) - go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone) - } + p.startChunkLoop(volumeID, h, layer) } return nil } +// startChunkLoop starts the periodic cuts of an attached layer, if configured +// and not already running. The caller holds h.attachMu and p.mu. +func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) { + if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil { + return + } + loopCtx, cancel := context.WithCancel(context.Background()) + h.chunkStop, h.chunkDone = cancel, make(chan struct{}) + go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone) +} + func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { ws, ok := h.storage.(*storage.WALStore) if !ok { @@ -743,12 +750,19 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN } // DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the -// volume's frontend I/O and waits (bounded by ctx) for the I/O already -// admitted to finish, stops the periodic cuts, then publishes one cut with -// HEAD state detached. It also returns the last LSN written. From its -// start, the volume stays stopped for this process, through any later -// RecoverVolume, even when the detach fails; a retry settles it and a -// repeated call returns the first result. +// volume's frontend I/O and waits for the I/O already admitted to finish, +// stops the periodic cuts, then publishes one cut with HEAD state detached. +// It also returns the last LSN written. The freeze (drain + final cut) is +// bounded by DetachFreezeTimeout and ctx. After a successful detach the +// volume stays stopped for this process, through any later RecoverVolume, +// and a repeated call returns the first result. A failed detach never leaves +// the guest frozen by a detach that did not happen (MIGRATION E4): +// - nothing published (the drain or the cut failed before its CAS, or the +// CAS was refused, or an unresolved detach CAS was cancelled): serving +// resumes and ErrDetachAborted is returned; +// - the detach CAS applied (its reply was lost): the detached result; +// - HEAD belongs to another holder: stays stopped (fenced); +// - undecidable (HEAD unreadable): stays stopped, ErrDetachOutcomeUnknown. func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) { p.mu.Lock() h, ok := p.volumes[volumeID] @@ -762,16 +776,60 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if err != nil { return storage.ChunkCutResult{}, 0, err } + freeze := p.cfg.DetachFreezeTimeout + if freeze <= 0 { + freeze = defaultDetachFreezeTimeout + } + fctx, cancel := context.WithTimeout(ctx, freeze) + defer cancel() + start := time.Now() + defer func() { + if d := time.Since(start); d > detachFreezeTarget { + log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) + } + }() h.chunkDetach = true - if err := h.backend.StopIO(ctx, "chunk detach: I/O stopped until a new attach"); err != nil { - return storage.ChunkCutResult{}, 0, err + if err := h.backend.StopIO(fctx, "chunk detach: I/O stopped until a new attach"); err != nil { + return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err) // nothing was cut } p.stopChunkLoop(h) - r, err := layer.Detach(ctx) - if err != nil { - return storage.ChunkCutResult{}, 0, err + r, err := layer.Detach(fctx) + if err == nil { + return r, h.storage.NextLSN() - 1, nil } - return r, h.storage.NextLSN() - 1, nil + // Settle with time of its own: the freeze bound may be what ended the cut. + sctx, scancel := context.WithTimeout(context.WithoutCancel(ctx), detachSettleTimeout) + defer scancel() + how, dr, serr := layer.SettleDetach(sctx) + switch { + case serr != nil: + return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w (settle: %w)", ErrDetachOutcomeUnknown, err, serr) + case how == storage.DetachApplied: + return dr, h.storage.NextLSN() - 1, nil + case how == storage.DetachFenced: + return storage.ChunkCutResult{}, 0, fmt.Errorf("durable: detach of %s: HEAD belongs to a newer epoch or another holder; I/O stays stopped: %w: %w", volumeID, storage.ErrChunkLayerFenced, err) + default: + return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err) + } +} + +const ( + defaultDetachFreezeTimeout = 20 * time.Second + detachFreezeTarget = 5 * time.Second + detachSettleTimeout = 10 * time.Second +) + +// resumeAfterDetach undoes a detach that provably did not happen: the +// periodic cuts restart, the stop is lifted, and the volume serves again. +// The caller holds h.attachMu. +func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error { + h.chunkDetach = false + p.mu.Lock() + p.startChunkLoop(volumeID, h, layer) + p.mu.Unlock() + h.backend.SetOperational(true, "chunk detach aborted: serving resumed") + log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause) + return fmt.Errorf("%w: %w", ErrDetachAborted, cause) } // Preserve the optional manifest capability only when the inner remote has it; diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go new file mode 100644 index 0000000000..556dabe8bd --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go @@ -0,0 +1,272 @@ +package durable_test + +// A failed detach (design MIGRATION E4, review S6): the guest is never left +// frozen by a detach that did not happen. When the final cut provably did not +// publish (a failed upload, a refused CAS, an unresolved detach CAS that a +// cancel at the same base settles), serving resumes on this host. When the +// detach landed, the volume stays stopped with the detached result. When the +// outcome cannot be decided (HEAD unreadable), it stays stopped: never resume +// on top of a possibly detached HEAD. + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// faultRemote injects one fault into the next detach's remote calls. +type faultRemote struct { + *storage.MemChunkRemote + mu sync.Mutex + putErr error // returned by every Put while set + casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold" + getHeadErr error // returned by every GetHead while set + getHeadFail int // the next N GetHead calls fail +} + +var errInjected = errors.New("injected remote fault") + +func (r *faultRemote) set(f func(r *faultRemote)) { r.mu.Lock(); f(r); r.mu.Unlock() } + +func (r *faultRemote) Put(ctx context.Context, key string, data []byte) error { + r.mu.Lock() + err := r.putErr + r.mu.Unlock() + if err != nil { + return err + } + return r.MemChunkRemote.Put(ctx, key, data) +} + +func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + r.mu.Lock() + err := r.getHeadErr + if err == nil && r.getHeadFail > 0 { + r.getHeadFail-- + err = errInjected + } + r.mu.Unlock() + if err != nil { + return storage.ChunkHead{}, err + } + return r.MemChunkRemote.GetHead(ctx) +} + +func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + r.mu.Lock() + mode := r.casMode + r.casMode = "" // one fault, on the next CAS only + r.mu.Unlock() + switch mode { + case "precondition": + return 0, storage.ErrChunkHeadPrecondition + case "lost": + return 0, errInjected + case "hold": // held until the caller gives up: not applied + <-ctx.Done() + return 0, ctx.Err() + case "applied-lost": + if _, err := r.MemChunkRemote.CASHead(ctx, expected, next); err != nil { + return 0, err + } + return 0, errInjected + } + return r.MemChunkRemote.CASHead(ctx, expected, next) +} + +// detachFixture: a chunk volume with one cut published and one more write +// (dirty), so the detach's final cut has something to upload. +func detachFixture(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend) { + t.Helper() + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 8192, block(2)); err != nil { + t.Fatal(err) + } + return remote, p, b +} + +// assertServing: the volume accepts writes and a cut publishes them, with a +// HEAD that is not detached. +func assertServing(t *testing.T, p *durable.DurableProvider, b frontend.Backend, remote *faultRemote) { + t.Helper() + ctx := context.Background() + if _, err := b.Write(ctx, 12288, block(3)); err != nil { + t.Fatalf("write after an aborted detach: %v; want the volume serving again", err) + } + r, err := p.CutVolume(ctx, "v1", 0) + if err != nil { + t.Fatalf("cut after an aborted detach: %v", err) + } + if r.Head.State == storage.ChunkHeadDetached { + t.Fatal("HEAD is detached after a detach that was reported aborted") + } + if !bytesEqual(headBlock(t, remote.MemChunkRemote, 2), block(2)) || !bytesEqual(headBlock(t, remote.MemChunkRemote, 3), block(3)) { + t.Fatal("the cut after an aborted detach lost the dirty blocks") + } +} + +func TestWALStoreChunk_FailedDetachUploadResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.putErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with failing uploads: %v; want ErrDetachAborted", err) + } + remote.set(func(r *faultRemote) { r.putErr = nil }) + assertServing(t, p, b, remote) +} + +func TestWALStoreChunk_RefusedDetachCASResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "precondition" }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err) + } + assertServing(t, p, b, remote) +} + +// The detach CAS's reply is lost and it did not apply: the settle cancels it +// with a CAS at the same base, so it can never land, and serving resumes. +func TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes(t *testing.T) { + remote, p, b := detachFixture(t) + base, _ := remote.MemChunkRemote.GetHead(context.Background()) + remote.set(func(r *faultRemote) { r.casMode = "lost" }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a lost, unapplied CAS: %v; want ErrDetachAborted after the cancel", err) + } + // The cancel is a real CAS at the detach's base: HEAD moved one generation + // and is not detached, so the lost detach CAS can never land afterwards. + if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached || head.Gen != base.Gen+1 { + t.Fatalf("HEAD after the cancel: gen %d state %q; want gen %d, not detached", head.Gen, head.State, base.Gen+1) + } + assertServing(t, p, b, remote) +} + +// The detach CAS's reply is lost but it applied: the detach succeeded, the +// volume stays stopped and DetachVolume returns the detached result. +func TestWALStoreChunk_LostDetachCASAppliedStaysDetached(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "applied-lost" }) + r, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach whose CAS applied but lost its reply: %+v %v; want the detached result", r, err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an applied detach: %v; want ErrNotReady", err) + } +} + +// The detach CAS applied but its reply was lost AND the cut's own HEAD re-read +// failed: only the settle can tell. It reads HEAD, finds the detach, and the +// detach succeeds (stays stopped) instead of resuming on a detached HEAD. +func TestWALStoreChunk_LostDetachCASAppliedFoundBySettle(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "applied-lost"; r.getHeadFail = 1 }) + r, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach whose applied CAS only the settle can see: %+v %v; want the detached result", r, err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a settled, applied detach: %v; want ErrNotReady", err) + } +} + +// The detach CAS's reply is lost and HEAD cannot be read: the outcome is +// unknown, so the volume stays stopped (also through a recovery). +func TestWALStoreChunk_UndecidableDetachStaysStopped(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an undecidable detach: %v; want ErrNotReady", err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) { + t.Fatalf("recovery after an undecidable detach: %v; want the volume to stay stopped", err) + } +} + +// The freeze is bounded by DetachFreezeTimeout: a CAS that hangs ends there, +// the outcome is settled (HEAD still at base: cancelled) and serving resumes, +// all well inside bound + settle. +func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) { + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), + BlockSize: 4096, + NumBlocks: pcBlocks, + ChunkBlocks: pcChunkBlocks, + DetachFreezeTimeout: 300 * time.Millisecond, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 8192, block(2)); err != nil { + t.Fatal(err) + } + remote.set(func(r *faultRemote) { r.casMode = "hold" }) + start := time.Now() + _, _, err = p.DetachVolume(context.Background(), "v1") + took := time.Since(start) + if !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("detach with a hung CAS: %v; want an aborted detach at the freeze bound", err) + } + if took < 300*time.Millisecond || took > 3*time.Second { + t.Fatalf("detach with a hung CAS took %v; want about the 300 ms freeze bound", took) + } + assertServing(t, p, b, remote) +} + +// HEAD belongs to a newer epoch: the detach's CAS is refused and the volume +// is fenced; it stays stopped (never resumes against another holder). +func TestWALStoreChunk_DetachAgainstNewerEpochStaysStopped(t *testing.T) { + remote, p, b := detachFixture(t) + ctx := context.Background() + cur, err := remote.MemChunkRemote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + newer := cur + newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder" + if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil { + t.Fatal(err) + } + if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) || errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach against a newer epoch: %v; want fenced, not aborted", err) + } + if _, err := b.Write(ctx, 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) && !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("write after a fenced detach: %v; want it refused (not ready / stale primary)", err) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go index 368b60d143..b52c96f1ec 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go @@ -118,10 +118,11 @@ func TestWALStoreChunk_DetachDrainsAdmittedWrite(t *testing.T) { } } -// The drain is bounded by the caller's context: a detach that cannot drain -// fails, publishes nothing and keeps I/O stopped, also through a recovery; -// once the admitted write finishes, a retry settles the detach with it. -func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { +// The drain is bounded (the caller's context or the freeze bound): a detach +// that cannot drain publishes nothing, so it aborts and the volume serves +// again (MIGRATION E4; it used to stay stopped, review S6); once the admitted +// write finishes, a retry detaches with every acknowledged write. +func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { ctx := context.Background() remote := storage.NewMemChunkRemote() p, view := parkedProvider(t, remote) @@ -139,21 +140,27 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { dctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) _, _, err = p.DetachVolume(dctx, "v1") cancel() - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("detach that cannot drain: %v; want the context's deadline", err) + if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach that cannot drain: %v; want an aborted detach on the context's deadline", err) } if head, _ := remote.GetHead(ctx); head.State == storage.ChunkHeadDetached { t.Fatalf("a detach that did not drain published a detached HEAD: %+v", head) } - if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) { - t.Fatalf("recovery after a failed detach: %v; want the volume to stay stopped", err) - } - if _, err := b.Write(ctx, 8192, block(6)); !errors.Is(err, frontend.ErrNotReady) { - t.Fatalf("new write after a failed detach and a recovery: %v; want ErrNotReady", err) - } + // Serving resumes: a new write is accepted. The drain still pending from + // the aborted stop orders new I/O after the I/O admitted before it, so + // this write completes once that admitted write does (never on the + // detach itself). + nerr := make(chan error, 1) + go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }() view.unpark() acked := <-werr == nil + if err := <-nerr; err != nil { + t.Fatalf("new write after an aborted detach: %v; want it accepted", err) + } + if _, err := p.RecoverVolume(ctx, "v1"); errors.Is(err, storage.ErrChunkLayerDetached) { + t.Fatalf("recovery after an aborted detach: %v; want the volume serving", err) + } o := detachOutcome{} o.r, o.last, o.err = p.DetachVolume(ctx, "v1") if o.err != nil || o.r.Head.State != storage.ChunkHeadDetached { @@ -162,6 +169,9 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { if acked && !bytesEqual(headBlock(t, remote, 1), block(5)) { t.Fatal("the write admitted before the stop was acknowledged but is not in the detached HEAD") } + if !bytesEqual(headBlock(t, remote, 2), block(6)) { + t.Fatal("the write accepted after the aborted detach is not in the detached HEAD") + } } // After a successful detach, RecoverVolume keeps I/O stopped and a repeated diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 9e0746d99c..d9365811c2 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -159,6 +159,7 @@ const ( codeFenced = "fenced" codeHeadConflict = "head_conflict" codeClosing = "closing" + codeDetachAborted = "detach_aborted" // the detach did not happen; the volume keeps serving here codeLSNBehind = "lsn_behind" codeInternal = "internal" codeBadRequest = "bad_request" @@ -231,6 +232,9 @@ func chunkErrorCode(err error) (int, string, bool) { switch { case errors.As(err, &ce): return catalogStatus(ce.Code), ce.Code, ce.Retryable + case errors.Is(err, durable.ErrDetachAborted): + // Before its cause: nothing was published and serving resumed here. + return http.StatusConflict, codeDetachAborted, true case errors.Is(err, storage.ErrChunkLayerFenced): return http.StatusConflict, codeFenced, false case errors.Is(err, storage.ErrChunkCASOutcomeUnknown): diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index 34bc6f3baf..60e9c7f302 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -222,6 +222,8 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) { {fmt.Errorf("x: %w", storage.ErrChunkRemoteUnavailable), "remote_unavailable", 503, true}, {fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false}, {fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false}, + {fmt.Errorf("%w: %w", durable.ErrDetachAborted, storage.ErrChunkRemoteUnavailable), "detach_aborted", 409, true}, + {fmt.Errorf("%w: %w (settle: %w)", durable.ErrDetachOutcomeUnknown, storage.ErrChunkCASOutcomeUnknown, storage.ErrChunkRemoteUnavailable), "outcome_unknown", 503, true}, {fmt.Errorf("%w: %w: cut LSN 1, HEAD remote_lsn 10", storage.ErrChunkCaptureRefused, storage.ErrChunkLSNBehind), "lsn_behind", 409, false}, {&chunkstore.CatalogError{Code: chunkstore.CodeInvalidLabel, Message: "m"}, "invalid_label", 400, false}, {fmt.Errorf("x: %w", durable.ErrNotChunkVolume), "not_chunk_volume", 409, false}, diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 7c96b0d050..0d9421bc20 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1157,6 +1157,75 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { return r, err } +// SettleDetach: see chunkLayer. Only an unresolved DETACH proposal needs a +// remote decision: if HEAD is still that CAS's base, it is cancelled by a CAS +// at the same base to the non-detached base image (this holder, this epoch), +// so whichever lands first decides and the detach can never land after a +// successful cancel. resolvePending would re-propose the detach instead. +func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) { + l.capMu.Lock() + defer l.capMu.Unlock() + if r, ok := l.storedDetach(); ok { + return detachApplied, r, nil + } + l.stMu.Lock() + fenced, pending, isDetach, base, intents := l.fenced, l.pending, l.pendingDetach, l.pendingBase, l.pendingIntents + baseHead := copyHead(l.head) + l.stMu.Unlock() + if fenced { + return detachFenced, chunkCutResult{}, nil + } + if pending == nil || !isDetach { + // Nothing of this detach can land: it failed before its CAS or was + // definitely refused (an unresolved ordinary cut settles as usual). + return detachNotPublished, chunkCutResult{}, nil + } + cur, err := l.remote.GetHead(ctx) + if err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved: %w: %w", errChunkCASOutcomeUnknown, err) + } + if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + if err := l.admit(); err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel refused: %w", errChunkCASOutcomeUnknown, err) + } + cancel := copyHead(baseHead) + cancel.Epoch, cancel.Holder = l.cfg.Epoch, l.cfg.Holder + cancel.State, cancel.DetachedBy = chunkHeadActive, nil + gen, casErr := l.remote.CASHead(ctx, base, cancel) + if casErr == nil { + cancel.Gen = gen + cur = cancel + } else if cur, err = l.remote.GetHead(ctx); err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): %w: %w", casErr, errChunkCASOutcomeUnknown, err) + } else if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) + } + } + // Settled: the detach landed, or it can never land. + l.dropIntents(ctx, intents) + l.stMu.Lock() + defer l.stMu.Unlock() + cut := l.pendingCut + l.pending, l.pendingIntents = nil, nil + l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} + switch { + case sameProposal(cur, *pending): + l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN + cut.Head = copyHead(cur) + l.detached = &cut + r := cut + r.Head = copyHead(cur) + return detachApplied, r, nil + case l.supersededBy(cur): + l.fenced = true + l.head = copyHead(cur) + return detachFenced, chunkCutResult{}, nil + default: + l.head = copyHead(cur) + return detachNotPublished, chunkCutResult{}, nil + } +} + func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) { l.stMu.Lock() defer l.stMu.Unlock() diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index 5ec9d54104..8dcfb337a7 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -20,6 +20,14 @@ type ( ChunkLayerStats = chunkLayerStats ChunkIntent = chunkIntent ChunkDetachedBy = chunkDetachedBy + DetachSettlement = detachSettlement +) + +// How a failed Detach ended (ChunkLayer.SettleDetach). +const ( + DetachNotPublished = detachNotPublished + DetachApplied = detachApplied + DetachFenced = detachFenced ) // HEAD states. diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 62f105cd1f..ae8cf78292 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -457,6 +457,15 @@ type chunkCutResult struct { } // chunkLayer is what the store owner drives. +// detachSettlement is how a failed Detach ended (SettleDetach). +type detachSettlement int + +const ( + detachNotPublished detachSettlement = iota + detachApplied + detachFenced +) + type chunkLayer interface { chunkSink // Cut takes a quiesced cut at H (the last written LSN), uploads the @@ -475,6 +484,14 @@ type chunkLayer interface { // Detach returns the first result. An unresolved detach CAS is settled // like any other unresolved CAS, before the next capture or Detach. Detach(ctx context.Context) (chunkCutResult, error) + // SettleDetach decides how a failed Detach ended, with the caller's I/O + // still stopped: detachNotPublished (HEAD does not and can never carry + // this layer's detach: serving may resume; the dirty set stays dirty), + // detachApplied (HEAD carries it: the detached result is returned) or + // detachFenced (HEAD belongs to a newer epoch or another holder). An + // error wrapping errChunkCASOutcomeUnknown leaves it undecided: stay + // stopped. It never resumes on top of a possibly detached HEAD. + SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) // MakeRemoteDurable is the durability point for snapshot, detach and // migrate: a Capture whose H >= t. Only a nil return makes t remote // durable; it requires the local Sync to cover t first, and fails From f9a8b5daab22758f85e2e654477659dc89103a86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:30:54 -0800 Subject: [PATCH 2/4] durable: detach review fold: settle every failure before resuming; one freeze budget - P1: every failed detach is settled before anything resumes, a failed drain included. A repeated detach after a successful one (or with a cancelled context) returns the first result and stays stopped, and a retry over an unresolved detach CAS stays stopped while the outcome is unknown. The StopIO failure path used to resume unconditionally. - P1: one freeze budget covers the drain, the final cut and the settlement (the cut gets three quarters, the settlement the rest); the settlement no longer adds 10 s of its own. The bound is cooperative (contexts), as documented. - P2: the resume does not restart the periodic cuts after a concurrent Close (or a replaced layer); ErrDetachOutcomeUnknown maps to outcome_unknown explicitly, before its cause. - Tests: the two P1 cases and the budget case (red on 26426dd5: resumed a detached volume, resumed over an unknown CAS, 10.4 s for a 400 ms bound); a detach CAS genuinely delayed until after the cancel then fails its precondition; the drain test now checks that the resumed write queues behind the admitted one and that recovery succeeds. - Mutants (declared, 9/9): plus a failed StopIO resuming without the settle, the settlement with time of its own, the cut taking the whole budget. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 10 +- .../core/frontend/durable/provider_chunk.go | 37 ++++-- .../provider_chunk_detach_abort_test.go | 125 +++++++++++++++++- .../provider_chunk_detach_stop_test.go | 9 +- .../core/host/volume/chunk_control.go | 3 + 5 files changed, 163 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index d115bc07af..7453e9f7b2 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -165,10 +165,12 @@ type ProviderConfig struct { // passed since the volume's last successful cut (of any kind). Zero // disables the timer. ChunkCaptureInterval time.Duration - // DetachFreezeTimeout bounds how long DetachVolume keeps guest I/O - // stopped for its drain and final cut (the caller's context can only - // shorten it). Zero: 20 s, below the host's 30 s I/O timeout; a freeze - // past the 5 s target is logged as an alarm. + // DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest + // I/O stopped before it resumes or settles: the drain and final cut get + // three quarters of it, the settlement of a failed cut the rest (the + // caller's context can only shorten the cut part). Zero: 20 s, below the + // host's 30 s I/O timeout; a freeze past the 5 s target is logged as an + // alarm. Cooperative: a syscall that never returns is not bounded. DetachFreezeTimeout time.Duration // ChunkDirtyThreshold is the bound on one cut's barrier copy, in // chunks. It never triggers a cut: the remote holds snapshots, and diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 95add9aadc..da0da1948f 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -780,25 +780,31 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if freeze <= 0 { freeze = defaultDetachFreezeTimeout } - fctx, cancel := context.WithTimeout(ctx, freeze) - defer cancel() + // One freeze budget covers the drain, the final cut AND the settlement: + // the cut gets three quarters, the settlement what is left. The bound is + // cooperative (contexts): a syscall that never returns is not bounded here. start := time.Now() + cutCtx, cancel := context.WithDeadline(ctx, start.Add(freeze*3/4)) + defer cancel() defer func() { if d := time.Since(start); d > detachFreezeTarget { log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) } }() h.chunkDetach = true - if err := h.backend.StopIO(fctx, "chunk detach: I/O stopped until a new attach"); err != nil { - return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err) // nothing was cut - } - p.stopChunkLoop(h) - r, err := layer.Detach(fctx) + err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") if err == nil { - return r, h.storage.NextLSN() - 1, nil + p.stopChunkLoop(h) + var r storage.ChunkCutResult + if r, err = layer.Detach(cutCtx); err == nil { + return r, h.storage.NextLSN() - 1, nil + } } - // Settle with time of its own: the freeze bound may be what ended the cut. - sctx, scancel := context.WithTimeout(context.WithoutCancel(ctx), detachSettleTimeout) + // Every failure, a failed drain included, is settled before anything + // resumes: an earlier detach that applied, an unresolved detach CAS or a + // fenced layer must never resume serving. The settlement keeps the rest + // of the freeze budget even when the caller's context is gone. + sctx, scancel := context.WithDeadline(context.WithoutCancel(ctx), start.Add(freeze)) defer scancel() how, dr, serr := layer.SettleDetach(sctx) switch { @@ -816,17 +822,22 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st const ( defaultDetachFreezeTimeout = 20 * time.Second detachFreezeTarget = 5 * time.Second - detachSettleTimeout = 10 * time.Second ) // resumeAfterDetach undoes a detach that provably did not happen: the // periodic cuts restart, the stop is lifted, and the volume serves again. // The caller holds h.attachMu. func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error { - h.chunkDetach = false p.mu.Lock() - p.startChunkLoop(volumeID, h, layer) + closed := p.closed || h.chunk != layer + if !closed { + p.startChunkLoop(volumeID, h, layer) + } p.mu.Unlock() + if closed { // a concurrent Close or detach of the layer owns the volume now + return fmt.Errorf("durable: detach of %s aborted while the provider closed: %w", volumeID, cause) + } + h.chunkDetach = false h.backend.SetOperational(true, "chunk detach aborted: serving resumed") log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause) return fmt.Errorf("%w: %w", ErrDetachAborted, cause) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go index 556dabe8bd..aeeb8c7a31 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go @@ -28,6 +28,11 @@ type faultRemote struct { casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold" getHeadErr error // returned by every GetHead while set getHeadFail int // the next N GetHead calls fail + getHeadHold bool // every GetHead blocks until its caller gives up + // "delayed": the CAS's reply is lost now, the CAS itself reaches the + // remote only when release closes; its own result goes to delayedErr. + release chan struct{} + delayedErr chan error } var errInjected = errors.New("injected remote fault") @@ -46,12 +51,17 @@ func (r *faultRemote) Put(ctx context.Context, key string, data []byte) error { func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { r.mu.Lock() + hold := r.getHeadHold err := r.getHeadErr if err == nil && r.getHeadFail > 0 { r.getHeadFail-- err = errInjected } r.mu.Unlock() + if hold { + <-ctx.Done() + return storage.ChunkHead{}, ctx.Err() + } if err != nil { return storage.ChunkHead{}, err } @@ -71,6 +81,16 @@ func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer case "hold": // held until the caller gives up: not applied <-ctx.Done() return 0, ctx.Err() + case "delayed": + r.mu.Lock() + release, out := r.release, r.delayedErr + r.mu.Unlock() + go func() { + <-release + _, err := r.MemChunkRemote.CASHead(context.Background(), expected, next) + out <- err + }() + return 0, errInjected case "applied-lost": if _, err := r.MemChunkRemote.CASHead(ctx, expected, next); err != nil { return 0, err @@ -243,8 +263,9 @@ func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) { if !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("detach with a hung CAS: %v; want an aborted detach at the freeze bound", err) } - if took < 300*time.Millisecond || took > 3*time.Second { - t.Fatalf("detach with a hung CAS took %v; want about the 300 ms freeze bound", took) + // The cut gets three quarters of the bound, the settlement the rest. + if took < 225*time.Millisecond || took > 300*time.Millisecond+200*time.Millisecond { + t.Fatalf("detach with a hung CAS took %v; want the cut ended at 3/4 of the 300 ms freeze bound and the total within it", took) } assertServing(t, p, b, remote) } @@ -270,3 +291,103 @@ func TestWALStoreChunk_DetachAgainstNewerEpochStaysStopped(t *testing.T) { t.Fatalf("write after a fenced detach: %v; want it refused (not ready / stale primary)", err) } } + +// P1 (review): a repeated detach after a successful one, with a cancelled +// context (its StopIO fails at once), returns the first result and never +// resumes serving. +func TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes(t *testing.T) { + _, p, b := detachFixture(t) + r1, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + cctx, cancel := context.WithCancel(context.Background()) + cancel() + r2, _, err := p.DetachVolume(cctx, "v1") + if err != nil || r2.Head.Gen != r1.Head.Gen || r2.Head.State != storage.ChunkHeadDetached { + t.Fatalf("repeated detach with a cancelled context: %+v %v; want the first result %+v", r2, err, r1) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a repeated detach: %v; want ErrNotReady (never resumed)", err) + } +} + +// P1 (review): after an undecidable detach, a retry whose StopIO fails (a +// cancelled context) settles first and stays stopped while the outcome is +// still unknown. +func TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("first detach: %v; want ErrDetachOutcomeUnknown", err) + } + cctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, _, err := p.DetachVolume(cctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("retry over an unresolved detach CAS: %v; want still unknown, never aborted", err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a retry over an unknown detach: %v; want ErrNotReady", err) + } +} + +// P1 (review): one freeze budget covers the cut AND the settlement: with the +// CAS and every HEAD read hung, DetachVolume returns within the bound (here +// undecided, so the volume stays stopped). +func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) { + const freeze = 400 * time.Millisecond + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + DetachFreezeTimeout: freeze, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + remote.set(func(r *faultRemote) { r.casMode = "hold"; r.getHeadHold = true }) + start := time.Now() + _, _, err = p.DetachVolume(context.Background(), "v1") + took := time.Since(start) + if !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("detach with a hung CAS and hung HEAD reads: %v; want the outcome unknown", err) + } + if took > freeze+200*time.Millisecond { + t.Fatalf("detach took %v; the %v freeze bound must cover the settlement too", took, freeze) + } + if _, err := b.Write(context.Background(), 8192, block(2)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an undecided detach: %v; want ErrNotReady", err) + } +} + +// P2 (review): the lost detach CAS really is in flight. It reaches the remote +// only after the cancel landed, and then fails its precondition: HEAD stays +// active. +func TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel(t *testing.T) { + remote, p, b := detachFixture(t) + release, delayed := make(chan struct{}), make(chan error, 1) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + t.Cleanup(unblock) + remote.set(func(r *faultRemote) { r.casMode = "delayed"; r.release, r.delayedErr = release, delayed }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a delayed CAS: %v; want ErrDetachAborted after the cancel", err) + } + unblock() + if err := <-delayed; !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", err) + } + if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached { + t.Fatal("the delayed detach CAS landed after the cancel") + } + assertServing(t, p, b, remote) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go index b52c96f1ec..d5d511af1f 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go @@ -152,14 +152,19 @@ func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { // detach itself). nerr := make(chan error, 1) go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }() + select { + case err := <-nerr: + t.Fatalf("new write completed (%v) ahead of the write admitted before the stop", err) + case <-time.After(100 * time.Millisecond): // queued behind the admitted write, as the drain orders it + } view.unpark() acked := <-werr == nil if err := <-nerr; err != nil { t.Fatalf("new write after an aborted detach: %v; want it accepted", err) } - if _, err := p.RecoverVolume(ctx, "v1"); errors.Is(err, storage.ErrChunkLayerDetached) { - t.Fatalf("recovery after an aborted detach: %v; want the volume serving", err) + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("recovery after an aborted detach: %v; want it to succeed", err) } o := detachOutcome{} o.r, o.last, o.err = p.DetachVolume(ctx, "v1") diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index d9365811c2..97525d2391 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -235,6 +235,9 @@ func chunkErrorCode(err error) (int, string, bool) { case errors.Is(err, durable.ErrDetachAborted): // Before its cause: nothing was published and serving resumed here. return http.StatusConflict, codeDetachAborted, true + case errors.Is(err, durable.ErrDetachOutcomeUnknown): + // Before its cause: the detach may still have landed; I/O stays stopped. + return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true case errors.Is(err, storage.ErrChunkLayerFenced): return http.StatusConflict, codeFenced, false case errors.Is(err, storage.ErrChunkCASOutcomeUnknown): From 89f0ca8b30fb941436c1b86d6bf4a8cdca508960 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:52:14 -0800 Subject: [PATCH 3/4] durable: detach review fold 2: forced failed-drain branch, recorded deadlines, handshakes, mapping order, invariants - Test-only hooks: DetachVolume's StopIO can be replaced (the repeat and retry tests now force and observe the failed-drain branch instead of racing a cancelled context against a finished drain); the detach's cut and settlement deadlines are traced (the budget test checks 3/4 of the freeze, then the bound); the backend signals an I/O passing its readiness check right before the I/O lock (the drain test's arrival handshake replaces a 100 ms non-completion window, with bounded receives). - The delayed detach CAS worker is joined, bounded, also on failure. - chunkErrorCode: the detach sentinels decide before a catalog-error cause; the table rows now discriminate that order (no storage CAS sentinel behind them). - Invariants: INV-WS-DETACH-ABORT-001 and INV-WS-DETACH-FREEZE-001, and the M4 transition Holder (detaching) -> Holder. - Mutants (declared, 10/10): plus a catalog cause deciding before the sentinels; the whole-budget cut is now caught by the deadline check too. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/export_chunk_test.go | 21 ++++++++ .../core/frontend/durable/provider.go | 5 ++ .../core/frontend/durable/provider_chunk.go | 14 +++++- .../provider_chunk_detach_abort_test.go | 48 +++++++++++++++---- .../provider_chunk_detach_stop_test.go | 28 +++++++++-- .../core/frontend/durable/storage_adapter.go | 7 +++ .../core/host/volume/chunk_control.go | 9 ++-- .../core/host/volume/chunk_control_test.go | 5 +- seaweed-block/docs/design/invariants.md | 5 +- 9 files changed, 123 insertions(+), 19 deletions(-) diff --git a/seaweed-block/core/frontend/durable/export_chunk_test.go b/seaweed-block/core/frontend/durable/export_chunk_test.go index 83300439e8..7a499b43d7 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -1,5 +1,26 @@ package durable +import ( + "context" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + // SetTestAfterChunkResolve installs the test-only hook CutVolume runs right // after it resolves the volume's handle and layer. func SetTestAfterChunkResolve(p *DurableProvider, f func()) { p.testAfterChunkResolve = f } + +// SetTestDetachStopIO replaces DetachVolume's StopIO call (test-only). +func SetTestDetachStopIO(p *DurableProvider, f func(ctx context.Context) error) { + p.testDetachStopIO = f +} + +// SetTestDetachTrace observes DetachVolume's stages and deadlines (test-only). +func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.Time)) { + p.testDetachTrace = f +} + +// SetTestBeforeIOLock runs f in the backend's admission, right before the I/O +// lock (test-only). +func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 7453e9f7b2..88722c9f40 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -194,6 +194,11 @@ type DurableProvider struct { // testAfterChunkResolve, test-only, runs in CutVolume right after the // volume's handle and layer are resolved. testAfterChunkResolve func() + // testDetachStopIO, test-only, replaces DetachVolume's StopIO call (so a + // test can force the failed-drain branch); testDetachTrace, test-only, + // observes the detach's stages and their deadlines ("cut", "settle"). + testDetachStopIO func(ctx context.Context) error + testDetachTrace func(stage string, deadline time.Time) // testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary. testBeforeChunkFreshRetire func() error diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index da0da1948f..66b3158d2a 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -791,8 +791,16 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) } }() + if trace := p.testDetachTrace; trace != nil { + dl, _ := cutCtx.Deadline() + trace("cut", dl) + } h.chunkDetach = true - err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") + if stop := p.testDetachStopIO; stop != nil { + err = stop(cutCtx) + } else { + err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") + } if err == nil { p.stopChunkLoop(h) var r storage.ChunkCutResult @@ -806,6 +814,10 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st // of the freeze budget even when the caller's context is gone. sctx, scancel := context.WithDeadline(context.WithoutCancel(ctx), start.Add(freeze)) defer scancel() + if trace := p.testDetachTrace; trace != nil { + dl, _ := sctx.Deadline() + trace("settle", dl) + } how, dr, serr := layer.SettleDetach(sctx) switch { case serr != nil: diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go index aeeb8c7a31..4584662a70 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go @@ -301,9 +301,12 @@ func TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes(t *testing.T if err != nil { t.Fatal(err) } - cctx, cancel := context.WithCancel(context.Background()) - cancel() - r2, _, err := p.DetachVolume(cctx, "v1") + forced := false + durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails + r2, _, err := p.DetachVolume(context.Background(), "v1") + if !forced { + t.Fatal("the failed-drain branch was not taken") + } if err != nil || r2.Head.Gen != r1.Head.Gen || r2.Head.State != storage.ChunkHeadDetached { t.Fatalf("repeated detach with a cancelled context: %+v %v; want the first result %+v", r2, err, r1) } @@ -321,9 +324,13 @@ func TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes(t *testing.T) { if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { t.Fatalf("first detach: %v; want ErrDetachOutcomeUnknown", err) } - cctx, cancel := context.WithCancel(context.Background()) - cancel() - if _, _, err := p.DetachVolume(cctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) { + forced := false + durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails + _, _, err := p.DetachVolume(context.Background(), "v1") + if !forced { + t.Fatal("the failed-drain branch was not taken") + } + if !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) { t.Fatalf("retry over an unresolved detach CAS: %v; want still unknown, never aborted", err) } if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { @@ -355,9 +362,15 @@ func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) { t.Fatal(err) } remote.set(func(r *faultRemote) { r.casMode = "hold"; r.getHeadHold = true }) + deadlines := map[string]time.Time{} + durable.SetTestDetachTrace(p, func(stage string, d time.Time) { deadlines[stage] = d }) start := time.Now() _, _, err = p.DetachVolume(context.Background(), "v1") took := time.Since(start) + cutAt, settleAt := deadlines["cut"].Sub(start), deadlines["settle"].Sub(start) + if cutAt < freeze*3/4-50*time.Millisecond || cutAt > freeze*3/4+50*time.Millisecond || settleAt < freeze-50*time.Millisecond || settleAt > freeze+50*time.Millisecond { + t.Fatalf("deadlines: cut %v, settle %v after the start; want three quarters of the %v freeze, then the bound", cutAt, settleAt, freeze) + } if !errors.Is(err, durable.ErrDetachOutcomeUnknown) { t.Fatalf("detach with a hung CAS and hung HEAD reads: %v; want the outcome unknown", err) } @@ -377,14 +390,31 @@ func TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel(t *testing.T) { release, delayed := make(chan struct{}), make(chan error, 1) var once sync.Once unblock := func() { once.Do(func() { close(release) }) } - t.Cleanup(unblock) + joined := false + t.Cleanup(func() { // join the delayed CAS worker, bounded + unblock() + if !joined { + select { + case <-delayed: + case <-time.After(5 * time.Second): + t.Error("delayed CAS worker not joined") + } + } + }) remote.set(func(r *faultRemote) { r.casMode = "delayed"; r.release, r.delayedErr = release, delayed }) if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { t.Fatalf("detach with a delayed CAS: %v; want ErrDetachAborted after the cancel", err) } unblock() - if err := <-delayed; !errors.Is(err, storage.ErrChunkHeadPrecondition) { - t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", err) + var derr error + select { + case derr = <-delayed: + joined = true + case <-time.After(5 * time.Second): + t.Fatal("the delayed detach CAS did not complete after its release") + } + if !errors.Is(derr, storage.ErrChunkHeadPrecondition) { + t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", derr) } if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached { t.Fatal("the delayed detach CAS landed after the cancel") diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go index d5d511af1f..0dda1b07f1 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go @@ -150,17 +150,39 @@ func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { // the aborted stop orders new I/O after the I/O admitted before it, so // this write completes once that admitted write does (never on the // detach itself). + arrived := make(chan struct{}) + var arriveOnce sync.Once + durable.SetTestBeforeIOLock(b, func() { arriveOnce.Do(func() { close(arrived) }) }) nerr := make(chan error, 1) go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }() + bounded := func(what string, ch <-chan struct{}) { + t.Helper() + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Fatalf("%s did not happen within 5s", what) + } + } + bounded("the new write passing the operational gate (serving resumed)", arrived) select { case err := <-nerr: t.Fatalf("new write completed (%v) ahead of the write admitted before the stop", err) - case <-time.After(100 * time.Millisecond): // queued behind the admitted write, as the drain orders it + default: // queued behind the admitted write at the I/O lock, as the drain orders it } view.unpark() - acked := <-werr == nil - if err := <-nerr; err != nil { + recv := func(what string, ch <-chan error) error { + t.Helper() + select { + case err := <-ch: + return err + case <-time.After(5 * time.Second): + t.Fatalf("%s did not complete within 5s", what) + return nil + } + } + acked := recv("the admitted write", werr) == nil + if err := recv("the new write", nerr); err != nil { t.Fatalf("new write after an aborted detach: %v; want it accepted", err) } if _, err := p.RecoverVolume(ctx, "v1"); err != nil { diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 30e3c05bbd..e2fcea011f 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -146,6 +146,10 @@ const maxFullBlockBatchBlocks = 64 // StorageBackend adapts a LogicalStorage into frontend.Backend. type StorageBackend struct { + // testBeforeIOLock, test-only, runs in admit after the readiness check, + // right before the I/O lock (an arrival handshake for queued I/O). + testBeforeIOLock func() + storage storage.LogicalStorage view frontend.ProjectionView id frontend.Identity @@ -582,6 +586,9 @@ func (b *StorageBackend) admit() (func(), error) { if err := b.readyCheck(); err != nil { return nil, err } + if hook := b.testBeforeIOLock; hook != nil { + hook() + } b.ioMu.RLock() if err := b.gate(); err != nil { b.ioMu.RUnlock() diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 97525d2391..a0053962cb 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -230,14 +230,15 @@ func writeChunkFailure(w http.ResponseWriter, err error) { func chunkErrorCode(err error) (int, string, bool) { var ce *chunkstore.CatalogError switch { - case errors.As(err, &ce): - return catalogStatus(ce.Code), ce.Code, ce.Retryable case errors.Is(err, durable.ErrDetachAborted): - // Before its cause: nothing was published and serving resumed here. + // Before any cause (a catalog error included): nothing was + // published and serving resumed here. return http.StatusConflict, codeDetachAborted, true case errors.Is(err, durable.ErrDetachOutcomeUnknown): - // Before its cause: the detach may still have landed; I/O stays stopped. + // Before any cause: the detach may still have landed; I/O stays stopped. return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true + case errors.As(err, &ce): + return catalogStatus(ce.Code), ce.Code, ce.Retryable case errors.Is(err, storage.ErrChunkLayerFenced): return http.StatusConflict, codeFenced, false case errors.Is(err, storage.ErrChunkCASOutcomeUnknown): diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index 60e9c7f302..6c8c76722d 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -223,7 +223,10 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) { {fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false}, {fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false}, {fmt.Errorf("%w: %w", durable.ErrDetachAborted, storage.ErrChunkRemoteUnavailable), "detach_aborted", 409, true}, - {fmt.Errorf("%w: %w (settle: %w)", durable.ErrDetachOutcomeUnknown, storage.ErrChunkCASOutcomeUnknown, storage.ErrChunkRemoteUnavailable), "outcome_unknown", 503, true}, + // The detach sentinels decide even over a catalog-error cause (which + // alone maps to its own code), and without the storage CAS sentinel. + {fmt.Errorf("%w: %w", durable.ErrDetachAborted, &chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}), "detach_aborted", 409, true}, + {fmt.Errorf("%w: %w", durable.ErrDetachOutcomeUnknown, &chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}), "outcome_unknown", 503, true}, {fmt.Errorf("%w: %w: cut LSN 1, HEAD remote_lsn 10", storage.ErrChunkCaptureRefused, storage.ErrChunkLSNBehind), "lsn_behind", 409, false}, {&chunkstore.CatalogError{Code: chunkstore.CodeInvalidLabel, Message: "m"}, "invalid_label", 400, false}, {fmt.Errorf("x: %w", durable.ErrNotChunkVolume), "not_chunk_volume", 409, false}, diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b032a37af0..7ab2bda3af 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -91,6 +91,8 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | | Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | +| `INV-WS-DETACH-ABORT-001` | A failed detach resumes serving only when it provably did not publish (before its CAS, a refused CAS, or an unresolved detach CAS cancelled at the same base). An applied, fenced or undecided detach keeps I/O stopped, also on a repeated detach or a retry: every failure is settled before any resume. | M4 Holder (detaching) → Holder | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume`; `core/storage/chunk_layer.go` `chunkLayerImpl.SettleDetach` | `TestWALStoreChunk_FailedDetachUploadResumes`, `TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes`, `TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel`, `TestWALStoreChunk_LostDetachCASAppliedFoundBySettle`, `TestWALStoreChunk_UndecidableDetachStaysStopped`, `TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes`, `TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes` (`core/frontend/durable/provider_chunk_detach_abort_test.go`) | - | ACTIVE | +| `INV-WS-DETACH-FREEZE-001` | One freeze budget (`DetachFreezeTimeout`, default 20 s) bounds a failing detach's drain, final cut and settlement together: the cut gets three quarters, the settlement the rest. Cooperative: contexts only. | M4 Holder (detaching) → Holder | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume` | `TestWALStoreChunk_DetachFreezeIsBoundedThenResumes`, `TestWALStoreChunk_DetachFreezeBoundCoversTheSettle` (`core/frontend/durable/provider_chunk_detach_abort_test.go`) | - | ACTIVE | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | @@ -174,6 +176,7 @@ stateDiagram-v2 | Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | | Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | +| Holder (detaching) | Holder | a failed detach that provably did not publish resumes serving: nothing reached its CAS, the CAS was refused, or an unresolved detach CAS was cancelled by a CAS at the same base | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume`; `core/storage/chunk_layer.go` `chunkLayerImpl.SettleDetach` | `INV-WS-DETACH-ABORT-001`, `INV-WS-DETACH-FREEZE-001` | | Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | @@ -264,7 +267,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th ## Part B. Invariant ledger -80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 new. +82 rows: 71 ACTIVE, 11 STUB; 15 kept from the internal ledger, 67 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. From 0a35653775e03433027f2407c6dcade82988a90f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:09:41 -0800 Subject: [PATCH 4/4] docs: keep the detach invariant rows off the public PR (archived on the share) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7ab2bda3af..b032a37af0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -91,8 +91,6 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | | Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | -| `INV-WS-DETACH-ABORT-001` | A failed detach resumes serving only when it provably did not publish (before its CAS, a refused CAS, or an unresolved detach CAS cancelled at the same base). An applied, fenced or undecided detach keeps I/O stopped, also on a repeated detach or a retry: every failure is settled before any resume. | M4 Holder (detaching) → Holder | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume`; `core/storage/chunk_layer.go` `chunkLayerImpl.SettleDetach` | `TestWALStoreChunk_FailedDetachUploadResumes`, `TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes`, `TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel`, `TestWALStoreChunk_LostDetachCASAppliedFoundBySettle`, `TestWALStoreChunk_UndecidableDetachStaysStopped`, `TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes`, `TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes` (`core/frontend/durable/provider_chunk_detach_abort_test.go`) | - | ACTIVE | -| `INV-WS-DETACH-FREEZE-001` | One freeze budget (`DetachFreezeTimeout`, default 20 s) bounds a failing detach's drain, final cut and settlement together: the cut gets three quarters, the settlement the rest. Cooperative: contexts only. | M4 Holder (detaching) → Holder | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume` | `TestWALStoreChunk_DetachFreezeIsBoundedThenResumes`, `TestWALStoreChunk_DetachFreezeBoundCoversTheSettle` (`core/frontend/durable/provider_chunk_detach_abort_test.go`) | - | ACTIVE | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | @@ -176,7 +174,6 @@ stateDiagram-v2 | Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | | Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | -| Holder (detaching) | Holder | a failed detach that provably did not publish resumes serving: nothing reached its CAS, the CAS was refused, or an unresolved detach CAS was cancelled by a CAS at the same base | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume`; `core/storage/chunk_layer.go` `chunkLayerImpl.SettleDetach` | `INV-WS-DETACH-ABORT-001`, `INV-WS-DETACH-FREEZE-001` | | Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | @@ -267,7 +264,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th ## Part B. Invariant ledger -82 rows: 71 ACTIVE, 11 STUB; 15 kept from the internal ledger, 67 new. +80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.