From 74fab1baf090024ad438bc15d4c5c562e9f730ab Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 16:58:15 -0800 Subject: [PATCH 1/6] durable: tests for timer cuts refused for held host slots (red) A periodic cut refused because every host cut slot is held must be a wait, not a failure: no backoff, retry after the volume's jitter, and the wait reported in status. The types the tests name are added; the behaviour is not. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/cut_loop_fence_test.go | 2 +- .../core/frontend/durable/cut_policy_test.go | 44 +++++++++ .../frontend/durable/host_slot_wait_test.go | 99 +++++++++++++++++++ .../core/frontend/durable/provider.go | 7 ++ .../core/frontend/durable/provider_chunk.go | 11 ++- seaweed-block/core/hostlimit/limiter.go | 9 +- 6 files changed, 167 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/host_slot_wait_test.go diff --git a/seaweed-block/core/frontend/durable/cut_loop_fence_test.go b/seaweed-block/core/frontend/durable/cut_loop_fence_test.go index 42800970c1..febe7a702d 100644 --- a/seaweed-block/core/frontend/durable/cut_loop_fence_test.go +++ b/seaweed-block/core/frontend/durable/cut_loop_fence_test.go @@ -31,7 +31,7 @@ func TestChunkLoop_EndsWhenTheLayerIsFenced(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() done := make(chan struct{}) - go p.chunkLoop(ctx, "v1", layer, done) + go p.chunkLoop(ctx, "v1", layer, done, nil) deadline := time.Now().Add(5 * time.Second) for layer.cuts.Load() == 0 { if time.Now().After(deadline) { diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index 415a178d1e..5fb066a80e 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -5,8 +5,12 @@ package durable import ( "errors" + "fmt" "testing" "time" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" ) var t0 = time.Unix(1_700_000_000, 0) @@ -206,3 +210,43 @@ func TestCutPolicy_TimerRunsOnObservationTime(t *testing.T) { t.Fatalf("the cut existing at start was taken in as new: %+v", got) } } + +// A cut refused because every host slot is held ran nothing: no backoff, +// no minimum spacing, the timer is not reset, and the retry comes after +// the volume's slot jitter. The wait is counted and its start kept until +// a cut succeeds. Any other error still backs off. +func TestCutPolicy_HostSlotBusyIsAWaitNotAFailure(t *testing.T) { + pol := testPolicy() + pol.slotJitter = 150 * time.Millisecond + busy := fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrSlotsHeld) + s := cutSchedule{lastSuccess: t0} + now := at(30 * time.Second) + for i := 0; i < 5; i++ { + s = pol.after(s, now, now.Add(time.Millisecond), busy, 0) + if s.backoff != 0 || !s.lastAuto.IsZero() || !s.lastSuccess.Equal(t0) { + t.Fatalf("busy refusal %d treated as a cut or a failure: %+v", i, s) + } + if _, ok := pol.dueNR(s, now.Add(100*time.Millisecond)); ok { + t.Fatalf("busy retry %d due before its jitter", i) + } + now = now.Add(time.Millisecond + pol.slotJitter) + if _, ok := pol.dueNR(s, now); !ok { + t.Fatalf("busy retry %d not due after its jitter", i) + } + } + if s.slotWaits != 5 || !s.slotWaitSince.Equal(at(30*time.Second)) { + t.Fatalf("waits %d since %v; want 5 since the first refusal", s.slotWaits, s.slotWaitSince) + } + s = pol.after(s, now, now, nil, 101) + if !s.slotWaitSince.IsZero() || s.slotWaits != 5 { + t.Fatalf("success must end the wait and keep the count: %+v", s) + } + refusedOther := fmt.Errorf("%w: not primary", storage.ErrChunkCaptureRefused) + if s = pol.after(s, now, now, refusedOther, 101); s.backoff != time.Second { + t.Fatalf("another refusal must back off: %+v", s) + } + tooLarge := fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrBusy) + if s = pol.after(s, now, now, tooLarge, 101); s.backoff != 2*time.Second { + t.Fatalf("a busy result that is not held slots must back off: %+v", s) + } +} diff --git a/seaweed-block/core/frontend/durable/host_slot_wait_test.go b/seaweed-block/core/frontend/durable/host_slot_wait_test.go new file mode 100644 index 0000000000..ca59221668 --- /dev/null +++ b/seaweed-block/core/frontend/durable/host_slot_wait_test.go @@ -0,0 +1,99 @@ +package durable_test + +import ( + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A timer cut refused because every host slot is held is a wait, not a +// failure: once the slot frees, the cut runs within one poll plus the +// volume's jitter, however long the slot was held. +func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { + c := hostlimit.DefaultConfig(t.TempDir()) + c.NormalSlots, c.UrgentSlots = 1, 1 + holder, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + defer holder.Close() + ticket, err := holder.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + held := true + defer func() { + if held { + holder.Release(ticket) + } + }() + lim, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + defer lim.Close() + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, + ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkCaptureInterval: 100 * time.Millisecond, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + defer p.Close() + s := openRecovered(t, p) + if _, err = s.Write(0, block(0x5c)); err != nil { + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + + // Long enough for a failure backoff to have grown past 1 s. + time.Sleep(2500 * time.Millisecond) + cs := chunkStatus(t, p) + if h, _ := remote.GetHead(context.Background()); h.Gen != 0 { + t.Fatal("a cut published while the only slot was held") + } + if cs.CutSchedule == nil || cs.CutSchedule.HostSlotWaits == 0 || cs.CutSchedule.HostSlotWaitSinceNs == 0 { + t.Fatalf("waiting for a host slot is not reported: %+v", cs.CutSchedule) + } + + holder.Release(ticket) + held = false + freed := time.Now() + for { + if h, _ := remote.GetHead(context.Background()); h.Gen != 0 { + break + } + if time.Since(freed) > 300*time.Millisecond { + t.Fatalf("no cut within 300 ms of the slot freeing") + } + time.Sleep(5 * time.Millisecond) + } + deadline := time.Now().Add(time.Second) + for { + cs = chunkStatus(t, p) + if cs.CutSchedule != nil && cs.CutSchedule.HostSlotWaitSinceNs == 0 { + break + } + if time.Now().After(deadline) { + t.Fatalf("the wait is still reported after a successful cut: %+v", cs.CutSchedule) + } + time.Sleep(10 * time.Millisecond) + } +} + +func chunkStatus(t *testing.T, p *durable.DurableProvider) durable.ChunkStatus { + t.Helper() + for _, st := range p.DurableStatuses() { + if st.VolumeID == "v1" && st.Chunk != nil { + return *st.Chunk + } + } + t.Fatal("no chunk status for v1") + return durable.ChunkStatus{} +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index f3e73a9c8f..fcc6756528 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -343,6 +343,13 @@ type ChunkStatus struct { Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir ScheduledSnapshot *ScheduledSnapshotStatus `json:",omitempty"` // the scheduled-snapshot state; absent when the schedule is off or its loop has not started + CutSchedule *CutScheduleStatus `json:",omitempty"` // the automatic-cut timer's state; absent when the timer is off or its loop has not started +} + +// CutScheduleStatus is the automatic-cut timer's view of host slot waits. +type CutScheduleStatus struct { + HostSlotWaits uint64 // automatic cuts refused because every host slot was held + HostSlotWaitSinceNs int64 // wall time of the first such refusal since the last successful cut; 0 when not waiting } // NewDurableProvider constructs a provider. view is the ONLY diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index e7a877d293..e09347215a 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -663,6 +663,7 @@ const ( // restarts the timer. type cutPolicy struct { interval, minSpacing, backoffMin, backoffMax time.Duration + slotJitter time.Duration // this volume's delay before retrying a cut refused for held host slots } // cutSchedule runs on in-process monotonic time: every time in it is a @@ -679,6 +680,8 @@ type cutSchedule struct { firstDue time.Time // startup phase only; never a fabricated success seenSeq uint64 // the layer's CutSeq last taken in failedSeenSeq uint64 // the layer's CutSeq when the last automatic cut failed + slotWaitSince time.Time // first refusal for held host slots since the last success; zero when not waiting + slotWaits uint64 // automatic cuts refused for held host slots } // observe takes in, at now, the latest cut the layer reports (any @@ -760,7 +763,7 @@ func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, // cut (not a healthy primary of this lineage, BASE install) is expected // and logged only when it is something else. A fenced layer can never // publish again: the loop ends. -func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, done chan struct{}) { +func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, done chan struct{}, wait *cutWaitSlot) { defer close(done) pol := cutPolicy{ interval: p.cfg.ChunkCaptureInterval, @@ -831,7 +834,7 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca go func() { defer workers.Done() cutDone := make(chan struct{}) - p.chunkLoop(ctx, volumeID, layer, cutDone) + p.chunkLoop(ctx, volumeID, layer, cutDone, nil) }() } if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil { @@ -1360,3 +1363,7 @@ func (p *DurableProvider) publishSettledHook(volumeID string) func(context.Conte } return func(ctx context.Context, prev, next storage.ChunkHead) { hook(ctx, volumeID, prev, next) } } + +// cutWaitSlot publishes the automatic-cut timer's host slot waits to +// status. +type cutWaitSlot struct{} diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 3ab765d5e6..9617672dac 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -18,6 +18,11 @@ import ( ) var ErrBusy = errors.New("hostlimit: no background slot") + +// ErrSlotsHeld is the ErrBusy of a host whose slots are all held by other +// work: retrying once one is released can succeed. Other ErrBusy results +// (an oversized payload, an unusable pool) do not change by waiting. +var ErrSlotsHeld = fmt.Errorf("%w: every slot is held", ErrBusy) var ErrConfig = errors.New("hostlimit: incompatible host configuration") var ErrRevoked = errors.New("hostlimit: cut budget revoked") @@ -184,7 +189,7 @@ func (l *Limiter) pool(c Class) (*os.File, error) { return nil, e } } - return nil, ErrBusy + return nil, ErrSlotsHeld } // publishConfig runs under the configuration OS lock. A killed initializer @@ -285,7 +290,7 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) ( if ctx.Err() != nil { return 0, ctx.Err() } - return 0, ErrBusy + return 0, ErrSlotsHeld } l.next++ id := l.next From 57e30e11c0176eaaa5133debfd2c062dfbb54acf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 16:58:33 -0800 Subject: [PATCH 2/6] durable: a timer cut refused for held host slots waits instead of backing off Host admission is a try-lock. With one cut slot per host, every volume whose timer fires while another volume's cut holds the slot was refused and backed off 1 s doubling to 30 s, adding up to 30 s to its interval and favouring whichever volume happened to win. hostlimit returns ErrSlotsHeld (an ErrBusy) when every slot is held. The cut policy treats that refusal as a wait: no backoff, no minimum spacing, the timer is not reset, and the retry comes after the volume's stable slot jitter (at most 200 ms). Other errors, an oversized payload or an unusable pool included, keep the backoff. Status reports CutSchedule.HostSlotWaits and HostSlotWaitSinceNs, the start of the current wait (0 when not waiting). Ledger row INV-CUT-TIMER-SLOT-WAIT-001. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 10 +++- .../core/frontend/durable/provider_chunk.go | 60 +++++++++++++++++-- seaweed-block/docs/design/invariants.md | 3 +- 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index fcc6756528..d8bcc6e4ca 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -299,6 +299,9 @@ type volHandle struct { // snapshots is the scheduled-snapshot state of the running loop, nil // when the schedule is off. snapshots *snapshotSlot + // cutWait is the automatic-cut timer's host slot waits, nil when the + // timer is off. + cutWait *cutWaitSlot } // VolumeStatus is a read-only diagnostic snapshot of one durable volume @@ -606,6 +609,7 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { layer storage.ChunkLayer awaiting bool snapshots *snapshotSlot + cutWait *cutWaitSlot } p.mu.Lock() handles := make(map[string]*volHandle, len(p.volumes)) @@ -613,7 +617,7 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { for volumeID, h := range p.volumes { handles[volumeID] = h if p.cfg.Impl == ImplWALStoreChunk { - chunks[volumeID] = chunkView{layer: h.chunk, awaiting: h.waitGen != 0, snapshots: h.snapshots} + chunks[volumeID] = chunkView{layer: h.chunk, awaiting: h.waitGen != 0, snapshots: h.snapshots, cutWait: h.cutWait} } } p.mu.Unlock() @@ -633,6 +637,10 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { ss := cv.snapshots.status(time.Now()) cs.ScheduledSnapshot = &ss } + if cv.cutWait != nil { + cw := cv.cutWait.status() + cs.CutSchedule = &cw + } st.Chunk = cs } out = append(out, st) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index e09347215a..7957c66377 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -333,9 +333,14 @@ func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer st } else if h.snapshots == nil { h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now())} } + if p.cfg.ChunkCaptureInterval <= 0 { + h.cutWait = nil + } else if h.cutWait == nil { + h.cutWait = &cutWaitSlot{} + } lin := h.chunkLineage current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) } - go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current, h.snapshots) + go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current, h.snapshots, h.cutWait) } func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { @@ -646,6 +651,7 @@ const ( chunkCutMinSpacing = time.Second chunkCutBackoffMin = time.Second chunkCutBackoffMax = 30 * time.Second + chunkSlotJitterMax = 200 * time.Millisecond ) // cutPolicy decides when an automatic cut is due. The remote holds @@ -660,7 +666,11 @@ const ( // - a failed automatic cut resets nothing and is retried after a backoff // doubling from backoffMin to backoffMax; any later successful cut (a // no-op cut and an explicit cut included) clears the backoff and -// restarts the timer. +// restarts the timer; +// - an automatic cut refused because every host slot is held ran +// nothing: it is retried after the volume's slot jitter, with no +// backoff and no minimum spacing, and the wait lasts until a cut +// succeeds. type cutPolicy struct { interval, minSpacing, backoffMin, backoffMax time.Duration slotJitter time.Duration // this volume's delay before retrying a cut refused for held host slots @@ -696,6 +706,7 @@ func (s cutSchedule) observe(seq uint64, now time.Time) cutSchedule { s.lastSuccess = now } s.firstDue = time.Time{} + s.slotWaitSince = time.Time{} if !s.failedAt.IsZero() && seq != s.failedSeenSeq { s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} } @@ -725,10 +736,19 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string // after records the outcome of an automatic cut started at start, with // the layer's CutSeq read after it. func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq uint64) cutSchedule { + if errors.Is(err, hostlimit.ErrSlotsHeld) { + s.slotWaits++ + if s.slotWaitSince.IsZero() { + s.slotWaitSince = start + } + s.retryAt = end.Add(pol.slotJitter) + return s + } s.lastAuto = start if err == nil { s.seenSeq = seq s.firstDue = time.Time{} + s.slotWaitSince = time.Time{} s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} if end.After(s.lastSuccess) { s.lastSuccess = end @@ -770,8 +790,12 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer minSpacing: chunkCutMinSpacing, backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax, + slotJitter: hostlimit.Phase(volumeID+":slot", chunkSlotJitterMax), } s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger, layer.Stats().CutSeq) + if wait != nil { + s.slotWaits = wait.status().HostSlotWaits + } t := time.NewTicker(chunkSchedulePoll) defer t.Stop() for { @@ -786,6 +810,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer ls := layer.Stats() start := time.Now() s = s.observe(ls.CutSeq, start) + wait.record(s) reason, ok := pol.due(s, start, ls.Reconciling) if !ok { continue @@ -816,6 +841,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } cancel() s = pol.after(s, start, time.Now(), err, layer.Stats().CutSeq) + wait.record(s) if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff) } @@ -825,7 +851,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer // chunkBackground owns both workers and their cancellation. A fence is observed // even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN: // done closes only after every admitted worker has returned. -func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot) { +func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot, cutWait *cutWaitSlot) { defer close(done) defer cancel() var workers sync.WaitGroup @@ -834,7 +860,7 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca go func() { defer workers.Done() cutDone := make(chan struct{}) - p.chunkLoop(ctx, volumeID, layer, cutDone, nil) + p.chunkLoop(ctx, volumeID, layer, cutDone, cutWait) }() } if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil { @@ -1365,5 +1391,27 @@ func (p *DurableProvider) publishSettledHook(volumeID string) func(context.Conte } // cutWaitSlot publishes the automatic-cut timer's host slot waits to -// status. -type cutWaitSlot struct{} +// status. A nil slot records nothing. +type cutWaitSlot struct { + mu sync.Mutex + st CutScheduleStatus +} + +func (w *cutWaitSlot) record(s cutSchedule) { + if w == nil { + return + } + st := CutScheduleStatus{HostSlotWaits: s.slotWaits} + if !s.slotWaitSince.IsZero() { + st.HostSlotWaitSinceNs = s.slotWaitSince.UnixNano() + } + w.mu.Lock() + w.st = st + w.mu.Unlock() +} + +func (w *cutWaitSlot) status() CutScheduleStatus { + w.mu.Lock() + defer w.mu.Unlock() + return w.st +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7847a9c0a8..62e440807b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -403,7 +403,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -185 rows: 163 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 170 new. +186 rows: 164 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 171 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -599,6 +599,7 @@ Notes: | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | | `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | +| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff and no minimum spacing; it retries after the volume's slot jitter (at most 200 ms), and status reports the wait count and start until a cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees` (`core/frontend/durable/host_slot_wait_test.go`) | — | ACTIVE | A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. From 1d861a806c8d35a3c0a99586cc1df9316d2d42a1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:13:21 -0800 Subject: [PATCH 3/6] durable: slot wait ends with any later cut; a closed limiter refuses as revoked - Status ends a recorded host slot wait once the layer's CutSeq moves past the one it was recorded under, so a detach's seal (made after the timer stopped) or an explicit cut clears it; the count is kept. - A successful cut observed during a slot wait also drops the pending slot retry. - Admission that finds the limiter closed after acquiring its pool slot returns ErrRevoked, not ErrSlotsHeld. - The provider test witnesses every refused attempt with a timestamp (at least 8 in 2.5 s, none more than 400 ms apart), then bounds the admission after the slot frees (400 ms) and publication (5 s) separately. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/cut_policy_test.go | 31 +++++ .../frontend/durable/host_slot_wait_test.go | 121 +++++++++++++----- .../core/frontend/durable/provider.go | 2 +- .../core/frontend/durable/provider_chunk.go | 25 +++- seaweed-block/core/hostlimit/limiter.go | 6 +- seaweed-block/core/hostlimit/limiter_test.go | 27 ++++ seaweed-block/docs/design/invariants.md | 2 +- 7 files changed, 171 insertions(+), 43 deletions(-) diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index 5fb066a80e..e6986adb20 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -250,3 +250,34 @@ func TestCutPolicy_HostSlotBusyIsAWaitNotAFailure(t *testing.T) { t.Fatalf("a busy result that is not held slots must back off: %+v", s) } } + +// A successful cut observed during a slot wait (an explicit cut) ends the +// wait and its pending retry; the count is kept. +func TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry(t *testing.T) { + pol := testPolicy() + pol.interval = 100 * time.Millisecond + pol.slotJitter = 150 * time.Millisecond + busy := fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrSlotsHeld) + s := cutSchedule{lastSuccess: t0, seenSeq: 100} + s = pol.after(s, at(time.Second), at(time.Second), busy, 100) + s = s.observe(101, at(time.Second+10*time.Millisecond)) + if !s.retryAt.IsZero() || !s.slotWaitSince.IsZero() || s.slotWaits != 1 { + t.Fatalf("explicit success left the slot wait: %+v", s) + } + if _, ok := pol.dueNR(s, at(time.Second+110*time.Millisecond)); !ok { + t.Fatal("next timer cut held back by a stale slot retry") + } +} + +// Status ends a recorded wait once the layer's CutSeq moves past the one +// it was recorded under, also when the timer is no longer running. +func TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut(t *testing.T) { + w := &cutWaitSlot{} + w.record(cutSchedule{seenSeq: 5, slotWaits: 3, slotWaitSince: at(time.Second)}) + if st := w.status(5); st.HostSlotWaitSinceNs == 0 || st.HostSlotWaits != 3 { + t.Fatalf("wait not reported at its own CutSeq: %+v", st) + } + if st := w.status(6); st.HostSlotWaitSinceNs != 0 || st.HostSlotWaits != 3 { + t.Fatalf("wait reported after a later cut: %+v", st) + } +} diff --git a/seaweed-block/core/frontend/durable/host_slot_wait_test.go b/seaweed-block/core/frontend/durable/host_slot_wait_test.go index ca59221668..71a365068e 100644 --- a/seaweed-block/core/frontend/durable/host_slot_wait_test.go +++ b/seaweed-block/core/frontend/durable/host_slot_wait_test.go @@ -10,40 +10,41 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -// A timer cut refused because every host slot is held is a wait, not a -// failure: once the slot frees, the cut runs within one poll plus the -// volume's jitter, however long the slot was held. -func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { +// slotWaitProvider opens v1 with a 100 ms cut timer under a host limiter +// whose only normal slot another process holds; release frees it. +func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *hostlimit.Limiter, remote *storage.MemChunkRemote, release func()) { + t.Helper() c := hostlimit.DefaultConfig(t.TempDir()) c.NormalSlots, c.UrgentSlots = 1, 1 holder, err := hostlimit.New(c) if err != nil { t.Fatal(err) } - defer holder.Close() + t.Cleanup(holder.Close) ticket, err := holder.Admit(context.Background(), 1, nil) if err != nil { t.Fatal(err) } held := true - defer func() { + release = func() { if held { + held = false holder.Release(ticket) } - }() - lim, err := hostlimit.New(c) - if err != nil { + } + t.Cleanup(release) + if lim, err = hostlimit.New(c); err != nil { t.Fatal(err) } - defer lim.Close() - remote := storage.NewMemChunkRemote() - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, + t.Cleanup(lim.Close) + remote = storage.NewMemChunkRemote() + p, err = durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkCaptureInterval: 100 * time.Millisecond, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) if err != nil { t.Fatal(err) } - defer p.Close() + t.Cleanup(func() { p.Close() }) s := openRecovered(t, p) if _, err = s.Write(0, block(0x5c)); err != nil { t.Fatal(err) @@ -51,39 +52,93 @@ func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { if _, err = s.Sync(); err != nil { t.Fatal(err) } + return p, lim, remote, release +} - // Long enough for a failure backoff to have grown past 1 s. - time.Sleep(2500 * time.Millisecond) - cs := chunkStatus(t, p) +// watchWaits samples status every 10 ms for d and returns the times at +// which HostSlotWaits went up (one per refused timer cut). +func watchWaits(t *testing.T, p *durable.DurableProvider, d time.Duration) []time.Time { + t.Helper() + var at []time.Time + var last uint64 + for end := time.Now().Add(d); time.Now().Before(end); time.Sleep(10 * time.Millisecond) { + cs := chunkStatus(t, p).CutSchedule + if cs != nil && cs.HostSlotWaits > last { + for ; last < cs.HostSlotWaits; last++ { + at = append(at, time.Now()) + } + if cs.HostSlotWaitSinceNs == 0 { + t.Fatalf("waits counted but no wait start reported: %+v", cs) + } + } + } + return at +} + +// A timer cut refused because every host slot is held is retried within +// one poll plus the volume's jitter, every time, however long the slot is +// held; once it frees, the next attempt is admitted within that bound. +func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { + p, lim, remote, release := slotWaitProvider(t) + refusals := watchWaits(t, p, 2500*time.Millisecond) + // A failure backoff (1 s, 2 s, ...) allows at most 3 attempts in 2.5 s. + if len(refusals) < 8 { + t.Fatalf("%d refused attempts in 2.5 s; a slot wait retries every <= 300 ms", len(refusals)) + } + for i := 1; i < len(refusals); i++ { + if gap := refusals[i].Sub(refusals[i-1]); gap > 400*time.Millisecond { + t.Fatalf("retry %d came %s after the previous refusal", i, gap) + } + } if h, _ := remote.GetHead(context.Background()); h.Gen != 0 { t.Fatal("a cut published while the only slot was held") } - if cs.CutSchedule == nil || cs.CutSchedule.HostSlotWaits == 0 || cs.CutSchedule.HostSlotWaitSinceNs == 0 { - t.Fatalf("waiting for a host slot is not reported: %+v", cs.CutSchedule) - } - holder.Release(ticket) - held = false + admitted := lim.Snapshot().(hostlimit.Stats).Admitted + release() freed := time.Now() - for { - if h, _ := remote.GetHead(context.Background()); h.Gen != 0 { - break - } - if time.Since(freed) > 300*time.Millisecond { - t.Fatalf("no cut within 300 ms of the slot freeing") + for lim.Snapshot().(hostlimit.Stats).Admitted == admitted { + if time.Since(freed) > 400*time.Millisecond { + t.Fatal("no cut admitted within 400 ms of the slot freeing") } time.Sleep(5 * time.Millisecond) } - deadline := time.Now().Add(time.Second) - for { - cs = chunkStatus(t, p) - if cs.CutSchedule != nil && cs.CutSchedule.HostSlotWaitSinceNs == 0 { + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if h, _ := remote.GetHead(context.Background()); h.Gen != 0 { break } if time.Now().After(deadline) { - t.Fatalf("the wait is still reported after a successful cut: %+v", cs.CutSchedule) + t.Fatal("the admitted cut did not publish within 5 s") } - time.Sleep(10 * time.Millisecond) + } + for deadline := time.Now().Add(time.Second); ; time.Sleep(10 * time.Millisecond) { + if cs := chunkStatus(t, p).CutSchedule; cs != nil && cs.HostSlotWaitSinceNs == 0 && cs.HostSlotWaits >= uint64(len(refusals)) { + break + } + if time.Now().After(deadline) { + t.Fatalf("the wait is still reported after a successful cut: %+v", chunkStatus(t, p).CutSchedule) + } + } +} + +// A plain detach stops the timer before its seal; the seal (urgent, so it +// takes the urgent slot) succeeds, and status no longer reports a wait. +func TestSlotWaitEndsWithASuccessfulDetachSeal(t *testing.T) { + p, _, remote, _ := slotWaitProvider(t) + if refusals := watchWaits(t, p, 600*time.Millisecond); len(refusals) == 0 { + t.Fatal("no refused timer cut while the slot was held") + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, _, err := p.DetachVolumePlain(ctx, "v1"); err != nil { + t.Fatalf("plain detach: %v", err) + } + if h, _ := remote.GetHead(context.Background()); h.Gen == 0 { + t.Fatal("the seal did not publish") + } + cs := chunkStatus(t, p).CutSchedule + if cs == nil || cs.HostSlotWaitSinceNs != 0 || cs.HostSlotWaits == 0 { + t.Fatalf("after a successful seal: %+v; want the count kept and no current wait", cs) } } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index d8bcc6e4ca..83aa2241ad 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -638,7 +638,7 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { cs.ScheduledSnapshot = &ss } if cv.cutWait != nil { - cw := cv.cutWait.status() + cw := cv.cutWait.status(cs.Stats.CutSeq) cs.CutSchedule = &cw } st.Chunk = cs diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 7957c66377..55762afbcb 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -706,6 +706,9 @@ func (s cutSchedule) observe(seq uint64, now time.Time) cutSchedule { s.lastSuccess = now } s.firstDue = time.Time{} + if !s.slotWaitSince.IsZero() { + s.retryAt = time.Time{} // the slot retry is moot: a cut succeeded + } s.slotWaitSince = time.Time{} if !s.failedAt.IsZero() && seq != s.failedSeenSeq { s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} @@ -794,7 +797,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger, layer.Stats().CutSeq) if wait != nil { - s.slotWaits = wait.status().HostSlotWaits + s.slotWaits = wait.status(0).HostSlotWaits } t := time.NewTicker(chunkSchedulePoll) defer t.Stop() @@ -1391,10 +1394,13 @@ func (p *DurableProvider) publishSettledHook(volumeID string) func(context.Conte } // cutWaitSlot publishes the automatic-cut timer's host slot waits to -// status. A nil slot records nothing. +// status. A nil slot records nothing. A wait is recorded with the layer's +// CutSeq it started under, so any later successful cut ends it in status, +// also one made after the timer stopped (a detach's seal). type cutWaitSlot struct { - mu sync.Mutex - st CutScheduleStatus + mu sync.Mutex + st CutScheduleStatus + waitSeq uint64 } func (w *cutWaitSlot) record(s cutSchedule) { @@ -1406,12 +1412,17 @@ func (w *cutWaitSlot) record(s cutSchedule) { st.HostSlotWaitSinceNs = s.slotWaitSince.UnixNano() } w.mu.Lock() - w.st = st + w.st, w.waitSeq = st, s.seenSeq w.mu.Unlock() } -func (w *cutWaitSlot) status() CutScheduleStatus { +// status is the recorded state as of the layer's current CutSeq. +func (w *cutWaitSlot) status(cutSeq uint64) CutScheduleStatus { w.mu.Lock() defer w.mu.Unlock() - return w.st + st := w.st + if st.HostSlotWaitSinceNs != 0 && cutSeq != w.waitSeq { + st.HostSlotWaitSinceNs = 0 + } + return st } diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 9617672dac..0d9590f46b 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -282,12 +282,16 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) ( fallback := err != nil // Urgent fallback has no coordinated host resource/rate bound. l.mu.Lock() if l.closed || ctx.Err() != nil || len(l.live) >= l.cfg.NormalSlots+l.cfg.UrgentSlots+l.cfg.FillSlots+l.cfg.IdleSlots { + closed := l.closed l.stats.Skipped++ l.mu.Unlock() if f != nil { _ = f.Close() } - if ctx.Err() != nil { + switch { + case closed: + return 0, ErrRevoked + case ctx.Err() != nil: return 0, ctx.Err() } return 0, ErrSlotsHeld diff --git a/seaweed-block/core/hostlimit/limiter_test.go b/seaweed-block/core/hostlimit/limiter_test.go index cbc5f3cdb5..fba52a4295 100644 --- a/seaweed-block/core/hostlimit/limiter_test.go +++ b/seaweed-block/core/hostlimit/limiter_test.go @@ -593,3 +593,30 @@ func TestPacingFreshProcessesDoNotShareDebt(t *testing.T) { // not preserve pacing debt, so these bytes cannot certify a host-rate cap. t.Logf("fresh_processes=%d attempted_payload_bytes=%d elapsed=%s", starts, starts*(4<<20), time.Since(start)) } + +// A limiter closed while an admission is acquiring its pool slot refuses +// it as revoked: closing is terminal, not a held-slot wait. +func TestAdmitClosedDuringPoolAcquisitionIsRevoked(t *testing.T) { + l, err := New(testConfig(t)) + if err != nil { + t.Fatal(err) + } + closed := make(chan struct{}) + l.testBeforeConfigLock = func(*os.File) { + go func() { l.Close(); close(closed) }() + for { + l.mu.Lock() + c := l.closed + l.mu.Unlock() + if c { + return + } + time.Sleep(time.Millisecond) + } + } + id, err := l.Acquire(context.Background(), Normal, nil) + if id != 0 || !errors.Is(err, ErrRevoked) || errors.Is(err, ErrSlotsHeld) { + t.Fatalf("admission racing Close: id=%d err=%v; want ErrRevoked", id, err) + } + <-closed +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 62e440807b..168dba84fd 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -599,7 +599,7 @@ Notes: | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | | `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | -| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff and no minimum spacing; it retries after the volume's slot jitter (at most 200 ms), and status reports the wait count and start until a cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees` (`core/frontend/durable/host_slot_wait_test.go`) | — | ACTIVE | +| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff and no minimum spacing; it retries after the volume's slot jitter (at most 200 ms), and status reports the wait count and start until a cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. From e94dbbafd6ba34c95c0bcc8bd7e79d06d7cddec3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:19:00 -0800 Subject: [PATCH 4/6] durable: slot retry delay is random per attempt and shrinks with lateness A timer cut refused for held host slots retries after a delay drawn below 200 ms x interval/(interval+late), so the volume furthest behind its interval retries soonest; a fixed per-volume phase let the same volumes win every round. A deterministic test runs V timer policies against one slot (service T, all due at once) and checks no volume waits longer than (V-1)(T + poll + 200 ms) and every volume keeps cutting. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/cut_policy_test.go | 90 +++++++++++++++++-- .../core/frontend/durable/provider_chunk.go | 36 ++++++-- seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 115 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index e6986adb20..ba62bde3ac 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -6,6 +6,7 @@ package durable import ( "errors" "fmt" + "math/rand/v2" "testing" "time" @@ -217,7 +218,8 @@ func TestCutPolicy_TimerRunsOnObservationTime(t *testing.T) { // a cut succeeds. Any other error still backs off. func TestCutPolicy_HostSlotBusyIsAWaitNotAFailure(t *testing.T) { pol := testPolicy() - pol.slotJitter = 150 * time.Millisecond + const delay = 150 * time.Millisecond + pol.slotDelay = func(time.Duration) time.Duration { return delay } busy := fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrSlotsHeld) s := cutSchedule{lastSuccess: t0} now := at(30 * time.Second) @@ -227,11 +229,11 @@ func TestCutPolicy_HostSlotBusyIsAWaitNotAFailure(t *testing.T) { t.Fatalf("busy refusal %d treated as a cut or a failure: %+v", i, s) } if _, ok := pol.dueNR(s, now.Add(100*time.Millisecond)); ok { - t.Fatalf("busy retry %d due before its jitter", i) + t.Fatalf("busy retry %d due before its delay", i) } - now = now.Add(time.Millisecond + pol.slotJitter) + now = now.Add(time.Millisecond + delay) if _, ok := pol.dueNR(s, now); !ok { - t.Fatalf("busy retry %d not due after its jitter", i) + t.Fatalf("busy retry %d not due after its delay", i) } } if s.slotWaits != 5 || !s.slotWaitSince.Equal(at(30*time.Second)) { @@ -256,7 +258,7 @@ func TestCutPolicy_HostSlotBusyIsAWaitNotAFailure(t *testing.T) { func TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry(t *testing.T) { pol := testPolicy() pol.interval = 100 * time.Millisecond - pol.slotJitter = 150 * time.Millisecond + pol.slotDelay = func(time.Duration) time.Duration { return 150 * time.Millisecond } busy := fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrSlotsHeld) s := cutSchedule{lastSuccess: t0, seenSeq: 100} s = pol.after(s, at(time.Second), at(time.Second), busy, 100) @@ -281,3 +283,81 @@ func TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut(t *testing.T) { t.Fatalf("wait reported after a later cut: %+v", st) } } + +// The slot retry delay is random and shrinks as the volume falls behind: +// at most chunkSlotDelayMax on time, a tenth of it nine intervals late. +func TestNewSlotDelay_ShrinksWithLateness(t *testing.T) { + d := newSlotDelay(time.Minute, rand.New(rand.NewPCG(1, 2))) + var sum time.Duration + for i := 0; i < 1000; i++ { + on, late := d(0), d(9*time.Minute) + if on < 0 || on >= chunkSlotDelayMax || late < 0 || late >= chunkSlotDelayMax/10 { + t.Fatalf("delay %s on time, %s nine intervals late", on, late) + } + sum += on + } + if avg := sum / 1000; avg < chunkSlotDelayMax/4 || avg > 3*chunkSlotDelayMax/4 { + t.Fatalf("on-time delays average %s; want them spread over [0, %s)", avg, chunkSlotDelayMax) + } +} + +// V timer loops under the cut policy share one host slot (service T per +// cut) with every volume due at the same instant, the worst start. With +// V x T <= c, no volume waits for the slot longer than (V-1) x (T + gap), +// gap being one poll plus the largest retry delay, and every volume keeps +// cutting. +func TestCutPolicy_OneSlotWaitBound(t *testing.T) { + const ( + V = 10 + T = 1400 * time.Millisecond + poll = chunkSchedulePoll + runFor = 20 * time.Minute + ) + interval := time.Minute + busy := fmt.Errorf("%w: budget admission: %w", storage.ErrChunkCaptureRefused, hostlimit.ErrSlotsHeld) + pols := make([]cutPolicy, V) + ss := make([]cutSchedule, V) + cuts := make([]int, V) + for i := range pols { + pols[i] = cutPolicy{interval: interval, minSpacing: chunkCutMinSpacing, backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax, + slotDelay: newSlotDelay(interval, rand.New(rand.NewPCG(1, uint64(i))))} + ss[i] = cutSchedule{lastSuccess: t0} + } + order := rand.New(rand.NewPCG(7, 7)) + holder, start, seq := -1, time.Time{}, uint64(0) + var worst time.Duration + for now := t0; now.Before(t0.Add(runFor)); now = now.Add(poll) { + if holder >= 0 && !now.Before(start.Add(T)) { + seq++ + ss[holder] = pols[holder].after(ss[holder], start, start.Add(T), nil, seq) + cuts[holder]++ + holder = -1 + } + for _, i := range order.Perm(V) { + if i == holder { + continue + } + if _, ok := pols[i].due(ss[i], now, false); !ok { + continue + } + if holder < 0 { + if !ss[i].slotWaitSince.IsZero() { + worst = max(worst, now.Sub(ss[i].slotWaitSince)) + } + holder, start = i, now + continue + } + ss[i] = pols[i].after(ss[i], now, now, busy, seq) + } + } + bound := (V - 1) * (T + poll + chunkSlotDelayMax) + if worst > bound { + t.Fatalf("a volume waited %s for the slot; bound (V-1)(T+gap) = %s", worst, bound) + } + for i, n := range cuts { + if n < int(runFor/(interval+bound))-1 { + t.Fatalf("volume %d cut %d times in %s", i, n, runFor) + } + } + t.Logf("worst slot wait %s (bound %s); cuts per volume %v", worst, bound, cuts) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 55762afbcb..3963960333 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "log" + "math/rand/v2" "os" "path/filepath" "runtime" @@ -651,7 +652,7 @@ const ( chunkCutMinSpacing = time.Second chunkCutBackoffMin = time.Second chunkCutBackoffMax = 30 * time.Second - chunkSlotJitterMax = 200 * time.Millisecond + chunkSlotDelayMax = 200 * time.Millisecond ) // cutPolicy decides when an automatic cut is due. The remote holds @@ -668,12 +669,29 @@ const ( // no-op cut and an explicit cut included) clears the backoff and // restarts the timer; // - an automatic cut refused because every host slot is held ran -// nothing: it is retried after the volume's slot jitter, with no -// backoff and no minimum spacing, and the wait lasts until a cut -// succeeds. +// nothing: it is retried after a random delay that shrinks as the +// volume falls behind its interval (the latest volume retries +// soonest), with no backoff and no minimum spacing, and the wait +// lasts until a cut succeeds. type cutPolicy struct { interval, minSpacing, backoffMin, backoffMax time.Duration - slotJitter time.Duration // this volume's delay before retrying a cut refused for held host slots + // slotDelay is the delay before retrying a cut refused for held host + // slots, given how late the volume is past its interval; nil retries + // at the next poll. + slotDelay func(late time.Duration) time.Duration +} + +// newSlotDelay draws a retry delay below chunkSlotDelayMax scaled by +// interval/(interval+late): a volume one interval late draws below half of +// it, nine intervals late below a tenth. +func newSlotDelay(interval time.Duration, r *rand.Rand) func(time.Duration) time.Duration { + return func(late time.Duration) time.Duration { + limit := float64(chunkSlotDelayMax) + if interval > 0 && late > 0 { + limit *= float64(interval) / float64(interval+late) + } + return time.Duration(r.Float64() * limit) + } } // cutSchedule runs on in-process monotonic time: every time in it is a @@ -744,7 +762,11 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq u if s.slotWaitSince.IsZero() { s.slotWaitSince = start } - s.retryAt = end.Add(pol.slotJitter) + var delay time.Duration + if pol.slotDelay != nil { + delay = pol.slotDelay(max(0, end.Sub(s.lastSuccess.Add(pol.interval)))) + } + s.retryAt = end.Add(delay) return s } s.lastAuto = start @@ -793,7 +815,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer minSpacing: chunkCutMinSpacing, backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax, - slotJitter: hostlimit.Phase(volumeID+":slot", chunkSlotJitterMax), + slotDelay: newSlotDelay(p.cfg.ChunkCaptureInterval, rand.New(rand.NewPCG(uint64(time.Now().UnixNano()), uint64(hostlimit.Phase(volumeID, time.Hour))))), } s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger, layer.Stats().CutSeq) if wait != nil { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 168dba84fd..d9fa281f9f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -599,7 +599,7 @@ Notes: | `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | | `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE | | `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE | -| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff and no minimum spacing; it retries after the volume's slot jitter (at most 200 ms), and status reports the wait count and start until a cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | +| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff or minimum spacing; it retries after a random delay under 200 ms that shrinks with lateness, and status reports the wait until any later cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestNewSlotDelay_ShrinksWithLateness`, `TestCutPolicy_OneSlotWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks. From 23522de1454e26807df50605a6fb291a3352b0c2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 17:30:02 -0800 Subject: [PATCH 5/6] durable: slot-wait tests record the limiter's own admissions - The provider tests wrap the real limiter and record every Admit call with its time and outcome. Retry gaps are measured between recorded held-slot refusals, and the first admission after the slot frees is timed from the release (<= 400 ms); publication is bounded separately. - The close-race control bounds its wait for Close and joins it from a cleanup registered before the goroutine starts. - Wording: a shorter delay range makes a late volume likely, not certain, to retry first; the seeded one-slot simulation is a regression check, not a proof of the bound. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/cut_policy_test.go | 5 +- .../frontend/durable/host_slot_wait_test.go | 98 +++++++++++++------ .../core/frontend/durable/provider_chunk.go | 8 +- seaweed-block/core/hostlimit/limiter_test.go | 15 ++- 4 files changed, 87 insertions(+), 39 deletions(-) diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index ba62bde3ac..c6bfad5f8e 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -302,10 +302,11 @@ func TestNewSlotDelay_ShrinksWithLateness(t *testing.T) { } // V timer loops under the cut policy share one host slot (service T per -// cut) with every volume due at the same instant, the worst start. With +// cut) with every volume due at the same instant. In this seeded run, with // V x T <= c, no volume waits for the slot longer than (V-1) x (T + gap), // gap being one poll plus the largest retry delay, and every volume keeps -// cutting. +// cutting. One seeded run is a regression check of the policy, not a +// proof of the bound for every schedule. func TestCutPolicy_OneSlotWaitBound(t *testing.T) { const ( V = 10 diff --git a/seaweed-block/core/frontend/durable/host_slot_wait_test.go b/seaweed-block/core/frontend/durable/host_slot_wait_test.go index 71a365068e..f0278922d3 100644 --- a/seaweed-block/core/frontend/durable/host_slot_wait_test.go +++ b/seaweed-block/core/frontend/durable/host_slot_wait_test.go @@ -2,6 +2,8 @@ package durable_test import ( "context" + "errors" + "sync" "testing" "time" @@ -10,9 +12,37 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) +// admitRecorder is the provider's cut budget: the real limiter, with +// every Admit call's time and outcome recorded. +type admitRecorder struct { + *hostlimit.Limiter + mu sync.Mutex + events []admitEvent +} + +type admitEvent struct { + at time.Time + held bool // refused because every slot was held + ok bool +} + +func (r *admitRecorder) Admit(ctx context.Context, payload int64, abort func(error)) (uint64, error) { + id, err := r.Limiter.Admit(ctx, payload, abort) + r.mu.Lock() + r.events = append(r.events, admitEvent{at: time.Now(), held: errors.Is(err, hostlimit.ErrSlotsHeld), ok: err == nil}) + r.mu.Unlock() + return id, err +} + +func (r *admitRecorder) snapshot() []admitEvent { + r.mu.Lock() + defer r.mu.Unlock() + return append([]admitEvent(nil), r.events...) +} + // slotWaitProvider opens v1 with a 100 ms cut timer under a host limiter // whose only normal slot another process holds; release frees it. -func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *hostlimit.Limiter, remote *storage.MemChunkRemote, release func()) { +func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *admitRecorder, remote *storage.MemChunkRemote, release func()) { t.Helper() c := hostlimit.DefaultConfig(t.TempDir()) c.NormalSlots, c.UrgentSlots = 1, 1 @@ -33,10 +63,12 @@ func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *hostlimit. } } t.Cleanup(release) - if lim, err = hostlimit.New(c); err != nil { + inner, err := hostlimit.New(c) + if err != nil { t.Fatal(err) } - t.Cleanup(lim.Close) + t.Cleanup(inner.Close) + lim = &admitRecorder{Limiter: inner} remote = storage.NewMemChunkRemote() p, err = durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkCaptureInterval: 100 * time.Millisecond, @@ -55,53 +87,58 @@ func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *hostlimit. return p, lim, remote, release } -// watchWaits samples status every 10 ms for d and returns the times at -// which HostSlotWaits went up (one per refused timer cut). -func watchWaits(t *testing.T, p *durable.DurableProvider, d time.Duration) []time.Time { - t.Helper() +// refusedAt returns the times of the recorded held-slot refusals. +func refusedAt(events []admitEvent) []time.Time { var at []time.Time - var last uint64 - for end := time.Now().Add(d); time.Now().Before(end); time.Sleep(10 * time.Millisecond) { - cs := chunkStatus(t, p).CutSchedule - if cs != nil && cs.HostSlotWaits > last { - for ; last < cs.HostSlotWaits; last++ { - at = append(at, time.Now()) - } - if cs.HostSlotWaitSinceNs == 0 { - t.Fatalf("waits counted but no wait start reported: %+v", cs) - } + for _, e := range events { + if e.held { + at = append(at, e.at) } } return at } // A timer cut refused because every host slot is held is retried within -// one poll plus the volume's jitter, every time, however long the slot is -// held; once it frees, the next attempt is admitted within that bound. +// one poll plus the largest retry delay, every time, however long the +// slot is held; once it frees, the next attempt is admitted within that +// bound. Times are the limiter's own Admit calls. func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { p, lim, remote, release := slotWaitProvider(t) - refusals := watchWaits(t, p, 2500*time.Millisecond) + time.Sleep(2500 * time.Millisecond) + refusals := refusedAt(lim.snapshot()) // A failure backoff (1 s, 2 s, ...) allows at most 3 attempts in 2.5 s. if len(refusals) < 8 { - t.Fatalf("%d refused attempts in 2.5 s; a slot wait retries every <= 300 ms", len(refusals)) + t.Fatalf("%d refused admissions in 2.5 s; a slot wait retries every <= 300 ms", len(refusals)) } for i := 1; i < len(refusals); i++ { if gap := refusals[i].Sub(refusals[i-1]); gap > 400*time.Millisecond { - t.Fatalf("retry %d came %s after the previous refusal", i, gap) + t.Fatalf("admission %d came %s after the previous refusal", i, gap) } } if h, _ := remote.GetHead(context.Background()); h.Gen != 0 { t.Fatal("a cut published while the only slot was held") } + if cs := chunkStatus(t, p).CutSchedule; cs == nil || cs.HostSlotWaits == 0 || cs.HostSlotWaitSinceNs == 0 { + t.Fatalf("waiting for a host slot is not reported: %+v", cs) + } - admitted := lim.Snapshot().(hostlimit.Stats).Admitted - release() + before := len(lim.snapshot()) freed := time.Now() - for lim.Snapshot().(hostlimit.Stats).Admitted == admitted { - if time.Since(freed) > 400*time.Millisecond { - t.Fatal("no cut admitted within 400 ms of the slot freeing") + release() + var admittedAt time.Time + for deadline := time.Now().Add(5 * time.Second); admittedAt.IsZero(); time.Sleep(10 * time.Millisecond) { + for _, e := range lim.snapshot()[before:] { + if e.ok { + admittedAt = e.at + break + } } - time.Sleep(5 * time.Millisecond) + if admittedAt.IsZero() && time.Now().After(deadline) { + t.Fatal("no cut admitted within 5 s of the slot freeing") + } + } + if d := admittedAt.Sub(freed); d > 400*time.Millisecond { + t.Fatalf("the first admission came %s after the slot freed; want <= 400 ms", d) } for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { if h, _ := remote.GetHead(context.Background()); h.Gen != 0 { @@ -124,8 +161,9 @@ func TestTimerCutRunsSoonAfterHostSlotFrees(t *testing.T) { // A plain detach stops the timer before its seal; the seal (urgent, so it // takes the urgent slot) succeeds, and status no longer reports a wait. func TestSlotWaitEndsWithASuccessfulDetachSeal(t *testing.T) { - p, _, remote, _ := slotWaitProvider(t) - if refusals := watchWaits(t, p, 600*time.Millisecond); len(refusals) == 0 { + p, lim, remote, _ := slotWaitProvider(t) + time.Sleep(600 * time.Millisecond) + if len(refusedAt(lim.snapshot())) == 0 { t.Fatal("no refused timer cut while the slot was held") } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 3963960333..cd384de1c0 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -669,10 +669,10 @@ const ( // no-op cut and an explicit cut included) clears the backoff and // restarts the timer; // - an automatic cut refused because every host slot is held ran -// nothing: it is retried after a random delay that shrinks as the -// volume falls behind its interval (the latest volume retries -// soonest), with no backoff and no minimum spacing, and the wait -// lasts until a cut succeeds. +// nothing: it is retried after a random delay drawn from a range that +// shrinks as the volume falls behind its interval (a late volume is +// likely, not certain, to retry first), with no backoff and no +// minimum spacing, and the wait lasts until a cut succeeds. type cutPolicy struct { interval, minSpacing, backoffMin, backoffMax time.Duration // slotDelay is the delay before retrying a cut refused for held host diff --git a/seaweed-block/core/hostlimit/limiter_test.go b/seaweed-block/core/hostlimit/limiter_test.go index fba52a4295..28b73b72b6 100644 --- a/seaweed-block/core/hostlimit/limiter_test.go +++ b/seaweed-block/core/hostlimit/limiter_test.go @@ -602,21 +602,30 @@ func TestAdmitClosedDuringPoolAcquisitionIsRevoked(t *testing.T) { t.Fatal(err) } closed := make(chan struct{}) + t.Cleanup(func() { + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("Close did not return within 5 s") + } + }) l.testBeforeConfigLock = func(*os.File) { go func() { l.Close(); close(closed) }() - for { + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(time.Millisecond) { l.mu.Lock() c := l.closed l.mu.Unlock() if c { return } - time.Sleep(time.Millisecond) + if time.Now().After(deadline) { + t.Error("Close did not mark the limiter closed within 5 s") + return + } } } id, err := l.Acquire(context.Background(), Normal, nil) if id != 0 || !errors.Is(err, ErrRevoked) || errors.Is(err, ErrSlotsHeld) { t.Fatalf("admission racing Close: id=%d err=%v; want ErrRevoked", id, err) } - <-closed } From 5991507bebf29b9508a0d063846a15e699b1ec99 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 18:12:31 -0800 Subject: [PATCH 6/6] docs: status schema lists Chunk.CutSchedule Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/status-schema.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index cf87c7c7ea..1d5a4b5ee1 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -289,6 +289,9 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.ScheduledSnapshot.attempts` | int | Attempts counts the failed attempts since the last success. | | `Volumes[].Chunk.ScheduledSnapshot.skipped{}` | int64 | Skipped counts attempts not made, by reason. (omitted when empty) | | `Volumes[].Chunk.ScheduledSnapshot.snapshot_overdue` | bool | Overdue reports that no scheduled snapshot succeeded within one period plus the retry cap, counted from the last success or, before any, from the start of the schedule. | +| `Volumes[].Chunk.CutSchedule` | object | the automatic-cut timer's state; absent when the timer is off or its loop has not started (omitted when empty) | +| `Volumes[].Chunk.CutSchedule.HostSlotWaits` | uint64 | automatic cuts refused because every host slot was held | +| `Volumes[].Chunk.CutSchedule.HostSlotWaitSinceNs` | int64 | wall time of the first such refusal since the last successful cut; 0 when not waiting | | `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | | `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |