From 4f395e23f77dbb5f636240367f6ada15e1dd20cc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:02:38 -0800 Subject: [PATCH 1/3] feat: allow idle frontend plain chunk detach --- .../core/frontend/durable/provider_chunk.go | 28 ++++- .../durable/provider_plain_detach_test.go | 113 ++++++++++++++++++ .../core/frontend/durable/storage_adapter.go | 20 ++++ .../core/host/volume/chunk_control.go | 33 ++++- .../host/volume/chunk_plain_detach_test.go | 69 +++++++++++ seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/spec/PlainDetach.tla | 19 +++ seaweed-block/docs/spec/README.md | 18 +++ seaweed-block/docs/spec/cfg/PlainDetach.cfg | 3 + .../docs/spec/cfg/PlainDetach_no_idle.cfg | 3 + 10 files changed, 308 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_plain_detach_test.go create mode 100644 seaweed-block/core/host/volume/chunk_plain_detach_test.go create mode 100644 seaweed-block/docs/spec/PlainDetach.tla create mode 100644 seaweed-block/docs/spec/cfg/PlainDetach.cfg create mode 100644 seaweed-block/docs/spec/cfg/PlainDetach_no_idle.cfg diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 415d804e56..5ab9b9eb68 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -883,6 +883,19 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN // - 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) { + return p.detachVolume(ctx, volumeID, false) +} + +// ErrPlainDetachBusy refuses a plain detach without closing frontend admission. +var ErrPlainDetachBusy = errors.New("durable: plain detach requires idle frontend I/O") + +// DetachVolumePlain bypasses pre-copy cost admission only after atomically +// closing an idle frontend. Publication and failure settlement are unchanged. +func (p *DurableProvider) DetachVolumePlain(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) { + return p.detachVolume(ctx, volumeID, true) +} + +func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, plain bool) (storage.ChunkCutResult, uint64, error) { p.mu.Lock() h, ok := p.volumes[volumeID] p.mu.Unlock() @@ -895,6 +908,12 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if err != nil { return storage.ChunkCutResult{}, 0, err } + if plain { + if err := ctx.Err(); err != nil { + return storage.ChunkCutResult{}, 0, err + } + } + precopy := p.cfg.ChunkDetachPrecopy && !plain freeze := p.cfg.DetachFreezeTimeout if freeze <= 0 { freeze = defaultDetachFreezeTimeout @@ -940,7 +959,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } } var r storage.ChunkCutResult - if p.cfg.ChunkDetachPrecopy { + if precopy { owner, ok := layer.(interface { PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error) }) @@ -987,6 +1006,11 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st } } else { beginFreeze() + if plain { + if err := h.backend.stopPlainDetachIfIdle(); err != nil { + return r, 0, err + } + } if trace := p.testDetachTrace; trace != nil { trace("cut", start.Add(freeze*3/4)) } @@ -1019,7 +1043,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st trace("settle", dl) } how, dr, serr := layer.SettleDetach(sctx) - if p.cfg.ChunkDetachPrecopy { + if precopy { attempts := countCAS() - casAtFreeze extra := uint64(0) if attempts > 0 { diff --git a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go new file mode 100644 index 0000000000..25760f74b5 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go @@ -0,0 +1,113 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + hooks := &detachHooks{} + p := precopyProvider(t, remote, &parkView{stubView: v1View()}, hooks) + openRecovered(t, p) + b, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(ctx, 4096, block(0x4a)); err != nil { + t.Fatal(err) + } + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + joined := false + t.Cleanup(func() { + unblock() + cancel() + if !joined { + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("admitted sync did not join") + } + } + }) + if err = b.(*durable.StorageBackend).SetWriteObserver(writeObserverFunc{sync: func(ctx context.Context, _ uint64) error { + close(entered) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }}); err != nil { + t.Fatal(err) + } + go func() { done <- b.Sync(ctx) }() + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("sync was not admitted") + } + r, _, err := p.DetachVolume(ctx, "v1") + if !errors.Is(err, storage.ErrPrecopyNotConverged) || r.Precopy.Frozen { + t.Fatalf("expected thawed pre-copy refusal: %+v %v", r, err) + } + before, err := remote.GetHead(ctx) + if err != nil || before.State == storage.ChunkHeadDetached { + t.Fatalf("refusal detached: %+v %v", before, err) + } + if _, _, err = p.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrPlainDetachBusy) { + t.Fatalf("plain accepted admitted I/O: %v", err) + } + after, err := remote.GetHead(ctx) + if err != nil || after.Gen != before.Gen || after.State != before.State { + t.Fatalf("busy plain mutated HEAD: before=%+v after=%+v err=%v", before, after, err) + } + starts, resumes := hooks.calls() + if len(starts) != 1 || len(resumes) != 1 { + t.Fatalf("busy plain mutated detach hooks: %v %v", starts, resumes) + } + unblock() + select { + case err = <-done: + joined = true + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("sync did not finish") + } + // A refused plain request left service and authority unchanged. + if _, err = b.Write(ctx, 8192, block(0x5b)); err != nil { + t.Fatal("busy plain stopped service:", err) + } + r, last, err := p.DetachVolumePlain(ctx, "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached || r.H != last || len(r.Precopy.Rounds) != 0 { + t.Fatalf("plain did not use ordinary detached cut: %+v last=%d err=%v", r, last, err) + } + for _, x := range []struct { + lba uint32 + value byte + }{{1, 0x4a}, {2, 0x5b}} { + if !bytes.Equal(headBlock(t, remote, x.lba), block(x.value)) { + t.Fatalf("plain lost acknowledged block %d", x.lba) + } + } + if _, err = b.Write(ctx, 12288, block(0x6c)); err == nil { + t.Fatal("old frontend serves after plain detach") + } + again, last2, err := p.DetachVolumePlain(ctx, "v1") + if err != nil || again.Head.Gen != r.Head.Gen || last2 != last { + t.Fatalf("plain retry changed result: %+v last=%d err=%v", again, last2, err) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 3b4830344b..f1c9e3779c 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -543,6 +543,26 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { return true } +// stopPlainDetachIfIdle closes admission without waiting for a live command. +// Taking ioMu exclusively also excludes commands between their gate and final +// registration; a failed try leaves every admission/pause field unchanged. +func (b *StorageBackend) stopPlainDetachIfIdle() error { + if !b.ioMu.TryLock() { + return ErrPlainDetachBusy + } + defer b.ioMu.Unlock() + b.mu.Lock() + defer b.mu.Unlock() + if b.closed { + return frontend.ErrBackendClosed + } + if b.admittedIO != 0 { + return ErrPlainDetachBusy + } + b.setOperationalLocked(false, "chunk plain detach: idle frontend stopped") + return nil +} + // StopIO makes the backend refuse every new Read, Write and Sync with // ErrNotReady (evidence), then waits, bounded by ctx, for the I/O admitted // before the stop to finish. After a nil return no I/O admitted before the diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 392e12a380..7234b81f2d 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -238,6 +238,8 @@ func writeChunkFailure(w http.ResponseWriter, err error) { func chunkErrorCode(err error) (int, string, bool) { var ce *chunkstore.CatalogError switch { + case errors.Is(err, durable.ErrPlainDetachBusy): + return http.StatusConflict, "plain_detach_busy", true case errors.Is(err, storage.ErrPrecopyUnknown): return http.StatusConflict, "precopy_unknown", true case errors.Is(err, storage.ErrPrecopyNotConverged): @@ -488,6 +490,7 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) var req struct { VolumeID string `json:"volumeID"` TimeoutMs int64 `json:"timeoutMs"` + Plain bool `json:"plain,omitempty"` } if !decodeChunkBody(w, r, &req) { return @@ -498,7 +501,20 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) } ctx, cancel := chunkContext(r, req.TimeoutMs) defer cancel() - res, err := ctl.Detach(ctx, req.VolumeID) + var res ChunkDetachResponse + var err error + if req.Plain { + plain, ok := ctl.(interface { + DetachPlain(context.Context, string) (ChunkDetachResponse, error) + }) + if !ok { + writeChunkErr(w, http.StatusConflict, "plain_detach_unsupported", false, "plain detach unsupported") + return + } + res, err = plain.DetachPlain(ctx, req.VolumeID) + } else { + res, err = ctl.Detach(ctx, req.VolumeID) + } if err != nil { writeChunkFailure(w, err) return @@ -599,6 +615,21 @@ func (s *StatusServer) handleStatusChunk(w http.ResponseWriter, r *http.Request) func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetachResponse, error) { r, last, err := c.p.DetachVolume(ctx, volumeID) + return chunkDetachResponse(volumeID, r, last, err) +} + +func (c *chunkControl) DetachPlain(ctx context.Context, volumeID string) (ChunkDetachResponse, error) { + p, ok := c.p.(interface { + DetachVolumePlain(context.Context, string) (storage.ChunkCutResult, uint64, error) + }) + if !ok { + return ChunkDetachResponse{}, fmt.Errorf("plain detach unsupported by provider") + } + r, last, err := p.DetachVolumePlain(ctx, volumeID) + return chunkDetachResponse(volumeID, r, last, err) +} + +func chunkDetachResponse(volumeID string, r storage.ChunkCutResult, last uint64, err error) (ChunkDetachResponse, error) { if err != nil { return ChunkDetachResponse{}, err } diff --git a/seaweed-block/core/host/volume/chunk_plain_detach_test.go b/seaweed-block/core/host/volume/chunk_plain_detach_test.go new file mode 100644 index 0000000000..1d129984aa --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_plain_detach_test.go @@ -0,0 +1,69 @@ +package volume + +import ( + "context" + "encoding/json" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" + "net/http" + "testing" +) + +type plainDetachControl struct { + *fakeChunkControl + plainCalls int +} + +func (c *plainDetachControl) DetachPlain(ctx context.Context, id string) (ChunkDetachResponse, error) { + c.plainCalls++ + return c.fakeChunkControl.Detach(ctx, id) +} +func TestChunkDetachPlainFieldDispatch(t *testing.T) { + c := &plainDetachControl{fakeChunkControl: &fakeChunkControl{detach: ChunkDetachResponse{VolumeID: "v1"}}} + s := chunkServer(t, c, true) + for _, body := range []string{`{"volumeID":"v1"}`, `{"volumeID":"v1","plain":false}`} { + w := serve(t, s, http.MethodPost, "/chunk/detach", body, "") + if w.Code != 200 || c.plainCalls != 0 { + t.Fatalf("ordinary request changed: %d %s plain=%d", w.Code, w.Body, c.plainCalls) + } + } + w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + if w.Code != 200 || c.plainCalls != 1 { + t.Fatalf("plain request not dispatched: %d %s plain=%d", w.Code, w.Body, c.plainCalls) + } +} + +type plainDetachProvider struct { + *fakeChunkProvider + plainCalls int + err error +} + +func (p *plainDetachProvider) DetachVolumePlain(ctx context.Context, id string) (storage.ChunkCutResult, uint64, error) { + p.plainCalls++ + if p.err != nil { + return storage.ChunkCutResult{}, 0, p.err + } + return p.DetachVolume(ctx, id) +} +func TestChunkDetachPlainAdapterAndBusyResponse(t *testing.T) { + p := &plainDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 9, Head: storage.ChunkHead{Gen: 3, Epoch: 2, State: storage.ChunkHeadDetached}}, last: 9}} + s := chunkServer(t, NewChunkControl(p, nil), true) + w := serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + if w.Code != 200 || p.plainCalls != 1 { + t.Fatalf("plain adapter: %d %s calls=%d", w.Code, w.Body, p.plainCalls) + } + p.err = errors.Join(durable.ErrPlainDetachBusy, errors.New("held I/O")) + w = serve(t, s, http.MethodPost, "/chunk/detach", `{"volumeID":"v1","plain":true}`, "") + if w.Code != 409 { + t.Fatalf("busy status: %d %s", w.Code, w.Body) + } + var body struct { + Code string `json:"code"` + Retryable bool `json:"retryable"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Code != "plain_detach_busy" || !body.Retryable { + t.Fatalf("busy classification: %s %v", w.Body, err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index cdd34e146d..935e1b5a53 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -206,6 +206,8 @@ A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. Th stateDiagram-v2 [*] --> Admit Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid + Admit --> PlainStop: plain detach and idle frontend lock acquired + PlainStop --> Quiesce: frontend stopped; ordinary detached cut Admit --> Stage: budget admitted, earlier unknown CAS settled Stage --> Quiesce: spill-budget remainder reached or no shrink Quiesce --> FinalFreeze: opt-in measured tail fits after bounded admission drain @@ -235,7 +237,9 @@ stateDiagram-v2 | Admit | optional Budget admitted before staging/barrier; not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease) | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-WS-LEASE-001` | | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | -| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | +| Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | +| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | diff --git a/seaweed-block/docs/spec/PlainDetach.tla b/seaweed-block/docs/spec/PlainDetach.tla new file mode 100644 index 0000000000..0bd3733bb2 --- /dev/null +++ b/seaweed-block/docs/spec/PlainDetach.tla @@ -0,0 +1,19 @@ +----------------------------- MODULE PlainDetach ----------------------------- +\* Idle-gated admission only. HEAD CAS, authority, physical I/O and timing +\* remain the existing detach/cut obligations, outside this abstraction. +EXTENDS Naturals, TLC +CONSTANT IdleGuard +VARIABLES phase, readers +vars == <> +Init == /\ phase = "serving" /\ readers = 0 +BeginIO == /\ phase = "serving" /\ readers < 2 + /\ readers' = readers + 1 /\ UNCHANGED phase +EndIO == /\ readers > 0 /\ readers' = readers - 1 /\ UNCHANGED phase +Plain == /\ phase = "serving" /\ (~IdleGuard \/ readers = 0) + /\ phase' = "stopped" /\ UNCHANGED readers +Publish == /\ phase = "stopped" /\ phase' = "detached" /\ UNCHANGED readers +Abort == /\ phase = "stopped" /\ phase' = "serving" /\ UNCHANGED readers +Next == BeginIO \/ EndIO \/ Plain \/ Publish \/ Abort +Spec == Init /\ [][Next]_vars +IdleAtStop == phase \in {"stopped", "detached"} => readers = 0 +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 7b0862480e..bfe79c4383 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -334,3 +334,21 @@ one missing-probe/newer-ACK schedule. `R293_review_safe` checks four invariants; four negative controls separately remove retirement, the frame join, the readiness guard or ACK progress restoration. This abstracts successful admitted frames and does not prove physical-I/O, authority rollback or timing behavior. + + +## Plain detach admission + +`PlainDetach.tla` models the explicit plain-detach idle gate and atomic closure +of frontend admission, with up to two I/O readers. `IdleAtStop` checks that +stopping or detached states have no admitted/entering reader. HEAD publication, +authority, physical I/O, wall-clock bounds, and failure settlement are outside +this small admission abstraction and retain their existing native controls. + +Local run 2026-11-21 00:00 UTC, tools distribution v1.7.4 (TLC 2.19), jar SHA-256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`. +From `docs/spec`, SANY `PlainDetach.tla` exited 0; TLC with +`-deadlock -config cfg/PlainDetach.cfg PlainDetach` exited 0 (8 generated, +5 distinct, queue empty, depth 3). Replacing the config with +`cfg/PlainDetach_no_idle.cfg` exited 12: `IdleAtStop` fails on +BeginIO -> Plain (7 generated / 5 distinct, depth 3). The negative uses a +distinct `-metadir` to avoid timestamp-directory collisions between short runs. diff --git a/seaweed-block/docs/spec/cfg/PlainDetach.cfg b/seaweed-block/docs/spec/cfg/PlainDetach.cfg new file mode 100644 index 0000000000..71ab7aaaa2 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PlainDetach.cfg @@ -0,0 +1,3 @@ +CONSTANT IdleGuard = TRUE +SPECIFICATION Spec +INVARIANT IdleAtStop diff --git a/seaweed-block/docs/spec/cfg/PlainDetach_no_idle.cfg b/seaweed-block/docs/spec/cfg/PlainDetach_no_idle.cfg new file mode 100644 index 0000000000..300b94071a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/PlainDetach_no_idle.cfg @@ -0,0 +1,3 @@ +CONSTANT IdleGuard = FALSE +SPECIFICATION Spec +INVARIANT IdleAtStop From ea38af0f9c4dd9f138c46686932e3f3fd34cd6f7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:04:25 -0800 Subject: [PATCH 2/3] test: isolate plain detach pre-copy bypass control --- .../durable/provider_plain_detach_test.go | 19 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go index 25760f74b5..37edd575bc 100644 --- a/seaweed-block/core/frontend/durable/provider_plain_detach_test.go +++ b/seaweed-block/core/frontend/durable/provider_plain_detach_test.go @@ -111,3 +111,22 @@ func TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend(t *testing.T) { t.Fatalf("plain retry changed result: %+v last=%d err=%v", again, last2, err) } } + +func TestPlainDetachSkipsPrecopyCostAdmission(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + p := precopyProvider(t, remote, &parkView{stubView: v1View()}) + openRecovered(t, p) + b, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Write(ctx, 4096, block(0x7c)); err != nil { + t.Fatal(err) + } + r, _, err := p.DetachVolumePlain(ctx, "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached || len(r.Precopy.Rounds) != 0 || !bytes.Equal(headBlock(t, remote, 1), block(0x7c)) { + t.Fatalf("plain request used pre-copy admission or lost its point: %+v %v", r, err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 935e1b5a53..4d7b0705b9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -238,7 +238,7 @@ stateDiagram-v2 | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | -| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | +| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy 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` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | From a28f2b73b5cb55193c14f291614c6b68abcf4360 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 16:13:44 -0800 Subject: [PATCH 3/3] docs: restore pre-copy transition and place plain detach invariant --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 4d7b0705b9..5775395d50 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -238,8 +238,7 @@ stateDiagram-v2 | Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | | Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001` | | Plain detach | explicit `plain=true` bypasses pre-copy cost admission only after exclusive frontend I/O admission succeeds immediately; busy requests change no frontend/pause/HEAD state. It then uses the ordinary StopIO, final cut and outcome settlement. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | -| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy 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` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | -| `INV-CUT-PRECOPY-001` | +| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` | | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | @@ -481,6 +480,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` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy 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` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | | `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first fitting attempt; earlier over-budget estimates must refuse), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | Controlled callers; measured latency is not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | | `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE |