Merge pull request #690 from seaweedfs/fix/plain-settle-reserve

fix(durable): a plain detach keeps a settlement reserve inside the caller's bound
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-28 12:29:28 -08:00
commit 5d6c0883e9
4 files changed
+112 -2

No files matched your search

@@ -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
@@ -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)
}
+1 -1
View File
@@ -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 |
@@ -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