From 89f0ca8b30fb941436c1b86d6bf4a8cdca508960 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:52:14 -0800 Subject: [PATCH] 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.