From a8ddae011f09b9e9696e7d731e0ba701b83bd820 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 08:57:27 -0800 Subject: [PATCH 1/7] storage: the pre-barrier sync repeats until a round is short The first loaded cut after a fill paid the fill's write-back in its one pre-barrier sync, and what the guest wrote meanwhile became the pause's own sync work, growing with the fill. The pre-barrier sync now repeats while a round takes longer than 10 ms (above one device flush), at most 6 rounds and while the cut is live: the pause then flushes only about one short round of writes, whatever the fill. Status reports the rounds (LastCut.PreSyncRounds). Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_presync_test.go | 80 +++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 32 ++++++-- seaweed-block/core/storage/chunk_seam.go | 3 +- seaweed-block/core/storage/walstore.go | 10 ++- seaweed-block/docs/status-schema.md | 1 + 5 files changed, 117 insertions(+), 9 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_cut_presync_test.go diff --git a/seaweed-block/core/storage/chunk_cut_presync_test.go b/seaweed-block/core/storage/chunk_cut_presync_test.go new file mode 100644 index 0000000000..12c6fcf745 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_presync_test.go @@ -0,0 +1,80 @@ +package storage + +import ( + "sync" + "sync/atomic" + "testing" + "time" +) + +// presyncCutAfterFill fills the volume with n writes, then cuts while a +// writer keeps writing (a loaded cut), under a sync cost model: a store +// Sync's file sync takes perWrite for every write since the previous one +// (write-back that grows with what is dirty). It returns the cut's in-pause +// sync time and its pre-barrier sync time. +func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) (inPause, pre time.Duration) { + t.Helper() + s, _ := newChunkTestStore(t) + l := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) + if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed and an empty set + t.Fatal(err) + } + var synced atomic.Uint64 // walMutation at the previous modelled sync + synced.Store(s.walMutation.Load()) + s.testBeforeSyncCache = func() { + now := s.walMutation.Load() + pending := now - synced.Swap(now) + time.Sleep(time.Duration(pending) * perWrite) + } + t.Cleanup(func() { s.testBeforeSyncCache = nil }) + for i := 0; i < n; i++ { // the fill: dirty, never synced + if _, err := s.Write(uint32(i%ctNumBlocks), makeBlock(ctBlockSize, byte(i))); err != nil { + t.Fatal(err) + } + } + stop, done := make(chan struct{}), make(chan struct{}) + var wg sync.WaitGroup + wg.Add(1) + go func() { // the guest, writing through the cut + defer wg.Done() + defer close(done) + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + if _, err := s.Write(uint32(i%ctNumBlocks), makeBlock(ctBlockSize, byte(i))); err != nil { + return + } + time.Sleep(200 * time.Microsecond) + } + }() + r, err := l.Cut(ctTimeout(t)) + close(stop) + select { + case <-done: + case <-time.After(ctLocalBound): + t.Error("the writer did not stop") + } + wg.Wait() + if err != nil { + t.Fatal(err) + } + return time.Duration(r.Stats.SyncNs), time.Duration(r.Stats.PreSyncNs) +} + +// The first loaded cut after a fill: its in-pause sync does not grow with the +// fill. The pre-barrier sync pays the fill's write-back and repeats until one +// round is short, so the pause flushes only what the guest wrote in about +// that window. (One pre-barrier sync left the pause the writes made during +// the fill's write-back, which grow with the fill.) +func TestTheFirstLoadedCutAfterAFillHasAFlatInPauseSync(t *testing.T) { + const perWrite = 50 * time.Microsecond + smallPause, smallPre := presyncCutAfterFill(t, 256, perWrite) + largePause, largePre := presyncCutAfterFill(t, 4096, perWrite) + t.Logf("fill 256: pre %v in-pause %v; fill 4096: pre %v in-pause %v", smallPre, smallPause, largePre, largePause) + if largePause > 2*smallPause+5*time.Millisecond { + t.Fatalf("the in-pause sync grew with the fill: %v after 256 writes, %v after 4096", smallPause, largePause) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index d2b8c0285d..230ee6c1aa 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1522,6 +1522,15 @@ func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, vers } } +// The pre-barrier sync repeats while a round takes longer than +// preSyncShortRound (above one device flush, about 5-8 ms), at most +// preSyncMaxRounds times: after a short round the pause's own sync has only +// about that round's writes to flush. +const ( + preSyncShortRound = 10 * time.Millisecond + preSyncMaxRounds = 6 +) + func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { defer func() { err = l.latchIdentityMoved(err) }() done, err := l.register() @@ -1688,14 +1697,25 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, cause } - // Before the pause: the once-per-layer UNKNOWN seed, and one sync so the - // pause's own sync flushes only what came after it (the first cut after a - // fill pays its write-back here). The in-pause sync still fixes H. + // Before the pause: the once-per-layer UNKNOWN seed, and the pre-barrier + // sync, so the pause's own sync flushes only what came after it. The first + // cut after a fill pays the fill's write-back here, and what the guest + // writes meanwhile would be the pause's work, so the sync repeats until a + // round is short (preSyncShortRound, at most preSyncMaxRounds): the pause + // then flushes only about one short round of writes, whatever the fill. + // The in-pause sync still fixes H. l.prepareTouched() preSync := time.Now() - if _, err := l.s.syncWithPhases(nil); err != nil { - st.PreSyncNs = time.Since(preSync).Nanoseconds() - return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err) + for { + round := time.Now() + st.PreSyncRounds++ + if _, err := l.s.syncWithPhases(nil); err != nil { + st.PreSyncNs = time.Since(preSync).Nanoseconds() + return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err) + } + if time.Since(round) <= preSyncShortRound || st.PreSyncRounds >= preSyncMaxRounds || ctx.Err() != nil { + break + } } st.PreSyncNs = time.Since(preSync).Nanoseconds() diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 52ea605ff4..4863464e0d 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -433,7 +433,8 @@ type chunkCutStats struct { // PreSyncNs is the sync right before the barrier, outside the guest // pause (never part of BarrierPauseNs): the pause's own sync then has // only what came after it. - PreSyncNs int64 + PreSyncNs int64 + PreSyncRounds int // pre-barrier sync rounds (repeated until one is short) // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 WindowSetupNs int64 diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 6844a2d0cc..1c37658ecd 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -168,6 +168,7 @@ type WALStore struct { // testBeforeFileSync, when set, runs in syncFile just before fileSyncMu // is taken. Tests only. testBeforeFileSync func() + testBeforeSyncCache func() // before a store Sync's file sync (syncWithPhases); tests only 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 @@ -874,8 +875,13 @@ func (s *WALStore) syncWithPhases(phases *SyncPhaseStats) (uint64, error) { return 0, ErrGroupCommitShutdown default: } - } else if err := s.syncCache(); err != nil { - return 0, fmt.Errorf("storage: group commit fsync: %w", err) + } else { + if h := s.testBeforeSyncCache; h != nil { + h() // tests only: a stand-in for write-back that grows with what is dirty + } + if err := s.syncCache(); err != nil { + return 0, fmt.Errorf("storage: group commit fsync: %w", err) + } } if phases != nil { phases.GroupCommitNs += time.Since(at).Nanoseconds() diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 150f29cfdb..b202e99154 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -313,6 +313,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.CandidateVisits` | int64 | CandidateVisits counts the chunk indices the barrier's candidate step visited (scanned entries and set members), the work a pause pays for. | | `Volumes[].Chunk.Stats.LastCut.PauseCandidateOps` | int64 | PauseCandidateOps counts per-candidate operations done while the guest is paused (from the barrier lock to its release): zero when the pause does O(1) work. | | `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. | +| `Volumes[].Chunk.Stats.LastCut.PreSyncRounds` | int | pre-barrier sync rounds (repeated until one is short) | | `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | From 44edaa4f0e05cb6a5472f8d3affd4c981945f5a8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 09:12:38 -0800 Subject: [PATCH 2/7] storage: the pre-barrier sync stops on the tail it leaves, bounded The pre-barrier sync repeats until the store-file bytes dirtied during its last pass (WAL appends and extent writes) are at most a named bound (1 MiB), at most 6 passes and while the cut is live; past the last pass the cut proceeds and reports the tail above the bound. LastCut reports PreSyncRounds, TailBytes and TailOverBound. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_presync_test.go | 43 ++++++++++++++----- seaweed-block/core/storage/chunk_layer.go | 32 ++++++++------ seaweed-block/core/storage/chunk_seam.go | 8 +++- seaweed-block/core/storage/walstore.go | 10 +++++ seaweed-block/docs/status-schema.md | 4 +- 5 files changed, 70 insertions(+), 27 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_presync_test.go b/seaweed-block/core/storage/chunk_cut_presync_test.go index 12c6fcf745..ae81163b7b 100644 --- a/seaweed-block/core/storage/chunk_cut_presync_test.go +++ b/seaweed-block/core/storage/chunk_cut_presync_test.go @@ -10,9 +10,8 @@ import ( // presyncCutAfterFill fills the volume with n writes, then cuts while a // writer keeps writing (a loaded cut), under a sync cost model: a store // Sync's file sync takes perWrite for every write since the previous one -// (write-back that grows with what is dirty). It returns the cut's in-pause -// sync time and its pre-barrier sync time. -func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) (inPause, pre time.Duration) { +// (write-back that grows with what is dirty). It returns the cut's stats. +func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) chunkCutStats { t.Helper() s, _ := newChunkTestStore(t) l := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) @@ -61,20 +60,42 @@ func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) (inPause, if err != nil { t.Fatal(err) } - return time.Duration(r.Stats.SyncNs), time.Duration(r.Stats.PreSyncNs) + return r.Stats } // The first loaded cut after a fill: its in-pause sync does not grow with the -// fill. The pre-barrier sync pays the fill's write-back and repeats until one -// round is short, so the pause flushes only what the guest wrote in about -// that window. (One pre-barrier sync left the pause the writes made during -// the fill's write-back, which grow with the fill.) +// fill. The pre-barrier sync pays the fill's write-back and repeats until the +// bytes dirtied during its last pass are at most the bound, so the pause +// flushes only that tail. (One pre-barrier sync left the pause the writes +// made during the fill's write-back, which grow with the fill.) func TestTheFirstLoadedCutAfterAFillHasAFlatInPauseSync(t *testing.T) { const perWrite = 50 * time.Microsecond - smallPause, smallPre := presyncCutAfterFill(t, 256, perWrite) - largePause, largePre := presyncCutAfterFill(t, 4096, perWrite) - t.Logf("fill 256: pre %v in-pause %v; fill 4096: pre %v in-pause %v", smallPre, smallPause, largePre, largePause) + small := presyncCutAfterFill(t, 256, perWrite) + large := presyncCutAfterFill(t, 4096, perWrite) + smallPause, largePause := time.Duration(small.SyncNs), time.Duration(large.SyncNs) + t.Logf("fill 256: pre %v (%d passes, tail %d B) in-pause %v; fill 4096: pre %v (%d passes, tail %d B) in-pause %v", + time.Duration(small.PreSyncNs), small.PreSyncRounds, small.TailBytes, smallPause, + time.Duration(large.PreSyncNs), large.PreSyncRounds, large.TailBytes, largePause) if largePause > 2*smallPause+5*time.Millisecond { t.Fatalf("the in-pause sync grew with the fill: %v after 256 writes, %v after 4096", smallPause, largePause) } + for _, st := range []chunkCutStats{small, large} { + if st.TailBytes > preSyncTailBound || st.TailOverBound { + t.Fatalf("a cut left a pre-barrier tail of %d bytes (bound %d, over=%v)", st.TailBytes, preSyncTailBound, st.TailOverBound) + } + } +} + +// When the tail never falls to the bound (sustained writes faster than the +// device; here the bound is forced below any tail), the pre-barrier sync +// stops after its last allowed pass, reports the tail above the bound as a +// finding, and the cut proceeds: a cut is never starved. +func TestAPreBarrierSyncThatCannotReachTheBoundStillCuts(t *testing.T) { + saved := preSyncTailBound + preSyncTailBound = 0 // every pass leaves some guest writes: never reached + t.Cleanup(func() { preSyncTailBound = saved }) + st := presyncCutAfterFill(t, 64, 20*time.Microsecond) + if st.PreSyncRounds != preSyncMaxRounds || !st.TailOverBound || st.TailBytes == 0 { + t.Fatalf("an unreachable bound: %d passes (want %d), over=%v, tail %d B", st.PreSyncRounds, preSyncMaxRounds, st.TailOverBound, st.TailBytes) + } } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 230ee6c1aa..793d29b86a 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1522,14 +1522,16 @@ func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, vers } } -// The pre-barrier sync repeats while a round takes longer than -// preSyncShortRound (above one device flush, about 5-8 ms), at most -// preSyncMaxRounds times: after a short round the pause's own sync has only -// about that round's writes to flush. -const ( - preSyncShortRound = 10 * time.Millisecond - preSyncMaxRounds = 6 -) +// The pre-barrier sync repeats until the store-file bytes dirtied during its +// last pass (WAL appends and extent writes) are at most preSyncTailBound, so +// the pause's own sync flushes at most about that much; at most +// preSyncMaxRounds passes, then the cut proceeds anyway (sustained writes +// faster than the device) and reports the tail above the bound. A cut is +// never starved. preSyncTailBound is a variable only so a test can force the +// bounded path. +var preSyncTailBound uint64 = 1 << 20 + +const preSyncMaxRounds = 6 func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { defer func() { err = l.latchIdentityMoved(err) }() @@ -1700,23 +1702,25 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // Before the pause: the once-per-layer UNKNOWN seed, and the pre-barrier // sync, so the pause's own sync flushes only what came after it. The first // cut after a fill pays the fill's write-back here, and what the guest - // writes meanwhile would be the pause's work, so the sync repeats until a - // round is short (preSyncShortRound, at most preSyncMaxRounds): the pause - // then flushes only about one short round of writes, whatever the fill. - // The in-pause sync still fixes H. + // writes meanwhile would be the pause's work, so the sync repeats until the + // bytes dirtied during its last pass are at most preSyncTailBound (at most + // preSyncMaxRounds passes): the pause then flushes at most about that tail, + // whatever the fill. The in-pause sync still fixes H. l.prepareTouched() preSync := time.Now() for { - round := time.Now() st.PreSyncRounds++ + dirtied := l.s.storeFileDirtiedBytes() if _, err := l.s.syncWithPhases(nil); err != nil { st.PreSyncNs = time.Since(preSync).Nanoseconds() return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err) } - if time.Since(round) <= preSyncShortRound || st.PreSyncRounds >= preSyncMaxRounds || ctx.Err() != nil { + st.TailBytes = l.s.storeFileDirtiedBytes() - dirtied + if st.TailBytes <= preSyncTailBound || st.PreSyncRounds >= preSyncMaxRounds || ctx.Err() != nil { break } } + st.TailOverBound = st.TailBytes > preSyncTailBound // a finding: the cut proceeds anyway st.PreSyncNs = time.Since(preSync).Nanoseconds() // Quiesced cut. The guest pause starts at the Lock REQUEST: a pending diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 4863464e0d..91e93fc66d 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -434,7 +434,13 @@ type chunkCutStats struct { // pause (never part of BarrierPauseNs): the pause's own sync then has // only what came after it. PreSyncNs int64 - PreSyncRounds int // pre-barrier sync rounds (repeated until one is short) + PreSyncRounds int // pre-barrier sync passes (repeated until the tail is at most the bound) + // TailBytes is the store-file bytes (WAL appends and extent writes) + // dirtied during the last pre-barrier sync pass: about what the pause's own + // sync has to flush. TailOverBound is set when it stayed above the bound + // after the last pass (a finding; the cut proceeds). + TailBytes uint64 + TailOverBound bool // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 WindowSetupNs int64 diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 1c37658ecd..639073c02e 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1249,6 +1249,16 @@ var _ LogicalStorage = (*WALStore)(nil) // Sync calls or the separate checkpoint/extent metadata sync operations. func (s *WALStore) WALSyncCount() uint64 { return s.walSyncCalls.Load() } +// storeFileDirtiedBytes counts the bytes written into the store file in this +// open: WAL appends and the flusher's extent writes (cumulative atomics). +func (s *WALStore) storeFileDirtiedBytes() uint64 { + n := s.instr.walAppendBytes.Load() + if s.flusher != nil { + n += s.flusher.instr.extentWriteBytes.Load() + } + return n +} + // walSyncCovered is used only after the caller has captured its publication // frontier. A later concurrent write may force extra I/O, never a false ACK. func (s *WALStore) walSyncCovered() bool { diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index b202e99154..154638ea61 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -313,7 +313,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.CandidateVisits` | int64 | CandidateVisits counts the chunk indices the barrier's candidate step visited (scanned entries and set members), the work a pause pays for. | | `Volumes[].Chunk.Stats.LastCut.PauseCandidateOps` | int64 | PauseCandidateOps counts per-candidate operations done while the guest is paused (from the barrier lock to its release): zero when the pause does O(1) work. | | `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. | -| `Volumes[].Chunk.Stats.LastCut.PreSyncRounds` | int | pre-barrier sync rounds (repeated until one is short) | +| `Volumes[].Chunk.Stats.LastCut.PreSyncRounds` | int | pre-barrier sync passes (repeated until the tail is at most the bound) | +| `Volumes[].Chunk.Stats.LastCut.TailBytes` | uint64 | TailBytes is the store-file bytes (WAL appends and extent writes) dirtied during the last pre-barrier sync pass: about what the pause's own sync has to flush. TailOverBound is set when it stayed above the bound after the last pass (a finding; the cut proceeds). | +| `Volumes[].Chunk.Stats.LastCut.TailOverBound` | bool | (group of `TailBytes`) TailBytes is the store-file bytes (WAL appends and extent writes) dirtied during the last pre-barrier sync pass: about what the pause's own sync has to flush. TailOverBound is set when it stayed above the bound after the last pass (a finding; the cut proceeds). | | `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | From c525b5f40bd5921556024ba0468469025c24fa7b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 10:05:47 -0800 Subject: [PATCH 3/7] storage: hold flusher extent writes over the last pre-barrier pass TailBytes now runs from the start of the last pre-barrier pass to the barrier lock, since the pause flushes all of that. A loaded cut right after a fill, with the flusher draining, did not converge: a flusher cycle landing in the last pass left the pause about 4 MiB to flush. The last pass now runs with new flusher extent writes held until the barrier is released (one pass and the pause; the cut needs the WAL only up to H), so the pause flushes the guest's WAL tail alone. The flusher waits before an extent write, holding no store lock, and stops waiting when it is stopped. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_presync_test.go | 82 +++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 47 ++++++++--- seaweed-block/core/storage/chunk_seam.go | 7 +- seaweed-block/core/storage/flusher.go | 6 ++ seaweed-block/core/storage/walstore.go | 25 +++++- seaweed-block/docs/status-schema.md | 4 +- 6 files changed, 149 insertions(+), 22 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_presync_test.go b/seaweed-block/core/storage/chunk_cut_presync_test.go index ae81163b7b..44b33dc933 100644 --- a/seaweed-block/core/storage/chunk_cut_presync_test.go +++ b/seaweed-block/core/storage/chunk_cut_presync_test.go @@ -1,6 +1,7 @@ package storage import ( + "path/filepath" "sync" "sync/atomic" "testing" @@ -99,3 +100,84 @@ func TestAPreBarrierSyncThatCannotReachTheBoundStillCuts(t *testing.T) { t.Fatalf("an unreachable bound: %d passes (want %d), over=%v, tail %d B", st.PreSyncRounds, preSyncMaxRounds, st.TailOverBound, st.TailBytes) } } + +// The first loaded cut right after a fill, while the flusher drains it: the +// fill becomes drainable at the cut's first pre-barrier pass (the flusher +// writes only synced records), and from then on a flusher cycle lands in +// every pre-barrier pass (the test wakes the flusher at each pass and gives +// it up to 20 ms to write 1 MiB of extents). The last pass and the pause hold +// new extent writes, so the tail the pause flushes is the guest's alone, +// within the bound. (Without the hold, the cycle in the last pass leaves a +// tail of about 4 MiB, over the bound.) +func TestALoadedCutWhileTheFlusherDrainsHasABoundedTail(t *testing.T) { + const blocks = 8192 // 32 MiB: a fill of distinct blocks leaves extent work to drain + const perByte = 10 * time.Nanosecond + s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "vol.bin"), blocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks}) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, s) }) + l := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) + if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed and an empty set + t.Fatal(err) + } + s.flusher = newFlusher(s, flusherConfig{}) // the background flusher drains, as in production + started := make(chan struct{}) + go s.flusher.runWithStartSignal(started) + <-started + var synced atomic.Uint64 // store-file bytes at the previous modelled sync + synced.Store(s.storeFileDirtiedBytes()) + extent := func() uint64 { return s.flusher.instr.extentWriteBytes.Load() } + s.testBeforeSyncCache = func() { + if !l.paused { // a pre-barrier pass (this hook runs on the cut's goroutine): a flusher cycle lands in it + before := extent() + s.flusher.Notify() + for deadline := time.Now().Add(20 * time.Millisecond); extent()-before < 1<<20 && time.Now().Before(deadline); { + time.Sleep(time.Millisecond) + } + } + now := s.storeFileDirtiedBytes() + time.Sleep(time.Duration(now-synced.Swap(now)) * perByte) + } + t.Cleanup(func() { s.testBeforeSyncCache = nil }) + for i := 0; i < 4096; i++ { // the fill: 16 MiB of distinct blocks, never synced + if _, err := s.Write(uint32(i), makeBlock(ctBlockSize, byte(i))); err != nil { + t.Fatal(err) + } + } + stop := make(chan struct{}) + var wg sync.WaitGroup + wg.Add(1) + go func() { // the guest, writing through the cut + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + if _, err := s.Write(uint32(4096+i%4096), makeBlock(ctBlockSize, byte(i))); err != nil { + return + } + time.Sleep(time.Millisecond) + } + }() + r, err := l.Cut(ctTimeout(t)) + close(stop) + wg.Wait() + if err != nil { + t.Fatal(err) + } + st := r.Stats + t.Logf("pre %v (%d passes) tail %d B over=%v in-pause %v; flusher extent bytes %d", + time.Duration(st.PreSyncNs), st.PreSyncRounds, st.TailBytes, st.TailOverBound, time.Duration(st.SyncNs), s.flusher.instr.extentWriteBytes.Load()) + if s.flusher.instr.extentWriteBytes.Load() == 0 { + t.Fatal("setup: the flusher drained nothing during the cut") + } + if st.TailBytes > preSyncTailBound || st.TailOverBound { + t.Fatalf("the tail the pause flushes: %d bytes (bound %d, over=%v)", st.TailBytes, preSyncTailBound, st.TailOverBound) + } + // The tail is what the checkers judge; the in-pause sync time is logged + // (it also carries the host's real fsync, which can spike on a busy host). +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 793d29b86a..8d7fac87ea 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1522,13 +1522,14 @@ func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, vers } } -// The pre-barrier sync repeats until the store-file bytes dirtied during its -// last pass (WAL appends and extent writes) are at most preSyncTailBound, so -// the pause's own sync flushes at most about that much; at most -// preSyncMaxRounds passes, then the cut proceeds anyway (sustained writes -// faster than the device) and reports the tail above the bound. A cut is -// never starved. preSyncTailBound is a variable only so a test can force the -// bounded path. +// The pre-barrier sync repeats until a pass dirties at most preSyncTailBound +// store-file bytes (WAL appends and extent writes), then runs one last pass +// with the flusher's extent writes held until the barrier is released, so the +// pause's own sync flushes only the guest's WAL tail since that pass began +// (TailBytes, judged against the bound). At most preSyncMaxRounds passes in +// all; past them the cut proceeds anyway (sustained writes faster than the +// device) and reports the tail above the bound. A cut is never starved. +// preSyncTailBound is a variable only so a test can force the bounded path. var preSyncTailBound uint64 = 1 << 20 const preSyncMaxRounds = 6 @@ -1708,19 +1709,33 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // whatever the fill. The in-pause sync still fixes H. l.prepareTouched() preSync := time.Now() - for { + preSyncPass := func() error { st.PreSyncRounds++ - dirtied := l.s.storeFileDirtiedBytes() if _, err := l.s.syncWithPhases(nil); err != nil { st.PreSyncNs = time.Since(preSync).Nanoseconds() - return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err) + return fmt.Errorf("storage: capture sync (before the barrier): %w", err) } - st.TailBytes = l.s.storeFileDirtiedBytes() - dirtied - if st.TailBytes <= preSyncTailBound || st.PreSyncRounds >= preSyncMaxRounds || ctx.Err() != nil { + return nil + } + for st.PreSyncRounds < preSyncMaxRounds-1 && ctx.Err() == nil { + start := l.s.storeFileDirtiedBytes() + if err := preSyncPass(); err != nil { + return chunkCutResult{}, err + } + if l.s.storeFileDirtiedBytes()-start <= preSyncTailBound { break } } - st.TailOverBound = st.TailBytes > preSyncTailBound // a finding: the cut proceeds anyway + // The last pass runs with the flusher's extent writes held until the + // barrier is released: the pause then flushes the guest's WAL tail since + // this pass began, never a drain burst. The hold lasts one pass and the + // pause (milliseconds); the cut needs the WAL only up to H. + releaseExtentHold := l.s.holdExtentWrites() + defer releaseExtentHold() + lastPass := l.s.storeFileDirtiedBytes() + if err := preSyncPass(); err != nil { + return chunkCutResult{}, err + } st.PreSyncNs = time.Since(preSync).Nanoseconds() // Quiesced cut. The guest pause starts at the Lock REQUEST: a pending @@ -1751,6 +1766,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch unlockCapture := func() { l.paused = false l.s.captureMu.Unlock() + releaseExtentHold() if !detach && releasePrecopy != nil { releasePrecopy() releasePrecopy = nil @@ -1760,6 +1776,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch hook() } l.s.captureMu.Lock() + // The pause's sync flushes everything dirtied since the last pre-barrier + // pass started: that is the tail judged against the bound. + st.TailBytes = l.s.storeFileDirtiedBytes() - lastPass + st.TailOverBound = st.TailBytes > preSyncTailBound // a finding: the cut proceeds anyway l.paused, l.pauseOps = true, 0 defer func() { st.PauseCandidateOps = l.pauseOps }() barrier := time.Now() @@ -1811,6 +1831,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // is back now, and its pause did O(1) work. drained := releasePrecopy != nil l.s.captureMu.Unlock() + releaseExtentHold() st.WindowSetupNs += time.Since(windowStart).Nanoseconds() if !drained { l.paused = false diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 91e93fc66d..4a361dfaa3 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -436,9 +436,10 @@ type chunkCutStats struct { PreSyncNs int64 PreSyncRounds int // pre-barrier sync passes (repeated until the tail is at most the bound) // TailBytes is the store-file bytes (WAL appends and extent writes) - // dirtied during the last pre-barrier sync pass: about what the pause's own - // sync has to flush. TailOverBound is set when it stayed above the bound - // after the last pass (a finding; the cut proceeds). + // dirtied from the start of the last pre-barrier sync pass (the one run + // with the flusher's extent writes held) to the barrier lock: what the + // pause's own sync has to flush. TailOverBound is set when it is above the + // bound (a finding; the cut proceeds). TailBytes uint64 TailOverBound bool // Disjoint non-payload intervals within barrier-to-settlement fixed cost. diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index cb28278784..0deaabc377 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -369,6 +369,12 @@ func (f *flusher) flushCycle(allowClosed bool, p flushPass) (r flushCycleResult, if f.beforeExtentWriteForTest != nil { f.beforeExtentWriteForTest() } + if p := store.extentHold.Load(); p != nil { // a cut's last pass and pause + select { + case <-*p: + case <-f.stopCh: + } + } writeStart := time.Now() written, err := store.writeExtentIfCurrent(e.LBA, e.LSN, data) if written || err != nil { diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 639073c02e..08a7f0e648 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -168,10 +168,11 @@ type WALStore struct { // testBeforeFileSync, when set, runs in syncFile just before fileSyncMu // is taken. Tests only. testBeforeFileSync func() - testBeforeSyncCache func() // before a store Sync's file sync (syncWithPhases); tests only - 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 + testBeforeSyncCache func() // before a store Sync's file sync (syncWithPhases); tests only + extentHold atomic.Pointer[chan struct{}] // a cut's hold on new flusher extent writes (holdExtentWrites) + 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 @@ -1249,6 +1250,22 @@ var _ LogicalStorage = (*WALStore)(nil) // Sync calls or the separate checkpoint/extent metadata sync operations. func (s *WALStore) WALSyncCount() uint64 { return s.walSyncCalls.Load() } +// holdExtentWrites holds the flusher's new extent writes until the returned +// release (idempotent): a cut's last pre-barrier pass and its pause then +// flush only the guest's WAL tail. The flusher waits before an extent write, +// holding no store lock, and stops waiting when it is stopped. +func (s *WALStore) holdExtentWrites() (release func()) { + ch := make(chan struct{}) + s.extentHold.Store(&ch) + var once sync.Once + return func() { + once.Do(func() { + s.extentHold.CompareAndSwap(&ch, nil) + close(ch) + }) + } +} + // storeFileDirtiedBytes counts the bytes written into the store file in this // open: WAL appends and the flusher's extent writes (cumulative atomics). func (s *WALStore) storeFileDirtiedBytes() uint64 { diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 154638ea61..2b07cbef56 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -314,8 +314,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.PauseCandidateOps` | int64 | PauseCandidateOps counts per-candidate operations done while the guest is paused (from the barrier lock to its release): zero when the pause does O(1) work. | | `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. | | `Volumes[].Chunk.Stats.LastCut.PreSyncRounds` | int | pre-barrier sync passes (repeated until the tail is at most the bound) | -| `Volumes[].Chunk.Stats.LastCut.TailBytes` | uint64 | TailBytes is the store-file bytes (WAL appends and extent writes) dirtied during the last pre-barrier sync pass: about what the pause's own sync has to flush. TailOverBound is set when it stayed above the bound after the last pass (a finding; the cut proceeds). | -| `Volumes[].Chunk.Stats.LastCut.TailOverBound` | bool | (group of `TailBytes`) TailBytes is the store-file bytes (WAL appends and extent writes) dirtied during the last pre-barrier sync pass: about what the pause's own sync has to flush. TailOverBound is set when it stayed above the bound after the last pass (a finding; the cut proceeds). | +| `Volumes[].Chunk.Stats.LastCut.TailBytes` | uint64 | TailBytes is the store-file bytes (WAL appends and extent writes) dirtied from the start of the last pre-barrier sync pass (the one run with the flusher's extent writes held) to the barrier lock: what the pause's own sync has to flush. TailOverBound is set when it is above the bound (a finding; the cut proceeds). | +| `Volumes[].Chunk.Stats.LastCut.TailOverBound` | bool | (group of `TailBytes`) TailBytes is the store-file bytes (WAL appends and extent writes) dirtied from the start of the last pre-barrier sync pass (the one run with the flusher's extent writes held) to the barrier lock: what the pause's own sync has to flush. TailOverBound is set when it is above the bound (a finding; the cut proceeds). | | `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | From f3a8ef433548d143895e6731867d93a688782ce1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 10:56:52 -0800 Subject: [PATCH 4/7] storage: the cut's extent hold never stalls a guest write A guest write waiting at the WAL hard mark holds the capture lock's read side while it waits for the flusher, and the cut's hold stopped the flusher until after the barrier took that lock: the write failed at its admission budget. The barrier now only tries for its lock while the hold is on (5 ms); at the hard mark, or when the try fails, it releases the hold first and takes the lock normally, and the cut reports TailOverBound with TailCause. Before the barrier a held extent write also goes through while a writer waits at the hard mark. The hold is now a read/write gate around each extent write and its count: holdExtentWrites returns only after admitted writes have landed, so the last pass's baseline misses none. A cut whose context ended in an unheld pass returns before taking the hold. Tests: two hard-mark reds and a failed-cut release test in bounded children, a gate test, bounded writer joins, a deterministic unreachable bound, and proof that a flusher cycle reached the held pass. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_presync_test.go | 267 ++++++++++++++++-- seaweed-block/core/storage/chunk_layer.go | 24 +- seaweed-block/core/storage/chunk_seam.go | 6 +- seaweed-block/core/storage/flusher.go | 8 +- seaweed-block/core/storage/walstore.go | 83 +++++- seaweed-block/docs/status-schema.md | 5 +- 6 files changed, 350 insertions(+), 43 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_presync_test.go b/seaweed-block/core/storage/chunk_cut_presync_test.go index 44b33dc933..988e125986 100644 --- a/seaweed-block/core/storage/chunk_cut_presync_test.go +++ b/seaweed-block/core/storage/chunk_cut_presync_test.go @@ -1,8 +1,8 @@ package storage import ( + "context" "path/filepath" - "sync" "sync/atomic" "testing" "time" @@ -11,8 +11,10 @@ import ( // presyncCutAfterFill fills the volume with n writes, then cuts while a // writer keeps writing (a loaded cut), under a sync cost model: a store // Sync's file sync takes perWrite for every write since the previous one -// (write-back that grows with what is dirty). It returns the cut's stats. -func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) chunkCutStats { +// (write-back that grows with what is dirty). With guestEachPass, every +// pre-barrier pass also waits (bounded) for one guest write, so no pass is +// clean. It returns the cut's stats. +func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration, guestEachPass bool) chunkCutStats { t.Helper() s, _ := newChunkTestStore(t) l := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) @@ -22,6 +24,12 @@ func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) chunkCutSt var synced atomic.Uint64 // walMutation at the previous modelled sync synced.Store(s.walMutation.Load()) s.testBeforeSyncCache = func() { + if guestEachPass && !l.paused { + at := s.walMutation.Load() + for deadline := time.Now().Add(ctLocalBound); s.walMutation.Load() == at && time.Now().Before(deadline); { + time.Sleep(100 * time.Microsecond) + } + } now := s.walMutation.Load() pending := now - synced.Swap(now) time.Sleep(time.Duration(pending) * perWrite) @@ -33,10 +41,7 @@ func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) chunkCutSt } } stop, done := make(chan struct{}), make(chan struct{}) - var wg sync.WaitGroup - wg.Add(1) go func() { // the guest, writing through the cut - defer wg.Done() defer close(done) for i := 0; ; i++ { select { @@ -52,12 +57,11 @@ func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) chunkCutSt }() r, err := l.Cut(ctTimeout(t)) close(stop) - select { + select { // bounded: a writer that never stops fails the test, never hangs it case <-done: case <-time.After(ctLocalBound): - t.Error("the writer did not stop") + t.Fatal("the writer did not stop") } - wg.Wait() if err != nil { t.Fatal(err) } @@ -71,8 +75,8 @@ func presyncCutAfterFill(t *testing.T, n int, perWrite time.Duration) chunkCutSt // made during the fill's write-back, which grow with the fill.) func TestTheFirstLoadedCutAfterAFillHasAFlatInPauseSync(t *testing.T) { const perWrite = 50 * time.Microsecond - small := presyncCutAfterFill(t, 256, perWrite) - large := presyncCutAfterFill(t, 4096, perWrite) + small := presyncCutAfterFill(t, 256, perWrite, false) + large := presyncCutAfterFill(t, 4096, perWrite, false) smallPause, largePause := time.Duration(small.SyncNs), time.Duration(large.SyncNs) t.Logf("fill 256: pre %v (%d passes, tail %d B) in-pause %v; fill 4096: pre %v (%d passes, tail %d B) in-pause %v", time.Duration(small.PreSyncNs), small.PreSyncRounds, small.TailBytes, smallPause, @@ -93,9 +97,9 @@ func TestTheFirstLoadedCutAfterAFillHasAFlatInPauseSync(t *testing.T) { // finding, and the cut proceeds: a cut is never starved. func TestAPreBarrierSyncThatCannotReachTheBoundStillCuts(t *testing.T) { saved := preSyncTailBound - preSyncTailBound = 0 // every pass leaves some guest writes: never reached + preSyncTailBound = 0 // every pass waits for a guest write: never reached t.Cleanup(func() { preSyncTailBound = saved }) - st := presyncCutAfterFill(t, 64, 20*time.Microsecond) + st := presyncCutAfterFill(t, 64, 20*time.Microsecond, true) if st.PreSyncRounds != preSyncMaxRounds || !st.TailOverBound || st.TailBytes == 0 { t.Fatalf("an unreachable bound: %d passes (want %d), over=%v, tail %d B", st.PreSyncRounds, preSyncMaxRounds, st.TailOverBound, st.TailBytes) } @@ -129,11 +133,16 @@ func TestALoadedCutWhileTheFlusherDrainsHasABoundedTail(t *testing.T) { var synced atomic.Uint64 // store-file bytes at the previous modelled sync synced.Store(s.storeFileDirtiedBytes()) extent := func() uint64 { return s.flusher.instr.extentWriteBytes.Load() } + var overlapped atomic.Int32 // held passes a flusher cycle reached (and waited in) s.testBeforeSyncCache = func() { if !l.paused { // a pre-barrier pass (this hook runs on the cut's goroutine): a flusher cycle lands in it - before := extent() + before, waits, held := extent(), s.extentHeldWaits.Load(), s.extentHeld.Load() s.flusher.Notify() for deadline := time.Now().Add(20 * time.Millisecond); extent()-before < 1<<20 && time.Now().Before(deadline); { + if held && s.extentHeldWaits.Load() > waits { + overlapped.Add(1) // proof: the cycle reached the held pass and was held + break + } time.Sleep(time.Millisecond) } } @@ -146,11 +155,9 @@ func TestALoadedCutWhileTheFlusherDrainsHasABoundedTail(t *testing.T) { t.Fatal(err) } } - stop := make(chan struct{}) - var wg sync.WaitGroup - wg.Add(1) + stop, done := make(chan struct{}), make(chan struct{}) go func() { // the guest, writing through the cut - defer wg.Done() + defer close(done) for i := 0; ; i++ { select { case <-stop: @@ -165,19 +172,235 @@ func TestALoadedCutWhileTheFlusherDrainsHasABoundedTail(t *testing.T) { }() r, err := l.Cut(ctTimeout(t)) close(stop) - wg.Wait() + select { // bounded: a writer that never stops fails the test, never hangs it + case <-done: + case <-time.After(ctLocalBound): + t.Fatal("the writer did not stop") + } if err != nil { t.Fatal(err) } st := r.Stats t.Logf("pre %v (%d passes) tail %d B over=%v in-pause %v; flusher extent bytes %d", time.Duration(st.PreSyncNs), st.PreSyncRounds, st.TailBytes, st.TailOverBound, time.Duration(st.SyncNs), s.flusher.instr.extentWriteBytes.Load()) - if s.flusher.instr.extentWriteBytes.Load() == 0 { - t.Fatal("setup: the flusher drained nothing during the cut") - } if st.TailBytes > preSyncTailBound || st.TailOverBound { t.Fatalf("the tail the pause flushes: %d bytes (bound %d, over=%v)", st.TailBytes, preSyncTailBound, st.TailOverBound) } + if overlapped.Load() == 0 { + t.Fatal("setup: no flusher cycle reached the held last pass") + } // The tail is what the checkers judge; the in-pause sync time is logged // (it also carries the host's real fsync, which can spike on a busy host). } + +// hardMarkStore is a v3 store with a small WAL, a chunk layer attached and +// seeded, and a running background flusher: a few dozen writes reach the WAL +// hard mark whenever the flusher cannot drain. +func hardMarkStore(t *testing.T) (*WALStore, *chunkLayerImpl) { + t.Helper() + s, err := createMappedWALStoreV3ForTest(filepath.Join(t.TempDir(), "volume"), ctNumBlocks, ctBlockSize, 256*1024, WModeStrict, ctChunkBlocks) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { closeBounded(t, s) }) + cfg := ctConfig(1) + cfg.Bitmap = nil + cfg.BarrierBound = 0 + l := mustAttach(t, s, newFakeChunkRemote(), cfg).(*chunkLayerImpl) + if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed and an empty set + t.Fatal(err) + } + s.flusher = newFlusher(s, flusherConfig{}) + started := make(chan struct{}) + go s.flusher.runWithStartSignal(started) + <-started + for i := 0; i < ctNumBlocks; i++ { // the fill, drained by the flusher + if _, err := s.Write(uint32(i), makeBlock(ctBlockSize, byte(i))); err != nil { + t.Fatal(err) + } + } + return s, l +} + +// writeToTheHardMark starts a guest writing 256 blocks (more than the WAL +// holds) and waits, bounded, until one of its writes waits at the +// hard mark. The returned channel yields the writer's first error (nil when +// every write was admitted). +func writeToTheHardMark(t *testing.T, s *WALStore) <-chan error { + t.Helper() + res := make(chan error, 1) + go func() { + for i := 0; i < 256; i++ { + if _, err := s.Write(uint32(i%ctNumBlocks), makeBlock(ctBlockSize, byte(i))); err != nil { + res <- err + return + } + } + res <- nil + }() + for deadline := time.Now().Add(ctLocalBound); !s.writerAtHardMark(); time.Sleep(time.Millisecond) { + select { + case err := <-res: + t.Fatalf("setup: the writer ended (%v) before a write reached the WAL hard mark", err) + default: + } + if time.Now().After(deadline) { + t.Fatal("setup: no write reached the WAL hard mark") + } + } + return res +} + +// A guest write waiting at the WAL hard mark while a cut holds the flusher's +// extent writes: the barrier gives the hold up rather than wait for that +// writer's read lock, so no write is refused for WAL space, the cut +// completes, and its tail is reported over the bound with the hard mark as +// the cause. (A barrier that simply waited for its lock waited for the +// writer, which waited for the held flusher: the write failed with +// wal_reclaim_stalled at the admission budget.) The flusher's own yield to +// the hard mark is switched off here, so only the barrier can break it. +func TestALoadedCutGivesItsHoldUpToAWriterAtTheHardMark(t *testing.T) { + if !inBoundedChild(t) { + if err := runBoundedChild(t.Name(), boundedChildBound); err != nil { + t.Fatal(err) + } + return + } + s, l := hardMarkStore(t) + s.testHoldIgnoresHardMark = true + var writer <-chan error + l.testBeforeBarrierLockHook = func() { // the hold is on; the barrier is next + l.testBeforeBarrierLockHook = nil + writer = writeToTheHardMark(t, s) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + select { + case werr := <-writer: + if werr != nil { + t.Fatalf("a guest write was refused while the cut held the flusher: %v", werr) + } + case <-time.After(ctLocalBound): + t.Fatal("the guest writer did not finish") + } + st := r.Stats + t.Logf("tail %d B over=%v cause=%q lock wait %v", st.TailBytes, st.TailOverBound, st.TailCause, time.Duration(st.LockWaitNs)) + if !st.TailOverBound || st.TailCause != "writer_at_hard_mark" { + t.Fatalf("the finding: over=%v cause=%q, want the hard mark", st.TailOverBound, st.TailCause) + } +} + +// The same writer reaching the hard mark during the held last pass, before +// the barrier: the held flusher lets its extent writes through, so the write +// is admitted while the pass is still running. (A flusher that stayed held +// left that writer to the admission budget: wal_reclaim_stalled.) +func TestAHeldFlusherWritesThroughForAWriterAtTheHardMark(t *testing.T) { + if !inBoundedChild(t) { + if err := runBoundedChild(t.Name(), boundedChildBound); err != nil { + t.Fatal(err) + } + return + } + s, l := hardMarkStore(t) + var werr error + var ran atomic.Bool + s.testBeforeSyncCache = func() { + if l.paused || !s.extentHeld.Load() || ran.Swap(true) { + return + } + // The held last pass (on the cut's goroutine): it waits for the writer. + werr = <-writeToTheHardMark(t, s) + } + t.Cleanup(func() { s.testBeforeSyncCache = nil }) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if !ran.Load() { + t.Fatal("setup: no held pass ran") + } + if werr != nil { + t.Fatalf("a guest write was refused while the cut held the flusher: %v", werr) + } +} + +// The hold is serialized with extent-write admission: an extent write the +// flusher was admitted to before the hold is finished (and counted) before +// holdExtentWrites returns, so the last pass's baseline cannot miss it; one +// asked for after the hold waits until the release. (A check-only hold +// returned at once, with that write still to land in the held pass.) +func TestAHoldWaitsForAnAdmittedExtentWriteAndHoldsNewOnes(t *testing.T) { + s, _ := newChunkTestStore(t) + stop := make(chan struct{}) + defer close(stop) + admitted := s.admitExtentWrite(stop) // the flusher, admitted and mid-write + held := make(chan func(), 1) + go func() { held <- s.holdExtentWrites() }() + select { + case <-held: + t.Fatal("the hold returned while an admitted extent write was still in flight") + case <-time.After(20 * time.Millisecond): + } + admitted() + var release func() + select { + case release = <-held: + case <-time.After(ctLocalBound): + t.Fatal("the hold did not return after the admitted write finished") + } + next := make(chan struct{}) + go func() { s.admitExtentWrite(stop)(); close(next) }() + select { + case <-next: + t.Fatal("an extent write was admitted while the hold was on") + case <-time.After(20 * time.Millisecond): + } + release() + select { + case <-next: + case <-time.After(ctLocalBound): + t.Fatal("the held extent write did not resume after the release") + } + release() // idempotent +} + +// A cut that fails after the hold is on (its context ends during the held +// last pass) releases the hold on its way out: the flusher drains again. +func TestACutThatFailsInItsHeldPassReleasesTheFlusher(t *testing.T) { + if !inBoundedChild(t) { + if err := runBoundedChild(t.Name(), boundedChildBound); err != nil { + t.Fatal(err) + } + return + } + s, l := hardMarkStore(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + s.testBeforeSyncCache = func() { + if !l.paused && s.extentHeld.Load() { + cancel() + } + } + t.Cleanup(func() { s.testBeforeSyncCache = nil }) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x5a)); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctx); err == nil { + t.Fatal("setup: the cut did not fail") + } + if s.extentHeld.Load() { + t.Fatal("the failed cut left the flusher's extent writes held") + } + before := s.flusher.instr.extentWriteBytes.Load() + if _, err := s.Write(1, makeBlock(ctBlockSize, 0x5b)); err != nil { + t.Fatal(err) + } + for deadline := time.Now().Add(ctLocalBound); s.flusher.instr.extentWriteBytes.Load() == before; time.Sleep(time.Millisecond) { + s.flusher.Notify() + if time.Now().After(deadline) { + t.Fatal("the flusher wrote no extent after the failed cut") + } + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 8d7fac87ea..2c4ffb7384 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1532,6 +1532,12 @@ func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, vers // preSyncTailBound is a variable only so a test can force the bounded path. var preSyncTailBound uint64 = 1 << 20 +// barrierHoldTry bounds how long the barrier tries for its lock while the +// flusher's extent writes are held. Past it, or as soon as a guest write +// waits at the WAL hard mark, the hold is released before the barrier waits: +// the hold is never a wait edge the barrier depends on. +var barrierHoldTry = 5 * time.Millisecond + const preSyncMaxRounds = 6 func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) { @@ -1726,6 +1732,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch break } } + if cause := context.Cause(ctx); cause != nil { // ended during an unheld pass + st.PreSyncNs = time.Since(preSync).Nanoseconds() + return chunkCutResult{}, cause + } // The last pass runs with the flusher's extent writes held until the // barrier is released: the pause then flushes the guest's WAL tail since // this pass began, never a drain burst. The hold lasts one pass and the @@ -1775,11 +1785,21 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if hook := l.testBeforeBarrierLockHook; hook != nil { hook() } - l.s.captureMu.Lock() + // A writer holding captureMu.RLock may be parked in WAL admission waiting + // for the flusher, which the hold stops: so the barrier only tries for its + // lock while the hold is on, and gives the hold up first otherwise. + if cause := l.s.tryCaptureLockWhileHeld(barrierHoldTry); cause != "" { + releaseExtentHold() + l.s.captureMu.Lock() + st.TailCause = cause + } // The pause's sync flushes everything dirtied since the last pre-barrier // pass started: that is the tail judged against the bound. st.TailBytes = l.s.storeFileDirtiedBytes() - lastPass - st.TailOverBound = st.TailBytes > preSyncTailBound // a finding: the cut proceeds anyway + if st.TailCause == "" && st.TailBytes > preSyncTailBound { + st.TailCause = "tail" + } + st.TailOverBound = st.TailCause != "" // a finding: the cut proceeds anyway l.paused, l.pauseOps = true, 0 defer func() { st.PauseCandidateOps = l.pauseOps }() barrier := time.Now() diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 4a361dfaa3..0413f07996 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -439,9 +439,13 @@ type chunkCutStats struct { // dirtied from the start of the last pre-barrier sync pass (the one run // with the flusher's extent writes held) to the barrier lock: what the // pause's own sync has to flush. TailOverBound is set when it is above the - // bound (a finding; the cut proceeds). + // bound, or when the hold was given up before the barrier (a finding; the + // cut proceeds). TailCause says which: "tail", "writer_at_hard_mark" (a + // guest write waited for WAL space, so the flusher was let through) or + // "barrier_busy" (the barrier lock was not free within its short try). TailBytes uint64 TailOverBound bool + TailCause string // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 WindowSetupNs int64 diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 0deaabc377..f415a8940b 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -369,17 +369,13 @@ func (f *flusher) flushCycle(allowClosed bool, p flushPass) (r flushCycleResult, if f.beforeExtentWriteForTest != nil { f.beforeExtentWriteForTest() } - if p := store.extentHold.Load(); p != nil { // a cut's last pass and pause - select { - case <-*p: - case <-f.stopCh: - } - } + admitted := store.admitExtentWrite(f.stopCh) // a cut's last pass and pause writeStart := time.Now() written, err := store.writeExtentIfCurrent(e.LBA, e.LSN, data) if written || err != nil { f.instr.recordExtentWrite(len(data), time.Since(writeStart), err) } + admitted() if err != nil { return r, fmt.Errorf("flusher: write extent LBA %d: %w", e.LBA, err) } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 08a7f0e648..75e5a5587d 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "runtime" "sync" "sync/atomic" "time" @@ -168,11 +169,21 @@ type WALStore struct { // testBeforeFileSync, when set, runs in syncFile just before fileSyncMu // is taken. Tests only. testBeforeFileSync func() - testBeforeSyncCache func() // before a store Sync's file sync (syncWithPhases); tests only - extentHold atomic.Pointer[chan struct{}] // a cut's hold on new flusher extent writes (holdExtentWrites) - 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 + testBeforeSyncCache func() // before a store Sync's file sync (syncWithPhases); tests only + 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 + + // A cut's hold on new flusher extent writes (holdExtentWrites): extentGate + // serializes the hold with extent-write admission, extentHeld says it is + // on, extentHoldWake is closed when it is released. + extentGate sync.RWMutex + extentHeld atomic.Bool + extentHoldWake atomic.Pointer[chan struct{}] + extentHeldWaits atomic.Uint64 // extent writes that waited for a hold + // testHoldIgnoresHardMark keeps held extent writes held at the hard mark + // (only the barrier gives the hold up); false in production. + testHoldIgnoresHardMark bool // Generations cover completed append attempts and recovery publication. walMutation atomic.Uint64 durableMutation atomic.Uint64 @@ -1251,21 +1262,73 @@ var _ LogicalStorage = (*WALStore)(nil) func (s *WALStore) WALSyncCount() uint64 { return s.walSyncCalls.Load() } // holdExtentWrites holds the flusher's new extent writes until the returned -// release (idempotent): a cut's last pre-barrier pass and its pause then -// flush only the guest's WAL tail. The flusher waits before an extent write, -// holding no store lock, and stops waiting when it is stopped. +// release (idempotent). It returns only after every extent write already +// admitted has finished and been counted, so a baseline taken after it does +// not miss one. A writer blocked at the WAL hard mark lets the flusher write +// through the hold (writerAtHardMark): a held flusher never stalls the guest. func (s *WALStore) holdExtentWrites() (release func()) { ch := make(chan struct{}) - s.extentHold.Store(&ch) + s.extentGate.Lock() + s.extentHoldWake.Store(&ch) + s.extentHeld.Store(true) + s.extentGate.Unlock() var once sync.Once return func() { once.Do(func() { - s.extentHold.CompareAndSwap(&ch, nil) + s.extentHeld.Store(false) close(ch) }) } } +// admitExtentWrite admits one flusher extent write: while a cut holds them it +// waits (holding no store lock), unless a writer is blocked at the WAL hard +// mark or the flusher is stopping. The returned done is called once the write +// has finished and been counted. +func (s *WALStore) admitExtentWrite(stop <-chan struct{}) (done func()) { + for { + s.extentGate.RLock() + if !s.extentHeld.Load() || (s.writerAtHardMark() && !s.testHoldIgnoresHardMark) { + return s.extentGate.RUnlock + } + wake := s.extentHoldWake.Load() + s.extentGate.RUnlock() + s.extentHeldWaits.Add(1) + select { + case <-*wake: + case <-stop: + return func() {} + case <-time.After(time.Millisecond): // re-check the hard mark + } + } +} + +// tryCaptureLockWhileHeld tries for captureMu's write side for at most +// bound, without ever waiting on a reader: it returns "" holding the lock, or, +// not holding it, why it gave up: "writer_at_hard_mark" once a guest write +// waits at the WAL hard mark, "barrier_busy" when the bound passes. +func (s *WALStore) tryCaptureLockWhileHeld(bound time.Duration) string { + deadline := time.Now().Add(bound) + for { + if s.writerAtHardMark() { + return "writer_at_hard_mark" + } + if s.captureMu.TryLock() { // no reader left, so none parked in admission + return "" + } + if !time.Now().Before(deadline) { + return "barrier_busy" + } + runtime.Gosched() + } +} + +// writerAtHardMark reports a guest write waiting for WAL space at the hard +// mark (admission's latest sample). +func (s *WALStore) writerAtHardMark() bool { + return s.admission != nil && s.admission.hardBlocked.Load() +} + // storeFileDirtiedBytes counts the bytes written into the store file in this // open: WAL appends and the flusher's extent writes (cumulative atomics). func (s *WALStore) storeFileDirtiedBytes() uint64 { diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 2b07cbef56..8c99afccc3 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -314,8 +314,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.PauseCandidateOps` | int64 | PauseCandidateOps counts per-candidate operations done while the guest is paused (from the barrier lock to its release): zero when the pause does O(1) work. | | `Volumes[].Chunk.Stats.LastCut.PreSyncNs` | int64 | PreSyncNs is the sync right before the barrier, outside the guest pause (never part of BarrierPauseNs): the pause's own sync then has only what came after it. | | `Volumes[].Chunk.Stats.LastCut.PreSyncRounds` | int | pre-barrier sync passes (repeated until the tail is at most the bound) | -| `Volumes[].Chunk.Stats.LastCut.TailBytes` | uint64 | TailBytes is the store-file bytes (WAL appends and extent writes) dirtied from the start of the last pre-barrier sync pass (the one run with the flusher's extent writes held) to the barrier lock: what the pause's own sync has to flush. TailOverBound is set when it is above the bound (a finding; the cut proceeds). | -| `Volumes[].Chunk.Stats.LastCut.TailOverBound` | bool | (group of `TailBytes`) TailBytes is the store-file bytes (WAL appends and extent writes) dirtied from the start of the last pre-barrier sync pass (the one run with the flusher's extent writes held) to the barrier lock: what the pause's own sync has to flush. TailOverBound is set when it is above the bound (a finding; the cut proceeds). | +| `Volumes[].Chunk.Stats.LastCut.TailBytes` | uint64 | TailBytes is the store-file bytes (WAL appends and extent writes) dirtied from the start of the last pre-barrier sync pass (the one run with the flusher's extent writes held) to the barrier lock: what the pause's own sync has to flush. TailOverBound is set when it is above the bound, or when the hold was given up before the barrier (a finding; the cut proceeds). TailCause says which: "tail", "writer_at_hard_mark" (a guest write waited for WAL space, so the flusher was let through) or "barrier_busy" (the barrier lock was not free within its short try). | +| `Volumes[].Chunk.Stats.LastCut.TailOverBound` | bool | (group of `TailBytes`) TailBytes is the store-file bytes (WAL appends and extent writes) dirtied from the start of the last pre-barrier sync pass (the one run with the flusher's extent writes held) to the barrier lock: what the pause's own sync has to flush. TailOverBound is set when it is above the bound, or when the hold was given up before the barrier (a finding; the cut proceeds). TailCause says which: "tail", "writer_at_hard_mark" (a guest write waited for WAL space, so the flusher was let through) or "barrier_busy" (the barrier lock was not free within its short try). | +| `Volumes[].Chunk.Stats.LastCut.TailCause` | string | (group of `TailBytes`) TailBytes is the store-file bytes (WAL appends and extent writes) dirtied from the start of the last pre-barrier sync pass (the one run with the flusher's extent writes held) to the barrier lock: what the pause's own sync has to flush. TailOverBound is set when it is above the bound, or when the hold was given up before the barrier (a finding; the cut proceeds). TailCause says which: "tail", "writer_at_hard_mark" (a guest write waited for WAL space, so the flusher was let through) or "barrier_busy" (the barrier lock was not free within its short try). | | `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | From e0be76898309932995a089a40542584431190b04 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 11:16:59 -0800 Subject: [PATCH 5/7] volume: the /chunk/cut body mirrors the pre-barrier tail stats PreSyncRounds, TailBytes, TailOverBound and TailCause join the cut body, which mirrors the storage cut stats field for field. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/chunk_control.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index ce26c0ef76..060c0351d0 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -64,6 +64,10 @@ type ChunkCutStatsBody struct { SyncPhases storage.SyncPhaseStats `json:"syncPhases"` CandidateVisits int64 `json:"candidateVisits"` // chunk indices the barrier's candidate step touched PreSyncNs int64 `json:"preSyncNs"` // the sync right before the barrier, outside the pause + PreSyncRounds int `json:"preSyncRounds"` // pre-barrier sync passes (the last with flusher extent writes held) + TailBytes uint64 `json:"tailBytes"` // store-file bytes the pause's own sync flushes + TailOverBound bool `json:"tailOverBound"` // the tail was over its bound or the hold was given up (a finding) + TailCause string `json:"tailCause"` // why TailOverBound: tail, writer_at_hard_mark or barrier_busy PauseCandidateOps int64 `json:"pauseCandidateOps"` // per-candidate operations done while the guest was paused CandidateNs int64 `json:"candidateNs"` WindowSetupNs int64 `json:"windowSetupNs"` @@ -117,6 +121,10 @@ func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { SyncPhases: s.SyncPhases, CandidateVisits: s.CandidateVisits, PreSyncNs: s.PreSyncNs, + PreSyncRounds: s.PreSyncRounds, + TailBytes: s.TailBytes, + TailOverBound: s.TailOverBound, + TailCause: s.TailCause, PauseCandidateOps: s.PauseCandidateOps, CandidateNs: s.CandidateNs, WindowSetupNs: s.WindowSetupNs, From 419f2b65b53f92df3fc850239d74cff6e9d391b5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 11:43:00 -0800 Subject: [PATCH 6/7] storage: #959 tests: contested arrival, a busy-barrier witness, a failed held sync The gate test runs in a bounded child, sees each side reach the contested boundary (the hold pending on the gate, the new extent write counted as waiting) before asserting, and releases and joins on every exit. A new red holds a capture reader without WAL pressure: the barrier must give the hold up while that reader is still held and report barrier_busy. A new control fails the held last pass's own sync (a test-only fault seam) and requires that error, a released hold and extent draining again; the cancellation control stays. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_presync_test.go | 153 ++++++++++++++++-- seaweed-block/core/storage/walstore.go | 6 + 2 files changed, 148 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_presync_test.go b/seaweed-block/core/storage/chunk_cut_presync_test.go index 988e125986..0055173a7a 100644 --- a/seaweed-block/core/storage/chunk_cut_presync_test.go +++ b/seaweed-block/core/storage/chunk_cut_presync_test.go @@ -2,7 +2,9 @@ package storage import ( "context" + "errors" "path/filepath" + "sync" "sync/atomic" "testing" "time" @@ -329,33 +331,75 @@ func TestAHeldFlusherWritesThroughForAWriterAtTheHardMark(t *testing.T) { // The hold is serialized with extent-write admission: an extent write the // flusher was admitted to before the hold is finished (and counted) before // holdExtentWrites returns, so the last pass's baseline cannot miss it; one -// asked for after the hold waits until the release. (A check-only hold -// returned at once, with that write still to land in the held pass.) +// asked for after the hold waits until the release. Each side is first seen +// at the contested boundary: the hold pending on the gate (a pending writer +// makes TryRLock fail) and the new write counted as waiting. (A check-only +// hold returned at once, with that write still to land in the held pass.) func TestAHoldWaitsForAnAdmittedExtentWriteAndHoldsNewOnes(t *testing.T) { + if !inBoundedChild(t) { + if err := runBoundedChild(t.Name(), boundedChildBound); err != nil { + t.Fatal(err) + } + return + } s, _ := newChunkTestStore(t) stop := make(chan struct{}) - defer close(stop) admitted := s.admitExtentWrite(stop) // the flusher, admitted and mid-write + var once sync.Once + finish := func() { once.Do(admitted) } held := make(chan func(), 1) go func() { held <- s.holdExtentWrites() }() - select { - case <-held: - t.Fatal("the hold returned while an admitted extent write was still in flight") - case <-time.After(20 * time.Millisecond): - } - admitted() var release func() + t.Cleanup(func() { // every exit: the admitted write ends, the hold is released, waiters stop + finish() + if release == nil { + select { + case release = <-held: + case <-time.After(ctLocalBound): + } + } + if release != nil { + release() + } + close(stop) + }) + for deadline := time.Now().Add(ctLocalBound); ; time.Sleep(100 * time.Microsecond) { + select { + case release = <-held: + t.Fatal("the hold returned while an admitted extent write was still in flight") + default: + } + if !s.extentGate.TryRLock() { + break // the hold is pending on the gate, behind the admitted write + } + s.extentGate.RUnlock() + if time.Now().After(deadline) { + t.Fatal("setup: the hold never reached the gate") + } + } + finish() select { case release = <-held: case <-time.After(ctLocalBound): t.Fatal("the hold did not return after the admitted write finished") } + waits := s.extentHeldWaits.Load() next := make(chan struct{}) go func() { s.admitExtentWrite(stop)(); close(next) }() + for deadline := time.Now().Add(ctLocalBound); s.extentHeldWaits.Load() == waits; time.Sleep(100 * time.Microsecond) { + select { + case <-next: + t.Fatal("an extent write was admitted while the hold was on") + default: + } + if time.Now().After(deadline) { + t.Fatal("setup: the new extent write never reached the hold") + } + } select { case <-next: t.Fatal("an extent write was admitted while the hold was on") - case <-time.After(20 * time.Millisecond): + default: } release() select { @@ -363,7 +407,54 @@ func TestAHoldWaitsForAnAdmittedExtentWriteAndHoldsNewOnes(t *testing.T) { case <-time.After(ctLocalBound): t.Fatal("the held extent write did not resume after the release") } - release() // idempotent +} + +// A capture reader the barrier cannot get past within its short try, with no +// WAL pressure: the barrier gives the hold up while that reader is still +// held (it never waits for it with the flusher stopped), then takes its lock +// once the reader leaves; the cut completes and reports barrier_busy. (A +// barrier that simply waited for its lock kept the hold on until the reader +// left.) +func TestABusyBarrierGivesItsHoldUpBeforeWaiting(t *testing.T) { + if !inBoundedChild(t) { + if err := runBoundedChild(t.Name(), boundedChildBound); err != nil { + t.Fatal(err) + } + return + } + s, l := hardMarkStore(t) + releasedWhileHeld := make(chan bool, 1) + l.testBeforeBarrierLockHook = func() { // the hold is on; the barrier is next + l.testBeforeBarrierLockHook = nil + s.captureMu.RLock() // a capture reader, as a guest write in flight holds it + go func() { + defer s.captureMu.RUnlock() + deadline := time.Now().Add(ctLocalBound) + for s.extentHeld.Load() && time.Now().Before(deadline) { + time.Sleep(100 * time.Microsecond) + } + releasedWhileHeld <- !s.extentHeld.Load() + }() + } + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x6a)); err != nil { + t.Fatal(err) + } + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + select { + case ok := <-releasedWhileHeld: + if !ok { + t.Fatal("the barrier kept the hold on while it waited for a capture reader") + } + case <-time.After(ctLocalBound): + t.Fatal("the reader never reported") + } + st := r.Stats + if !st.TailOverBound || st.TailCause != "barrier_busy" { + t.Fatalf("the finding: over=%v cause=%q, want barrier_busy", st.TailOverBound, st.TailCause) + } } // A cut that fails after the hold is on (its context ends during the held @@ -404,3 +495,43 @@ func TestACutThatFailsInItsHeldPassReleasesTheFlusher(t *testing.T) { } } } + +// A held last pass whose own sync fails: the cut returns that error, the +// hold is released on the way out, and the flusher drains again. +func TestACutWhoseHeldSyncFailsReleasesTheFlusher(t *testing.T) { + if !inBoundedChild(t) { + if err := runBoundedChild(t.Name(), boundedChildBound); err != nil { + t.Fatal(err) + } + return + } + s, l := hardMarkStore(t) + injected := errors.New("injected held-pass sync failure") + var failed atomic.Bool + s.testSyncCacheFault = func() error { + if !l.paused && s.extentHeld.Load() && failed.CompareAndSwap(false, true) { + return injected + } + return nil + } + t.Cleanup(func() { s.testSyncCacheFault = nil }) + if _, err := s.Write(0, makeBlock(ctBlockSize, 0x5c)); err != nil { + t.Fatal(err) + } + if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, injected) { + t.Fatalf("the cut's answer: %v, want the held sync's failure", err) + } + if s.extentHeld.Load() { + t.Fatal("the failed cut left the flusher's extent writes held") + } + before := s.flusher.instr.extentWriteBytes.Load() + if _, err := s.Write(1, makeBlock(ctBlockSize, 0x5d)); err != nil { + t.Fatal(err) + } + for deadline := time.Now().Add(ctLocalBound); s.flusher.instr.extentWriteBytes.Load() == before; time.Sleep(time.Millisecond) { + s.flusher.Notify() + if time.Now().After(deadline) { + t.Fatal("the flusher wrote no extent after the failed cut") + } + } +} diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 75e5a5587d..6b24288997 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -170,6 +170,7 @@ type WALStore struct { // is taken. Tests only. testBeforeFileSync func() testBeforeSyncCache func() // before a store Sync's file sync (syncWithPhases); tests only + testSyncCacheFault func() error // after it: a non-nil error fails that Sync (nothing latched); tests only 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 @@ -891,6 +892,11 @@ func (s *WALStore) syncWithPhases(phases *SyncPhaseStats) (uint64, error) { if h := s.testBeforeSyncCache; h != nil { h() // tests only: a stand-in for write-back that grows with what is dirty } + if f := s.testSyncCacheFault; f != nil { + if err := f(); err != nil { + return 0, fmt.Errorf("storage: group commit fsync: %w", err) + } + } if err := s.syncCache(); err != nil { return 0, fmt.Errorf("storage: group commit fsync: %w", err) } From 260aeffda1fb5d02a29bbee0485d6b0b7861d8a3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 11:52:26 -0800 Subject: [PATCH 7/7] storage: #959 gate test joins both workers before the store closes The cleanup keeps both worker handles in scope: it ends the admitted write and releases the hold, then joins the hold worker and, if started, the held extent-write worker, each bounded with a reported timeout, and closes stop only after the joins. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_cut_presync_test.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_presync_test.go b/seaweed-block/core/storage/chunk_cut_presync_test.go index 0055173a7a..82b23eb228 100644 --- a/seaweed-block/core/storage/chunk_cut_presync_test.go +++ b/seaweed-block/core/storage/chunk_cut_presync_test.go @@ -350,17 +350,31 @@ func TestAHoldWaitsForAnAdmittedExtentWriteAndHoldsNewOnes(t *testing.T) { held := make(chan func(), 1) go func() { held <- s.holdExtentWrites() }() var release func() - t.Cleanup(func() { // every exit: the admitted write ends, the hold is released, waiters stop + next := make(chan struct{}) // the second worker's end; nil until it starts + var nextStarted bool + // Every exit, before the store's own cleanup: the admitted write ends and + // the hold is released, then each started worker is joined (bounded, a + // timeout reported). Releasing the hold lets the second worker finish; + // stop is closed only after the joins. + t.Cleanup(func() { finish() if release == nil { select { case release = <-held: case <-time.After(ctLocalBound): + t.Error("cleanup: the hold worker did not return") } } if release != nil { release() } + if nextStarted { + select { + case <-next: + case <-time.After(ctLocalBound): + t.Error("cleanup: the held extent-write worker did not finish") + } + } close(stop) }) for deadline := time.Now().Add(ctLocalBound); ; time.Sleep(100 * time.Microsecond) { @@ -384,7 +398,7 @@ func TestAHoldWaitsForAnAdmittedExtentWriteAndHoldsNewOnes(t *testing.T) { t.Fatal("the hold did not return after the admitted write finished") } waits := s.extentHeldWaits.Load() - next := make(chan struct{}) + nextStarted = true go func() { s.admitExtentWrite(stop)(); close(next) }() for deadline := time.Now().Add(ctLocalBound); s.extentHeldWaits.Load() == waits; time.Sleep(100 * time.Microsecond) { select {