Merge pull request #959 from seaweedfs/feat/presync-until-short

storage: the pre-barrier sync repeats until its tail is bounded
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-02 12:37:58 -08:00
commit 8145e4decf
7 files changed
+753 -9

No files matched your search

@@ -68,6 +68,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"`
@@ -121,6 +125,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,
@@ -0,0 +1,551 @@
package storage
import (
"context"
"errors"
"path/filepath"
"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). 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)
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() {
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)
}
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{})
go func() { // the guest, writing through the cut
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 { // 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)
}
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 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
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,
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 waits for a guest write: never reached
t.Cleanup(func() { preSyncTailBound = saved })
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)
}
}
// 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() }
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, 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)
}
}
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, done := make(chan struct{}), make(chan struct{})
go func() { // the guest, writing through the cut
defer close(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)
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 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. 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{})
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() }()
var release func()
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) {
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()
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 {
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")
default:
}
release()
select {
case <-next:
case <-time.After(ctLocalBound):
t.Fatal("the held extent write did not resume after the release")
}
}
// 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
// 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")
}
}
}
// 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")
}
}
}
+71 -6
View File
@@ -1522,6 +1522,24 @@ func (l *chunkLayerImpl) recordCapturedEqualMarks(captured []capturedChunk, vers
}
}
// 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
// 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) {
defer func() { err = l.latchIdentityMoved(err) }()
done, err := l.register()
@@ -1688,14 +1706,45 @@ 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 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()
if _, err := l.s.syncWithPhases(nil); err != nil {
preSyncPass := func() error {
st.PreSyncRounds++
if _, err := l.s.syncWithPhases(nil); err != nil {
st.PreSyncNs = time.Since(preSync).Nanoseconds()
return fmt.Errorf("storage: capture sync (before the barrier): %w", err)
}
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
}
}
if cause := context.Cause(ctx); cause != nil { // ended during an unheld pass
st.PreSyncNs = time.Since(preSync).Nanoseconds()
return chunkCutResult{}, fmt.Errorf("storage: capture sync (before the barrier): %w", err)
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
// 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()
@@ -1727,6 +1776,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
@@ -1735,7 +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
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()
@@ -1787,6 +1851,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
+13 -1
View File
@@ -433,7 +433,19 @@ 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 passes (repeated until the tail is at most the bound)
// 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).
TailBytes uint64
TailOverBound bool
TailCause string
// Disjoint non-payload intervals within barrier-to-settlement fixed cost.
CandidateNs int64
WindowSetupNs int64
+2
View File
@@ -369,11 +369,13 @@ func (f *flusher) flushCycle(allowClosed bool, p flushPass) (r flushCycleResult,
if f.beforeExtentWriteForTest != nil {
f.beforeExtentWriteForTest()
}
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)
}
+104 -2
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"time"
@@ -168,9 +169,22 @@ 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
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
// 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
@@ -874,8 +888,18 @@ 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 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)
}
}
if phases != nil {
phases.GroupCommitNs += time.Since(at).Nanoseconds()
@@ -1243,6 +1267,84 @@ 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). 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.extentGate.Lock()
s.extentHoldWake.Store(&ch)
s.extentHeld.Store(true)
s.extentGate.Unlock()
var once sync.Once
return func() {
once.Do(func() {
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 {
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 {
+4
View File
@@ -313,6 +313,10 @@ 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 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, 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. |