diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 468fa39d48..e3c28d5839 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -14,13 +14,52 @@ 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 + CheckpointSteps CheckpointStepStatus // the checkpoint's step in progress and its per-step time, count and bytes + 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 +} + +// 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 +73,24 @@ 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(), + CheckpointSteps: s.ckpt.status(), + FenceZeroed: s.fenceZeroBytes.Load(), + FenceSkips: s.fenceSkips.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/checkpoint_steps.go b/seaweed-block/core/storage/checkpoint_steps.go new file mode 100644 index 0000000000..bdfc7b6a45 --- /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"` // 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 { + 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 ca5e4c0896..cb28278784 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,25 +442,20 @@ 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 { 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() 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/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 a86245a566..c002e8133c 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -89,8 +89,11 @@ 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 + 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 // chunk is the attached chunk layer's hooks; nil when none. chunk atomic.Pointer[chunkHooks] @@ -162,7 +165,10 @@ type WALStore struct { testAfterAdmit func() // testBeforeFileSync, when set, runs in syncFile just before fileSyncMu // is taken. Tests only. - testBeforeFileSync func() + 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 new file mode 100644 index 0000000000..0f989241f2 --- /dev/null +++ b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go @@ -0,0 +1,530 @@ +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}) + // 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) + } + 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) + } + 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) + } +} + +// 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} + 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) + } + 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()) + } + // 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) + } +} + +// 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() }() + 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 + } + } + 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_fence_slice_v3_test.go b/seaweed-block/core/storage/walstore_fence_slice_v3_test.go new file mode 100644 index 0000000000..bee0a2a436 --- /dev/null +++ b/seaweed-block/core/storage/walstore_fence_slice_v3_test.go @@ -0,0 +1,254 @@ +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++ } + 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 + 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) +} + +// 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_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 1296d51a8d..7311ece84e 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -151,9 +151,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") @@ -166,7 +170,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 } @@ -181,16 +185,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 @@ -198,7 +206,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. @@ -230,7 +240,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) @@ -252,7 +264,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) @@ -262,6 +274,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] @@ -286,6 +300,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..4f2332e8a8 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -27,6 +27,12 @@ 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) + // 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 @@ -191,6 +197,22 @@ func probeWALStoreV3At(r io.ReaderAt) error { // tests. var testSkipFenceOnRecoverV3 bool +// 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 +// 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 } @@ -459,13 +481,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 +520,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 @@ -756,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 { @@ -765,22 +799,75 @@ func (s *WALStore) fenceV3(E, floor, walSize uint64, sameNonce bool, walOffset u if len(ranges) == 0 || testSkipFenceOnRecoverV3 { return nil } - return s.syncFile(func() error { - const chunk = 64 * 1024 - zero := make([]byte, chunk) - for _, r := range ranges { - 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) + v := s.v3 + 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() + } + } + 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))) + 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 + } + w += k + } + 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 } - done += n + if h := s.testAfterFenceFsync; h != nil { + h() + } + return nil + }) + if err != nil { + return err } + // 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 rec != nil { + v.lastFence = rec + } + return nil } // appendWriteV3 is the v3 body of Write's append, under s.mu. DurableLSN is @@ -1417,7 +1504,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 +1524,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 ccbed3adf2..a62c4e5a59 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -79,11 +79,11 @@ 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-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` | -| 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-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` | @@ -626,6 +626,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 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 | @@ -723,6 +727,7 @@ 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-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 | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 8938c48b43..67fd20cf44 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -28,6 +28,14 @@ These notes collect v1.1's changes as they land; v1.1 is not released. changed plus one summary word per 4,096 chunks, so an idle cut's pause does not grow with the volume's size. The cut also syncs the store once right before its barrier, outside the guest pause (reported as `PreSyncNs`), so the pause's own sync has only what was written after it. +- 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`. +- 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 41028664ab..3638511c7c 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -214,6 +214,20 @@ 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[].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. | | `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 |