diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index de94be8d33..52a6e6ffaf 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -979,6 +979,9 @@ func (p *DurableProvider) openExisting(volumeID, path string, impl ImplName) (*v // Defer before Recover can publish a completed BASE away. if impl == ImplWALStoreChunk { ws.DeferBaseRetirementV3() + // Before Recover: a replayed write reaches the extent only + // after the chunk layer attaches, so it is marked local. + ws.HoldExtentDrainUntilChunkLayer() } if p.cfg.WALRetentionLSNs > 0 { ws.SetRecoveryRetentionLSNs(p.cfg.WALRetentionLSNs) @@ -1039,6 +1042,9 @@ func (p *DurableProvider) createFresh(volumeID, path string, impl ImplName) (*vo // Defer before Recover can publish a completed BASE away. if impl == ImplWALStoreChunk { ws.DeferBaseRetirementV3() + // Before Recover: a replayed write reaches the extent only + // after the chunk layer attaches, so it is marked local. + ws.HoldExtentDrainUntilChunkLayer() } if p.cfg.WALRetentionLSNs > 0 { ws.SetRecoveryRetentionLSNs(p.cfg.WALRetentionLSNs) diff --git a/seaweed-block/core/storage/base_install_v3.go b/seaweed-block/core/storage/base_install_v3.go index 0bf6e6855d..9740d542fb 100644 --- a/seaweed-block/core/storage/base_install_v3.go +++ b/seaweed-block/core/storage/base_install_v3.go @@ -265,6 +265,12 @@ func (s *WALStore) beginBaseInstallV3(baseLSN uint64, id [16]byte) (*installHand // the section 8.1 begin; a v2 store keeps its pre-seam behaviour behind the // legacy handle (it had no begin step). func (s *WALStore) BeginBaseInstall(baseLSN uint64, installID [16]byte) (InstallHandle, error) { + // A store awaiting its chunk layer takes no BASE: a BASE writes the + // extent and its install drains through the held flusher. (A chunk + // store takes no replication, the only BASE source.) + if s.drainHeld.Load() { + return nil, ErrDrainHeldForChunkLayer + } if s.v3 == nil { return NewLegacyInstallHandle(s, baseLSN), nil } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 37b5822ea1..1a5b7b2365 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -303,6 +303,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, err } + // Every later drain reaches OnExtentWrite: release a held drain. + s.drainHeld.Store(false) + if s.flusher != nil { + s.flusher.Notify() + } return l, nil } diff --git a/seaweed-block/core/storage/chunk_replay_before_attach_test.go b/seaweed-block/core/storage/chunk_replay_before_attach_test.go index 6480b75426..afd33b752d 100644 --- a/seaweed-block/core/storage/chunk_replay_before_attach_test.go +++ b/seaweed-block/core/storage/chunk_replay_before_attach_test.go @@ -2,6 +2,12 @@ package storage import ( "bytes" + "errors" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "strings" "testing" ) @@ -65,3 +71,110 @@ func TestReplayedWriteIsNotDrainedBeforeTheChunkLayerAttaches(t *testing.T) { t.Fatalf("after the drain LBA 9 = %#x (err %v); want the synced write %#x", got[0], err, newer[0]) } } + +// The final flush of a stop is held too: a clean Close before the chunk +// layer attaches leaves the replayed write in the WAL, so the next open +// replays it again and it reads back after attach. +func TestAStopBeforeAttachDrainsNothing(t *testing.T) { + s, path, crash := crashableStore(t) + f := newFakeChunkRemote() + cfg := ctConfig(1) + layer := mustAttach(t, s, f, cfg) + if _, err := s.Write(9, makeBlock(ctBlockSize, 0x89)); err != nil { + t.Fatal(err) + } + mustSyncFlush(t, s) + if _, err := layer.Capture(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if err := layer.EvictChunk(2); err != nil { + t.Fatal(err) + } + newer := makeBlock(ctBlockSize, 0xE9) + if _, err := s.Write(9, newer); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crash() + + reopenHeld := func() *WALStore { + t.Helper() + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.HoldExtentDrainUntilChunkLayer() + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + return r + } + first := reopenHeld() + if err := first.Close(); err != nil { // the flusher's stop flush runs here + t.Fatal(err) + } + second := reopenHeld() + t.Cleanup(func() { closeBounded(t, second) }) + second.DisableAutoFlushForRecoveryTest() + mustAttach(t, second, f, cfg) + if got, err := second.Read(9); err != nil || !bytes.Equal(got, newer) { + t.Fatalf("after a stop before attach and a reopen, LBA 9 = %#x (err %v); want %#x", got[0], err, newer[0]) + } +} + +// A store whose drain is held takes no BASE (a BASE writes the extent). +func TestABaseInstallIsRefusedWhileTheDrainIsHeld(t *testing.T) { + s, _, _ := crashableStore(t) + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.BeginBaseInstall(1, [16]byte{1}); !errors.Is(err, ErrDrainHeldForChunkLayer) { + t.Fatalf("BeginBaseInstall while held: %v; want ErrDrainHeldForChunkLayer", err) + } +} + +// Every path that writes the extent is listed with how it keeps a block +// written before the chunk layer attaches local: the flusher's drain (held +// until attach), a BASE (refused while held) and a fetched block (only an +// attached layer fetches). A new writer fails here until it is classified. +func TestExtentWritersAreEnumerated(t *testing.T) { + want := map[string]string{ + "writeExtentIfCurrent": "the flusher's drain; held until attach (flushOnceInternal)", + "WriteBase": "BASE install; refused while held (BeginBaseInstall)", + "installFetchedBlock": "a fetched block; only an attached chunk layer fetches", + } + fset := token.NewFileSet() + pkgs, err := parser.ParseDir(fset, ".", func(fi fs.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") }, 0) + if err != nil { + t.Fatal(err) + } + got := map[string]bool{} + for _, pkg := range pkgs { + for _, file := range pkg.Files { + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + if call, ok := n.(*ast.CallExpr); ok { + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "writeExtentUnlocked" { + got[fn.Name.Name] = true + } + } + return true + }) + } + } + } + for name := range got { + if _, ok := want[name]; !ok { + t.Errorf("%s writes the extent and is not classified: a block it writes before the chunk layer attaches must be held or marked local", name) + } + } + for name, why := range want { + if !got[name] { + t.Errorf("listed extent writer %s (%s) no longer calls writeExtentUnlocked; update the list", name, why) + } + } +} diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 9ea96f526c..432ae40171 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -159,6 +159,14 @@ func (f *flusher) flushOnceAllowClosed() error { func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { cycleStart := time.Now() store := f.store + // A store opened for chunk use drains nothing before its chunk layer + // attaches: the dirty blocks stay in the WAL (replayed again after a + // crash) and are served from the dirty map; the first drain after + // attach marks them local (OnExtentWrite). This includes the final + // flush of a stop. + if store.drainHeld.Load() { + return nil + } if err := store.stickyIOFault(); err != nil { return err // no checkpoint advance after a failed fsync } diff --git a/seaweed-block/core/storage/layout_fresh_mutators_test.go b/seaweed-block/core/storage/layout_fresh_mutators_test.go index 1d2c81a199..ede2316f21 100644 --- a/seaweed-block/core/storage/layout_fresh_mutators_test.go +++ b/seaweed-block/core/storage/layout_fresh_mutators_test.go @@ -25,12 +25,12 @@ var walStoreMethods = map[string]string{ "AdvanceWALTail": "replication", "FormatV3": "base", "Recover": "recovery", "SetLayoutIdentity": "control", "SetWMode": "control", "SetMultiBlockRecords": "control", "SetRecoveryRetentionLSNs": "control", - "SetRecycleFloorSource": "control", "AllowBaseRetirementV3": "control", "DeferBaseRetirementV3": "control", + "SetRecycleFloorSource": "control", "AllowBaseRetirementV3": "control", "DeferBaseRetirementV3": "control", "HoldExtentDrainUntilChunkLayer": "control (holds the extent drain until the chunk layer attaches)", "DisableAutoFlushForRecoveryTest": "test control", "ResetFlusherForMeasurement": "test control", "Sync": "control", "Close": "control", "AllBlocks": "read", "AppliedLSNs": "read", "CanSeedChunkFrontier": "read (the seed precondition, no write)", "BlockSize": "read", "StoreID": "read (the superblock UUID)", "ChunkBlocks": "read (immutable local map shape)", "Boundaries": "read", "CheckpointLSN": "read", "CheckpointLSNForPOC": "read", "CheckpointPersistence": "read", "ChunkMapStatsV3": "read", "DataSyncPolicy": "read", - "DurabilityLatency": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", + "DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", "InstalledBaseLSN": "read", "LayoutIdentity": "read", "NextLSN": "read", "NumBlocks": "read", "OwnerChunkAttachDurableV3": "read", "Read": "read", "ReadContext": "read", "RecoveryMode": "read", "RecoveryRetentionLSNs": "read", "RecoveryWarnings": "read", "ScanLBAs": "read", "WALCapacityBytes": "read", diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 231011552d..0b0276c795 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -92,6 +92,9 @@ type WALStore struct { // chunk is the attached chunk layer's hooks; nil when none. chunk atomic.Pointer[chunkHooks] + // drainHeld (HoldExtentDrainUntilChunkLayer): the flusher drains no + // dirty block to the extent until a chunk layer is attached. + drainHeld atomic.Bool extentMu [64]sync.RWMutex closed bool nextLSN uint64 // next LSN to assign to a write @@ -705,7 +708,14 @@ func (s *WALStore) DisableAutoFlushForRecoveryTest() { // until a chunk layer is attached. A block drained earlier would not be // marked local, and a later fetch of its absent chunk would install the // remote block over the acknowledged write. -func (s *WALStore) HoldExtentDrainUntilChunkLayer() {} +func (s *WALStore) HoldExtentDrainUntilChunkLayer() { s.drainHeld.Store(true) } + +// ErrDrainHeldForChunkLayer: the store's extent drain waits for its chunk +// layer, so no path that writes the extent may start. +var ErrDrainHeldForChunkLayer = errors.New("storage: the extent drain is held until the chunk layer attaches") + +// ExtentDrainHeld reports whether the extent drain waits for a chunk layer. +func (s *WALStore) ExtentDrainHeld() bool { return s.drainHeld.Load() } func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) { return s.readFromExtentContext(context.Background(), lba) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e1308a0487..5bd56be9f7 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -320,7 +320,7 @@ stateDiagram-v2 | Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-SNAPK-HEAD-WRITE-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 | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and an unresolved cut session remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead` | `INV-SNAPK-HEAD-WRITE-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` | +| 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; a block that reached the extent while its chunk was absent is already local (a chunk store drains nothing before its chunk layer attaches) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/flusher.go` `flushOnceInternal` | `INV-CUT-READMISS-001`, `INV-CHUNK-LOCAL-BEFORE-FETCH-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | | Holder | (background hydrate) | an independent restore's walker fills every HEAD-named absent chunk through the same shared fill flights (never a second fetch, never over a local write); it yields while any flight has guest waiters, takes one host fill permit per flight (no cut payload, class `BackgroundFill` from the caller) and the permit is released only when that flight's I/O is over, also when the walker returns early on cancel, revocation or close | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked` | `INV-RESTORE-HYDRATE-001`, `INV-CUT-READMISS-001` | @@ -907,6 +907,7 @@ Notes: | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | | `INV-CUT-HYDRATION-PROGRESS-001` | The status reports per volume the HEAD-named chunks still to hydrate (`AbsentChunks`) and the chunks hydrated so far (`Hydration.Completed`, cumulative); a read of an un-hydrated chunk moves both by one, a repeat read neither. Observation only. | M5 hydration (reader; no transition) | `core/storage/chunk_layer.go` `Stats` (`absentHydratable`); `core/storage/chunk_hydration.go` `hydrationWorker` | `TestHydrationProgressCountersFollowFirstReads` (`core/frontend/durable/hydration_progress_test.go`) | — | ACTIVE | | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is 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. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch) | — | ACTIVE | +| `INV-CHUNK-LOCAL-BEFORE-FETCH-001` | A block that reaches the extent while its chunk is absent is local to the chunk layer before any fetch can install over it: a store opened for chunk use drains nothing to the extent and takes no BASE until its chunk layer attaches. | M4 Holder (lazy restore) | `core/frontend/durable/provider.go` (open and create of `walstore-chunk`, before Recover); `core/storage/walstore.go` `HoldExtentDrainUntilChunkLayer`; `core/storage/flusher.go` `flushOnceInternal` (every drain, the stop's included); `core/storage/base_install_v3.go` `BeginBaseInstall`; `core/storage/chunk_layer.go` `attachChunkLayerImpl` (releases the hold) | `TestReplayedWriteIsNotDrainedBeforeTheChunkLayerAttaches`, `TestAStopBeforeAttachDrainsNothing`, `TestABaseInstallIsRefusedWhileTheDrainIsHeld`, `TestExtentWritersAreEnumerated` (`core/storage/chunk_replay_before_attach_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime`, `TestCutPolicy_StaggerPreservesExplicitTimerReset` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff or minimum spacing; it retries after a random delay under 200 ms that shrinks with lateness, and status reports the wait until any later cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestNewSlotDelay_ShrinksWithLateness`, `TestCutPolicy_OneSlotWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |