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..c6bfad5f8e 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -5,8 +5,13 @@ package durable import ( "errors" + "fmt" + "math/rand/v2" "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 +211,154 @@ 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() + 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) + 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 delay", i) + } + now = now.Add(time.Millisecond + delay) + if _, ok := pol.dueNR(s, now); !ok { + t.Fatalf("busy retry %d not due after its delay", 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) + } +} + +// 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.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) + 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) + } +} + +// 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. 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. 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 + 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/host_slot_wait_test.go b/seaweed-block/core/frontend/durable/host_slot_wait_test.go new file mode 100644 index 0000000000..212b709562 --- /dev/null +++ b/seaweed-block/core/frontend/durable/host_slot_wait_test.go @@ -0,0 +1,211 @@ +package durable_test + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "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. baseGen +// is HEAD's generation once the volume is open (opening may publish one +// itself, without a cut). +func slotWaitProvider(t *testing.T) (p *durable.DurableProvider, lim *admitRecorder, remote *storage.MemChunkRemote, release func(), baseGen uint64) { + t.Helper() + c := hostlimit.DefaultConfig(t.TempDir()) + c.NormalSlots, c.UrgentSlots = 1, 1 + holder, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(holder.Close) + ticket, err := holder.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + held := true + release = func() { + if held { + held = false + holder.Release(ticket) + } + } + t.Cleanup(release) + inner, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + 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, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { 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) + } + h, err := remote.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + return p, lim, remote, release, h.Gen +} + +// admitted reports whether any recorded Admit call succeeded. +func admitted(events []admitEvent) bool { + for _, e := range events { + if e.ok { + return true + } + } + return false +} + +// refusedAt returns the times of the recorded held-slot refusals. +func refusedAt(events []admitEvent) []time.Time { + var at []time.Time + 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 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, baseGen := slotWaitProvider(t) + 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 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("admission %d came %s after the previous refusal", i, gap) + } + } + if admitted(lim.snapshot()) { + t.Fatal("a cut was admitted while the only slot was held") + } + if h, _ := remote.GetHead(context.Background()); h.Gen != baseGen { + t.Fatalf("HEAD moved from generation %d to %d while the only slot was held", baseGen, h.Gen) + } + 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) + } + + before := len(lim.snapshot()) + freed := time.Now() + 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 + } + } + 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 > baseGen { + break + } + if time.Now().After(deadline) { + t.Fatal("the admitted cut did not publish within 5 s") + } + } + 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, lim, remote, _, baseGen := 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) + defer cancel() + if _, _, err := p.DetachVolumePlain(ctx, "v1"); err != nil { + t.Fatalf("plain detach: %v", err) + } + if h, _ := remote.GetHead(context.Background()); h.Gen <= baseGen { + t.Fatalf("the seal did not publish: HEAD generation %d, %d at open", h.Gen, baseGen) + } + 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) + } +} + +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..83aa2241ad 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 @@ -343,6 +346,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 @@ -599,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)) @@ -606,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() @@ -626,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.Stats.CutSeq) + 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 3e4d44b04e..7018eb0363 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" @@ -339,9 +340,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) { @@ -654,6 +660,7 @@ const ( chunkCutMinSpacing = time.Second chunkCutBackoffMin = time.Second chunkCutBackoffMax = 30 * time.Second + chunkSlotDelayMax = 200 * time.Millisecond ) // cutPolicy decides when an automatic cut is due. The remote holds @@ -668,9 +675,31 @@ 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 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 + // 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 @@ -687,6 +716,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 @@ -701,6 +732,10 @@ 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{} } @@ -730,10 +765,23 @@ 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 + } + 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 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 @@ -768,15 +816,19 @@ 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, minSpacing: chunkCutMinSpacing, backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax, + 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 { + s.slotWaits = wait.status(0).HostSlotWaits + } t := time.NewTicker(chunkSchedulePoll) defer t.Stop() for { @@ -791,6 +843,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 @@ -821,6 +874,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) } @@ -830,7 +884,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 @@ -839,7 +893,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, cutWait) }() } if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil { @@ -1385,3 +1439,37 @@ 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. 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 + waitSeq uint64 +} + +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, w.waitSeq = st, s.seenSeq + w.mu.Unlock() +} + +// 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() + 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 3ab765d5e6..0d9590f46b 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 @@ -277,15 +282,19 @@ 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, ErrBusy + return 0, ErrSlotsHeld } l.next++ id := l.next diff --git a/seaweed-block/core/hostlimit/limiter_test.go b/seaweed-block/core/hostlimit/limiter_test.go index cbc5f3cdb5..28b73b72b6 100644 --- a/seaweed-block/core/hostlimit/limiter_test.go +++ b/seaweed-block/core/hostlimit/limiter_test.go @@ -593,3 +593,39 @@ 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{}) + 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 deadline := time.Now().Add(5 * time.Second); ; time.Sleep(time.Millisecond) { + l.mu.Lock() + c := l.closed + l.mu.Unlock() + if c { + return + } + 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) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d2f32d4b05..5954fb6f01 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -409,7 +409,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO ## Part B. Invariant ledger -296 rows: 210 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 281 new. +297 rows: 211 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 282 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. @@ -739,6 +739,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`, `TestCutPolicy_StaggerPreservesExplicitTimerReset` (`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 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. 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) |