From 0e7c439ce3d286d673cf69a6888b1857542ec907 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 27 Nov 2026 22:17:58 -0800 Subject: [PATCH 1/2] fix(durable): a plain detach keeps a settlement reserve inside the caller's bound A plain detach whose final cut ran to the caller's deadline settled on that already expired context: its first remote call failed and the caller was told the outcome was unknown, while the background settlement found nothing committed and resumed serving a moment later. With a caller deadline, the cut is now cancelled min(4 s, a quarter of the bound) early and the settlement runs on WithoutCancel(cutCtx) up to the deadline, the shape the live detach already uses. Outcomes are unchanged: an undecidable settlement still answers outcome unknown. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider_chunk.go | 12 ++- ...rovider_layout_plain_settle_budget_test.go | 96 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_layout_plain_settle_budget_test.go diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 5bda51d763..cd75023833 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1293,7 +1293,13 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } casAtFreeze = countCAS() if plain { // M5 PlainStop -> Quiesce: no live frontend, caller owns the bound. + // The settlement keeps a reserve inside that bound: a cut run to + // the caller's deadline would leave it no time to say what happened. settleDeadline, _ = ctx.Deadline() + if !settleDeadline.IsZero() { + remaining := max(time.Duration(0), time.Until(settleDeadline)) + timer = time.AfterFunc(remaining-min(plainSettleReserve, remaining/4), func() { cancel(context.DeadlineExceeded) }) + } return } operationStart := start @@ -1427,7 +1433,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // 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.WithCancel(cutCtx) - if !plain { // Live detach retains its reserved settlement budget. + if !plain || !settleDeadline.IsZero() { // the reserved settlement budget scancel() sctx, scancel = context.WithDeadline(context.WithoutCancel(cutCtx), settleDeadline) } @@ -1559,6 +1565,10 @@ func (p *DurableProvider) retryUnknownDetach(volumeID string, h *volHandle, laye const ( defaultDetachFreezeTimeout = 20 * time.Second detachFreezeTarget = 5 * time.Second + // plainSettleReserve: a plain detach's settlement (a conditional abort + // and a HEAD read, each a 2 s HEAD operation), kept inside the caller's + // bound, at most a quarter of it. + plainSettleReserve = 4 * time.Second ) // resumeAfterDetach undoes a detach that provably did not happen: the diff --git a/seaweed-block/core/frontend/durable/provider_layout_plain_settle_budget_test.go b/seaweed-block/core/frontend/durable/provider_layout_plain_settle_budget_test.go new file mode 100644 index 0000000000..6f81f3e5c0 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_layout_plain_settle_budget_test.go @@ -0,0 +1,96 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// slowCutLayout is a layout remote whose chunk uploads run until their +// context ends (a final cut longer than the caller's bound), and whose +// settlement calls fail on an ended context as a filer reached over gRPC +// does (the in-memory filer ignores contexts). +type slowCutLayout struct { + *chunkstore.LayoutRemote + slow atomic.Bool +} + +func (r *slowCutLayout) Put(ctx context.Context, key string, data []byte) error { + if r.slow.Load() { + <-ctx.Done() + return ctx.Err() + } + return r.LayoutRemote.Put(ctx, key, data) +} + +func (r *slowCutLayout) AbortOpenSession(ctx context.Context) (string, error) { + if err := ctx.Err(); err != nil { + return "", err + } + return r.LayoutRemote.AbortOpenSession(ctx) +} + +func (r *slowCutLayout) ReadHead(ctx context.Context) (layout.Head, error) { + if err := ctx.Err(); err != nil { + return layout.Head{}, err + } + return r.LayoutRemote.ReadHead(ctx) +} + +// A plain detach whose final cut outlasts the caller's bound, against a +// session nothing was committed in, answers within that bound that it was +// aborted with nothing published (and the volume serves again), not that +// its outcome is unknown: the settlement keeps a reserve inside the bound. +func TestLayoutPlainDetachThatOutlastsItsBoundAnswersAborted(t *testing.T) { + c := newLayoutCase(t, 64, 4) + var remote *slowCutLayout + p := c.provider(t, t.TempDir(), v1View(), "s/r1", func(cfg *durable.ProviderConfig) { + cfg.ChunkLayoutRemoteFor = func(_ string, me layout.HolderID) (storage.ChunkRemote, error) { + r, err := chunkstore.NewLayoutRemote(c.cat, c.ref, me) + if err != nil { + return nil, err + } + remote = &slowCutLayout{LayoutRemote: r} + return remote, nil + } + }) + ws := openRecovered(t, p) + if _, err := ws.Write(0, bytes.Repeat([]byte{'Q'}, 4096)); err != nil { + t.Fatal(err) + } + if _, err := ws.Sync(); err != nil { + t.Fatal(err) + } + before := c.head(t) + remote.slow.Store(true) + bound := 3 * time.Second + ctx, cancel := context.WithTimeout(context.Background(), bound) + defer cancel() + start := time.Now() + _, _, err := p.DetachVolumePlain(ctx, "v1") + took := time.Since(start) + if errors.Is(err, durable.ErrDetachOutcomeUnknown) || !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("plain detach past its bound, nothing committed: %v; want ErrDetachAborted, not ErrDetachOutcomeUnknown", err) + } + if took > bound { + t.Errorf("the answer took %s, past the caller's %s bound", took, bound) + } + // Opening and aborting the stop session moves HEAD's generation; nothing + // is published: not detached, same position, an idle session. + if got := c.head(t); got.State == layout.StateDetached || got.Position != before.Position || got.Activity.Kind != layout.ActIdle { + t.Fatalf("an aborted detach published: %+v -> %+v", before, got) + } + remote.slow.Store(false) + if n, err := p.Backend("v1").Write(context.Background(), 4096, bytes.Repeat([]byte{'R'}, 4096)); err != nil || n != 4096 { + t.Fatalf("the volume does not serve after the aborted detach: %d %v", n, err) + } + t.Logf("answered in %s of %s: %v", took.Round(time.Millisecond), bound, err) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d60d7f1b99..7c9cf8a9c7 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -859,7 +859,7 @@ Notes: |---|---|---|---|---|---|---| | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | -| `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline`, `TestChunkPlainDetachRequiresExplicitBound` (`core/host/volume/chunk_offline_seal_test.go`) | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend, with a settle reserve inside that bound. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline`, `TestChunkPlainDetachRequiresExplicitBound` (`core/host/volume/chunk_offline_seal_test.go`); `TestLayoutPlainDetachThatOutlastsItsBoundAnswersAborted` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | | `INV-STOP-FLIP-CUTOFF-001` | A detach logs 'admission closed at' = the backend's flip, recorded under its mu just after operational goes false: an I/O whose gate ran before it is admitted and drained by StopIO; every gate after it refuses. Logged only on a successful stop. | M5 detach (StopIO / plain stop / pre-copy TryStopIO) | `core/frontend/durable/storage_adapter.go` `setOperationalLocked`, `TryStopIO`, `StopFlipAt`; `provider_chunk.go` detach log | `TestStopFlipIsTheAdmissionCutoff`, `TestLiveDetachLogsWhenAdmissionClosed` (`core/frontend/durable/stopio_began_log_test.go`) | — (no state machine change; the cutoff test is the proof form) | ACTIVE | | `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRequestRefusalCarriesNoBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE | | `INV-WS-FREEZE-REFUSAL-001` | HTTP 400 `invalid_freeze_budget`, retryable=false, is returned only by frozen-detach request validation, before any provider admission or mutation. | M5 frozen detach admission: [*] → Refused (invalid frozen request) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode` (`core/host/volume/chunk_frozen_budget_test.go`); `TestFrozenValidationPrecedesAnyProviderAccess` (`core/frontend/durable/frozen_validation_before_access_test.go`) | — (wire classification; validation/admission guards unchanged) | ACTIVE | From 6a259ea479b86f149ec091935e681892e811c466 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 11:45:20 -0800 Subject: [PATCH 2/2] docs: the plain seal's cut keeps a settlement reserve inside --timeout Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/standalone-deployment.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index cefc74dea4..76b1519aef 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -571,6 +571,10 @@ Perform a clean hand-over in this order: sw-block ops chunk detach --plain --volume V --status-addr OLD_STATUS --timeout 120s >seal.json ``` + The seal's final cut stops before `--timeout` ends: 4 s before it, or a + quarter of it for a timeout under 16 s. It keeps that reserve to settle + what happened, so a seal that runs out still answers within the timeout, + aborted (nothing published, the volume serves again) or unknown. Busy admission refuses the operation. Do not proceed on any failure or unknown outcome. JSON remains on stdout; a successful command also prints `sealed HEAD generation: G` on its own stderr line, taken from the same