From d6bf9aa03a0b508c7ccbc72018b8c066bb4ac27f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 23:22:57 -0800 Subject: [PATCH 1/9] storage: the WAL flusher reclaims in bounded cycles A flusher cycle drained the whole dirty map before one fsync and one checkpoint, so on a slow disk no WAL byte was freed until the cycle ended and a write waiting for space timed out while reclaim was running. A cycle now takes the LSN prefix of the synced entries that fits in a sixteenth of the WAL, cut at a record boundary (a native batch's blocks stay together), and checkpoints at its last LSN; the run loop starts the next cycle at once while entries remain. A pass position moves each cycle past the previous batch, so a checkpoint held below a batch does not repeat it, and it is trusted only within one recovery lifetime. A full drain runs cycles until its first frontier is drained. The durable status's checkpoint persistence gains the reclaim counters (ReclaimedBytes, BoundedCycles, FlusherPhase, CycleStarted, CycleExtentBytes, LastExtentWrite), and WALStore.ReclaimProgress reads them without a store lock for a write's hold path. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/checkpoint_diagnostics.go | 59 +++- .../storage/checkpoint_diagnostics_test.go | 7 +- seaweed-block/core/storage/flusher.go | 173 ++++++++-- .../core/storage/flusher_instrumentation.go | 43 +++ .../storage/layout_fresh_mutators_test.go | 2 +- .../storage/walstore_bounded_flush_v3_test.go | 320 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 3 +- seaweed-block/docs/releases/v1.1.md | 5 + seaweed-block/docs/status-schema.md | 6 + 9 files changed, 582 insertions(+), 36 deletions(-) create mode 100644 seaweed-block/core/storage/walstore_bounded_flush_v3_test.go diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 468fa39d48..1e58d433cf 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -14,13 +14,49 @@ import ( // this open), so a starved checkpoint shows Successes rising while // LastAdvance stays frozen. Fields are cumulative atomic observations, not a // coherent frontier. +// +// The reclaim fields tell slow reclaim from none: a write waiting for WAL +// space sees progress when the checkpoint advances (Advances, LastAdvance, +// ReclaimedBytes) or the cycle in progress writes extent bytes +// (CycleExtentBytes, LastExtentWrite); FlusherPhase says what the flusher is +// doing or waits on. type CheckpointPersistenceStatus struct { - Successes uint64 // checkpoint calls that succeeded (including unchanged ones) - Refusals uint64 // checkpoint calls refused because the map coverage was stale - Failures uint64 // checkpoint calls that failed with an error - CheckpointLSN uint64 // the persisted checkpoint LSN - Advances uint64 // successes that moved CheckpointLSN forward - LastAdvance time.Time // when the latest advance happened; zero if none in this open + Successes uint64 // checkpoint calls that succeeded (including unchanged ones) + Refusals uint64 // checkpoint calls refused because the map coverage was stale + Failures uint64 // checkpoint calls that failed with an error + CheckpointLSN uint64 // the persisted checkpoint LSN + Advances uint64 // successes that moved CheckpointLSN forward + LastAdvance time.Time // when the latest advance happened; zero if none in this open + ReclaimedBytes uint64 // WAL bytes the checkpoint advances released in this open + BoundedCycles uint64 // flusher cycles that stopped at the batch bound (a sixteenth of the WAL) with entries left for the next + FlusherPhase string // idle, drain_held (before the chunk layer attaches), wal_sync (every dirty entry above the synced WAL), writing, extent_sync or checkpoint + CycleStarted time.Time // when the flusher cycle in progress started; zero when none is + CycleExtentBytes uint64 // extent bytes the cycle in progress (or the latest) has written + LastExtentWrite time.Time // when the flusher last wrote extent bytes; zero if never in this open +} + +// ReclaimProgress is the flusher's reclaim progress for a write waiting for +// WAL space. It reads atomics only, never a store lock, so it answers while a +// cycle or a publication holds one. A waiter sees progress when ReclaimedBytes +// or ExtentBytes moves. +type ReclaimProgress struct { + ReclaimedBytes uint64 // WAL bytes made reusable in this open: the moves of the same-nonce reuse floor (the lower of both descriptor slots' retained tails) at the flusher's checkpoints + Advances uint64 // checkpoint advances in this open + ExtentBytes uint64 // extent bytes the flusher wrote in this open + Phase string // the flusher's phase (CheckpointPersistenceStatus.FlusherPhase) +} + +func (s *WALStore) ReclaimProgress() ReclaimProgress { + if s.flusher == nil { + return ReclaimProgress{Phase: flusherPhaseNames[flusherIdle]} + } + i := &s.flusher.instr + return ReclaimProgress{ + ReclaimedBytes: i.reclaimedBytes.Load(), + Advances: i.checkpointAdvances.Load(), + ExtentBytes: i.extentWriteBytes.Load(), + Phase: i.phaseName(), + } } func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { @@ -34,10 +70,21 @@ func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { Failures: i.checkpointFailures.Load(), CheckpointLSN: s.CheckpointLSN(), Advances: i.checkpointAdvances.Load(), + + ReclaimedBytes: i.reclaimedBytes.Load(), + BoundedCycles: i.boundedCycles.Load(), + FlusherPhase: i.phaseName(), + CycleExtentBytes: i.cycleExtentBytes.Load(), } if ns := i.checkpointLastAdvanceNanos.Load(); ns != 0 { st.LastAdvance = time.Unix(0, ns) } + if ns := i.cycleStartNanos.Load(); ns != 0 { + st.CycleStarted = time.Unix(0, ns) + } + if ns := i.lastExtentWriteNanos.Load(); ns != 0 { + st.LastExtentWrite = time.Unix(0, ns) + } return st } diff --git a/seaweed-block/core/storage/checkpoint_diagnostics_test.go b/seaweed-block/core/storage/checkpoint_diagnostics_test.go index 9bd7a10bd7..83fb99b535 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics_test.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics_test.go @@ -56,7 +56,9 @@ func TestCheckpointDiagnostics_RefusalThenSuccess(t *testing.T) { if err := json.Unmarshal(raw, &counts); err != nil { t.Fatal(err) } - if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != 1 || s.CheckpointLSN() != 2 || s.dm.len() != 0 { + // The drain runs bounded cycles (a sixteenth of this small WAL is one + // block): one checkpoint success per cycle, each bounded cycle but the last. + if counts["CheckpointRefusals"] != 1 || counts["CheckpointSuccesses"] != s.CheckpointPersistence().BoundedCycles+1 || s.CheckpointLSN() != 2 || s.dm.len() != 0 { t.Fatalf("retry counters/state: %s cp=%d", raw, s.CheckpointLSN()) } } @@ -163,7 +165,8 @@ func TestCheckpointDiagnostics_StarvedCheckpointIsVisible(t *testing.T) { t.Fatal(err) } moved := s.CheckpointPersistence() - if moved.CheckpointLSN != s.CheckpointLSN() || moved.CheckpointLSN <= 1 || moved.Advances != 2 || !moved.LastAdvance.After(first.LastAdvance) { + // One advance per cycle of the drain (bounded cycles on this small WAL). + if moved.CheckpointLSN != s.CheckpointLSN() || moved.CheckpointLSN <= 1 || moved.Advances != first.Advances+1+moved.BoundedCycles-starved.BoundedCycles || !moved.LastAdvance.After(first.LastAdvance) { t.Fatalf("after sync the checkpoint advance was not recorded: %+v", moved) } } diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index ca5e4c0896..aa3a87734a 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -2,6 +2,7 @@ package storage import ( "fmt" + "math" "sort" "sync" "sync/atomic" @@ -31,14 +32,19 @@ import ( // matches what we flushed. A concurrent Write() that bumped // the entry's LSN must NOT have its newer data lost. // -// Note: V2 has no batch-size cutoff. The flusher processes the -// whole snapshot in one cycle. This was a deliberate V2 choice -// (perf-acceptable; correctness simpler). An earlier draft of -// this file added a `maxBatch` truncation; that truncation -// silently broke the checkpoint invariant — if the truncated -// portion contained entries with smaller LSNs, the checkpoint -// could advance past unflushed older records and recovery would -// later skip them. Removed. +// A cycle is bounded: it takes the LSN prefix of the synced entries whose +// data fits in a sixteenth of the WAL (boundCycleBatch), cut only at a record +// boundary (a native batch's blocks stay together), and the run loop starts +// the next cycle at once while entries remain. On a slow disk the checkpoint, and so the WAL space, then moves +// every bounded cycle instead of once per whole-map cycle (a guest write +// waiting for space sees reclaim progress). The prefix is what keeps the +// checkpoint invariant: checkpoint L means every record with LSN <= L is in +// the extent or superseded by a record of the same LBA with LSN > L, still in +// the WAL because L is below it. An earlier `maxBatch` truncation in an +// arbitrary order broke exactly that (it could leave an older record behind +// a newer checkpoint) and was removed; the synced-frontier filter below was +// already such a prefix. A full drain (flushOnce, the final flush of a stop) +// runs bounded cycles until its first frontier is drained. type flusher struct { store *WALStore // the local data process this flusher serves interval time.Duration // upper bound on flush latency @@ -62,6 +68,36 @@ type flusher struct { afterExtentSyncForTest func() // Pauses after checkpoint/reuse publication, before the outer DM cleanup. afterCheckpointForTest func() + // Runs before each extent write of a cycle (a slow disk). Tests only. + beforeExtentWriteForTest func() + + pass flushPass // the run loop's pass position; owned by the run loop +} + +// flushPass is where a cycle starts within a pass over the dirty entries: +// entries with LSN in (after, limit]. A pass writes every entry once, in +// bounded cycles, even when the checkpoint is held below them (a recycle +// floor, retention, a map): the next cycle starts after the previous +// batch's last LSN, not at the oldest dirty entry, so a held batch is not +// repeated. after is meaningful only within the recovery lifetime gen: a +// Recover may reuse LSNs, and a cycle that sees another lifetime starts the +// pass over (after = 0). +type flushPass struct { + after, gen, limit uint64 +} + +// flushCycleResult is what one bounded cycle leaves: frontier is the synced +// WAL frontier it drained toward, last the batch's highest LSN, gen its +// recovery lifetime, and more reports entries in (last, frontier] that the +// batch bound left for the next cycle. +type flushCycleResult struct { + frontier, last, gen uint64 + more bool +} + +// next is the pass position after this cycle. +func (r flushCycleResult) next(limit uint64) flushPass { + return flushPass{after: r.last, gen: r.gen, limit: limit} } type flusherConfig struct { @@ -121,11 +157,11 @@ func (f *flusher) runWithStartSignal(started chan<- struct{}) { f.stopErr = f.flushOnceAllowClosed() return case <-ticker.C: - if err := f.flushOnce(); err != nil { + if err := f.cycle(); err != nil { diagnostics.report(err, time.Now()) } case <-f.notifyCh: - if err := f.flushOnce(); err != nil { + if err := f.cycle(); err != nil { diagnostics.report(err, time.Now()) } } @@ -145,8 +181,24 @@ func (f *flusher) Stop() error { func (f *flusher) FlushCount() uint64 { return f.flushes.Load() } func (f *flusher) BytesFlushed() uint64 { return f.bytesOut.Load() } -// flushOnce performs one flush cycle. Returns nil if there was -// nothing to flush, or surfaces extent-write / fsync errors. +// cycle runs one bounded cycle for the run loop and, while entries at or +// below the synced frontier remain, wakes the loop for the next one at once; +// between cycles the loop still sees a stop. A pass that ends (or fails) +// starts the next one at the oldest dirty entry. +func (f *flusher) cycle() error { + r, err := f.flushCycle(false, f.pass) + f.pass = flushPass{limit: math.MaxUint64} + if err == nil && r.more { + f.pass = r.next(math.MaxUint64) + f.Notify() + } + return err +} + +// flushOnce drains every entry at or below the synced WAL frontier that its +// first cycle observes, in bounded cycles. Returns nil if there was nothing +// to flush, or surfaces extent-write / fsync errors. Entries appended during +// the drain stay for the run loop: a drain under a steady writer ends. // // Algorithm faithful to V2 weed/storage/blockvol/flusher.go // FlushOnce. See type doc for the full sequence and the rationale @@ -159,15 +211,51 @@ func (f *flusher) flushOnceAllowClosed() error { return f.flushOnceInternal(true) } -func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { +func (f *flusher) flushOnceInternal(allowClosed bool) error { + p := flushPass{limit: math.MaxUint64} + for { + r, err := f.flushCycle(allowClosed, p) + if err != nil || !r.more { + return err + } + p = r.next(r.frontier) + } +} + +// boundCycleBatch keeps the LSN prefix of entries whose data fits in budget +// bytes, cut only at a record boundary: a native batch is one WAL record +// whose blocks carry consecutive LSNs (one WALOffset), and every entry of the +// last kept record stays, so a record is never split; the first record is +// kept whole even when it alone is over budget, so a cycle always makes +// progress. more reports entries left for the next cycle. It reorders +// entries by LSN. +func boundCycleBatch(entries []snapshotEntry, budget uint64, blockSize uint32) (kept []snapshotEntry, more bool) { + if uint64(len(entries))*uint64(blockSize) <= budget { + return entries, false + } + sort.Slice(entries, func(i, j int) bool { return entries[i].LSN < entries[j].LSN }) + k := int(max(budget/uint64(blockSize), 1)) + cut, rec := entries[k-1].LSN, entries[k-1].WALOffset + for k < len(entries) && (entries[k].LSN <= cut || entries[k].WALOffset == rec) { + cut = max(cut, entries[k].LSN) + k++ + } + return entries[:k], k < len(entries) +} + +// flushCycle runs one bounded cycle over the entries of pass p: LSN above +// p.after (within its recovery lifetime) and at or below both the synced WAL +// frontier and p.limit. +func (f *flusher) flushCycle(allowClosed bool, p flushPass) (r flushCycleResult, err error) { + defer f.instr.endBusyPhase() cycleStart := time.Now() store := f.store if err := store.stickyIOFault(); err != nil { - return err // no checkpoint advance after a failed fsync + return r, err // no checkpoint advance after a failed fsync } if err := store.syncWALPressureV3(); err != nil { - return fmt.Errorf("flusher: pressure WAL sync: %w", err) + return r, fmt.Errorf("flusher: pressure WAL sync: %w", err) } if f.beforeSnapshotForTest != nil { @@ -176,7 +264,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { store.mu.RLock() if store.closed && !allowClosed { store.mu.RUnlock() - return nil + return r, nil } // A store opened for chunk use drains nothing before its chunk layer // attaches: the dirty blocks stay in the WAL (replayed again after a @@ -187,7 +275,8 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { // started before the hold and snapshots the recovered dirty map sees it. if store.drainHeld.Load() { store.mu.RUnlock() - return nil + f.instr.setPhase(flusherDrainHeld) + return r, nil } snapshotStart := time.Now() // Hold the publication lock across all shards: a later shard must not @@ -198,6 +287,11 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { var recoveryGen uint64 recoveryGen = store.v3.recoverGen.Load() + r.gen = recoveryGen + after := p.after + if p.gen != recoveryGen { + after = 0 // another recovery lifetime: LSNs may be reused, start the pass over + } entries := store.dm.snapshot() // Write-ahead (INV-WAL-V3-WRITE-AHEAD-001): only entries whose WAL @@ -208,18 +302,37 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { // synced entry is idle: no extent write and no fsync. synced := store.v3.wack.Load() store.mu.RUnlock() + r.frontier = min(synced, p.limit) + dirty := len(entries) kept := entries[:0] for _, e := range entries { - if e.LSN <= synced { + if e.LSN > after && e.LSN <= r.frontier { kept = append(kept, e) } } entries = kept if len(entries) == 0 { - - return store.refreshW() // the mode-C idle refresh (DESIGN 6.2) + if dirty > 0 && after == 0 && p.limit == math.MaxUint64 { + f.instr.setPhase(flusherWALSync) // every dirty entry is above the synced frontier + } else { + f.instr.setPhase(flusherIdle) + } + return r, store.refreshW() // the mode-C idle refresh (DESIGN 6.2) } + desc, floorBefore, floorOK := store.v3.pub.walSnapshotV3() + walSize := desc.WALSize + if walSize == 0 { + walSize = store.sb.WALSize + } + entries, r.more = boundCycleBatch(entries, walSize/16, store.sb.BlockSize) + if r.more { + f.instr.boundedCycles.Add(1) + } + for _, e := range entries { + r.last = max(r.last, e.LSN) + } + f.instr.setPhase(flusherWriting) if f.afterSnapshotForTest != nil { f.afterSnapshotForTest() } @@ -251,7 +364,10 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { for _, e := range entries { data, _, err := f.readDirtyRecordV3Cached(e, recordCache) if err != nil { - return err + return r, err + } + if f.beforeExtentWriteForTest != nil { + f.beforeExtentWriteForTest() } writeStart := time.Now() written, err := store.writeExtentIfCurrent(e.LBA, e.LSN, data) @@ -259,7 +375,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { f.instr.recordExtentWrite(len(data), time.Since(writeStart), err) } if err != nil { - return fmt.Errorf("flusher: write extent LBA %d: %w", e.LBA, err) + return r, fmt.Errorf("flusher: write extent LBA %d: %w", e.LBA, err) } if written { f.bytesOut.Add(uint64(len(data))) @@ -273,11 +389,12 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { } // Step 2: one fsync covers all extent writes in this batch // (and any other in-flight WAL writes since they share a file). + f.instr.setPhase(flusherExtentSync) syncStart := time.Now() syncErr := store.syncFile(nil, func() error { return store.syncExtentFile() }) f.instr.recordExtentSync(time.Since(syncStart), syncErr) if syncErr != nil { - return fmt.Errorf("flusher: fsync after extent writes: %w", syncErr) + return r, fmt.Errorf("flusher: fsync after extent writes: %w", syncErr) } if f.afterExtentSyncForTest != nil { @@ -293,13 +410,17 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { // The released tail is persisted with the checkpoint, before the // writer may reuse those bytes. var publishErr error + f.instr.setPhase(flusherCheckpoint) cpBefore := store.CheckpointLSN() publishErr = store.persistCheckpointV3(maxLSN, recoveryGen) f.instr.recordCheckpoint(publishErr, cpBefore, store.CheckpointLSN(), time.Now()) + if _, floorAfter, ok := store.v3.pub.walSnapshotV3(); ok && floorOK && floorAfter > floorBefore { + f.instr.reclaimedBytes.Add(floorAfter - floorBefore) + } if err := publishErr; err != nil { - return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err) + return r, fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err) } } @@ -321,7 +442,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { store.mu.Lock() if !store.v3.flushLifetimeValidV3(recoveryGen) { store.mu.Unlock() - return mapCoverageRefusal("recovery_lifetime_changed") + return r, mapCoverageRefusal("recovery_lifetime_changed") } checkpoint := store.checkpointLSN if checkpoint >= maxLSN && maxLSN+1 > store.walTail { @@ -339,7 +460,7 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { f.flushes.Add(1) - return store.refreshW() // the mode-C idle refresh (DESIGN 6.2) + return r, store.refreshW() // the mode-C idle refresh (DESIGN 6.2) } diff --git a/seaweed-block/core/storage/flusher_instrumentation.go b/seaweed-block/core/storage/flusher_instrumentation.go index 939da10058..2798c6a508 100644 --- a/seaweed-block/core/storage/flusher_instrumentation.go +++ b/seaweed-block/core/storage/flusher_instrumentation.go @@ -65,7 +65,26 @@ type FlusherInstrumentationStatus struct { CheckpointMetadataSyncNanos uint64 } +// The flusher's phase: what it is doing, or what it waits on. +const ( + flusherIdle int32 = iota // nothing to drain + flusherDrainHeld // a chunk-opened store drains nothing before its chunk layer attaches + flusherWALSync // every dirty entry is above the synced WAL frontier + flusherWriting // writing a cycle's entries to the extent + flusherExtentSync // the cycle's extent fsync + flusherCheckpoint // persisting the cycle's checkpoint +) + +var flusherPhaseNames = [...]string{"idle", "drain_held", "wal_sync", "writing", "extent_sync", "checkpoint"} + type flusherInstrumentation struct { + phase atomic.Int32 + reclaimedBytes atomic.Uint64 // WAL bytes released by checkpoint advances (the reuse floor's moves) + boundedCycles atomic.Uint64 // cycles that left entries at or below the frontier for the next + cycleStartNanos atomic.Int64 // the cycle in progress (0: none) + cycleExtentBytes atomic.Uint64 // extent bytes the cycle in progress wrote + lastExtentWriteNanos atomic.Int64 + checkpointSuccesses atomic.Uint64 checkpointRefusals atomic.Uint64 checkpointFailures atomic.Uint64 @@ -128,6 +147,8 @@ func (i *flusherInstrumentation) recordCycle( blockSize uint32, ) func(bool) { i.cyclesStarted.Add(1) + i.cycleExtentBytes.Store(0) + i.cycleStartNanos.Store(cycleStart.UnixNano()) i.snapshotEntries.Add(uint64(len(entries))) i.snapshotDurationNanos.Add(storageDurationNanos(snapshotDuration)) opportunityStart := time.Now() @@ -139,6 +160,7 @@ func (i *flusherInstrumentation) recordCycle( i.snapshotCoalescibleEntries.Add(opportunity.coalescibleEntries) updateAtomicMax(&i.snapshotMaxContiguousRunBlocks, opportunity.maxRun) return func(success bool) { + i.cycleStartNanos.Store(0) duration := storageDurationNanos(time.Since(cycleStart)) i.cycleDurationNanos.Add(duration) updateAtomicMax(&i.cycleMaxDurationNanos, duration) @@ -253,6 +275,27 @@ func (i *flusherInstrumentation) recordExtentWrite(bytes int, duration time.Dura return } i.extentWriteBytes.Add(value) + i.cycleExtentBytes.Add(value) + i.lastExtentWriteNanos.Store(time.Now().UnixNano()) +} + +func (i *flusherInstrumentation) setPhase(p int32) { i.phase.Store(p) } + +// endBusyPhase returns a cycle's busy phase to idle when the cycle ends; the +// waiting phases (drain held, WAL sync) stay until the next cycle. +func (i *flusherInstrumentation) endBusyPhase() { + for _, p := range []int32{flusherWriting, flusherExtentSync, flusherCheckpoint} { + if i.phase.CompareAndSwap(p, flusherIdle) { + return + } + } +} + +func (i *flusherInstrumentation) phaseName() string { + if p := i.phase.Load(); p >= 0 && int(p) < len(flusherPhaseNames) { + return flusherPhaseNames[p] + } + return "unknown" } func (i *flusherInstrumentation) recordExtentSync(duration time.Duration, err error) { diff --git a/seaweed-block/core/storage/layout_fresh_mutators_test.go b/seaweed-block/core/storage/layout_fresh_mutators_test.go index 267cf6ef92..6ad75639e3 100644 --- a/seaweed-block/core/storage/layout_fresh_mutators_test.go +++ b/seaweed-block/core/storage/layout_fresh_mutators_test.go @@ -35,7 +35,7 @@ var walStoreMethods = map[string]string{ "Coverage": "read (atomic local bitmap coverage and chunk position)", "AllBlocks": "read", "AppliedLSNs": "read", "CanSeedChunkFrontier": "read (the seed precondition, no write)", "BlockSize": "read", "StoreID": "read (the superblock UUID)", "ChunkBlocks": "read (immutable local map shape)", "ChunkStateMarker": "read (the descriptor's chunk-state marker)", "Boundaries": "read", "CheckpointLSN": "read", "CheckpointLSNForPOC": "read", "CheckpointPersistence": "read", "ChunkMapStatsV3": "read", "DataSyncPolicy": "read", - "DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", + "DurabilityLatency": "read", "ExtentDrainHeld": "read", "FlushCount": "read", "FlusherInstrumentation": "read", "HolesSuspected": "read", "ReclaimProgress": "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_bounded_flush_v3_test.go b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go new file mode 100644 index 0000000000..d7ef288045 --- /dev/null +++ b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go @@ -0,0 +1,320 @@ +package storage + +import ( + "bytes" + "errors" + "math" + "math/rand" + "path/filepath" + "testing" + "time" +) + +// A batch is an LSN prefix cut only at a record boundary: a native batch (one +// WAL record, consecutive LSNs) is never split, the first record is kept +// whole even over budget, and more reports what is left. +func TestBoundCycleBatchCutsOnlyAtARecordBoundary(t *testing.T) { + es := func(lsns ...uint64) []snapshotEntry { + out := make([]snapshotEntry, len(lsns)) + for i, l := range lsns { + out[i] = snapshotEntry{LBA: uint64(i), LSN: l, WALOffset: 4096 * l} + } + return out + } + batch := func(es []snapshotEntry, from, to uint64) []snapshotEntry { // LSNs from..to share one record + for i := range es { + if es[i].LSN >= from && es[i].LSN <= to { + es[i].WALOffset = 4096 * from + } + } + return es + } + lsns := func(es []snapshotEntry) []uint64 { + out := make([]uint64, len(es)) + for i, e := range es { + out[i] = e.LSN + } + return out + } + for _, tc := range []struct { + name string + in []snapshotEntry + blocks uint64 // the budget in blocks + want []uint64 + more bool + }{ + {"fits", es(3, 1, 2), 3, []uint64{3, 1, 2}, false}, + {"prefix by LSN, not by order", es(9, 1, 5, 2, 7), 2, []uint64{1, 2}, true}, + {"a multi-block record stays whole", es(4, 2, 2, 2, 1), 2, []uint64{1, 2, 2, 2}, true}, + {"a native batch (consecutive LSNs, one record) stays whole", batch(es(1, 2, 3, 4, 5), 1, 3), 2, []uint64{1, 2, 3}, true}, + {"the first LSN over budget is kept whole", es(6, 6, 6, 8), 1, []uint64{6, 6, 6}, true}, + {"the tail is one record", es(1, 2, 2), 2, []uint64{1, 2, 2}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + got, more := boundCycleBatch(tc.in, tc.blocks*4096, 4096) + if g := lsns(got); more != tc.more || len(g) != len(tc.want) { + t.Fatalf("got %v more=%v, want %v more=%v", g, more, tc.want, tc.more) + } + for i, l := range lsns(got) { + if l != tc.want[i] { + t.Fatalf("got %v, want %v", lsns(got), tc.want) + } + } + }) + } +} + +// One bounded cycle checkpoints at the batch's last LSN L while a newer +// record of an LBA whose older record is at or below L is still unflushed: a +// crash then replays the newer record, and every LBA of the batch reads back +// from the extent. +func TestWALStoreV3BoundedCheckpointReplaysANewerRecordAfterACrash(t *testing.T) { + const walSize = 256 * 1024 // a batch of 16 KiB: 4 blocks + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, walSize, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + // LSN 1: LBA 0 = A; LSNs 2..8: LBAs 1..7; LSN 9: LBA 0 = B. + if _, err := s.Write(0, blk(0xA)); err != nil { + t.Fatal(err) + } + for i := uint32(1); i <= 7; i++ { + if _, err := s.Write(i, blk(byte(i))); err != nil { + t.Fatal(err) + } + } + newest, err := s.Write(0, blk(0xB)) + if err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + r, err := s.flusher.flushCycle(false, flushPass{limit: math.MaxUint64}) + if err != nil { + t.Fatal(err) + } + cp := s.CheckpointLSN() + if !r.more || cp == 0 || cp >= newest { + t.Fatalf("one bounded cycle: more=%v checkpoint=%d, want entries left and a checkpoint below LBA 0's newer record %d", r.more, cp, newest) + } + if st := s.CheckpointPersistence(); st.BoundedCycles != 1 || st.ReclaimedBytes == 0 { + t.Fatalf("counters after one bounded cycle: %+v", st) + } + crashRecoveryHardeningStore(t, s) + re, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = re.Close() }) + re.DisableAutoFlushForRecoveryTest() + if _, err := re.Recover(); err != nil { + t.Fatal(err) + } + if got := re.CheckpointLSN(); got != cp { + t.Fatalf("recovered checkpoint %d, want %d", got, cp) + } + if got, err := re.Read(0); err != nil || !bytes.Equal(got, blk(0xB)) { + t.Fatalf("LBA 0 after the crash: err=%v, want the newer record's data (B)", err) + } + for i := uint32(1); i <= 7; i++ { + if got, err := re.Read(i); err != nil || !bytes.Equal(got, blk(byte(i))) { + t.Fatalf("LBA %d after the crash: err=%v", i, err) + } + } +} + +// A full drain (flushOnce) still drains every synced entry, in bounded +// cycles, however many batches they span. +func TestWALStoreV3FullDrainRunsBoundedCyclesToTheEnd(t *testing.T) { + const walSize = 256 * 1024 + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, walSize, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + var last uint64 + for i := uint32(0); i < 40; i++ { + if last, err = s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + st := s.CheckpointPersistence() + if st.CheckpointLSN != last || st.BoundedCycles < 9 || s.dm.len() != 0 || st.FlusherPhase != "idle" { + t.Fatalf("after a full drain of 40 blocks in 4-block batches: %+v dirty=%d, want checkpoint %d, at least 9 bounded cycles, none dirty, idle", st, s.dm.len(), last) + } +} + +// A chunk-opened store drains nothing before its chunk layer attaches, and +// the flusher's phase says so (not idle, not a stall in a cycle). +func TestWALStoreV3DrainHeldIsTheFlusherPhase(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 256*1024, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + s.HoldExtentDrainUntilChunkLayer() + if _, err := s.Write(3, blk(3)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if st := s.CheckpointPersistence(); st.FlusherPhase != "drain_held" || st.CheckpointLSN != 0 || st.ReclaimedBytes != 0 { + t.Fatalf("a held drain: %+v, want phase drain_held and nothing reclaimed", st) + } +} + +// A dense image written as single 4 KiB writes in random order, three +// WALs' worth, on a slow disk (every extent write takes 2 ms), with a 500 ms admission +// budget. A whole-map cycle (about 480 entries, about 1 s) frees nothing +// until it ends, so a write times out waiting for space; bounded cycles free +// space every sixteenth of the WAL, and no write times out while reclaim +// moves. The guest sees a slow disk, not errors. +func TestWALStoreV3SlowExtentKeepsReclaimMoving(t *testing.T) { + const walSize = 2 << 20 + const count = 3 * walSize / 4096 + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, count, 4096, walSize, WModeLagged, 64) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.admissionTimeout = 500 * time.Millisecond + s.flusher.beforeExtentWriteForTest = func() { time.Sleep(2 * time.Millisecond) } + lbas := rand.New(rand.NewSource(1)).Perm(count) + start := time.Now() + busy := 0 + var maxAttempt time.Duration + for n, lba := range lbas { + for { + a := time.Now() + _, err := s.Write(uint32(lba), blk(byte(lba+1))) + maxAttempt = max(maxAttempt, time.Since(a)) + if err == nil { + break + } + if !errors.Is(err, ErrWALPressureTimeout) || time.Since(start) > 2*time.Minute { + t.Fatalf("write %d lba=%d: %v", n, lba, err) + } + busy++ + t.Logf("busy write=%d lba=%d at %v: %+v", n, lba, time.Since(start), s.CheckpointPersistence()) + } + } + st := s.CheckpointPersistence() + t.Logf("writes=%d busy=%d maxAttempt=%v total=%v %+v", count, busy, maxAttempt, time.Since(start), st) + if busy != 0 { + t.Fatalf("%d writes timed out waiting for WAL space while reclaim moved (max attempt %v)", busy, maxAttempt) + } + if st.BoundedCycles == 0 || st.ReclaimedBytes < walSize { + t.Fatalf("reclaim counters: %+v", st) + } + for _, lba := range lbas { + if got, err := s.Read(uint32(lba)); err != nil || !bytes.Equal(got, blk(byte(lba+1))) { + t.Fatalf("readback %d: %v", lba, err) + } + } +} + +// ReclaimProgress answers while the store lock is held (a write's hold path +// reads it without waiting behind a cycle or a publication), and moves with +// a drain. +func TestWALStoreV3ReclaimProgressReadsNoStoreLock(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 256*1024, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 8; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + before := s.ReclaimProgress() + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + s.mu.Lock() + got := make(chan ReclaimProgress, 1) + go func() { got <- s.ReclaimProgress() }() + var after ReclaimProgress + select { + case after = <-got: + case <-time.After(2 * time.Second): + s.mu.Unlock() + t.Fatal("ReclaimProgress waited for the store lock") + } + s.mu.Unlock() + if after.ReclaimedBytes <= before.ReclaimedBytes || after.ExtentBytes < before.ExtentBytes+8*4096 || after.Advances < 2 || after.Phase != "idle" { + t.Fatalf("progress across a drain of 8 blocks in 4-block batches: before %+v after %+v", before, after) + } +} + +// A checkpoint held below the batch (here by an active recycle floor) does +// not make a drain repeat the same batch: the pass moves past it, writes +// every entry to the extent once (as a whole-map cycle did) and ends, with +// the checkpoint at the floor. A Recover starts the pass over. +func TestWALStoreV3HeldCheckpointEndsTheDrain(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 256*1024, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 12; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 6, anyActive: true}) + done := make(chan error, 1) + go func() { done <- s.flusher.flushOnce() }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("a drain held by the recycle floor did not end") + } + if cp := s.CheckpointLSN(); cp != 6 { + t.Fatalf("checkpoint=%d, want the floor 6", cp) + } + for i := uint32(0); i < 12; i++ { + if got, err := s.readFromExtent(i); err != nil || !bytes.Equal(got, blk(byte(i+1))) { + t.Fatalf("LBA %d not in the extent after a held drain: %v", i, err) + } + if got, err := s.Read(i); err != nil || !bytes.Equal(got, blk(byte(i+1))) { + t.Fatalf("LBA %d: %v", i, err) + } + } + // A pass position from another recovery lifetime is not trusted. + r, err := s.flusher.flushCycle(false, flushPass{after: 11, gen: s.v3.recoverGen.Load() + 1, limit: math.MaxUint64}) + if err != nil || r.last == 0 || r.last > 11 { // a trusted stale position would take only LSN 12 + t.Fatalf("a stale pass position: last=%d err=%v, want the pass to restart at the oldest dirty entry", r.last, err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 57112b02b1..f44b74dd77 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -83,7 +83,7 @@ stateDiagram-v2 | Recovering | Serving (v1.1 upgrade, clean-stop seed) | the chunk layer attaches an unmarked store on the draft v1.1 format (lab builds only), after Recover and the storage claim: each whole local chunk is written Rebuilt all → U, Hash → HU, Commit → HP with HEAD's hash (a chunk HEAD does not name: the zero chunk's) only when all hold: a clean-stop proof (the HEAD the claim was built on was a committed, idle detach, `DetachedBy`), its claim id is the store's layout claim id, and its position is the store's synced position the pages are valid through; otherwise each whole local chunk is U (left to the compare pass); partial and absent chunks are classified alike in both; a marked store never seeds | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `INV-CHUNK-RECORD-SEED-001`, `INV-CHUNK-RECORD-UPGRADE-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` | -| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` | +| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`, `flushCycle`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-CHECKPOINT-PREFIX-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` | | Serving | Serving (map prepare refused) | a map preparer (the flusher's checkpoint, the chunk layer's captured-map publication, BASE complete) captured prior and a publication released it before the prepare's live-set snapshot: the prepare reuses no page, writes nothing, refuses with `prior_released` without latching, counts it, and the caller's next cycle prepares from the current root | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`; `core/storage/chunk_map_extents_v3.go` `liveSnapshotWithPriorV3`; `core/storage/map_extent_pins.go` `reserveCoverageV3` | `INV-WAL-V3-MAP-PRIOR-LIVE-001` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | @@ -623,6 +623,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CHECKPOINT-PREFIX-001` | A flusher cycle drains an LSN prefix of the synced dirty entries, at most a sixteenth of the WAL, cut only at a record boundary (a native batch, one WAL record whose blocks carry consecutive LSNs, stays whole; the first record whole even when larger), and checkpoints at its last LSN L: every record with LSN <= L is in the extent or superseded by a record of the same LBA with LSN > L, still in the WAL. The run loop starts the next cycle at once while entries remain; a full drain (`flushOnce`, the final flush of a stop) runs cycles until its first frontier is drained. A pass writes every dirty entry once even when the checkpoint is held below them (a recycle floor, retention, a map): the next cycle starts after the previous batch's last LSN, within one recovery lifetime (another lifetime restarts the pass), so a held batch is not repeated; when the hold ends the checkpoint moves over entries already written and fsynced in the pass. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushCycle`, `boundCycleBatch`, `flushOnceInternal`, `cycle`, `flushPass` | `TestBoundCycleBatchCutsOnlyAtARecordBoundary`, `TestWALStoreV3BoundedCheckpointReplaysANewerRecordAfterACrash`, `TestWALStoreV3FullDrainRunsBoundedCyclesToTheEnd`, `TestWALStoreV3SlowExtentKeepsReclaimMoving`, `TestWALStoreV3HeldCheckpointEndsTheDrain` (`core/storage/walstore_bounded_flush_v3_test.go`) | FlushCkpt CkptMeaning, ReadsLatest | ACTIVE | | `INV-WAL-FRONTIER-GAP-001` | A durable BASE anchor and its contiguous synced install-lane suffix survive recovery; an unpersisted frontier jump is not admitted. | M1 Recovering | `core/storage/walstore_v3.go` `recoverV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | — | ACTIVE | | `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent, superblock, or the chunk layer's presence save), the open store refuses every later `Sync`, write, checkpoint and presence save without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestNativeReplacementDataFsyncFailureIsSticky` (`core/storage/legacy_replacement_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestAPresenceSaveIsRefusedAfterAFailedFsync`, `TestAPresenceSavesFailedFsyncStaysFailed` (`core/storage/chunk_presence_fsync_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 2deb89237d..74295b4752 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -24,6 +24,11 @@ These notes collect v1.1's changes as they land; v1.1 is not released. the cgroup2 mount visible in its mount namespace) now starts on the 256 MiB default soft limit and logs one `level=WARN` line naming why, instead of exiting 2; status reports the reason in `Memory.SoftLimitFallback`. An explicit but invalid `--memory-limit-mib` or `GOMEMLIMIT` still refuses. +- The WAL flusher reclaims in bounded steps: each cycle flushes the oldest synced writes up to a sixteenth of the WAL + and advances the checkpoint, instead of flushing every dirty block before freeing any WAL space. On a slow disk a + write waiting for WAL space now sees space freed every step rather than once per whole-WAL cycle. Status reports + the reclaim progress in `CheckpointPersistence`: `ReclaimedBytes`, `BoundedCycles`, `FlusherPhase`, + `CycleStarted`, `CycleExtentBytes` and `LastExtentWrite`. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index af64538e58..6e01b49b8e 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -213,6 +213,12 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].CheckpointPersistence.CheckpointLSN` | uint64 | the persisted checkpoint LSN | | `Volumes[].CheckpointPersistence.Advances` | uint64 | successes that moved CheckpointLSN forward | | `Volumes[].CheckpointPersistence.LastAdvance` | time (RFC 3339) | when the latest advance happened; zero if none in this open | +| `Volumes[].CheckpointPersistence.ReclaimedBytes` | uint64 | WAL bytes the checkpoint advances released in this open | +| `Volumes[].CheckpointPersistence.BoundedCycles` | uint64 | flusher cycles that stopped at the batch bound (a sixteenth of the WAL) with entries left for the next | +| `Volumes[].CheckpointPersistence.FlusherPhase` | string | idle, drain_held (before the chunk layer attaches), wal_sync (every dirty entry above the synced WAL), writing, extent_sync or checkpoint | +| `Volumes[].CheckpointPersistence.CycleStarted` | time (RFC 3339) | when the flusher cycle in progress started; zero when none is | +| `Volumes[].CheckpointPersistence.CycleExtentBytes` | uint64 | extent bytes the cycle in progress (or the latest) has written | +| `Volumes[].CheckpointPersistence.LastExtentWrite` | time (RFC 3339) | when the flusher last wrote extent bytes; zero if never in this open | | `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | | `Volumes[].Chunk.CurrentCut` | object | active cut phase; absent when idle (omitted when empty) | | `Volumes[].Chunk.CurrentCut.attempt_started_at` | time (RFC 3339) | start of the whole attempt, unchanged across phase visits | From 5b486edcd56fa71f290aaec5410eb147c890025a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 23:49:45 -0800 Subject: [PATCH 2/9] storage: one checkpoint step retires every entry below it; time its steps Setting the store's checkpoint and retiring every dirty entry at or below it are one function on every path (the owned map's publication and rollover, the map candidate's, the flusher cycle's own retirement): a checkpoint that jumps past entries a pass wrote while it was held leaves none of them dirty, pointing at WAL records the released tail lets the writer reuse. The checkpoint's steps are timed where they happen: the hooks, the owned map's page writes and fsyncs, the waits for the leader role and the store lock, the descriptor slot writes and fsyncs (the store file), and the retirement. Status reports the step in progress with its start, and per step the time, count and bytes written. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/checkpoint_diagnostics.go | 26 ++-- .../core/storage/checkpoint_steps.go | 89 +++++++++++ .../core/storage/chunk_lsn_map_v3.go | 18 ++- seaweed-block/core/storage/flusher.go | 9 +- seaweed-block/core/storage/walstore.go | 5 +- .../storage/walstore_bounded_flush_v3_test.go | 139 ++++++++++++++++++ .../storage/walstore_map_checkpoint_v3.go | 20 ++- seaweed-block/core/storage/walstore_v3.go | 30 +++- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/status-schema.md | 6 + 10 files changed, 314 insertions(+), 30 deletions(-) create mode 100644 seaweed-block/core/storage/checkpoint_steps.go diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 1e58d433cf..bf905064f3 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -21,18 +21,19 @@ import ( // (CycleExtentBytes, LastExtentWrite); FlusherPhase says what the flusher is // doing or waits on. type CheckpointPersistenceStatus struct { - Successes uint64 // checkpoint calls that succeeded (including unchanged ones) - Refusals uint64 // checkpoint calls refused because the map coverage was stale - Failures uint64 // checkpoint calls that failed with an error - CheckpointLSN uint64 // the persisted checkpoint LSN - Advances uint64 // successes that moved CheckpointLSN forward - LastAdvance time.Time // when the latest advance happened; zero if none in this open - ReclaimedBytes uint64 // WAL bytes the checkpoint advances released in this open - BoundedCycles uint64 // flusher cycles that stopped at the batch bound (a sixteenth of the WAL) with entries left for the next - FlusherPhase string // idle, drain_held (before the chunk layer attaches), wal_sync (every dirty entry above the synced WAL), writing, extent_sync or checkpoint - CycleStarted time.Time // when the flusher cycle in progress started; zero when none is - CycleExtentBytes uint64 // extent bytes the cycle in progress (or the latest) has written - LastExtentWrite time.Time // when the flusher last wrote extent bytes; zero if never in this open + Successes uint64 // checkpoint calls that succeeded (including unchanged ones) + Refusals uint64 // checkpoint calls refused because the map coverage was stale + Failures uint64 // checkpoint calls that failed with an error + CheckpointLSN uint64 // the persisted checkpoint LSN + Advances uint64 // successes that moved CheckpointLSN forward + LastAdvance time.Time // when the latest advance happened; zero if none in this open + ReclaimedBytes uint64 // WAL bytes the checkpoint advances released in this open + BoundedCycles uint64 // flusher cycles that stopped at the batch bound (a sixteenth of the WAL) with entries left for the next + FlusherPhase string // idle, drain_held (before the chunk layer attaches), wal_sync (every dirty entry above the synced WAL), writing, extent_sync or checkpoint + CycleStarted time.Time // when the flusher cycle in progress started; zero when none is + CycleExtentBytes uint64 // extent bytes the cycle in progress (or the latest) has written + LastExtentWrite time.Time // when the flusher last wrote extent bytes; zero if never in this open + CheckpointSteps CheckpointStepStatus // the checkpoint's step in progress and its per-step time, count and bytes } // ReclaimProgress is the flusher's reclaim progress for a write waiting for @@ -75,6 +76,7 @@ func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { BoundedCycles: i.boundedCycles.Load(), FlusherPhase: i.phaseName(), CycleExtentBytes: i.cycleExtentBytes.Load(), + CheckpointSteps: s.ckpt.status(), } if ns := i.checkpointLastAdvanceNanos.Load(); ns != 0 { st.LastAdvance = time.Unix(0, ns) diff --git a/seaweed-block/core/storage/checkpoint_steps.go b/seaweed-block/core/storage/checkpoint_steps.go new file mode 100644 index 0000000000..b3bef665a9 --- /dev/null +++ b/seaweed-block/core/storage/checkpoint_steps.go @@ -0,0 +1,89 @@ +package storage + +import ( + "sync/atomic" + "time" +) + +// The steps of a flusher checkpoint, each timed where its I/O or wait +// happens. map_write and map_fsync are the owned map file's; slot_write and +// slot_fsync are the descriptor slots in the store file, whose fsync also +// writes back every other dirty page of that file (the WAL and the extent). +const ( + ckptHooks = iota // BeforeCheckpointAdvance of the metadata and the chunk layer + ckptMapWrite // the owned map candidate's page writes (map file) + ckptMapFsync // the owned map file's fsyncs + ckptLeaderWait // waiting for the leader role (syncMu) + ckptStoreLockWait // waiting for the store lock (WALStore.mu) + ckptSlotWrite // descriptor slot writes (store file) + ckptSlotFsync // descriptor slot fsyncs (store file) + ckptRetire // retiring the dirty entries at or below the checkpoint + ckptSteps +) + +var ckptStepNames = [ckptSteps]string{"hooks", "map_write", "map_fsync", "leader_wait", "store_lock_wait", "slot_write", "slot_fsync", "retire"} + +// checkpointSteps times the steps of the flusher's checkpoints. Atomics +// only: a status read never waits behind the step it reports. +type checkpointSteps struct { + cur atomic.Int32 // the step in progress + 1; 0: none + since atomic.Int64 // when it started (unix ns) + nanos [ckptSteps]atomic.Uint64 + count [ckptSteps]atomic.Uint64 + bytes [ckptSteps]atomic.Uint64 +} + +// enter marks step as in progress and returns its end, which adds the +// elapsed time and the bytes the step wrote, and restores the enclosing step. +func (c *checkpointSteps) enter(step int) func(bytes int) { + if c == nil { + return func(int) {} + } + prev, prevSince := c.cur.Load(), c.since.Load() + start := time.Now() + c.cur.Store(int32(step + 1)) + c.since.Store(start.UnixNano()) + return func(n int) { + c.nanos[step].Add(uint64(time.Since(start).Nanoseconds())) + c.count[step].Add(1) + if n > 0 { + c.bytes[step].Add(uint64(n)) + } + c.cur.Store(prev) + c.since.Store(prevSince) + } +} + +// CheckpointStepStatus is the flusher checkpoint's per-step timing in this +// open. Step and Since name the step in progress (empty when none). Nanos, +// Count and Bytes are cumulative per step name: hooks, map_write, map_fsync +// (the owned map file), leader_wait, store_lock_wait, slot_write, slot_fsync +// (the store file's descriptor slots; its fsync also writes back the file's +// other dirty pages) and retire. Bytes are the bytes a step wrote. +type CheckpointStepStatus struct { + Step string `json:",omitempty"` + Since time.Time `json:",omitempty"` + Nanos map[string]uint64 `json:",omitempty"` + Count map[string]uint64 `json:",omitempty"` + Bytes map[string]uint64 `json:",omitempty"` +} + +func (c *checkpointSteps) status() CheckpointStepStatus { + var st CheckpointStepStatus + if p := c.cur.Load(); p > 0 && int(p) <= ckptSteps { + st.Step = ckptStepNames[p-1] + st.Since = time.Unix(0, c.since.Load()) + } + for i, name := range ckptStepNames { + if n := c.count[i].Load(); n > 0 { + if st.Nanos == nil { + st.Nanos, st.Count, st.Bytes = map[string]uint64{}, map[string]uint64{}, map[string]uint64{} + } + st.Nanos[name], st.Count[name] = c.nanos[i].Load(), n + if b := c.bytes[i].Load(); b > 0 { + st.Bytes[name] = b + } + } + } + return st +} diff --git a/seaweed-block/core/storage/chunk_lsn_map_v3.go b/seaweed-block/core/storage/chunk_lsn_map_v3.go index 682c51fe27..916c361f0a 100644 --- a/seaweed-block/core/storage/chunk_lsn_map_v3.go +++ b/seaweed-block/core/storage/chunk_lsn_map_v3.go @@ -279,6 +279,7 @@ func (c *chunkMapCandidateV3) descriptor(d descriptorV3) descriptorV3 { } type chunkLSNMapV3 struct { + steps *checkpointSteps // the store's checkpoint step timing (nil: none) lastCheckpoint atomic.Pointer[MapCheckpointPhases] mu sync.Mutex fd *os.File @@ -505,7 +506,7 @@ func (m *chunkLSNMapV3) prepareEntriesLockedV3(g, C uint64, entries mapEntrySour } m.live.fileBytes.Store(keep) // the file is shorter even if the fsync fails m.live.truncations.Add(1) - if e := m.syncFile(); e != nil { + if e := m.timedSync(); e != nil { return nil, e } } @@ -525,7 +526,9 @@ func (m *chunkLSNMapV3) prepareEntriesLockedV3(g, C uint64, entries mapEntrySour if uint64(len(b)) > math.MaxInt64-at { return 0, ErrCounterExhausted } + endWrite := m.steps.enter(ckptMapWrite) n, e := m.fd.WriteAt(b, int64(at)) + endWrite(n) if end := at + uint64(n); end > m.live.fileBytes.Load() { m.live.fileBytes.Store(end) // also on a failed or short write } @@ -602,7 +605,7 @@ func (m *chunkLSNMapV3) prepareEntriesLockedV3(g, C uint64, entries mapEntrySour } refs = refs.with(int(j), mapPageRefV3{Offset: at, Hash: mapDigestV3(mapPageDomainV3, p[:4064])}) } - if e = m.syncFile(); e != nil { + if e = m.timedSync(); e != nil { return nil, e } var root []byte @@ -618,7 +621,7 @@ func (m *chunkLSNMapV3) prepareEntriesLockedV3(g, C uint64, entries mapEntrySour if e != nil { return nil, e } - if e = m.syncFile(); e != nil { + if e = m.timedSync(); e != nil { return nil, e } if e = m.syncDirectory(); e != nil { @@ -651,3 +654,12 @@ func (m *chunkLSNMapV3) Close() error { m.failed = fmt.Errorf("%w: closed", ErrMapInvalid) return m.fd.Close() } + +// timedSync is the map file's fsync on the checkpoint path, timed as the +// checkpoint's map_fsync step. +func (m *chunkLSNMapV3) timedSync() error { + end := m.steps.enter(ckptMapFsync) + err := m.syncFile() + end(0) + return err +} diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index aa3a87734a..cb28278784 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -448,13 +448,8 @@ func (f *flusher) flushCycle(allowClosed bool, p flushPass) (r flushCycleResult, if checkpoint >= maxLSN && maxLSN+1 > store.walTail { store.walTail = maxLSN + 1 } - - for _, e := range entries { - if e.LSN > checkpoint { - continue - } - store.dm.compareAndDelete(e.LBA, e.LSN) - } + // Every dirty entry at or below the checkpoint, not only this batch's. + store.checkpointedV3Locked(checkpoint) store.mu.Unlock() diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index a86245a566..a5d605c684 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -89,8 +89,9 @@ type WALStore struct { closeResult error lastStop atomic.Pointer[StoreStopPhases] closedCheckpoint atomic.Pointer[MapCheckpointPhases] - testDestructiveSnapshot func() // nil scheduling control, before any capture lock - testCloseSnapshot func() // nil in production; called without captureMu + ckpt checkpointSteps // the flusher checkpoint's per-step timing + testDestructiveSnapshot func() // nil scheduling control, before any capture lock + testCloseSnapshot func() // nil in production; called without captureMu // chunk is the attached chunk layer's hooks; nil when none. chunk atomic.Pointer[chunkHooks] diff --git a/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go index d7ef288045..c39b7f61da 100644 --- a/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go +++ b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go @@ -318,3 +318,142 @@ func TestWALStoreV3HeldCheckpointEndsTheDrain(t *testing.T) { t.Fatalf("a stale pass position: last=%d err=%v, want the pass to restart at the oldest dirty entry", r.last, err) } } + +// A checkpoint held below a pass and then released jumps past entries the +// pass wrote in earlier cycles: every dirty entry at or below the new +// checkpoint retires with it (not only the jumping cycle's batch), and the +// held blocks read back right after the writer reuses their WAL slots. +func TestWALStoreV3HeldThenJumpRetiresEveryEntryBelowTheCheckpoint(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 256*1024, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 12; i++ { // LSNs 1..12 + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + // Held at 6: a pass writes every entry to the extent, 7..12 stay dirty. + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 6, anyActive: true}) + p := flushPass{limit: math.MaxUint64} + for { + r, err := s.flusher.flushCycle(false, p) + if err != nil { + t.Fatal(err) + } + if !r.more { + p = r.next(math.MaxUint64) // the run loop's position after the held pass + break + } + p = r.next(math.MaxUint64) + } + if cp := s.CheckpointLSN(); cp != 6 || s.dm.len() != 6 { + t.Fatalf("held pass: checkpoint=%d dirty=%d, want 6 and 6", cp, s.dm.len()) + } + // The hold ends; new writes 13..16 and a cycle after the held pass's + // position: its batch is 13..16 alone, and the checkpoint jumps to 16. + s.SetRecycleFloorSource(nil) + for i := uint32(20); i < 24; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := s.flusher.flushCycle(false, p); err != nil { + t.Fatal(err) + } + cp := s.CheckpointLSN() + for _, e := range s.dm.snapshot() { + if e.LSN <= cp { + t.Fatalf("checkpoint %d jumped past a dirty entry left below it: LBA %d LSN %d", cp, e.LBA, e.LSN) + } + } + if cp != 16 { + t.Fatalf("checkpoint after the hold: %d, want 16", cp) + } + // Reuse every WAL slot several times over, then read the held blocks. + for n := 0; n < 400; n++ { + lba := uint32(30 + n%30) + if _, err := s.Write(lba, blk(byte(n))); err != nil { + t.Fatalf("write %d: %v", n, err) + } + if n%20 == 19 { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + } + } + for i := uint32(0); i < 12; i++ { + if got, err := s.Read(i); err != nil || !bytes.Equal(got, blk(byte(i+1))) { + t.Fatalf("held LBA %d after its WAL slot was reused: err=%v", i, err) + } + } +} + +// The checkpoint's steps are timed where they happen: a drain on an owned +// map store records each one (with the bytes the writing steps wrote), and +// a checkpoint waiting for the leader role shows that step in progress. +func TestWALStoreV3CheckpointStepsAreTimed(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 256*1024, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 8; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + st := s.CheckpointPersistence().CheckpointSteps + for _, step := range []string{"hooks", "map_write", "map_fsync", "leader_wait", "store_lock_wait", "slot_write", "slot_fsync", "retire"} { + if st.Count[step] == 0 { + t.Fatalf("step %s not recorded: %+v", step, st) + } + } + if st.Bytes["map_write"] == 0 || st.Bytes["slot_write"] == 0 || st.Step != "" { + t.Fatalf("bytes or a step left in progress: %+v", st) + } + if _, err := s.Write(20, blk(20)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.v3.syncMu.Lock() // the leader role, held elsewhere + done := make(chan error, 1) + go func() { done <- s.flusher.flushOnce() }() + deadline := time.Now().Add(5 * time.Second) + for { + if cur := s.CheckpointPersistence().CheckpointSteps; cur.Step == "leader_wait" && !cur.Since.IsZero() { + break + } + if time.Now().After(deadline) { + s.v3.syncMu.Unlock() + t.Fatalf("a checkpoint waiting for the leader role: %+v", s.CheckpointPersistence().CheckpointSteps) + } + time.Sleep(5 * time.Millisecond) + } + s.v3.syncMu.Unlock() + if err := <-done; err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 55067966cc..3f9a4a1832 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -148,9 +148,13 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) e } } if cp <= v.pub.current().CheckpointLSN { + endWait := s.ckpt.enter(ckptLeaderWait) v.syncMu.Lock() + endWait(0) defer v.syncMu.Unlock() + endLock := s.ckpt.enter(ckptStoreLockWait) s.mu.Lock() + endLock(0) defer s.mu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { return mapCoverageRefusal("recovery_lifetime_changed") @@ -163,7 +167,7 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) e return err } s.mu.Lock() - s.checkpointLSN = d.CheckpointLSN + s.checkpointedV3Locked(d.CheckpointLSN) s.mu.Unlock() return nil } @@ -178,16 +182,20 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) e // caller has made the extent durable. Nothing is published on any error. func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) (descriptorV3, error) { v := s.v3 + endHooks := s.ckpt.enter(ckptHooks) if s.metadata != nil { if err := s.metadata.BeforeCheckpointAdvance(cp); err != nil { + endHooks(0) return descriptorV3{}, err } } if h := s.chunk.Load(); h != nil { if err := h.sink.BeforeCheckpointAdvance(cp); err != nil { + endHooks(0) return descriptorV3{}, err } } + endHooks(0) prepared, err := s.prepareOwnedMapCheckpointV3(cp) if err != nil { return descriptorV3{}, err @@ -195,7 +203,9 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) if h := v.testMapPrepared; h != nil { h() } + endWait := s.ckpt.enter(ckptLeaderWait) v.syncMu.Lock() + endWait(0) defer v.syncMu.Unlock() // The candidate proof alone is insufficient: it was prepared after extent // I/O and could belong to a newer Recover lifetime than those bytes. @@ -227,7 +237,9 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // Keep writer admission excluded until both durable publications AND the // old dirty references are settled. The ordinary publisher releases a // supplied store lock before I/O, so acquire it here and pass nil instead. + endLock := s.ckpt.enter(ckptStoreLockWait) s.mu.Lock() + endLock(0) defer s.mu.Unlock() d, err := v.pub.publishMapV3(nil, nil, prepared, func(n *descriptorV3) error { n.W = max(n.W, wack) @@ -249,7 +261,7 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // Every current entry <= cp is durable in extent (a newer concurrent write // has a higher LSN and survives). No writer can reuse a released slot until // this store lock is released, after these references have disappeared. - s.retireCheckpointDirtyV3Locked(d.CheckpointLSN) + s.checkpointedV3Locked(d.CheckpointLSN) if seed { v.appended.Store(max(v.appended.Load(), cp)) v.wack.Store(wack) @@ -259,6 +271,8 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // Caller holds store.mu; the successful durable checkpoint proves the current // versions at/below cp are in extent. Each shard preserves newer WAL entries. +// Only checkpointedV3Locked calls it: every path that sets the checkpoint +// retires through the same step. func (s *WALStore) retireCheckpointDirtyV3Locked(cp uint64) { for i := range s.dm.shards { shard := &s.dm.shards[i] @@ -283,6 +297,6 @@ func (s *WALStore) rolloverCheckpointV3Locked() error { if _, err := s.v3.pub.rolloverIfPinned(); err != nil { return err } - s.retireCheckpointDirtyV3Locked(d.CheckpointLSN) + s.checkpointedV3Locked(d.CheckpointLSN) return nil } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 9c9c3f17bd..0fb26b537a 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -459,13 +459,20 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO return err } } + end := s.ckpt.enter(ckptSlotWrite) n, err := f.WriteAt(buf, off) + end(n) if err == nil && n != len(buf) { err = fmt.Errorf("storage: v3 slot short write %d of %d", n, len(buf)) } return err }, - fsync: f.Sync, + fsync: func() error { + end := s.ckpt.enter(ckptSlotFsync) + err := f.Sync() + end(0) + return err + }, syncFile: s.syncFile, sticky: s.stickyIOFault, latch: s.latchV3, @@ -491,6 +498,7 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO } openProgress.finish() v.ownedMap = ownedMap + ownedMap.steps = &s.ckpt v.mapEntries, err = v.mapEntries.recover(progressCtx, RecoveryOpenCopy, mapCurrent.entries) if err != nil { return err @@ -1417,7 +1425,9 @@ func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { if err != nil { return err } + endWait := s.ckpt.enter(ckptLeaderWait) v.syncMu.Lock() + endWait(0) defer v.syncMu.Unlock() if !v.flushLifetimeValidV3(recoveryGen) { return mapCoverageRefusal("recovery_lifetime_changed") @@ -1435,11 +1445,27 @@ func (s *WALStore) persistCheckpointV3(highestLSN, recoveryGen uint64) error { return err } s.mu.Lock() - s.checkpointLSN = d.CheckpointLSN + s.checkpointedV3Locked(d.CheckpointLSN) s.mu.Unlock() return nil } +// checkpointedV3Locked is the one step after every checkpoint the flusher +// publishes or keeps (the owned map's, the map candidate's, and the cycle's +// own retirement): the store's checkpoint becomes cp and every dirty entry +// at or below it retires, not only the cycle's batch. A pass may have +// written an entry to the extent in an earlier cycle while the checkpoint +// was held below it; left dirty under a checkpoint that has since jumped +// past it, it would still point at a WAL record the released tail lets the +// writer reuse. The caller holds s.mu and has checked that cp belongs to the +// current recovery lifetime (under the leader role or s.mu). +func (s *WALStore) checkpointedV3Locked(cp uint64) { + s.checkpointLSN = max(s.checkpointLSN, cp) + end := s.ckpt.enter(ckptRetire) + s.retireCheckpointDirtyV3Locked(cp) + end(0) +} + // v3BudgetAfterRollover is the last budget check of a v3 write: after the // rollover's metadata I/O (completed, owned) and before the payload append. func (s *WALStore) v3BudgetAfterRollover(budget func() error) error { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index f44b74dd77..920c47903e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -623,7 +623,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CHECKPOINT-PREFIX-001` | A flusher cycle drains an LSN prefix of the synced dirty entries, at most a sixteenth of the WAL, cut only at a record boundary (a native batch, one WAL record whose blocks carry consecutive LSNs, stays whole; the first record whole even when larger), and checkpoints at its last LSN L: every record with LSN <= L is in the extent or superseded by a record of the same LBA with LSN > L, still in the WAL. The run loop starts the next cycle at once while entries remain; a full drain (`flushOnce`, the final flush of a stop) runs cycles until its first frontier is drained. A pass writes every dirty entry once even when the checkpoint is held below them (a recycle floor, retention, a map): the next cycle starts after the previous batch's last LSN, within one recovery lifetime (another lifetime restarts the pass), so a held batch is not repeated; when the hold ends the checkpoint moves over entries already written and fsynced in the pass. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushCycle`, `boundCycleBatch`, `flushOnceInternal`, `cycle`, `flushPass` | `TestBoundCycleBatchCutsOnlyAtARecordBoundary`, `TestWALStoreV3BoundedCheckpointReplaysANewerRecordAfterACrash`, `TestWALStoreV3FullDrainRunsBoundedCyclesToTheEnd`, `TestWALStoreV3SlowExtentKeepsReclaimMoving`, `TestWALStoreV3HeldCheckpointEndsTheDrain` (`core/storage/walstore_bounded_flush_v3_test.go`) | FlushCkpt CkptMeaning, ReadsLatest | ACTIVE | +| `INV-WAL-CHECKPOINT-PREFIX-001` | A flusher cycle drains an LSN prefix of the synced dirty entries, at most a sixteenth of the WAL, cut only at a record boundary (a native batch, one WAL record whose blocks carry consecutive LSNs, stays whole; the first record whole even when larger), and checkpoints at its last LSN L: every record with LSN <= L is in the extent or superseded by a record of the same LBA with LSN > L, still in the WAL. The run loop starts the next cycle at once while entries remain; a full drain (`flushOnce`, the final flush of a stop) runs cycles until its first frontier is drained. A pass writes every dirty entry once even when the checkpoint is held below them (a recycle floor, retention, a map): the next cycle starts after the previous batch's last LSN, within one recovery lifetime (another lifetime restarts the pass), so a held batch is not repeated; when the hold ends the checkpoint moves over entries already written and fsynced in the pass. Setting the checkpoint and retiring every dirty entry at or below it (not only the cycle's batch) are one step, `checkpointedV3Locked`, on every path: the owned map's publication and rollover, the map candidate's, and the cycle's own retirement. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushCycle`, `boundCycleBatch`, `flushOnceInternal`, `cycle`, `flushPass`; `core/storage/walstore_v3.go` `checkpointedV3Locked` | `TestBoundCycleBatchCutsOnlyAtARecordBoundary`, `TestWALStoreV3BoundedCheckpointReplaysANewerRecordAfterACrash`, `TestWALStoreV3FullDrainRunsBoundedCyclesToTheEnd`, `TestWALStoreV3SlowExtentKeepsReclaimMoving`, `TestWALStoreV3HeldCheckpointEndsTheDrain`, `TestWALStoreV3HeldThenJumpRetiresEveryEntryBelowTheCheckpoint` (`core/storage/walstore_bounded_flush_v3_test.go`) | FlushCkpt CkptMeaning, ReadsLatest | ACTIVE | | `INV-WAL-FRONTIER-GAP-001` | A durable BASE anchor and its contiguous synced install-lane suffix survive recovery; an unpersisted frontier jump is not admitted. | M1 Recovering | `core/storage/walstore_v3.go` `recoverV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | — | ACTIVE | | `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent, superblock, or the chunk layer's presence save), the open store refuses every later `Sync`, write, checkpoint and presence save without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestNativeReplacementDataFsyncFailureIsSticky` (`core/storage/legacy_replacement_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestAPresenceSaveIsRefusedAfterAFailedFsync`, `TestAPresenceSavesFailedFsyncStaysFailed` (`core/storage/chunk_presence_fsync_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 6e01b49b8e..75ab8ed698 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -219,6 +219,12 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].CheckpointPersistence.CycleStarted` | time (RFC 3339) | when the flusher cycle in progress started; zero when none is | | `Volumes[].CheckpointPersistence.CycleExtentBytes` | uint64 | extent bytes the cycle in progress (or the latest) has written | | `Volumes[].CheckpointPersistence.LastExtentWrite` | time (RFC 3339) | when the flusher last wrote extent bytes; zero if never in this open | +| `Volumes[].CheckpointPersistence.CheckpointSteps` | object | the flusher checkpoint's per-step timing in this open | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Step` | string | the step in progress (omitted when none): hooks, map_write, map_fsync (the owned map file), leader_wait, store_lock_wait, slot_write, slot_fsync (the store file's descriptor slots; the fsync also writes back the file's other dirty pages) or retire | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Since` | time (RFC 3339) | when the step in progress started | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Nanos` | object | cumulative nanoseconds per step name | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Count` | object | how many times each step ran | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Bytes` | object | bytes each writing step wrote (map_write, slot_write) | | `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | | `Volumes[].Chunk.CurrentCut` | object | active cut phase; absent when idle (omitted when empty) | | `Volumes[].Chunk.CurrentCut.attempt_started_at` | time (RFC 3339) | start of the whole attempt, unchanged across phase visits | From 43c7f9eb1e1884fab442612fe0c0892c330e93a8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 23:53:39 -0800 Subject: [PATCH 3/9] docs: the bounded-cycle invariant as one-property rows The prefix cut, the checkpoint at the highest present LSN with whole-record reclaim, the one checkpoint-and-retire step, and the flusher pass are separate ledger rows, each one property. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 920c47903e..c7244703ef 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -83,7 +83,7 @@ stateDiagram-v2 | Recovering | Serving (v1.1 upgrade, clean-stop seed) | the chunk layer attaches an unmarked store on the draft v1.1 format (lab builds only), after Recover and the storage claim: each whole local chunk is written Rebuilt all → U, Hash → HU, Commit → HP with HEAD's hash (a chunk HEAD does not name: the zero chunk's) only when all hold: a clean-stop proof (the HEAD the claim was built on was a committed, idle detach, `DetachedBy`), its claim id is the store's layout claim id, and its position is the store's synced position the pages are valid through; otherwise each whole local chunk is U (left to the compare pass); partial and absent chunks are classified alike in both; a marked store never seeds | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `INV-CHUNK-RECORD-SEED-001`, `INV-CHUNK-RECORD-UPGRADE-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` | -| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`, `flushCycle`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-CHECKPOINT-PREFIX-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` | +| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse | `core/storage/flusher.go` `flushOnceInternal`, `flushCycle`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-CHECKPOINT-PREFIX-001`, `INV-WAL-CHECKPOINT-PRESENT-001`, `INV-WAL-CHECKPOINT-RETIRE-001`, `INV-WAL-FLUSH-PASS-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` | | Serving | Serving (map prepare refused) | a map preparer (the flusher's checkpoint, the chunk layer's captured-map publication, BASE complete) captured prior and a publication released it before the prepare's live-set snapshot: the prepare reuses no page, writes nothing, refuses with `prior_released` without latching, counts it, and the caller's next cycle prepares from the current root | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`; `core/storage/chunk_map_extents_v3.go` `liveSnapshotWithPriorV3`; `core/storage/map_extent_pins.go` `reserveCoverageV3` | `INV-WAL-V3-MAP-PRIOR-LIVE-001` | | Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | @@ -623,7 +623,10 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CHECKPOINT-PREFIX-001` | A flusher cycle drains an LSN prefix of the synced dirty entries, at most a sixteenth of the WAL, cut only at a record boundary (a native batch, one WAL record whose blocks carry consecutive LSNs, stays whole; the first record whole even when larger), and checkpoints at its last LSN L: every record with LSN <= L is in the extent or superseded by a record of the same LBA with LSN > L, still in the WAL. The run loop starts the next cycle at once while entries remain; a full drain (`flushOnce`, the final flush of a stop) runs cycles until its first frontier is drained. A pass writes every dirty entry once even when the checkpoint is held below them (a recycle floor, retention, a map): the next cycle starts after the previous batch's last LSN, within one recovery lifetime (another lifetime restarts the pass), so a held batch is not repeated; when the hold ends the checkpoint moves over entries already written and fsynced in the pass. Setting the checkpoint and retiring every dirty entry at or below it (not only the cycle's batch) are one step, `checkpointedV3Locked`, on every path: the owned map's publication and rollover, the map candidate's, and the cycle's own retirement. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushCycle`, `boundCycleBatch`, `flushOnceInternal`, `cycle`, `flushPass`; `core/storage/walstore_v3.go` `checkpointedV3Locked` | `TestBoundCycleBatchCutsOnlyAtARecordBoundary`, `TestWALStoreV3BoundedCheckpointReplaysANewerRecordAfterACrash`, `TestWALStoreV3FullDrainRunsBoundedCyclesToTheEnd`, `TestWALStoreV3SlowExtentKeepsReclaimMoving`, `TestWALStoreV3HeldCheckpointEndsTheDrain`, `TestWALStoreV3HeldThenJumpRetiresEveryEntryBelowTheCheckpoint` (`core/storage/walstore_bounded_flush_v3_test.go`) | FlushCkpt CkptMeaning, ReadsLatest | ACTIVE | +| `INV-WAL-CHECKPOINT-PREFIX-001` | A flusher cycle drains the LSN prefix of the synced dirty entries that fits in a sixteenth of the WAL, cut at a record boundary: a native batch (one record, consecutive LSNs) stays whole, as does a first record larger than the bound. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushCycle`, `boundCycleBatch` | `TestBoundCycleBatchCutsOnlyAtARecordBoundary`, `TestWALStoreV3SlowExtentKeepsReclaimMoving` (`core/storage/walstore_bounded_flush_v3_test.go`) | FlushCkpt CkptMeaning | ACTIVE | +| `INV-WAL-CHECKPOINT-PRESENT-001` | A cycle's checkpoint is its highest present LSN; reclaim releases only whole records at or below it, and recovery replays the kept records whole. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushCycle`; `core/storage/wal_io_v3.go` `reclaimThroughV3` | `TestWALStoreV3BoundedCheckpointReplaysANewerRecordAfterACrash` (`core/storage/walstore_bounded_flush_v3_test.go`) | FlushCkpt CkptMeaning, ReadsLatest | ACTIVE | +| `INV-WAL-CHECKPOINT-RETIRE-001` | Setting the checkpoint and retiring every dirty entry at or below it are one step on every path (the owned map's publication and rollover, the map candidate's, the cycle's), so no dirty entry stays at or below the checkpoint. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/walstore_v3.go` `checkpointedV3Locked` | `TestWALStoreV3HeldThenJumpRetiresEveryEntryBelowTheCheckpoint` (`core/storage/walstore_bounded_flush_v3_test.go`) | FlushCkpt DirtyInWAL | ACTIVE | +| `INV-WAL-FLUSH-PASS-001` | A flusher pass writes every dirty entry once even under a held checkpoint: each cycle starts after the previous batch's last LSN, within one recovery lifetime; a full drain runs cycles until its first frontier is drained. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushPass`, `cycle`, `flushOnceInternal` | `TestWALStoreV3HeldCheckpointEndsTheDrain`, `TestWALStoreV3FullDrainRunsBoundedCyclesToTheEnd` (`core/storage/walstore_bounded_flush_v3_test.go`) | FlushCkpt CkptMeaning (pass cursor) | ACTIVE | | `INV-WAL-FRONTIER-GAP-001` | A durable BASE anchor and its contiguous synced install-lane suffix survive recovery; an unpersisted frontier jump is not admitted. | M1 Recovering | `core/storage/walstore_v3.go` `recoverV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`) | — | ACTIVE | | `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent, superblock, or the chunk layer's presence save), the open store refuses every later `Sync`, write, checkpoint and presence save without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestNativeReplacementDataFsyncFailureIsSticky` (`core/storage/legacy_replacement_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestAPresenceSaveIsRefusedAfterAFailedFsync`, `TestAPresenceSavesFailedFsyncStaysFailed` (`core/storage/chunk_presence_fsync_test.go`) | — | ACTIVE | From fcb5f608ac4c8d9430b9f42c54efb2bdf4f26a89 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 00:23:43 -0800 Subject: [PATCH 4/9] storage: the recovery fence punches holes, and a repeat is skipped Every recovery zeroed the whole WAL range with pwrites and fsynced it: the WAL's size in writes on every open, twice on a new volume. On Linux, with the default sparse allocation, the fence now deallocates the range (a hole punch, which reads zeros) and then fsyncs; where the filesystem cannot punch, or off Linux, or on a prezeroed store, it writes zeros as before. A recovery skips the fence when the same range was fenced and fsynced in this open by the same writer with no WAL write since (a new volume's second recovery). The fence's bytes count only after its fsync: status reports FencePunched, FenceZeroed and FenceSkips. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/checkpoint_diagnostics.go | 6 + .../core/storage/fence_punch_linux.go | 21 +++ .../core/storage/fence_punch_other.go | 13 ++ seaweed-block/core/storage/wal_io_v3.go | 9 ++ seaweed-block/core/storage/walstore.go | 3 + .../storage/walstore_fence_punch_v3_test.go | 152 ++++++++++++++++++ seaweed-block/core/storage/walstore_v3.go | 68 +++++++- seaweed-block/docs/design/invariants.md | 5 +- seaweed-block/docs/releases/v1.1.md | 4 + seaweed-block/docs/status-schema.md | 3 + 10 files changed, 280 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/storage/fence_punch_linux.go create mode 100644 seaweed-block/core/storage/fence_punch_other.go create mode 100644 seaweed-block/core/storage/walstore_fence_punch_v3_test.go diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index bf905064f3..6aae6678ba 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -34,6 +34,9 @@ type CheckpointPersistenceStatus struct { CycleExtentBytes uint64 // extent bytes the cycle in progress (or the latest) has written LastExtentWrite time.Time // when the flusher last wrote extent bytes; zero if never in this open CheckpointSteps CheckpointStepStatus // the checkpoint's step in progress and its per-step time, count and bytes + FencePunched uint64 // WAL fence bytes deallocated by hole punching in this open, counted after the fsync + FenceZeroed uint64 // WAL fence bytes written as zeros in this open (no hole punching), counted after the fsync + FenceSkips uint64 // recovery fences skipped: the same range was fenced in this open with no WAL write since } // ReclaimProgress is the flusher's reclaim progress for a write waiting for @@ -77,6 +80,9 @@ func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { FlusherPhase: i.phaseName(), CycleExtentBytes: i.cycleExtentBytes.Load(), CheckpointSteps: s.ckpt.status(), + FencePunched: s.fencePunchedBytes.Load(), + FenceZeroed: s.fenceZeroBytes.Load(), + FenceSkips: s.fenceSkips.Load(), } if ns := i.checkpointLastAdvanceNanos.Load(); ns != 0 { st.LastAdvance = time.Unix(0, ns) diff --git a/seaweed-block/core/storage/fence_punch_linux.go b/seaweed-block/core/storage/fence_punch_linux.go new file mode 100644 index 0000000000..f6d2f3d2db --- /dev/null +++ b/seaweed-block/core/storage/fence_punch_linux.go @@ -0,0 +1,21 @@ +//go:build linux + +package storage + +import ( + "errors" + "os" + + "golang.org/x/sys/unix" +) + +// punchHole deallocates [off, off+n) of f, keeping its size: the range reads +// zeros afterwards. The caller fsyncs. +func punchHole(f *os.File, off, n int64) error { + return unix.Fallocate(int(f.Fd()), unix.FALLOC_FL_PUNCH_HOLE|unix.FALLOC_FL_KEEP_SIZE, off, n) +} + +// punchUnsupported reports a filesystem or kernel without hole punching. +func punchUnsupported(err error) bool { + return errors.Is(err, errFencePunchUnsupported) || errors.Is(err, unix.EOPNOTSUPP) || errors.Is(err, unix.ENOSYS) +} diff --git a/seaweed-block/core/storage/fence_punch_other.go b/seaweed-block/core/storage/fence_punch_other.go new file mode 100644 index 0000000000..bf7e1a013a --- /dev/null +++ b/seaweed-block/core/storage/fence_punch_other.go @@ -0,0 +1,13 @@ +//go:build !linux + +package storage + +import ( + "errors" + "os" +) + +// punchHole is unsupported off Linux: the fence writes zeros instead. +func punchHole(*os.File, int64, int64) error { return errFencePunchUnsupported } + +func punchUnsupported(err error) bool { return errors.Is(err, errFencePunchUnsupported) } diff --git a/seaweed-block/core/storage/wal_io_v3.go b/seaweed-block/core/storage/wal_io_v3.go index ae608fcbdc..d93d2f5758 100644 --- a/seaweed-block/core/storage/wal_io_v3.go +++ b/seaweed-block/core/storage/wal_io_v3.go @@ -45,6 +45,14 @@ type walWriterV3 struct { // only the trusted kept prefix; a batch is one indivisible point. reclaim []walReclaimPointV3 instr *writeInstrumentation + writes uint64 // WAL region writes by this writer (a fence that saw no write since need not repeat) +} + +// writeCountV3 is how many WAL region writes this writer made. +func (w *walWriterV3) writeCountV3() uint64 { + w.mu.Lock() + defer w.mu.Unlock() + return w.writes } type walReclaimPointV3 struct{ lastLSN, end uint64 } @@ -140,6 +148,7 @@ func (w *walWriterV3) append(e walEntryV3, durableLSN uint64, budget func() erro } write := func(b []byte, pos uint64) error { start := time.Now() + w.writes++ n, err := w.writeAt(b, int64(d.WALOffset+pos%d.WALSize)) if w.instr != nil { w.instr.recordWALAppend(n, time.Since(start)) diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index a5d605c684..d41ccd601c 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -90,6 +90,9 @@ type WALStore struct { lastStop atomic.Pointer[StoreStopPhases] closedCheckpoint atomic.Pointer[MapCheckpointPhases] ckpt checkpointSteps // the flusher checkpoint's per-step timing + fencePunchedBytes atomic.Uint64 // WAL fence bytes deallocated (hole punch), counted after the fsync + fenceZeroBytes atomic.Uint64 // WAL fence bytes written as zeros, counted after the fsync + fenceSkips atomic.Uint64 // fences skipped: the same range was fenced in this open with no WAL write since testDestructiveSnapshot func() // nil scheduling control, before any capture lock testCloseSnapshot func() // nil in production; called without captureMu diff --git a/seaweed-block/core/storage/walstore_fence_punch_v3_test.go b/seaweed-block/core/storage/walstore_fence_punch_v3_test.go new file mode 100644 index 0000000000..15af17293a --- /dev/null +++ b/seaweed-block/core/storage/walstore_fence_punch_v3_test.go @@ -0,0 +1,152 @@ +package storage + +import ( + "bytes" + "os" + "path/filepath" + "runtime" + "testing" +) + +// The fence on both of its paths: hole punching (Linux, sparse) and zero +// writes (no punching). On each, records dropped by one recovery do not +// resurface after a second crash. +func TestWALStoreV3FenceBothPathsReplayNoStaleRecord(t *testing.T) { + for _, path := range []string{"punch", "zero"} { + t.Run(path, func(t *testing.T) { + if path == "zero" { + punchHoleFn = func(*os.File, int64, int64) error { return errFencePunchUnsupported } + t.Cleanup(func() { punchHoleFn = punchHole }) + } + for _, mode := range []WMode{WModeLagged, WModeStrict} { + if resurrectionSchedule(t, mode, false) { + t.Fatalf("%s fence, mode %d: a record dropped by recovery resurfaced after the second crash", path, mode) + } + } + }) + } +} + +// The fence counts its bytes after the fsync, by path; a repeated recovery +// with no WAL write since skips the fence (a new volume's second recovery), +// and one after a write fences again. +func TestWALStoreV3FenceCountsAndSkipsARepeat(t *testing.T) { + for _, path := range []string{"punch", "zero"} { + t.Run(path, func(t *testing.T) { + if path == "zero" { + punchHoleFn = func(*os.File, int64, int64) error { return errFencePunchUnsupported } + t.Cleanup(func() { punchHoleFn = punchHole }) + } + const walSize = 256 * 1024 + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 64, 4096, walSize, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + first := s.CheckpointPersistence() // creation recovers once, then this Recover + fenced := first.FencePunched + first.FenceZeroed + if fenced != walSize { + t.Fatalf("a new store's first recovery fenced %d bytes, want the whole WAL %d: %+v", fenced, walSize, first) + } + punchExpected := path == "punch" && runtime.GOOS == "linux" + if punchExpected != (first.FencePunched == walSize) || (!punchExpected && first.FenceZeroed != walSize) { + t.Fatalf("%s path on %s: punched=%d zeroed=%d", path, runtime.GOOS, first.FencePunched, first.FenceZeroed) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + second := s.CheckpointPersistence() + if second.FenceSkips != first.FenceSkips+1 || second.FencePunched+second.FenceZeroed != fenced { + t.Fatalf("a repeated recovery with no WAL write: skips=%d fenced %d -> %d", second.FenceSkips, fenced, second.FencePunched+second.FenceZeroed) + } + if _, err := s.Write(1, blk(1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + third := s.CheckpointPersistence() + if third.FenceSkips != second.FenceSkips || third.FencePunched+third.FenceZeroed <= fenced { + t.Fatalf("a recovery after a WAL write must fence again: %+v", third) + } + }) + } +} + +// A same-open recovery whose head did not move still fences when the WAL +// region was written since the last fence: here records 4 and 5 were +// appended and 4 is torn, so the head stays at 3 while 5 still sits behind +// it. Skipping that fence (the same range key) would let 5 resurface once a +// new record of 4's size refills its place and the store crashes. +func TestWALStoreV3SameOpenRecoveryAfterWritesStillFences(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + writeSynced(t, s, 1, 3) + if _, err := s.Recover(); err != nil { // fences at head 3 + t.Fatal(err) + } + for _, lba := range []uint32{4, 5} { + if _, err := s.Write(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + } + damageOpenRecord(t, s, 4) + skips := s.CheckpointPersistence().FenceSkips + if _, err := s.Recover(); err != nil { // head 3 again: the same range key + t.Fatal(err) + } + skipped := s.CheckpointPersistence().FenceSkips != skips + if bytes.Equal(readV3(t, s, 5), blk(5)) { + t.Fatal("the recovery kept LSN 5 above the torn 4") + } + if _, err := s.Write(9, blk(0x99)); err != nil { // refills 4's place, same size + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + defer r.Close() + if bytes.Equal(readV3(t, r, 5), blk(5)) { + t.Fatalf("a record dropped by a same-open recovery resurfaced after the crash (its fence skipped: %v)", skipped) + } + if skipped { + t.Fatal("a recovery after WAL writes skipped its fence") + } +} + +// damageOpenRecord flips one payload byte of the WAL record carrying lsn +// through the open store's own file (no second handle, which a locked file +// refuses on Windows). +func damageOpenRecord(t *testing.T, s *WALStore, lsn uint64) { + t.Helper() + d := s.v3.pub.current() + r, err := scanWALV3(s.fd, d) + if err != nil { + t.Fatal(err) + } + for _, rec := range r.Records { + if rec.Entry.LSN != lsn { + continue + } + size := uint64(walEntryHeaderSizeV3 + len(rec.Entry.Data)) + off := int64(d.WALOffset+(rec.End-size)%d.WALSize) + walEntryPrefixSizeV3 + 100 + x := []byte{0} + if _, err := s.fd.ReadAt(x, off); err != nil { + t.Fatal(err) + } + x[0] ^= 0xFF + if _, err := s.fd.WriteAt(x, off); err != nil { + t.Fatal(err) + } + return + } + t.Fatalf("no WAL record with LSN %d", lsn) +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 0fb26b537a..ef489680d2 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -27,6 +27,7 @@ import ( // migration tool or restore into a newly created volume. BASE mutations use // install handles; raw extent writes and frontier jumps remain refused. type walStoreV3State struct { + lastFence *fenceRecordV3 // the last completed fence in this open (recovery only) // layoutFresh mirrors the descriptor's layout identity: set while the // local root is fresh, when no guest write may be acknowledged. layoutFresh atomic.Bool @@ -191,6 +192,24 @@ func probeWALStoreV3At(r io.ReaderAt) error { // tests. var testSkipFenceOnRecoverV3 bool +// punchHoleFn is punchHole; tests replace it to force the zero-write path. +var punchHoleFn = punchHole + +// errFencePunchUnsupported is a hole punch the platform cannot do: the +// fence writes zeros instead. +var errFencePunchUnsupported = errors.New("storage: hole punching unsupported") + +// fenceRecordV3 is the last completed fence: its range key, and the writer +// and that writer's WAL write count when it completed. A fence with the same +// key, the same writer and no WAL write since would change no byte. +type fenceRecordV3 struct { + nonce [16]byte + E, floor, walSize uint64 + walOffset uint64 + writer *walWriterV3 + writesAtFence uint64 +} + // FormatV3 reports whether the store uses the v3 format. func (s *WALStore) FormatV3() bool { return s.v3 != nil } @@ -773,10 +792,46 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u if len(ranges) == 0 || testSkipFenceOnRecoverV3 { return nil } - return s.syncFile(func() error { + v := s.v3 + rec := fenceRecordV3{nonce: v.pub.current().Nonce, E: E, floor: floor, walSize: walSize, walOffset: walOffset, writer: v.w} + if last := v.lastFence; last != nil && rec.writer != nil && last.writer == rec.writer && + last.nonce == rec.nonce && last.E == E && last.floor == floor && last.walSize == walSize && last.walOffset == walOffset && + rec.writer.writeCountV3() == last.writesAtFence { + // The same range was fenced and fsynced in this open, and nothing has + // written the WAL region since: the fence would change no byte (a new + // volume's second recovery). + s.fenceSkips.Add(1) + return nil + } + if rec.writer != nil { + rec.writesAtFence = rec.writer.writeCountV3() + } + mode, err := configuredAllocationMode() + if err != nil { + return err + } + punch := mode == "sparse" // a prezeroed store stays allocated: zero writes + var punched, zeroed uint64 + err = s.syncFile(func() error { const chunk = 64 * 1024 - zero := make([]byte, chunk) + var zero []byte for _, r := range ranges { + if punch { + perr := punchHoleFn(s.fd, int64(walOffset+r.Off), int64(r.Len)) + if perr == nil { + punched += r.Len + continue + } + if !punchUnsupported(perr) { + perr = fmt.Errorf("storage: v3 drop fence: %w", perr) + s.latchV3(perr) + return perr + } + punch = false // the filesystem cannot punch: zeros from here on + } + if zero == nil { + zero = make([]byte, chunk) + } for done := uint64(0); done < r.Len; { n := min(r.Len-done, chunk) if _, err := s.fd.WriteAt(zero[:n], int64(walOffset+r.Off+done)); err != nil { @@ -786,9 +841,18 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u } done += n } + zeroed += r.Len } return nil }, s.fd.Sync) + if err != nil { + return err + } + // The fence counts only after its fsync. + s.fencePunchedBytes.Add(punched) + s.fenceZeroBytes.Add(zeroed) + v.lastFence = &rec + return nil } // appendWriteV3 is the v3 body of Write's append, under s.mu. DurableLSN is diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index c7244703ef..9e17dd9ddd 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -79,7 +79,7 @@ stateDiagram-v2 | — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | | — | OpenRefused | the file's header carries a removed experimental engine's magic (smartwal, parallel-walstore): refused typed under every selector, read-only, never modified | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001`, `INV-RECOVERY-PROGRESS-WINDOW-001` | -| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait); a primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (otherwise not Healthy, `NotReadyReason` naming both profiles, ahead of the backend's own refusal) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held`; `core/host/volume/workspace_startup.go` `noteAckProfile` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-001`, `INV-ATTACH-ASSIGNMENT-BOUND-001`, `INV-LAYOUT-REMOTE-CAPABILITIES-001` | +| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait); a primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (otherwise not Healthy, `NotReadyReason` naming both profiles, ahead of the backend's own refusal) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held`; `core/host/volume/workspace_startup.go` `noteAckProfile` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-FENCE-PUNCH-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-001`, `INV-ATTACH-ASSIGNMENT-BOUND-001`, `INV-LAYOUT-REMOTE-CAPABILITIES-001` | | Recovering | Serving (v1.1 upgrade, clean-stop seed) | the chunk layer attaches an unmarked store on the draft v1.1 format (lab builds only), after Recover and the storage claim: each whole local chunk is written Rebuilt all → U, Hash → HU, Commit → HP with HEAD's hash (a chunk HEAD does not name: the zero chunk's) only when all hold: a clean-stop proof (the HEAD the claim was built on was a committed, idle detach, `DetachedBy`), its claim id is the store's layout claim id, and its position is the store's synced position the pages are valid through; otherwise each whole local chunk is U (left to the compare pass); partial and absent chunks are classified alike in both; a marked store never seeds | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `INV-CHUNK-RECORD-SEED-001`, `INV-CHUNK-RECORD-UPGRADE-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` | @@ -722,7 +722,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-W-CHECKPOINT-CLAMP-001` | A v3 checkpoint never exceeds the acknowledged W; entries the flusher wrote to the extent above the published checkpoint stay retry work, so a later Sync and flusher cycle advance the checkpoint and map coverage together. | M1 write lifecycle: InExtent → Checkpointed (v3) | `core/storage/walstore_v3.go` `WALStore.persistCheckpointV3`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.persistOwnedMapCheckpointV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | — | STUB | | `INV-WAL-V3-W-SETWMODE-001` | `SetWMode` first syncs every write admitted before it under the old mode, then publishes the new mode while holding the v3 leader role, so no Sync batch acknowledges under a mode other than the descriptor's. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.SetWMode`, `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`) | — | DORMANT | | `INV-WAL-V3-W-RECOVER-STRADDLE-001` | No v3 W publication or Sync acknowledgement straddles a recovery: a Sync whose completion sees a changed recovery generation is refused, and recovery sets the acknowledged W to its recovered prefix R. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.refreshW`, `WALStore.syncWALBatchV3Internal`; `core/storage/walstore.go` `WALStore.syncWithPhases` | `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`) | — | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes the logical WAL interval [E, floor + WALSize), floor being the both-slot same-nonce reuse floor, fsyncs it through the leaf, and only then publishes retainedHead = E. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | +| `INV-WAL-V3-FENCE-PUNCH-001` | The fence deallocates its range (a hole punch, which reads zeros) on a sparse store where the filesystem can, else writes zeros; a recovery skips the fence only when the same range was fenced and fsynced in this open with no WAL write since. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`; `core/storage/fence_punch_linux.go` `punchHole`; `core/storage/wal_io_v3.go` `writeCountV3` | `TestWALStoreV3FenceBothPathsReplayNoStaleRecord`, `TestWALStoreV3FenceCountsAndSkipsARepeat`, `TestWALStoreV3SameOpenRecoveryAfterWritesStillFences` (`core/storage/walstore_fence_punch_v3_test.go`) | `WALFormat` `NoResurrection` | ACTIVE | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes the logical WAL interval [E, floor + WALSize), floor being the both-slot same-nonce reuse floor, fsyncs it through the leaf, and only then publishes retainedHead = E. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FenceBothPathsReplayNoStaleRecord` (`core/storage/walstore_fence_punch_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | | `INV-WAL-V3-FENCE-EXACT-001` | The v3 drop fence changes only the bytes of [E, floor + WALSize) mapped modulo WALSize, in at most two ranges split at the physical wrap; no byte before E or outside the interval changes. | M1 Recovering → Serving (v3) | `core/storage/recovery_v3.go` `fenceRangesV3`; `core/storage/walstore_v3.go` `WALStore.fenceV3` | `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | — | STUB | | `INV-WAL-V3-NO-RESURRECTION-001` | A WAL record dropped by one v3 recovery is never replayed by a later recovery, also after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | | `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused with `ErrResetNotPreserved`, writing nothing, unless the dirty map is empty and CheckpointLSN is at least every appended LSN (and so equals the acknowledged W). | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | DORMANT | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 74295b4752..a7adccc05e 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -29,6 +29,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released. write waiting for WAL space now sees space freed every step rather than once per whole-WAL cycle. Status reports the reclaim progress in `CheckpointPersistence`: `ReclaimedBytes`, `BoundedCycles`, `FlusherPhase`, `CycleStarted`, `CycleExtentBytes` and `LastExtentWrite`. +- Recovery's WAL fence no longer writes the whole WAL as zeros on every open: on Linux, with the default sparse + allocation, it deallocates the range (a hole punch, which reads as zeros), falling back to zero writes where the + filesystem cannot; a new volume's second recovery skips the fence its first one just made. Status counts the bytes + in `CheckpointPersistence.FencePunched`, `FenceZeroed` and `FenceSkips`. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 75ab8ed698..758823f346 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -225,6 +225,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].CheckpointPersistence.CheckpointSteps.Nanos` | object | cumulative nanoseconds per step name | | `Volumes[].CheckpointPersistence.CheckpointSteps.Count` | object | how many times each step ran | | `Volumes[].CheckpointPersistence.CheckpointSteps.Bytes` | object | bytes each writing step wrote (map_write, slot_write) | +| `Volumes[].CheckpointPersistence.FencePunched` | uint64 | WAL fence bytes deallocated by hole punching in this open, counted after the fsync | +| `Volumes[].CheckpointPersistence.FenceZeroed` | uint64 | WAL fence bytes written as zeros in this open (no hole punching), counted after the fsync | +| `Volumes[].CheckpointPersistence.FenceSkips` | uint64 | recovery fences skipped: the same range was fenced in this open with no WAL write since | | `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | | `Volumes[].Chunk.CurrentCut` | object | active cut phase; absent when idle (omitted when empty) | | `Volumes[].Chunk.CurrentCut.attempt_started_at` | time (RFC 3339) | start of the whole attempt, unchanged across phase visits | From af34018f4613f8006bed9c18d61bab44f70268be Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 00:34:39 -0800 Subject: [PATCH 5/9] storage: a fence on a store without open v3 state keys no repeat fenceV3 is also called on a bare store (a test of the restore frontier); the repeat key needs the descriptor publisher, so without it the fence runs and records nothing. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/walstore_v3.go | 31 +++++++++++++---------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index ef489680d2..f49bfb0e87 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -793,18 +793,21 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u return nil } v := s.v3 - rec := fenceRecordV3{nonce: v.pub.current().Nonce, E: E, floor: floor, walSize: walSize, walOffset: walOffset, writer: v.w} - if last := v.lastFence; last != nil && rec.writer != nil && last.writer == rec.writer && - last.nonce == rec.nonce && last.E == E && last.floor == floor && last.walSize == walSize && last.walOffset == walOffset && - rec.writer.writeCountV3() == last.writesAtFence { - // The same range was fenced and fsynced in this open, and nothing has - // written the WAL region since: the fence would change no byte (a new - // volume's second recovery). - s.fenceSkips.Add(1) - return nil - } - if rec.writer != nil { - rec.writesAtFence = rec.writer.writeCountV3() + var rec *fenceRecordV3 // nil: no open store state to key a repeat on + if v != nil && v.pub != nil { + rec = &fenceRecordV3{nonce: v.pub.current().Nonce, E: E, floor: floor, walSize: walSize, walOffset: walOffset, writer: v.w} + if last := v.lastFence; last != nil && rec.writer != nil && last.writer == rec.writer && + last.nonce == rec.nonce && last.E == E && last.floor == floor && last.walSize == walSize && last.walOffset == walOffset && + rec.writer.writeCountV3() == last.writesAtFence { + // The same range was fenced and fsynced in this open, and nothing + // has written the WAL region since: the fence would change no byte + // (a new volume's second recovery). + s.fenceSkips.Add(1) + return nil + } + if rec.writer != nil { + rec.writesAtFence = rec.writer.writeCountV3() + } } mode, err := configuredAllocationMode() if err != nil { @@ -851,7 +854,9 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u // The fence counts only after its fsync. s.fencePunchedBytes.Add(punched) s.fenceZeroBytes.Add(zeroed) - v.lastFence = &rec + if rec != nil { + v.lastFence = rec + } return nil } From e709950124596d82dfb732ebbf2520fb9b86b0b8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 00:57:37 -0800 Subject: [PATCH 6/9] storage: the recovery fence zero-fills in 4 MiB slices The fence stays a zero fill (a punched WAL would make the next lap's appends allocating writes, each fsync committing metadata); the hole punch is removed. The fill now runs in 4 MiB slices, each written, fsynced, and only then counted (FenceZeroed) and reported to fenceSliceHook, the per-slice recovery-progress hook: a recovery over a slow disk shows progress every slice and the journal never takes the whole WAL as one burst. The repeat skip stays: a new volume's second recovery does not fill again. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/checkpoint_diagnostics.go | 4 +- .../core/storage/fence_punch_linux.go | 21 -- .../core/storage/fence_punch_other.go | 13 -- seaweed-block/core/storage/walstore.go | 4 +- .../storage/walstore_fence_punch_v3_test.go | 152 -------------- .../storage/walstore_fence_slice_v3_test.go | 195 ++++++++++++++++++ seaweed-block/core/storage/walstore_v3.go | 90 ++++---- seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/releases/v1.1.md | 7 +- seaweed-block/docs/status-schema.md | 3 +- 10 files changed, 249 insertions(+), 246 deletions(-) delete mode 100644 seaweed-block/core/storage/fence_punch_linux.go delete mode 100644 seaweed-block/core/storage/fence_punch_other.go delete mode 100644 seaweed-block/core/storage/walstore_fence_punch_v3_test.go create mode 100644 seaweed-block/core/storage/walstore_fence_slice_v3_test.go diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 6aae6678ba..e3c28d5839 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -34,8 +34,7 @@ type CheckpointPersistenceStatus struct { CycleExtentBytes uint64 // extent bytes the cycle in progress (or the latest) has written LastExtentWrite time.Time // when the flusher last wrote extent bytes; zero if never in this open CheckpointSteps CheckpointStepStatus // the checkpoint's step in progress and its per-step time, count and bytes - FencePunched uint64 // WAL fence bytes deallocated by hole punching in this open, counted after the fsync - FenceZeroed uint64 // WAL fence bytes written as zeros in this open (no hole punching), counted after the fsync + FenceZeroed uint64 // WAL fence bytes written as zeros in this open, counted per 4 MiB slice after its fsync FenceSkips uint64 // recovery fences skipped: the same range was fenced in this open with no WAL write since } @@ -80,7 +79,6 @@ func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { FlusherPhase: i.phaseName(), CycleExtentBytes: i.cycleExtentBytes.Load(), CheckpointSteps: s.ckpt.status(), - FencePunched: s.fencePunchedBytes.Load(), FenceZeroed: s.fenceZeroBytes.Load(), FenceSkips: s.fenceSkips.Load(), } diff --git a/seaweed-block/core/storage/fence_punch_linux.go b/seaweed-block/core/storage/fence_punch_linux.go deleted file mode 100644 index f6d2f3d2db..0000000000 --- a/seaweed-block/core/storage/fence_punch_linux.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build linux - -package storage - -import ( - "errors" - "os" - - "golang.org/x/sys/unix" -) - -// punchHole deallocates [off, off+n) of f, keeping its size: the range reads -// zeros afterwards. The caller fsyncs. -func punchHole(f *os.File, off, n int64) error { - return unix.Fallocate(int(f.Fd()), unix.FALLOC_FL_PUNCH_HOLE|unix.FALLOC_FL_KEEP_SIZE, off, n) -} - -// punchUnsupported reports a filesystem or kernel without hole punching. -func punchUnsupported(err error) bool { - return errors.Is(err, errFencePunchUnsupported) || errors.Is(err, unix.EOPNOTSUPP) || errors.Is(err, unix.ENOSYS) -} diff --git a/seaweed-block/core/storage/fence_punch_other.go b/seaweed-block/core/storage/fence_punch_other.go deleted file mode 100644 index bf7e1a013a..0000000000 --- a/seaweed-block/core/storage/fence_punch_other.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !linux - -package storage - -import ( - "errors" - "os" -) - -// punchHole is unsupported off Linux: the fence writes zeros instead. -func punchHole(*os.File, int64, int64) error { return errFencePunchUnsupported } - -func punchUnsupported(err error) bool { return errors.Is(err, errFencePunchUnsupported) } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index d41ccd601c..2f859fe2d8 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -90,7 +90,6 @@ type WALStore struct { lastStop atomic.Pointer[StoreStopPhases] closedCheckpoint atomic.Pointer[MapCheckpointPhases] ckpt checkpointSteps // the flusher checkpoint's per-step timing - fencePunchedBytes atomic.Uint64 // WAL fence bytes deallocated (hole punch), counted after the fsync fenceZeroBytes atomic.Uint64 // WAL fence bytes written as zeros, counted after the fsync fenceSkips atomic.Uint64 // fences skipped: the same range was fenced in this open with no WAL write since testDestructiveSnapshot func() // nil scheduling control, before any capture lock @@ -166,7 +165,8 @@ type WALStore struct { testAfterAdmit func() // testBeforeFileSync, when set, runs in syncFile just before fileSyncMu // is taken. Tests only. - testBeforeFileSync func() + testBeforeFileSync func() + testAfterFenceFsync func() // after each fence slice's fsync returns; tests only // Generations cover completed append attempts and recovery publication. walMutation atomic.Uint64 durableMutation atomic.Uint64 diff --git a/seaweed-block/core/storage/walstore_fence_punch_v3_test.go b/seaweed-block/core/storage/walstore_fence_punch_v3_test.go deleted file mode 100644 index 15af17293a..0000000000 --- a/seaweed-block/core/storage/walstore_fence_punch_v3_test.go +++ /dev/null @@ -1,152 +0,0 @@ -package storage - -import ( - "bytes" - "os" - "path/filepath" - "runtime" - "testing" -) - -// The fence on both of its paths: hole punching (Linux, sparse) and zero -// writes (no punching). On each, records dropped by one recovery do not -// resurface after a second crash. -func TestWALStoreV3FenceBothPathsReplayNoStaleRecord(t *testing.T) { - for _, path := range []string{"punch", "zero"} { - t.Run(path, func(t *testing.T) { - if path == "zero" { - punchHoleFn = func(*os.File, int64, int64) error { return errFencePunchUnsupported } - t.Cleanup(func() { punchHoleFn = punchHole }) - } - for _, mode := range []WMode{WModeLagged, WModeStrict} { - if resurrectionSchedule(t, mode, false) { - t.Fatalf("%s fence, mode %d: a record dropped by recovery resurfaced after the second crash", path, mode) - } - } - }) - } -} - -// The fence counts its bytes after the fsync, by path; a repeated recovery -// with no WAL write since skips the fence (a new volume's second recovery), -// and one after a write fences again. -func TestWALStoreV3FenceCountsAndSkipsARepeat(t *testing.T) { - for _, path := range []string{"punch", "zero"} { - t.Run(path, func(t *testing.T) { - if path == "zero" { - punchHoleFn = func(*os.File, int64, int64) error { return errFencePunchUnsupported } - t.Cleanup(func() { punchHoleFn = punchHole }) - } - const walSize = 256 * 1024 - s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 64, 4096, walSize, WModeLagged, 4) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = s.Close() }) - s.DisableAutoFlushForRecoveryTest() - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - first := s.CheckpointPersistence() // creation recovers once, then this Recover - fenced := first.FencePunched + first.FenceZeroed - if fenced != walSize { - t.Fatalf("a new store's first recovery fenced %d bytes, want the whole WAL %d: %+v", fenced, walSize, first) - } - punchExpected := path == "punch" && runtime.GOOS == "linux" - if punchExpected != (first.FencePunched == walSize) || (!punchExpected && first.FenceZeroed != walSize) { - t.Fatalf("%s path on %s: punched=%d zeroed=%d", path, runtime.GOOS, first.FencePunched, first.FenceZeroed) - } - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - second := s.CheckpointPersistence() - if second.FenceSkips != first.FenceSkips+1 || second.FencePunched+second.FenceZeroed != fenced { - t.Fatalf("a repeated recovery with no WAL write: skips=%d fenced %d -> %d", second.FenceSkips, fenced, second.FencePunched+second.FenceZeroed) - } - if _, err := s.Write(1, blk(1)); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - third := s.CheckpointPersistence() - if third.FenceSkips != second.FenceSkips || third.FencePunched+third.FenceZeroed <= fenced { - t.Fatalf("a recovery after a WAL write must fence again: %+v", third) - } - }) - } -} - -// A same-open recovery whose head did not move still fences when the WAL -// region was written since the last fence: here records 4 and 5 were -// appended and 4 is torn, so the head stays at 3 while 5 still sits behind -// it. Skipping that fence (the same range key) would let 5 resurface once a -// new record of 4's size refills its place and the store crashes. -func TestWALStoreV3SameOpenRecoveryAfterWritesStillFences(t *testing.T) { - s, path := newStoreV3(t, WModeLagged) - writeSynced(t, s, 1, 3) - if _, err := s.Recover(); err != nil { // fences at head 3 - t.Fatal(err) - } - for _, lba := range []uint32{4, 5} { - if _, err := s.Write(lba, blk(byte(lba))); err != nil { - t.Fatal(err) - } - } - damageOpenRecord(t, s, 4) - skips := s.CheckpointPersistence().FenceSkips - if _, err := s.Recover(); err != nil { // head 3 again: the same range key - t.Fatal(err) - } - skipped := s.CheckpointPersistence().FenceSkips != skips - if bytes.Equal(readV3(t, s, 5), blk(5)) { - t.Fatal("the recovery kept LSN 5 above the torn 4") - } - if _, err := s.Write(9, blk(0x99)); err != nil { // refills 4's place, same size - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - crashRecoveryHardeningStore(t, s) - r := mustReopenV3(t, path) - defer r.Close() - if bytes.Equal(readV3(t, r, 5), blk(5)) { - t.Fatalf("a record dropped by a same-open recovery resurfaced after the crash (its fence skipped: %v)", skipped) - } - if skipped { - t.Fatal("a recovery after WAL writes skipped its fence") - } -} - -// damageOpenRecord flips one payload byte of the WAL record carrying lsn -// through the open store's own file (no second handle, which a locked file -// refuses on Windows). -func damageOpenRecord(t *testing.T, s *WALStore, lsn uint64) { - t.Helper() - d := s.v3.pub.current() - r, err := scanWALV3(s.fd, d) - if err != nil { - t.Fatal(err) - } - for _, rec := range r.Records { - if rec.Entry.LSN != lsn { - continue - } - size := uint64(walEntryHeaderSizeV3 + len(rec.Entry.Data)) - off := int64(d.WALOffset+(rec.End-size)%d.WALSize) + walEntryPrefixSizeV3 + 100 - x := []byte{0} - if _, err := s.fd.ReadAt(x, off); err != nil { - t.Fatal(err) - } - x[0] ^= 0xFF - if _, err := s.fd.WriteAt(x, off); err != nil { - t.Fatal(err) - } - return - } - t.Fatalf("no WAL record with LSN %d", lsn) -} diff --git a/seaweed-block/core/storage/walstore_fence_slice_v3_test.go b/seaweed-block/core/storage/walstore_fence_slice_v3_test.go new file mode 100644 index 0000000000..674da839e3 --- /dev/null +++ b/seaweed-block/core/storage/walstore_fence_slice_v3_test.go @@ -0,0 +1,195 @@ +package storage + +import ( + "bytes" + "errors" + "path/filepath" + "testing" +) + +// The fence counts its bytes after the fsync; a repeated recovery with no +// WAL write since skips the fence (a new volume's second recovery), and one +// after a write fences again. +func TestWALStoreV3FenceCountsAndSkipsARepeat(t *testing.T) { + const walSize = 256 * 1024 + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 64, 4096, walSize, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + first := s.CheckpointPersistence() // creation recovers once, then this Recover + if first.FenceZeroed != walSize { + t.Fatalf("a new store fenced %d bytes, want the whole WAL %d once: %+v", first.FenceZeroed, walSize, first) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + second := s.CheckpointPersistence() + if second.FenceSkips != first.FenceSkips+1 || second.FenceZeroed != first.FenceZeroed { + t.Fatalf("a repeated recovery with no WAL write: skips %d -> %d, zeroed %d -> %d", first.FenceSkips, second.FenceSkips, first.FenceZeroed, second.FenceZeroed) + } + if _, err := s.Write(1, blk(1)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + third := s.CheckpointPersistence() + if third.FenceSkips != second.FenceSkips || third.FenceZeroed <= second.FenceZeroed { + t.Fatalf("a recovery after a WAL write must fence again: %+v", third) + } +} + +// A same-open recovery whose head did not move still fences when the WAL +// region was written since the last fence: here records 4 and 5 were +// appended and 4 is torn, so the head stays at 3 while 5 still sits behind +// it. Skipping that fence (the same range key) would let 5 resurface once a +// new record of 4's size refills its place and the store crashes. +func TestWALStoreV3SameOpenRecoveryAfterWritesStillFences(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + writeSynced(t, s, 1, 3) + if _, err := s.Recover(); err != nil { // fences at head 3 + t.Fatal(err) + } + for _, lba := range []uint32{4, 5} { + if _, err := s.Write(lba, blk(byte(lba))); err != nil { + t.Fatal(err) + } + } + damageOpenRecord(t, s, 4) + skips := s.CheckpointPersistence().FenceSkips + if _, err := s.Recover(); err != nil { // head 3 again: the same range key + t.Fatal(err) + } + skipped := s.CheckpointPersistence().FenceSkips != skips + if bytes.Equal(readV3(t, s, 5), blk(5)) { + t.Fatal("the recovery kept LSN 5 above the torn 4") + } + if _, err := s.Write(9, blk(0x99)); err != nil { // refills 4's place, same size + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r := mustReopenV3(t, path) + defer r.Close() + if bytes.Equal(readV3(t, r, 5), blk(5)) { + t.Fatalf("a record dropped by a same-open recovery resurfaced after the crash (its fence skipped: %v)", skipped) + } + if skipped { + t.Fatal("a recovery after WAL writes skipped its fence") + } +} + +// The fence runs in 4 MiB slices: each is zero-written, fsynced, and only +// then counted and reported to the slice hook, in order. +func TestWALStoreV3FenceSlicesCountAfterEachSync(t *testing.T) { + const walSize = 2*fenceSliceBytes + 1<<20 + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 4096, 4096, walSize, WModeLagged, 64) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + writeSynced(t, s, 1, 1) // moves the head: the next recovery fences again + syncs := 0 // the fence's fsyncs that returned + s.testAfterFenceFsync = func() { syncs++ } + t.Cleanup(func() { s.testAfterFenceFsync = nil }) + var slices []uint64 + var syncsAt []int + before := s.CheckpointPersistence() + s.v3.fenceSliceHook = func(n uint64) { + counted := s.fenceZeroBytes.Load() - before.FenceZeroed // atomics: the hook runs under the store lock + var reported uint64 + for _, b := range slices { + reported += b + } + if counted != reported+n { + t.Errorf("slice %d reached the hook before it was counted: counted %d, reported %d + %d", len(slices), counted, reported, n) + } + slices = append(slices, n) + syncsAt = append(syncsAt, syncs) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + fenced := s.CheckpointPersistence().FenceZeroed - before.FenceZeroed + var sum uint64 + for i, n := range slices { + if n == 0 || n > fenceSliceBytes { + t.Fatalf("slice %d is %d bytes", i, n) + } + if syncsAt[i] != i+1 { + t.Fatalf("slice %d reached the hook after %d fence fsyncs, want %d (one per slice; syncs %v)", i, syncsAt[i], i+1, syncsAt) + } + sum += n + } + if len(slices) < 3 || sum != fenced || fenced == 0 { + t.Fatalf("slices %v (sum %d), fenced %d: want at least 3 slices of at most 4 MiB covering the fence", slices, sum, fenced) + } +} + +// A slice that fails mid-fence (the store latched a fault after the first +// slice) stops the fence: only the slices whose fsync returned are counted, +// and the hook saw exactly those. +func TestWALStoreV3FenceSliceFailureCountsOnlyCompletedSlices(t *testing.T) { + const walSize = 2*fenceSliceBytes + 1<<20 + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 4096, 4096, walSize, WModeLagged, 64) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + writeSynced(t, s, 1, 1) + ioErr := errors.New("injected fence I/O fault") + hooked := 0 + s.v3.fenceSliceHook = func(uint64) { + if hooked++; hooked == 1 { + s.latchV3(ioErr) // the next slice's write/fsync step refuses + } + } + before := s.CheckpointPersistence() + if _, err := s.Recover(); !errors.Is(err, ioErr) { + t.Fatalf("recovery over a failing slice: %v", err) + } + if got := s.CheckpointPersistence().FenceZeroed - before.FenceZeroed; got != fenceSliceBytes || hooked != 1 { + t.Fatalf("after the 2nd slice failed: zeroed %d (want one slice, %d), hook calls %d", got, fenceSliceBytes, hooked) + } +} + +// damageOpenRecord flips one payload byte of the WAL record carrying lsn +// through the open store's own file (no second handle, which a locked file +// refuses on Windows). +func damageOpenRecord(t *testing.T, s *WALStore, lsn uint64) { + t.Helper() + d := s.v3.pub.current() + r, err := scanWALV3(s.fd, d) + if err != nil { + t.Fatal(err) + } + for _, rec := range r.Records { + if rec.Entry.LSN != lsn { + continue + } + size := uint64(walEntryHeaderSizeV3 + len(rec.Entry.Data)) + off := int64(d.WALOffset+(rec.End-size)%d.WALSize) + walEntryPrefixSizeV3 + 100 + x := []byte{0} + if _, err := s.fd.ReadAt(x, off); err != nil { + t.Fatal(err) + } + x[0] ^= 0xFF + if _, err := s.fd.WriteAt(x, off); err != nil { + t.Fatal(err) + } + return + } + t.Fatalf("no WAL record with LSN %d", lsn) +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index f49bfb0e87..81363682e4 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -28,6 +28,11 @@ import ( // install handles; raw extent writes and frontier jumps remain refused. type walStoreV3State struct { lastFence *fenceRecordV3 // the last completed fence in this open (recovery only) + // fenceSliceHook, when set, is told the bytes of each fence slice once + // that slice's fsync has returned (recovery progress); nil: none. It runs + // on the recovering goroutine, which holds the store lock: it must not + // take a store lock (or call anything that does, such as CheckpointLSN). + fenceSliceHook func(bytes uint64) // layoutFresh mirrors the descriptor's layout identity: set while the // local root is fresh, when no guest write may be acknowledged. layoutFresh atomic.Bool @@ -192,12 +197,10 @@ func probeWALStoreV3At(r io.ReaderAt) error { // tests. var testSkipFenceOnRecoverV3 bool -// punchHoleFn is punchHole; tests replace it to force the zero-write path. -var punchHoleFn = punchHole - -// errFencePunchUnsupported is a hole punch the platform cannot do: the -// fence writes zeros instead. -var errFencePunchUnsupported = errors.New("storage: hole punching unsupported") +// fenceSliceBytes is one fence slice: its zero writes and their fsync, so a +// recovery over a slow disk reports progress every slice and the journal +// never takes the whole WAL as one burst. +const fenceSliceBytes = 4 << 20 // fenceRecordV3 is the last completed fence: its range key, and the writer // and that writer's WAL write count when it completed. A fence with the same @@ -783,7 +786,11 @@ func (s *WALStore) recoverV3(ctx context.Context) (uint64, error) { } // fenceV3 zeroes exactly the fence ranges and fsyncs them through the leaf -// before any admission (DESIGN 6.6). A write error latches inside the leaf. +// before any admission (DESIGN 6.6), in slices of fenceSliceBytes: each is +// zero writes, then its own fsync, and only then counts and reaches +// fenceSliceHook. The WAL stays allocated (zero-filled, not punched), so the +// next lap's appends are overwrites. A write or fsync error latches inside +// the leaf. func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset uint64) error { ranges, err := fenceRangesV3(E, floor, walSize, sameNonce) if err != nil { @@ -809,51 +816,42 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u rec.writesAtFence = rec.writer.writeCountV3() } } - mode, err := configuredAllocationMode() - if err != nil { - return err - } - punch := mode == "sparse" // a prezeroed store stays allocated: zero writes - var punched, zeroed uint64 - err = s.syncFile(func() error { - const chunk = 64 * 1024 - var zero []byte - for _, r := range ranges { - if punch { - perr := punchHoleFn(s.fd, int64(walOffset+r.Off), int64(r.Len)) - if perr == nil { - punched += r.Len - continue + zero := make([]byte, 64*1024) + for _, r := range ranges { + for done := uint64(0); done < r.Len; { + n := min(r.Len-done, fenceSliceBytes) + off := int64(walOffset + r.Off + done) + err := s.syncFile(func() error { + for w := uint64(0); w < n; { + k := min(n-w, uint64(len(zero))) + if _, err := s.fd.WriteAt(zero[:k], off+int64(w)); err != nil { + err = fmt.Errorf("storage: v3 drop fence: %w", err) + s.latchV3(err) + return err + } + w += k } - if !punchUnsupported(perr) { - perr = fmt.Errorf("storage: v3 drop fence: %w", perr) - s.latchV3(perr) - return perr - } - punch = false // the filesystem cannot punch: zeros from here on - } - if zero == nil { - zero = make([]byte, chunk) - } - for done := uint64(0); done < r.Len; { - n := min(r.Len-done, chunk) - if _, err := s.fd.WriteAt(zero[:n], int64(walOffset+r.Off+done)); err != nil { - err = fmt.Errorf("storage: v3 drop fence: %w", err) - s.latchV3(err) + return nil + }, func() error { + if err := s.fd.Sync(); err != nil { return err } - done += n + if h := s.testAfterFenceFsync; h != nil { + h() + } + return nil + }) + if err != nil { + return err } - zeroed += r.Len + // A slice counts only after its fsync. + s.fenceZeroBytes.Add(n) + if v != nil && v.fenceSliceHook != nil { + v.fenceSliceHook(n) + } + done += n } - return nil - }, s.fd.Sync) - if err != nil { - return err } - // The fence counts only after its fsync. - s.fencePunchedBytes.Add(punched) - s.fenceZeroBytes.Add(zeroed) if rec != nil { v.lastFence = rec } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9e17dd9ddd..15cc8d2c62 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -79,7 +79,7 @@ stateDiagram-v2 | — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | | — | OpenRefused | the file's header carries a removed experimental engine's magic (smartwal, parallel-walstore): refused typed under every selector, read-only, never modified | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001`, `INV-RECOVERY-PROGRESS-WINDOW-001` | -| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait); a primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (otherwise not Healthy, `NotReadyReason` naming both profiles, ahead of the backend's own refusal) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held`; `core/host/volume/workspace_startup.go` `noteAckProfile` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-FENCE-PUNCH-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-001`, `INV-ATTACH-ASSIGNMENT-BOUND-001`, `INV-LAYOUT-REMOTE-CAPABILITIES-001` | +| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait); a primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (otherwise not Healthy, `NotReadyReason` naming both profiles, ahead of the backend's own refusal) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held`; `core/host/volume/workspace_startup.go` `noteAckProfile` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-FENCE-SLICE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-001`, `INV-ATTACH-ASSIGNMENT-BOUND-001`, `INV-LAYOUT-REMOTE-CAPABILITIES-001` | | Recovering | Serving (v1.1 upgrade, clean-stop seed) | the chunk layer attaches an unmarked store on the draft v1.1 format (lab builds only), after Recover and the storage claim: each whole local chunk is written Rebuilt all → U, Hash → HU, Commit → HP with HEAD's hash (a chunk HEAD does not name: the zero chunk's) only when all hold: a clean-stop proof (the HEAD the claim was built on was a committed, idle detach, `DetachedBy`), its claim id is the store's layout claim id, and its position is the store's synced position the pages are valid through; otherwise each whole local chunk is U (left to the compare pass); partial and absent chunks are classified alike in both; a marked store never seeds | `core/frontend/chunkstore/layout/start.go` `Start` (`ReportCleanStop`); `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/storage/chunk_record_upgrade.go` `upgradeChunkRecordSeeded`, `seedsLineage`, `cleanStopHashes` | `INV-CHUNK-RECORD-SEED-001`, `INV-CHUNK-RECORD-UPGRADE-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | | Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-W-001` | @@ -722,8 +722,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-W-CHECKPOINT-CLAMP-001` | A v3 checkpoint never exceeds the acknowledged W; entries the flusher wrote to the extent above the published checkpoint stay retry work, so a later Sync and flusher cycle advance the checkpoint and map coverage together. | M1 write lifecycle: InExtent → Checkpointed (v3) | `core/storage/walstore_v3.go` `WALStore.persistCheckpointV3`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.persistOwnedMapCheckpointV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | — | STUB | | `INV-WAL-V3-W-SETWMODE-001` | `SetWMode` first syncs every write admitted before it under the old mode, then publishes the new mode while holding the v3 leader role, so no Sync batch acknowledges under a mode other than the descriptor's. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.SetWMode`, `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`) | — | DORMANT | | `INV-WAL-V3-W-RECOVER-STRADDLE-001` | No v3 W publication or Sync acknowledgement straddles a recovery: a Sync whose completion sees a changed recovery generation is refused, and recovery sets the acknowledged W to its recovered prefix R. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.refreshW`, `WALStore.syncWALBatchV3Internal`; `core/storage/walstore.go` `WALStore.syncWithPhases` | `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`) | — | STUB | -| `INV-WAL-V3-FENCE-PUNCH-001` | The fence deallocates its range (a hole punch, which reads zeros) on a sparse store where the filesystem can, else writes zeros; a recovery skips the fence only when the same range was fenced and fsynced in this open with no WAL write since. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`; `core/storage/fence_punch_linux.go` `punchHole`; `core/storage/wal_io_v3.go` `writeCountV3` | `TestWALStoreV3FenceBothPathsReplayNoStaleRecord`, `TestWALStoreV3FenceCountsAndSkipsARepeat`, `TestWALStoreV3SameOpenRecoveryAfterWritesStillFences` (`core/storage/walstore_fence_punch_v3_test.go`) | `WALFormat` `NoResurrection` | ACTIVE | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes the logical WAL interval [E, floor + WALSize), floor being the both-slot same-nonce reuse floor, fsyncs it through the leaf, and only then publishes retainedHead = E. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FenceBothPathsReplayNoStaleRecord` (`core/storage/walstore_fence_punch_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | +| `INV-WAL-V3-FENCE-SLICE-001` | The fence zero-writes its range in 4 MiB slices, each fsynced and only then counted as progress; a recovery skips the fence only when the same range was fenced and fsynced in this open by the same writer with no WAL write since. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`; `core/storage/wal_io_v3.go` `writeCountV3` | `TestWALStoreV3FenceCountsAndSkipsARepeat`, `TestWALStoreV3SameOpenRecoveryAfterWritesStillFences`, `TestWALStoreV3FenceSlicesCountAfterEachSync`, `TestWALStoreV3FenceSliceFailureCountsOnlyCompletedSlices` (`core/storage/walstore_fence_slice_v3_test.go`) | `WALFormat` `NoResurrection` | ACTIVE | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes the logical WAL interval [E, floor + WALSize), floor being the both-slot same-nonce reuse floor, fsyncs it through the leaf, and only then publishes retainedHead = E. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | | `INV-WAL-V3-FENCE-EXACT-001` | The v3 drop fence changes only the bytes of [E, floor + WALSize) mapped modulo WALSize, in at most two ranges split at the physical wrap; no byte before E or outside the interval changes. | M1 Recovering → Serving (v3) | `core/storage/recovery_v3.go` `fenceRangesV3`; `core/storage/walstore_v3.go` `WALStore.fenceV3` | `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | — | STUB | | `INV-WAL-V3-NO-RESURRECTION-001` | A WAL record dropped by one v3 recovery is never replayed by a later recovery, also after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB | | `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused with `ErrResetNotPreserved`, writing nothing, unless the dirty map is empty and CheckpointLSN is at least every appended LSN (and so equals the acknowledged W). | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | DORMANT | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index a7adccc05e..0a7e002f4c 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -29,10 +29,9 @@ These notes collect v1.1's changes as they land; v1.1 is not released. write waiting for WAL space now sees space freed every step rather than once per whole-WAL cycle. Status reports the reclaim progress in `CheckpointPersistence`: `ReclaimedBytes`, `BoundedCycles`, `FlusherPhase`, `CycleStarted`, `CycleExtentBytes` and `LastExtentWrite`. -- Recovery's WAL fence no longer writes the whole WAL as zeros on every open: on Linux, with the default sparse - allocation, it deallocates the range (a hole punch, which reads as zeros), falling back to zero writes where the - filesystem cannot; a new volume's second recovery skips the fence its first one just made. Status counts the bytes - in `CheckpointPersistence.FencePunched`, `FenceZeroed` and `FenceSkips`. +- Recovery's WAL fence writes its zeros in 4 MiB slices, each fsynced and counted as progress, instead of the whole + WAL as one burst; a new volume's second recovery skips the fence its first one just made (64 MiB at creation instead + of 128). Status counts the bytes in `CheckpointPersistence.FenceZeroed` and `FenceSkips`. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 758823f346..bbe3579072 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -225,8 +225,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].CheckpointPersistence.CheckpointSteps.Nanos` | object | cumulative nanoseconds per step name | | `Volumes[].CheckpointPersistence.CheckpointSteps.Count` | object | how many times each step ran | | `Volumes[].CheckpointPersistence.CheckpointSteps.Bytes` | object | bytes each writing step wrote (map_write, slot_write) | -| `Volumes[].CheckpointPersistence.FencePunched` | uint64 | WAL fence bytes deallocated by hole punching in this open, counted after the fsync | -| `Volumes[].CheckpointPersistence.FenceZeroed` | uint64 | WAL fence bytes written as zeros in this open (no hole punching), counted after the fsync | +| `Volumes[].CheckpointPersistence.FenceZeroed` | uint64 | WAL fence bytes written as zeros in this open, counted per 4 MiB slice after its fsync | | `Volumes[].CheckpointPersistence.FenceSkips` | uint64 | recovery fences skipped: the same range was fenced in this open with no WAL write since | | `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | | `Volumes[].Chunk.CurrentCut` | object | active cut phase; absent when idle (omitted when empty) | From d5c2fbdeae31421f0645008ef94460f226de0291 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 01:13:24 -0800 Subject: [PATCH 7/9] docs: regenerate the status schema for the checkpoint step fields The status schema's generated block takes its descriptions from the fields' comments: the checkpoint step fields now carry them, and the block is regenerated (STATUS_SCHEMA_UPDATE=1) instead of hand-edited. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/checkpoint_steps.go | 10 +++++----- seaweed-block/docs/status-schema.md | 12 ++++++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/storage/checkpoint_steps.go b/seaweed-block/core/storage/checkpoint_steps.go index b3bef665a9..bdfc7b6a45 100644 --- a/seaweed-block/core/storage/checkpoint_steps.go +++ b/seaweed-block/core/storage/checkpoint_steps.go @@ -61,11 +61,11 @@ func (c *checkpointSteps) enter(step int) func(bytes int) { // (the store file's descriptor slots; its fsync also writes back the file's // other dirty pages) and retire. Bytes are the bytes a step wrote. type CheckpointStepStatus struct { - Step string `json:",omitempty"` - Since time.Time `json:",omitempty"` - Nanos map[string]uint64 `json:",omitempty"` - Count map[string]uint64 `json:",omitempty"` - Bytes map[string]uint64 `json:",omitempty"` + Step string `json:",omitempty"` // the step in progress: hooks, map_write, map_fsync, leader_wait, store_lock_wait, slot_write, slot_fsync or retire + Since time.Time `json:",omitempty"` // when the step in progress started + Nanos map[string]uint64 `json:",omitempty"` // cumulative nanoseconds per step name + Count map[string]uint64 `json:",omitempty"` // how many times each step ran + Bytes map[string]uint64 `json:",omitempty"` // bytes each writing step wrote (map_write: the owned map file; slot_write: the store file's descriptor slots) } func (c *checkpointSteps) status() CheckpointStepStatus { diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index bbe3579072..ebfd88b64b 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -219,12 +219,12 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].CheckpointPersistence.CycleStarted` | time (RFC 3339) | when the flusher cycle in progress started; zero when none is | | `Volumes[].CheckpointPersistence.CycleExtentBytes` | uint64 | extent bytes the cycle in progress (or the latest) has written | | `Volumes[].CheckpointPersistence.LastExtentWrite` | time (RFC 3339) | when the flusher last wrote extent bytes; zero if never in this open | -| `Volumes[].CheckpointPersistence.CheckpointSteps` | object | the flusher checkpoint's per-step timing in this open | -| `Volumes[].CheckpointPersistence.CheckpointSteps.Step` | string | the step in progress (omitted when none): hooks, map_write, map_fsync (the owned map file), leader_wait, store_lock_wait, slot_write, slot_fsync (the store file's descriptor slots; the fsync also writes back the file's other dirty pages) or retire | -| `Volumes[].CheckpointPersistence.CheckpointSteps.Since` | time (RFC 3339) | when the step in progress started | -| `Volumes[].CheckpointPersistence.CheckpointSteps.Nanos` | object | cumulative nanoseconds per step name | -| `Volumes[].CheckpointPersistence.CheckpointSteps.Count` | object | how many times each step ran | -| `Volumes[].CheckpointPersistence.CheckpointSteps.Bytes` | object | bytes each writing step wrote (map_write, slot_write) | +| `Volumes[].CheckpointPersistence.CheckpointSteps` | object | the checkpoint's step in progress and its per-step time, count and bytes | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Step` | string | the step in progress: hooks, map_write, map_fsync, leader_wait, store_lock_wait, slot_write, slot_fsync or retire (omitted when empty) | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Since` | time (RFC 3339) | when the step in progress started (omitted when empty) | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Nanos{}` | uint64 | cumulative nanoseconds per step name (omitted when empty) | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Count{}` | uint64 | how many times each step ran (omitted when empty) | +| `Volumes[].CheckpointPersistence.CheckpointSteps.Bytes{}` | uint64 | bytes each writing step wrote (map_write: the owned map file; slot_write: the store file's descriptor slots) (omitted when empty) | | `Volumes[].CheckpointPersistence.FenceZeroed` | uint64 | WAL fence bytes written as zeros in this open, counted per 4 MiB slice after its fsync | | `Volumes[].CheckpointPersistence.FenceSkips` | uint64 | recovery fences skipped: the same range was fenced in this open with no WAL write since | | `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | From eec85d11ecb61c1c5f82f9f38f01d939bfeb4e66 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 01:26:24 -0800 Subject: [PATCH 8/9] storage: tests bound their drains and fail real fence slices The held-drain controls run the drain loop on the test goroutine with a cycle bound, and the leader-wait control joins its worker before the store's cleanup on every path. The fence's slices are checked at their fsync (the counter holds only the completed slices there), and a second slice's zero write or fsync fails through test seams: no credit for the failing slice, no completed fence recorded, the store latched. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/walstore.go | 6 +- .../storage/walstore_bounded_flush_v3_test.go | 52 +++++++++++----- .../storage/walstore_fence_slice_v3_test.go | 61 ++++++++++++++++++- seaweed-block/core/storage/walstore_v3.go | 12 ++++ 4 files changed, 112 insertions(+), 19 deletions(-) diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 2f859fe2d8..c002e8133c 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -165,8 +165,10 @@ type WALStore struct { testAfterAdmit func() // testBeforeFileSync, when set, runs in syncFile just before fileSyncMu // is taken. Tests only. - testBeforeFileSync func() - testAfterFenceFsync func() // after each fence slice's fsync returns; tests only + testBeforeFileSync func() + testBeforeFenceWrite func() error // before each fence slice's zero writes (an error fails the write); tests only + testBeforeFenceFsync func() error // before each fence slice's fsync (an error fails the fsync); tests only + testAfterFenceFsync func() // after each fence slice's fsync returns; tests only // Generations cover completed append attempts and recovery publication. walMutation atomic.Uint64 durableMutation atomic.Uint64 diff --git a/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go index c39b7f61da..cd895491a8 100644 --- a/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go +++ b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go @@ -291,15 +291,20 @@ func TestWALStoreV3HeldCheckpointEndsTheDrain(t *testing.T) { t.Fatal(err) } s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 6, anyActive: true}) - done := make(chan error, 1) - go func() { done <- s.flusher.flushOnce() }() - select { - case err := <-done: + // The drain's own loop (flushOnceInternal's), bounded on this goroutine: a + // pass that repeats its batch fails here instead of hanging the package. + p := flushPass{limit: math.MaxUint64} + ended := false + for i := 0; i < 64 && !ended; i++ { + r, err := s.flusher.flushCycle(false, p) if err != nil { t.Fatal(err) } - case <-time.After(10 * time.Second): - t.Fatal("a drain held by the recycle floor did not end") + ended = !r.more + p = r.next(r.frontier) + } + if !ended { + t.Fatal("a drain held by the recycle floor did not end within 64 cycles") } if cp := s.CheckpointLSN(); cp != 6 { t.Fatalf("checkpoint=%d, want the floor 6", cp) @@ -342,16 +347,17 @@ func TestWALStoreV3HeldThenJumpRetiresEveryEntryBelowTheCheckpoint(t *testing.T) // Held at 6: a pass writes every entry to the extent, 7..12 stay dirty. s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 6, anyActive: true}) p := flushPass{limit: math.MaxUint64} - for { + ended := false + for i := 0; i < 64 && !ended; i++ { // bounded: a pass that repeats its batch fails below r, err := s.flusher.flushCycle(false, p) if err != nil { t.Fatal(err) } - if !r.more { - p = r.next(math.MaxUint64) // the run loop's position after the held pass - break - } - p = r.next(math.MaxUint64) + ended = !r.more + p = r.next(math.MaxUint64) // after the last cycle: the run loop's position after the held pass + } + if !ended { + t.Fatal("the held pass did not end within 64 cycles") } if cp := s.CheckpointLSN(); cp != 6 || s.dm.len() != 6 { t.Fatalf("held pass: checkpoint=%d dirty=%d, want 6 and 6", cp, s.dm.len()) @@ -441,19 +447,33 @@ func TestWALStoreV3CheckpointStepsAreTimed(t *testing.T) { s.v3.syncMu.Lock() // the leader role, held elsewhere done := make(chan error, 1) go func() { done <- s.flusher.flushOnce() }() + // join releases the leader role and waits, bounded, for the drain to end + // before the store's cleanup closes it, on every path. + join := func() error { + s.v3.syncMu.Unlock() + select { + case err := <-done: + return err + case <-time.After(10 * time.Second): + t.Fatal("the drain did not end within 10 s of the leader role's release") + return nil + } + } deadline := time.Now().Add(5 * time.Second) for { if cur := s.CheckpointPersistence().CheckpointSteps; cur.Step == "leader_wait" && !cur.Since.IsZero() { break } if time.Now().After(deadline) { - s.v3.syncMu.Unlock() - t.Fatalf("a checkpoint waiting for the leader role: %+v", s.CheckpointPersistence().CheckpointSteps) + seen := s.CheckpointPersistence().CheckpointSteps + if err := join(); err != nil { + t.Errorf("drain: %v", err) + } + t.Fatalf("a checkpoint waiting for the leader role: %+v", seen) } time.Sleep(5 * time.Millisecond) } - s.v3.syncMu.Unlock() - if err := <-done; err != nil { + if err := join(); err != nil { t.Fatal(err) } } diff --git a/seaweed-block/core/storage/walstore_fence_slice_v3_test.go b/seaweed-block/core/storage/walstore_fence_slice_v3_test.go index 674da839e3..bee0a2a436 100644 --- a/seaweed-block/core/storage/walstore_fence_slice_v3_test.go +++ b/seaweed-block/core/storage/walstore_fence_slice_v3_test.go @@ -102,10 +102,21 @@ func TestWALStoreV3FenceSlicesCountAfterEachSync(t *testing.T) { writeSynced(t, s, 1, 1) // moves the head: the next recovery fences again syncs := 0 // the fence's fsyncs that returned s.testAfterFenceFsync = func() { syncs++ } - t.Cleanup(func() { s.testAfterFenceFsync = nil }) var slices []uint64 var syncsAt []int before := s.CheckpointPersistence() + // At each slice's fsync the counter still holds only the completed slices. + s.testBeforeFenceFsync = func() error { + var done uint64 + for _, b := range slices { + done += b + } + if counted := s.fenceZeroBytes.Load() - before.FenceZeroed; counted != done { + t.Errorf("slice %d counted before its fsync: counted %d, completed %d", len(slices), counted, done) + } + return nil + } + t.Cleanup(func() { s.testAfterFenceFsync, s.testBeforeFenceFsync = nil, nil }) s.v3.fenceSliceHook = func(n uint64) { counted := s.fenceZeroBytes.Load() - before.FenceZeroed // atomics: the hook runs under the store lock var reported uint64 @@ -193,3 +204,51 @@ func damageOpenRecord(t *testing.T, s *WALStore, lsn uint64) { } t.Fatalf("no WAL record with LSN %d", lsn) } + +// An injected failure of the second slice's zero write, or of its fsync, +// stops the fence: the failing slice earns no counter or hook credit, the +// fence is not recorded as completed (no repeat skip can rest on it), and +// the store latches. +func TestWALStoreV3FenceSliceWriteOrFsyncFailure(t *testing.T) { + for _, step := range []string{"write", "fsync"} { + t.Run(step, func(t *testing.T) { + const walSize = 2*fenceSliceBytes + 1<<20 + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), 4096, 4096, walSize, WModeLagged, 64) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + writeSynced(t, s, 1, 1) + ioErr := errors.New("injected fence " + step + " failure") + calls := 0 + fail := func() error { + if calls++; calls == 2 { + return ioErr + } + return nil + } + if step == "write" { + s.testBeforeFenceWrite = fail + } else { + s.testBeforeFenceFsync = fail + } + hooked := 0 + s.v3.fenceSliceHook = func(uint64) { hooked++ } + lastBefore := s.v3.lastFence + before := s.CheckpointPersistence() + if _, err := s.Recover(); !errors.Is(err, ioErr) { + t.Fatalf("recovery over a failing slice %s: %v", step, err) + } + if got := s.fenceZeroBytes.Load() - before.FenceZeroed; got != fenceSliceBytes || hooked != 1 { + t.Fatalf("after the 2nd slice's %s failed: zeroed %d (want one slice, %d), hook calls %d", step, got, fenceSliceBytes, hooked) + } + if s.v3.lastFence != lastBefore { + t.Fatalf("a fence whose slice %s failed was recorded as completed", step) + } + if s.stickyIOFault() == nil { + t.Fatalf("a failed fence slice %s did not latch the store", step) + } + }) + } +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 81363682e4..1766426be4 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -822,6 +822,13 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u n := min(r.Len-done, fenceSliceBytes) off := int64(walOffset + r.Off + done) err := s.syncFile(func() error { + if h := s.testBeforeFenceWrite; h != nil { + if err := h(); err != nil { + err = fmt.Errorf("storage: v3 drop fence: %w", err) + s.latchV3(err) + return err + } + } for w := uint64(0); w < n; { k := min(n-w, uint64(len(zero))) if _, err := s.fd.WriteAt(zero[:k], off+int64(w)); err != nil { @@ -833,6 +840,11 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u } return nil }, func() error { + if h := s.testBeforeFenceFsync; h != nil { + if err := h(); err != nil { + return err + } + } if err := s.fd.Sync(); err != nil { return err } From 74cca8ca05d1c67f9b49e6a281bffd4f531cd1ad Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 01:40:19 -0800 Subject: [PATCH 9/9] storage: the production drain and the leader wait run in bounded children The held-checkpoint control now also drives the production flushOnce, in a bounded child process of the test binary: a drain that repeats its batch is killed and reported at the bound. The leader-wait control moves to its own bounded child, so its worker is always received before the store's cleanup and a stuck one dies with the child. An injected fence write error takes the real WriteAt error's path (one wrap and latch). Co-Authored-By: Claude Opus 5.5 --- .../storage/walstore_bounded_flush_v3_test.go | 99 ++++++++++++++----- seaweed-block/core/storage/walstore_v3.go | 16 +-- 2 files changed, 83 insertions(+), 32 deletions(-) diff --git a/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go index cd895491a8..0f989241f2 100644 --- a/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go +++ b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go @@ -444,36 +444,87 @@ func TestWALStoreV3CheckpointStepsAreTimed(t *testing.T) { if _, err := s.Sync(); err != nil { t.Fatal(err) } +} + +// A checkpoint waiting for the leader role shows that step in progress. It +// runs in a bounded child process: the drain worker is always received +// (joined) before the store's cleanup, and a worker that never ends is +// killed with the child at the bound instead of racing that cleanup. +func TestWALStoreV3CheckpointLeaderWaitIsVisible(t *testing.T) { + if !inBoundedChild(t) { + if err := runBoundedChild(t.Name(), 20*time.Second); err != nil { + t.Fatal(err) + } + return + } + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 256*1024, WModeLagged, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Write(20, blk(20)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } s.v3.syncMu.Lock() // the leader role, held elsewhere done := make(chan error, 1) go func() { done <- s.flusher.flushOnce() }() - // join releases the leader role and waits, bounded, for the drain to end - // before the store's cleanup closes it, on every path. - join := func() error { - s.v3.syncMu.Unlock() - select { - case err := <-done: - return err - case <-time.After(10 * time.Second): - t.Fatal("the drain did not end within 10 s of the leader role's release") - return nil - } - } - deadline := time.Now().Add(5 * time.Second) - for { - if cur := s.CheckpointPersistence().CheckpointSteps; cur.Step == "leader_wait" && !cur.Since.IsZero() { + var seen CheckpointStepStatus + for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) { + if seen = s.CheckpointPersistence().CheckpointSteps; seen.Step == "leader_wait" && !seen.Since.IsZero() { break } - if time.Now().After(deadline) { - seen := s.CheckpointPersistence().CheckpointSteps - if err := join(); err != nil { - t.Errorf("drain: %v", err) - } - t.Fatalf("a checkpoint waiting for the leader role: %+v", seen) - } - time.Sleep(5 * time.Millisecond) } - if err := join(); err != nil { + s.v3.syncMu.Unlock() + drainErr := <-done // joined on every path; the parent bounds the child + if seen.Step != "leader_wait" || seen.Since.IsZero() { + t.Fatalf("a checkpoint waiting for the leader role: %+v", seen) + } + if drainErr != nil { + t.Fatal(drainErr) + } +} + +// The production drain (flushOnce) under a held checkpoint ends, with the +// checkpoint at the floor and every entry in the extent. It runs in a +// bounded child process: a drain that repeats its batch is killed at the +// bound and reported, not left to hang the package. +func TestWALStoreV3HeldDrainEndsInTheProductionDrain(t *testing.T) { + if !inBoundedChild(t) { + if err := runBoundedChild(t.Name(), 20*time.Second); err != nil { + t.Fatal(err) + } + return + } + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 64, 4096, 256*1024, WModeLagged, 4) + if err != nil { t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 12; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 6, anyActive: true}) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if cp := s.CheckpointLSN(); cp != 6 { + t.Fatalf("checkpoint=%d, want the floor 6", cp) + } + for i := uint32(0); i < 12; i++ { + if got, err := s.readFromExtent(i); err != nil || !bytes.Equal(got, blk(byte(i+1))) { + t.Fatalf("LBA %d not in the extent after a held drain: %v", i, err) + } } } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 1766426be4..4f2332e8a8 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -822,16 +822,16 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u n := min(r.Len-done, fenceSliceBytes) off := int64(walOffset + r.Off + done) err := s.syncFile(func() error { - if h := s.testBeforeFenceWrite; h != nil { - if err := h(); err != nil { - err = fmt.Errorf("storage: v3 drop fence: %w", err) - s.latchV3(err) - return err - } - } for w := uint64(0); w < n; { k := min(n-w, uint64(len(zero))) - if _, err := s.fd.WriteAt(zero[:k], off+int64(w)); err != nil { + var err error + if h := s.testBeforeFenceWrite; h != nil && w == 0 { + err = h() // an injected write error takes the real one's path + } + if err == nil { + _, err = s.fd.WriteAt(zero[:k], off+int64(w)) + } + if err != nil { err = fmt.Errorf("storage: v3 drop fence: %w", err) s.latchV3(err) return err