diff --git a/seaweed-block/core/frontend/durable/export_chunk_test.go b/seaweed-block/core/frontend/durable/export_chunk_test.go index 93158f44c0..5ed81e34c5 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -36,3 +36,11 @@ func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).tes func SetTestBeforeAttachWait(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeReadReadyWait = f } + +func SetTestAfterGate(b frontend.Backend, f func()) { b.(*StorageBackend).testAfterGate = f } + +func StopFlipAt(b frontend.Backend) time.Time { return b.(*StorageBackend).StopFlipAt() } + +func StopIOForTest(ctx context.Context, b frontend.Backend, evidence string) error { + return b.(*StorageBackend).StopIO(ctx, evidence) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 118aaab786..52d74ab8e6 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -1121,16 +1121,17 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // the cut gets three quarters, the settlement what is left. The bound is // cooperative (contexts): a syscall that never returns is not bounded here. var start time.Time - // stopIOBegan is taken just before the operational flip (from then on new - // I/O is refused by contract), stopIOReturned when the admitted I/O has - // drained; both are logged so a measurement can tell a refusal after the - // flip from an admitted I/O that failed. + // stopIOBegan is the backend's flip (admission closed, under its mu: an + // I/O whose gate runs after it is refused; one gated before it is + // admitted even if it registers later), stopIOReturned when the admitted + // I/O has drained; both are logged so a measurement can tell a refusal + // after the flip from an admitted I/O that failed. var stopIOBegan, stopIOReturned time.Time defer func() { if !stopIOReturned.IsZero() { // Emit after the cut releases its barrier, using the actual times. if !stopIOBegan.IsZero() { - log.Printf("durable: volume=%s I/O stop began at %s", volumeID, stopIOBegan.UTC().Format(time.RFC3339Nano)) + log.Printf("durable: volume=%s admission closed at %s", volumeID, stopIOBegan.UTC().Format(time.RFC3339Nano)) } log.Printf("durable: volume=%s StopIO returned at %s", volumeID, stopIOReturned.UTC().Format(time.RFC3339Nano)) } @@ -1201,11 +1202,11 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla // Cancel/join the periodic owner before any final freeze, while serving. p.stopChunkLoop(h) r, err = owner.PrecopyDetachWithAdmission(hostlimit.WithClass(cutCtx, hostlimit.Urgent), h.backend.BeginPrecopyPause, func() bool { - began := time.Now() if !h.backend.TryStopIO("chunk pre-copy: final detached cut") { return false } - stopIOBegan, stopIOReturned = began, time.Now() + stopIOReturned = time.Now() + stopIOBegan = h.backend.StopFlipAt() h.chunkDetach = true beginFreeze() return true @@ -1246,7 +1247,6 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } } else { beginFreeze() - stopIOBegan = time.Now() if plain { if err := h.backend.stopPlainDetachIfIdle(); err != nil { return r, 0, err @@ -1268,6 +1268,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla } if err == nil { stopIOReturned = time.Now() + stopIOBegan = h.backend.StopFlipAt() } if err == nil { p.stopChunkLoop(h) diff --git a/seaweed-block/core/frontend/durable/stopio_began_log_test.go b/seaweed-block/core/frontend/durable/stopio_began_log_test.go index 74b74af80c..52f272fc34 100644 --- a/seaweed-block/core/frontend/durable/stopio_began_log_test.go +++ b/seaweed-block/core/frontend/durable/stopio_began_log_test.go @@ -2,18 +2,23 @@ package durable_test import ( "context" + "errors" "strings" + "sync" + "sync/atomic" "testing" "time" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" ) -// A detach logs when its I/O stop began (the operational flip, from which -// the backend refuses new I/O) as well as when StopIO returned, both with -// RFC 3339 nanoseconds, so a test measuring guest errors can tell a refusal -// by contract (after the flip) from an admitted I/O that failed. -func TestLiveDetachLogsWhenTheIOStopBegan(t *testing.T) { +// A detach logs when admission closed (the backend's operational flip, +// taken under its lock) as well as when StopIO returned, both with RFC 3339 +// nanoseconds, so a test measuring guest errors can tell a refusal by +// contract (after the flip) from an admitted I/O that failed. +func TestLiveDetachLogsWhenAdmissionClosed(t *testing.T) { p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), time.Hour) openRecovered(t, p) b, err := p.Open(context.Background(), "v1") @@ -50,9 +55,133 @@ func TestLiveDetachLogsWhenTheIOStopBegan(t *testing.T) { } return found[0] } - began := stamp("volume=v1 I/O stop began at ") + closed := stamp("volume=v1 admission closed at ") returned := stamp("volume=v1 StopIO returned at ") - if began.Before(started) || returned.Before(began) || ended.Before(returned) { - t.Fatalf("began %s, returned %s: want started %s <= began <= returned <= ended %s", began, returned, started, ended) + if closed.Before(started) || returned.Before(closed) || ended.Before(returned) { + t.Fatalf("closed %s, returned %s: want started %s <= closed <= returned <= ended %s", closed, returned, started, ended) + } + if got := durable.StopFlipAt(b); !got.Equal(closed) { + t.Fatalf("logged %s, backend flip %s: the log must carry the flip itself", closed, got) + } +} + +// The flip time is the admission cutoff: a write whose gate passed before +// the flip is admitted and completes (StopIO drains it), and a write whose +// gate runs after the flip is refused, so nothing is admitted after the +// logged boundary. +func TestStopFlipIsTheAdmissionCutoff(t *testing.T) { + p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), time.Hour) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + parkedA, releaseA := make(chan struct{}), make(chan struct{}) + parkedB, releaseB := make(chan struct{}), make(chan struct{}) + var onceA, onceB sync.Once + freeA := func() { onceA.Do(func() { close(releaseA) }) } + freeB := func() { onceB.Do(func() { close(releaseB) }) } + errA, errB, stopErr := make(chan error, 1), make(chan error, 1), make(chan error, 1) + var launched struct{ a, b, stop atomic.Bool } + // Registered before anything starts: every parked writer is released and + // every goroutine is joined within a bound, whatever the test hits. + t.Cleanup(func() { + freeA() + freeB() + cancel() + for name, c := range map[string]struct { + on *atomic.Bool + ch chan error + }{"write A": {&launched.a, errA}, "write B": {&launched.b, errB}, "StopIO": {&launched.stop, stopErr}} { + if !c.on.Load() { + continue + } + select { + case <-c.ch: + case <-time.After(5 * time.Second): + t.Errorf("%s did not return", name) + } + } + }) + + // Write A passes the gate, then parks (it registers after the flip and + // still completes: admission is the gate's decision). + var parkA, parkB atomic.Bool + parkA.Store(true) + durable.SetTestAfterGate(b, func() { + if parkA.CompareAndSwap(true, false) { + close(parkedA) + <-releaseA + } + }) + launched.a.Store(true) + go func() { _, err := b.Write(context.Background(), 0, block(0x10)); errA <- err }() + select { + case <-parkedA: + case <-time.After(5 * time.Second): + t.Fatal("write A never passed the gate") + } + // Write B parks before the gate. + parkB.Store(true) + durable.SetTestBeforeIOLock(b, func() { + if parkB.CompareAndSwap(true, false) { + close(parkedB) + <-releaseB + } + }) + launched.b.Store(true) + go func() { _, err := b.Write(context.Background(), 4096, block(0x20)); errB <- err }() + select { + case <-parkedB: + case <-time.After(5 * time.Second): + t.Fatal("write B never reached the gate") + } + + launched.stop.Store(true) + go func() { stopErr <- durable.StopIOForTest(ctx, b, "test stop") }() + deadline := time.Now().Add(5 * time.Second) + for durable.StopFlipAt(b).IsZero() { + if time.Now().After(deadline) { + t.Fatal("the stop never flipped") + } + time.Sleep(time.Millisecond) + } + // B now reaches its gate after the flip (it may first wait behind the + // drain for ioMu); A is admitted and still in flight, so StopIO waits. + freeB() + select { + case err := <-stopErr: + stopErr <- err + t.Fatalf("StopIO returned (%v) while admitted write A was still in flight", err) + case <-time.After(100 * time.Millisecond): + } + freeA() + select { + case err := <-errA: + errA <- err + if err != nil { + t.Fatalf("write A (gate before the flip): %v, want admitted and completed", err) + } + case <-time.After(5 * time.Second): + t.Fatal("write A never returned") + } + select { + case err := <-stopErr: + stopErr <- err + if err != nil { + t.Fatalf("StopIO: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("StopIO never returned after A completed") + } + select { + case err := <-errB: + errB <- err + if !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write B (gate after the flip): %v, want refused (ErrNotReady)", err) + } + case <-time.After(5 * time.Second): + t.Fatal("write B never returned") } } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index a7641ecd08..98c7023841 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -148,7 +148,15 @@ const maxFullBlockBatchBlocks = 64 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() + testBeforeIOLock func() + // testAfterGate, test-only, runs in admit after the gate passed and + // before the I/O registers under mu. + testAfterGate func() + // stopFlipAt is when admission last closed for a stop, taken under mu + // just after operational went false; guarded by mu. An I/O whose gate + // saw operational before it was admitted (and StopIO drains it); every + // gate after it refuses. + stopFlipAt time.Time testPrecopyQueued func() // after FIFO registration, outside mu testPrecopyGranted func(*precopyWaiter) // FIFO grant under mu; nonblocking test hook testPrecopyStopFallback func() // before fallback lock attempts, outside mu @@ -482,8 +490,12 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { // The caller owns mu; publication never calls the store or waits for I/O. func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) { + flipped := !ok && b.operational.Load() b.opEvidence.Store(evidence) b.operational.Store(ok) + if flipped { + b.stopFlipAt = time.Now() // after the store: no gate after this instant admits + } b.waitAttachReady = false // A host drain closes storage admission, but is not the old path's // teardown. Keep a final pre-copy queue parked until Close or its budget; @@ -512,6 +524,7 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { } b.opEvidence.Store(evidence) b.operational.Store(false) + b.stopFlipAt = time.Now() b.waitAttachReady = false b.notifyReadReadyLocked() return true @@ -539,6 +552,7 @@ func (b *StorageBackend) TryStopIO(evidence string) bool { b.precopy = p b.opEvidence.Store(evidence) b.operational.Store(false) + b.stopFlipAt = time.Now() b.waitAttachReady = false b.notifyReadReadyLocked() return true @@ -561,6 +575,13 @@ func (b *StorageBackend) stopPlainDetachIfIdle() error { return nil } +// StopFlipAt is when admission last closed for a stop (zero if never). +func (b *StorageBackend) StopFlipAt() time.Time { + b.mu.Lock() + defer b.mu.Unlock() + return b.stopFlipAt +} + // 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 @@ -823,6 +844,9 @@ func (b *StorageBackend) admit() (func(), error) { b.ioMu.RUnlock() return nil, err } + if hook := b.testAfterGate; hook != nil { + hook() + } b.mu.Lock() if b.precopy != nil && b.precopy.active { b.mu.Unlock() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7847a9c0a8..b614f246eb 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -249,6 +249,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`, `INV-CUT-READ-LOGICAL-001` | | Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` | +| `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 | | Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `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 | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | @@ -403,7 +404,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -185 rows: 163 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 170 new. +186 rows: 164 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 171 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.