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 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-21 17:19:00 -08:00
1 parent 1d861a806c
commit e94dbbafd6
3 files changed
+115 -13

No files matched your search

@@ -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)
}
@@ -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 {
+1 -1
View File
@@ -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.