From 62ee69b0e2203c374471a52816c8df062cb8eba5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:24:05 -0800 Subject: [PATCH 1/3] hostlimit, storage, durable: red tests, a long cut yields its slot to a waiter Seams: Config.YieldAfter (S, default 5 min), Limiter.ShouldYield (never, for now), storage.ErrCutYielded, storage.BudgetYield, ChunkLayerStats. CutsYielded and CutScheduleStatus.CutYields. - TestShouldYieldOnlyAfterSWithALiveWaiter: a Normal hold yields only once it is S old and another process holds a live ticket; never a lone hold, never before S, never an urgent hold, not for a ticket judged stalled. Fails here: no hold ever yields. - TestCutYieldsAtABatchBoundaryAndKeepsItsStaging: a cut whose budget asks it to yield ends at the next staging batch boundary with ErrCutYielded, counted as a yield, not a failure, publishes nothing, and its staged chunks are kept for the next attempt. Fails here: the cut never yields. - TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart: a yielded attempt is retried at the next poll, never backed off as a failure, and status counts it apart. Fails here: the retry came 1.1 s later. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/cut_loop_yield_test.go | 77 +++++++++++++++++++ .../core/frontend/durable/provider.go | 1 + seaweed-block/core/hostlimit/limiter.go | 10 ++- seaweed-block/core/hostlimit/yield_test.go | 61 +++++++++++++++ .../core/storage/chunk_cut_budget.go | 14 +++- .../core/storage/chunk_cut_budget_test.go | 4 + .../core/storage/chunk_cut_yield_test.go | 39 ++++++++++ seaweed-block/core/storage/chunk_seam.go | 1 + 8 files changed, 204 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/cut_loop_yield_test.go create mode 100644 seaweed-block/core/hostlimit/yield_test.go create mode 100644 seaweed-block/core/storage/chunk_cut_yield_test.go diff --git a/seaweed-block/core/frontend/durable/cut_loop_yield_test.go b/seaweed-block/core/frontend/durable/cut_loop_yield_test.go new file mode 100644 index 0000000000..42d397f1b4 --- /dev/null +++ b/seaweed-block/core/frontend/durable/cut_loop_yield_test.go @@ -0,0 +1,77 @@ +package durable + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// slotYieldingLayer admits each cut through the budget (consuming its ticket); +// its first two attempts yield their slot, every later one succeeds. It +// reports nothing staged, so nothing but the yield rule can excuse a backoff. +type slotYieldingLayer struct { + storage.ChunkLayer // unused methods panic + budget storage.Budget + cuts atomic.Int32 + mu sync.Mutex + at []time.Time +} + +func (l *slotYieldingLayer) Fenced() bool { return false } +func (l *slotYieldingLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} } +func (l *slotYieldingLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) { + l.mu.Lock() + l.at = append(l.at, time.Now()) + l.mu.Unlock() + n := l.cuts.Add(1) + id, err := l.budget.Admit(ctx, 1, nil) + if err != nil { + return storage.ChunkCutResult{}, err + } + l.budget.Release(id) + if n <= 2 { + return storage.ChunkCutResult{}, storage.ErrCutYielded + } + return storage.ChunkCutResult{}, nil +} + +// A yielded attempt is not a failure: no backoff, it tries again at the next +// poll (on a ticket at the back, as any admitted attempt that did not +// succeed), and status counts it apart. +func TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart(t *testing.T) { + b := newRecordingBudget(t) + layer := &slotYieldingLayer{budget: b} + wait := &cutWaitSlot{} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkBudget: b}} + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go p.chunkLoop(ctx, "v1", layer, done, wait, nil) + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("the cut loop did not end within 5 s of its cancel") + } + }) + for deadline := time.Now().Add(5 * time.Second); layer.cuts.Load() < 3; time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatalf("the loop made %d attempts in 5 s, want 3", layer.cuts.Load()) + } + } + layer.mu.Lock() + at := append([]time.Time(nil), layer.at...) + layer.mu.Unlock() + for i := 1; i < 3; i++ { + if gap := at[i].Sub(at[i-1]); gap >= 500*time.Millisecond { + t.Fatalf("attempt %d came %s after a yield: a yield was backed off as a failure", i+1, gap.Round(time.Millisecond)) + } + } + if got := wait.status(0).CutYields; got != 2 { + t.Fatalf("status counts %d yields, want 2", got) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index ff4927c411..91b7d1c809 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -442,6 +442,7 @@ type CutScheduleStatus struct { TicketDueHostNs int64 `json:",omitempty"` // the waiting cut's host ticket: its due time on the host monotonic clock; absent when not waiting TicketsSkipped uint64 `json:",omitempty"` // earlier tickets the waiting cut passed by the skip rule TicketDropReason string `json:",omitempty"` // why the last ticket was given up before admission, when it was a refusal that waiting cannot fix + CutYields uint64 `json:",omitempty"` // automatic cut attempts that yielded their host slot to a waiting cut (seam) } // NewDurableProvider constructs a provider. view is the ONLY diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 888482df4f..106149f3f2 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -66,13 +66,16 @@ type Config struct { // FetchSlots caps the chunk fetches in flight on the host, across its // processes (HoldFetch): a guest read waits for a slot, never refused. FetchSlots int + // YieldAfter is S: a Normal hold this old yields its slot at its next + // staging batch when another cut waits (seam). + YieldAfter time.Duration } func DefaultConfig(dir string) Config { - return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, NoProgress: 60 * time.Second, FetchSlots: 64} + return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, NoProgress: 60 * time.Second, FetchSlots: 64, YieldAfter: 5 * time.Minute} } func (c Config) Validate() error { - if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.NoProgress <= 0 || c.FetchSlots < 1 || c.FetchSlots > 1024 { + if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.NoProgress <= 0 || c.FetchSlots < 1 || c.FetchSlots > 1024 || c.YieldAfter <= 0 { return errors.New("hostlimit: invalid configuration") } return nil @@ -500,6 +503,9 @@ func (l *Limiter) Progress(id uint64) { } } +// ShouldYield reports whether the hold id should yield its slot now (seam). +func (l *Limiter) ShouldYield(id uint64) bool { return false } + // expire runs when a hold's timer fires: a hold that progressed within its // window is armed again for the rest of it; one that did not is revoked. The // decision and the revocation are one step under the limiter's lock, reading diff --git a/seaweed-block/core/hostlimit/yield_test.go b/seaweed-block/core/hostlimit/yield_test.go new file mode 100644 index 0000000000..c30ec1e438 --- /dev/null +++ b/seaweed-block/core/hostlimit/yield_test.go @@ -0,0 +1,61 @@ +package hostlimit + +import ( + "context" + "path/filepath" + "testing" + "time" +) + +// A Normal hold yields only once it is S old AND another process waits (a +// live ticket in the pool): a lone hold never yields however old, a waiter +// before S changes nothing, an urgent hold never yields, and a ticket this +// process judged stalled is not a waiter. +func TestShouldYieldOnlyAfterSWithALiveWaiter(t *testing.T) { + c := testConfig(t) + c.NormalSlots = 2 + c.YieldAfter = 60 * time.Millisecond + l := newTest(t, c) + waiter := newTest(t, c) // another process on the host + x, err := l.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + defer l.Release(x) + if l.ShouldYield(x) { + t.Fatal("a fresh hold with no waiter yields") + } + tk, err := waiter.TakeTicket(HostNow()) + if err != nil { + t.Fatal(err) + } + if l.ShouldYield(x) { + t.Fatal("a hold younger than S yields to a waiter") + } + time.Sleep(80 * time.Millisecond) + if !l.ShouldYield(x) { + t.Fatal("a hold older than S does not yield to a live waiter") + } + l.markStalled(filepath.Base(tk.path)) + if l.ShouldYield(x) { + t.Fatal("a ticket this process judged stalled counts as a waiter") + } + tk.Close() + if l.ShouldYield(x) { + t.Fatal("a hold older than S yields with no waiter") + } + tk2, err := waiter.TakeTicket(HostNow()) + if err != nil { + t.Fatal(err) + } + defer tk2.Close() + u, err := l.Acquire(context.Background(), Urgent, nil) + if err != nil { + t.Fatal(err) + } + defer l.Release(u) + time.Sleep(80 * time.Millisecond) + if l.ShouldYield(u) { + t.Fatal("an urgent hold yields") + } +} diff --git a/seaweed-block/core/storage/chunk_cut_budget.go b/seaweed-block/core/storage/chunk_cut_budget.go index e74f7071b6..5b3159f36d 100644 --- a/seaweed-block/core/storage/chunk_cut_budget.go +++ b/seaweed-block/core/storage/chunk_cut_budget.go @@ -1,6 +1,18 @@ package storage -import "context" +import ( + "context" + "errors" +) + +// ErrCutYielded ends a cut attempt that gave its host slot to a waiting cut +// (seam). +var ErrCutYielded = errors.New("storage: the cut yielded its host slot to a waiting cut") + +// BudgetYield is a Budget that asks a long hold to yield (seam). +type BudgetYield interface { + ShouldYield(ticket uint64) bool +} // Budget is the host limiter seam. Admit runs before staging or the cut // barrier and reserves the configured payload ceiling. ReserveCOW accounts diff --git a/seaweed-block/core/storage/chunk_cut_budget_test.go b/seaweed-block/core/storage/chunk_cut_budget_test.go index 16c4b424d5..a6e53357b5 100644 --- a/seaweed-block/core/storage/chunk_cut_budget_test.go +++ b/seaweed-block/core/storage/chunk_cut_budget_test.go @@ -17,8 +17,12 @@ type testCutBudget struct { abort func(error) probe func() progressed int + yield bool // ShouldYield's answer (BudgetYield) } +// ShouldYield answers yield (BudgetYield). +func (b *testCutBudget) ShouldYield(uint64) bool { b.mu.Lock(); defer b.mu.Unlock(); return b.yield } + // Progress counts the cut's progress reports (BudgetProgress). func (b *testCutBudget) Progress(uint64) { b.mu.Lock(); b.progressed++; b.mu.Unlock() } diff --git a/seaweed-block/core/storage/chunk_cut_yield_test.go b/seaweed-block/core/storage/chunk_cut_yield_test.go new file mode 100644 index 0000000000..b557303bca --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_yield_test.go @@ -0,0 +1,39 @@ +package storage + +import ( + "errors" + "testing" +) + +// A cut whose budget asks it to yield ends its attempt at the next staging +// batch boundary with ErrCutYielded: an outcome of its own (never a failed +// cut in status), it publishes nothing, and the chunks it staged are kept, +// so the next attempt stages only the rest. +func TestCutYieldsAtABatchBoundaryAndKeepsItsStaging(t *testing.T) { + _, l := zeroStagedLayer(t, 6) + b := &testCutBudget{yield: true} + l.cfg.Budget = b + before := l.Stats() + if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, ErrCutYielded) { + t.Fatalf("cut: %v; want it to yield at a staging batch boundary", err) + } + after := l.Stats() + if after.CutsYielded != before.CutsYielded+1 || after.CutsFailed != before.CutsFailed || after.LastCutFailure != nil { + t.Fatalf("a yield counted yielded %d->%d, failed %d->%d, failure %+v; want one yield and no failure", + before.CutsYielded, after.CutsYielded, before.CutsFailed, after.CutsFailed, after.LastCutFailure) + } + staged := after.StagedChunks - before.StagedChunks + if staged == 0 || after.CutSeq != before.CutSeq { + t.Fatalf("the yielding attempt staged %d chunks and moved the cut sequence %d->%d; want a staged batch and no publication", + staged, before.CutSeq, after.CutSeq) + } + b.mu.Lock() + b.yield = false + b.mu.Unlock() + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if again := l.Stats().StagedChunks - after.StagedChunks; again >= staged { + t.Fatalf("the retry staged %d chunks again after the yield staged %d; want the yielded attempt's chunks kept", again, staged) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index f3b29d4e40..1fef53a31d 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -510,6 +510,7 @@ type chunkLayerStats struct { CutsNoop uint64 // cuts with nothing new (no CAS) CutsFailed uint64 // every other cut failure CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached + CutsYielded uint64 // attempts that gave their host slot to a waiting cut (seam) CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload CASConflicts uint64 // HEAD CAS precondition failures CASUnknown uint64 // HEAD CAS results still unresolved after the re-read From 49158029e72576621e8b71921c46a04dd4ae13cc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:32:41 -0800 Subject: [PATCH 2/3] hostlimit, storage, durable: a long cut yields its slot to a waiting cut - hostlimit: Config.YieldAfter (S, default 5 min). ShouldYield answers yes only for a Normal hold at least S old while another cut on the host holds a live ticket this process has not judged stalled (dead tickets are reaped on the way); the probe runs only once the hold is old enough and takes no limiter lock. - storage: a cut attempt asks at each staging batch boundary and ends with ErrCutYielded, keeping what it staged; CutsYielded counts it, never as a failed cut. - durable: a yielded attempt is retried at the next poll with no backoff, on a ticket at the back (it was admitted), counted in status (CutYields) and not logged as a failure. - blockvolume: --host-limit-yield-after. Invariants: INV-HOST-CUT-YIELD-001; M7 states the rule. v1.1 notes carry it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/host_limit.go | 1 + .../core/frontend/durable/provider.go | 2 +- .../core/frontend/durable/provider_chunk.go | 12 ++++- seaweed-block/core/hostlimit/limiter.go | 49 +++++++++++++++++-- .../core/storage/chunk_cut_budget.go | 17 +++++-- .../core/storage/chunk_cut_observation.go | 13 ++++- seaweed-block/core/storage/chunk_layer.go | 8 +++ seaweed-block/core/storage/chunk_seam.go | 2 +- seaweed-block/docs/design/invariants.md | 3 +- seaweed-block/docs/releases/v1.1.md | 3 ++ 10 files changed, 96 insertions(+), 14 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/host_limit.go b/seaweed-block/cmd/blockvolume/host_limit.go index b20da0de9a..2a0538da93 100644 --- a/seaweed-block/cmd/blockvolume/host_limit.go +++ b/seaweed-block/cmd/blockvolume/host_limit.go @@ -17,6 +17,7 @@ func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) { fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "pacing parameter divided per process by cut-slot count; not a host rate cap. --host-limit-no-progress must exceed one chunk's send time at this rate per held slot, or a steadily sending cut is revoked") fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "kept for configuration compatibility; the urgent fallback is not paced (no shared host cap to protect)") fs.IntVar(&c.FetchSlots, "host-limit-fetch-slots", c.FetchSlots, "chunk fetches in flight on the host, across its processes (1-1024); a read of an absent chunk waits for a slot, bounded by its read-miss timeout") + fs.DurationVar(&c.YieldAfter, "host-limit-yield-after", c.YieldAfter, "a normal cut that has held its slot this long gives it to a waiting cut at its next staging batch (keeping what it staged); a lone cut never yields") fs.DurationVar(&c.NoProgress, "host-limit-no-progress", c.NoProgress, "a held slot is revoked after this long with no progress of its work (chunks compared, staged, uploaded or filled); revocation aborts but waits for admitted I/O before release") fs.DurationVar(&c.NoProgress, "host-limit-max-hold", c.NoProgress, "deprecated: the same as --host-limit-no-progress (a hold is no longer limited by its age)") } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 91b7d1c809..3221fa911f 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -442,7 +442,7 @@ type CutScheduleStatus struct { TicketDueHostNs int64 `json:",omitempty"` // the waiting cut's host ticket: its due time on the host monotonic clock; absent when not waiting TicketsSkipped uint64 `json:",omitempty"` // earlier tickets the waiting cut passed by the skip rule TicketDropReason string `json:",omitempty"` // why the last ticket was given up before admission, when it was a refusal that waiting cannot fix - CutYields uint64 `json:",omitempty"` // automatic cut attempts that yielded their host slot to a waiting cut (seam) + CutYields uint64 `json:",omitempty"` // automatic cut attempts that yielded their host slot to a waiting cut (not failures) } // 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 6bc826195b..f1204b8822 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -843,6 +843,7 @@ type cutSchedule struct { 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 + yields uint64 // automatic cut attempts that yielded their slot to a waiting cut } // observe takes in, at now, the latest cut the layer reports (any @@ -890,6 +891,13 @@ 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, storage.ErrCutYielded) { + // Not a failure: the slot went to a waiting cut; try again at the + // next poll (on a ticket at the back of the queue). + s.yields++ + s.retryAt = end + return s + } if errors.Is(err, hostlimit.ErrSlotsHeld) { s.slotWaits++ if s.slotWaitSince.IsZero() { @@ -1084,7 +1092,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } s = pol.afterStaging(s, start, time.Now(), err, after.CutSeq, after.StagedChunks-ls.StagedChunks) wait.record(s, ticket) - if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { + if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && !errors.Is(err, storage.ErrCutYielded) && ctx.Err() == nil { if note, stuck := capturePendingNote(err); stuck { log.Printf("durable: %s chunk cut for volume=%s REFUSED: %s (retry in %s)", reason, volumeID, note, s.backoff) } else { @@ -2004,7 +2012,7 @@ func (w *cutWaitSlot) record(s cutSchedule, ticket *hostlimit.Ticket) { } w.mu.Lock() defer w.mu.Unlock() - st := CutScheduleStatus{HostSlotWaits: s.slotWaits, TicketDropReason: w.st.TicketDropReason} + st := CutScheduleStatus{HostSlotWaits: s.slotWaits, CutYields: s.yields, TicketDropReason: w.st.TicketDropReason} if !s.slotWaitSince.IsZero() { st.HostSlotWaitSinceNs = s.slotWaitSince.UnixNano() } diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 106149f3f2..39ef7b704f 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -66,8 +66,9 @@ type Config struct { // FetchSlots caps the chunk fetches in flight on the host, across its // processes (HoldFetch): a guest read waits for a slot, never refused. FetchSlots int - // YieldAfter is S: a Normal hold this old yields its slot at its next - // staging batch when another cut waits (seam). + // YieldAfter is S: a Normal hold at least this old yields its slot at + // its cut's next staging batch when another cut on the host waits (a + // live ticket). A lone hold never yields; an urgent one never does. YieldAfter time.Duration } @@ -503,8 +504,48 @@ func (l *Limiter) Progress(id uint64) { } } -// ShouldYield reports whether the hold id should yield its slot now (seam). -func (l *Limiter) ShouldYield(id uint64) bool { return false } +// ShouldYield reports whether the hold id should yield its slot now: it is +// a Normal hold at least YieldAfter old and another cut on the host waits. +// It takes no lock of the limiter; the waiter probe (the tickets directory) +// runs only once the hold is old enough. +func (l *Limiter) ShouldYield(id uint64) bool { + v, ok := l.leases.Load(id) + if !ok { + return false + } + x := v.(*lease) + if x.class != Normal || time.Since(x.started) < l.cfg.YieldAfter { + return false + } + return l.waiterLive() +} + +// waiterLive reports whether another cut waits on the host: a live ticket in +// the pool (its holder's lock held) that this process has not judged stalled. +// A dead ticket found on the way is reaped, as a waiter's head check does. +func (l *Limiter) waiterLive() bool { + dir := filepath.Join(l.cfg.Directory, ticketsDir) + ents, err := os.ReadDir(dir) + if err != nil { + return false + } + present := make(map[string]bool, len(ents)) + for _, e := range ents { + present[e.Name()] = true + } + stalled := l.stalledTickets(present) + for _, e := range ents { + n := e.Name() + if _, ok := ticketDue(n); !ok || stalled[n] { + continue + } + if reap(filepath.Join(dir, n)) { + continue // its holder exited + } + return true + } + return false +} // expire runs when a hold's timer fires: a hold that progressed within its // window is armed again for the rest of it; one that did not is revoked. The diff --git a/seaweed-block/core/storage/chunk_cut_budget.go b/seaweed-block/core/storage/chunk_cut_budget.go index 5b3159f36d..e7255a2bac 100644 --- a/seaweed-block/core/storage/chunk_cut_budget.go +++ b/seaweed-block/core/storage/chunk_cut_budget.go @@ -5,15 +5,26 @@ import ( "errors" ) -// ErrCutYielded ends a cut attempt that gave its host slot to a waiting cut -// (seam). +// ErrCutYielded ends a cut attempt that gave its host slot to a waiting cut, +// at a staging batch boundary. It is its own outcome, never a failed cut: the +// chunks the attempt staged are kept, and its next attempt stages the rest. var ErrCutYielded = errors.New("storage: the cut yielded its host slot to a waiting cut") -// BudgetYield is a Budget that asks a long hold to yield (seam). +// BudgetYield is a Budget that asks a long hold to yield its slot: +// ShouldYield must be nonblocking and cheap while the hold is young. type BudgetYield interface { ShouldYield(ticket uint64) bool } +// budgetYield is the question a cut asks at each staging batch boundary; nil +// when the Budget never asks a hold to yield. +func budgetYield(b Budget, ticket uint64) func() bool { + if y, ok := b.(BudgetYield); ok { + return func() bool { return y.ShouldYield(ticket) } + } + return nil +} + // Budget is the host limiter seam. Admit runs before staging or the cut // barrier and reserves the configured payload ceiling. ReserveCOW accounts // each saved chunk until Release. ReserveCOW and Release must be nonblocking diff --git a/seaweed-block/core/storage/chunk_cut_observation.go b/seaweed-block/core/storage/chunk_cut_observation.go index cea4e073d7..bc69ca172d 100644 --- a/seaweed-block/core/storage/chunk_cut_observation.go +++ b/seaweed-block/core/storage/chunk_cut_observation.go @@ -22,11 +22,20 @@ type cutAttemptObservation struct { // progress renews the attempt's host hold (set at its admission, before // any worker starts; nil without a budget). progress func() - spans [cutWorkSpanCount]atomic.Int64 - counts [cutWorkCountCount]atomic.Int64 + // yield asks the attempt's host hold whether to give its slot to a + // waiting cut (set at its admission; nil without a yielding budget). + yield func() bool + spans [cutWorkSpanCount]atomic.Int64 + counts [cutWorkCountCount]atomic.Int64 } type cutObservationKey struct{} +// shouldYield asks, at a staging batch boundary, whether the attempt gives +// its host slot to a waiting cut. +func (w *cutAttemptObservation) shouldYield() bool { + return w != nil && w.yield != nil && w.yield() +} + // progressed reports one unit of the attempt's work to its host hold. func (w *cutAttemptObservation) progressed() { if w != nil && w.progress != nil { diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index aa522e46ae..580ffddaec 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1122,6 +1122,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } budget = &cutBudgetReservation{budget: host, ticket: ticket, ctx: ctx} work.progress = budgetProgress(host, ticket) + work.yield = budgetYield(host, ticket) defer func() { if err != nil { err = errors.Join(err, context.Cause(budgetCtx)) @@ -1987,6 +1988,8 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error reason = "fenced" case errors.Is(err, errChunkLayerDetached): reason = "detached" + case errors.Is(err, ErrCutYielded): + l.stats.CutsYielded++ // its own outcome: never a failed cut default: l.stats.CutsFailed++ l.noteCutFailureLocked(err, abortReason) @@ -2184,6 +2187,11 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap if hook := l.testAfterStageHook; hook != nil { hook(round) } + // A batch boundary: a long hold gives its slot to a waiting cut here, + // keeping what it staged (its next attempt stages only the rest). + if cutObservation(ctx).shouldYield() { + return nil, ErrCutYielded + } } return staged, nil } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 1fef53a31d..dc02640da8 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -510,7 +510,7 @@ type chunkLayerStats struct { CutsNoop uint64 // cuts with nothing new (no CAS) CutsFailed uint64 // every other cut failure CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached - CutsYielded uint64 // attempts that gave their host slot to a waiting cut (seam) + CutsYielded uint64 // attempts that gave their host slot to a waiting cut at a staging batch boundary CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload CASConflicts uint64 // HEAD CAS precondition failures CASUnknown uint64 // HEAD CAS results still unresolved after the re-read diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5f715d47af..a2c950cd30 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -509,7 +509,7 @@ snapshot lifetime; local persistence does not bypass it. ### M7. Host background-cut admission -`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, after the limiter's first fetch checked the host's configuration; with all held they wait, unordered and bounded by the read's own timeout (a read miss answers pending) (`INV-HOST-FETCH-CAP-001`). Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. +`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, after the limiter's first fetch checked the host's configuration; with all held they wait, unordered and bounded by the read's own timeout (a read miss answers pending) (`INV-HOST-FETCH-CAP-001`). A Normal hold at least `YieldAfter` old (default 5 min) yields its slot at its cut's next staging batch while another cut on the host holds a live ticket (`INV-HOST-CUT-YIELD-001`): the attempt ends as `yielded`, keeps what it staged, and its next attempt takes a ticket at the back; a lone hold never yields. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. **Waiting (timer cuts).** A timer cut waiting for a slot holds a ticket: a file in `tickets/` named by its due time on the host monotonic clock, locked while it waits; it is taken by create, lock, and a re-check that the path still names the locked file. It is admitted only when no earlier ticket is live: an earlier ticket whose lock can be taken (its process exited) is removed by lock, re-check, unlink, unlock; a live one is passed only after the waiter has seen it stay ahead for 2 s of time with a normal slot free and no urgent work pending, summed across polls (a busy period pauses the count; the skip rule; it can be wrong about a slow holder: ticket order is fairness only, the slot lock is the exclusion). Only the earliest live earlier ticket not yet judged stalled is observed; a process keeps its judgement, for its later tickets too, until that ticket's file disappears, so one stalled ticket costs one skip, not one per hand-off. Admission consumes the ticket; a success elsewhere, fencing, Close, exit, not attempting (backoff, spacing, reconciling), or a refusal that waiting cannot fix drop it (the reason is reported). A refusal for held slots, pending urgent work, an earlier ticket or a held configuration lock is a wait. A timer cut that meets another capture holding the capture lock waits for it and is then skipped (that capture restarted the timer); while it waits, other waiters judge its ticket stalled after the skip time, once. @@ -1004,6 +1004,7 @@ Notes: | `INV-HOST-CUT-BUDGET-SETTLE-001` | A slot's OS lock is released only after its cut's workers settle and Release is called; cancellation, hold expiry and limiter Close abort the cut but keep the slot until then. | M7 draining → joined → released | `core/hostlimit/limiter.go` `Release`, `releaseLoop`, `revoke`, `Close`; `core/storage/chunk_layer.go` `captureLocked` | `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot` (`core/hostlimit/limiter_test.go`); `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`) | `HostBudget` HeldUntilJoined | ACTIVE | | `INV-HOST-HOLD-NO-PROGRESS-001` | A held slot is revoked only after its no-progress window passes with no reported progress of its work (a chunk compared, staged or uploaded by its cut): work that keeps progressing is never revoked, and a stalled hold is revoked within the window. | M7 admitted → draining (revoked) | `core/hostlimit/limiter.go` `Admit`, `Progress`, `expire`; `core/storage/chunk_cut_budget.go` `BudgetProgress`, `budgetProgress`; `core/storage/chunk_cut_observation.go` `progressed`; `core/storage/chunk_layer.go` `captureLocked` | `TestStalledHoldIsRevokedWithinTheWindow`, `TestProgressRenewsTheHold` (`core/hostlimit/limiter_progress_test.go`); `TestProgressRacingTheExpiryIsHonoured`, `TestProgressDoesNotWaitForTheLimiterLock`, `TestProgressStampIsMonotonicElapsed` (`core/hostlimit/limiter_review_test.go`); `TestCutReportsProgressToItsBudget` (`core/storage/chunk_cut_hold_progress_test.go`) | SlotShare (its progress-window rule; the share rule is a later change) | ACTIVE | | `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only; a limiter's first fetch checks the host configuration (ErrConfig on a mismatch). With all held it waits, never refused: unordered, bounded by its context alone. Only non-blocking tries: an ended wait leaves nothing. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `checkFetchConfig`, `waitFetch`; `core/hostlimit/limiter.go` `configGuard`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossLimiters`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestHoldFetchFirstFetchChecksTheHostConfiguration`, `TestHoldFetchSlotDiesWithItsProcess`, `TestHoldFetchEndedWaitsLeaveNothingBehind`, `TestHoldFetchCancelledAtTheHandoffHoldsNothing`, `TestHoldFetchAPassedWaiterEndsByItsDeadline` (`core/hostlimit/fetch_review_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE | +| `INV-HOST-CUT-YIELD-001` | A Normal hold at least YieldAfter old yields its slot at its cut's next staging batch only while another cut on the host holds a live ticket it has not judged stalled; the attempt ends as yielded, never a failure, and keeps what it staged. A lone or urgent hold never yields. | M7 admitted → released (yielded) | `core/hostlimit/limiter.go` `ShouldYield`, `waiterLive`; `core/storage/chunk_layer.go` `stage`; `core/storage/chunk_cut_budget.go` `ErrCutYielded`, `budgetYield`; `core/frontend/durable/provider_chunk.go` `cutPolicy.after` | `TestShouldYieldOnlyAfterSWithALiveWaiter` (`core/hostlimit/yield_test.go`); `TestCutYieldsAtABatchBoundaryAndKeepsItsStaging` (`core/storage/chunk_cut_yield_test.go`); `TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart` (`core/frontend/durable/cut_loop_yield_test.go`) | SlotShareN (yield on the waiting probe, a new ticket at the back); SlotShare rows 189 to 193 | ACTIVE | | `INV-HOST-CUT-BUDGET-CONFIG-001` | A busy configuration lock or a mismatched pool configuration refuses every class, urgent included, with no fallback. | M7 free → admitted (refused) | `core/hostlimit/limiter.go` `pool`, `Admit` | `TestConfigurationLockContentionRefusesAllClasses` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | | `INV-HOST-CUT-BUDGET-FALLBACK-001` | Only urgent admissions (urgent move-final cuts and named seals) proceed while the pool is unavailable, on a per-process fallback that claims no host-wide bound, leaves uploads unpaced while only fallback leases live, and is reported as fallback while any such lease lives. | M7 free → admitted (pool unavailable) | `core/hostlimit/limiter.go` `Admit`, `releaseLoop`, `WaitUpload` | `TestUnusablePoolClassPolicy`, `TestLastFallbackReleaseClearsActiveStatus`, `TestUrgentFallbackUploadIsNotPaced`, `TestFallbackDoesNotUnpaceAHealthyLease`, `TestConfigurationLockFailurePreservesPoolPolicy` (`core/hostlimit/limiter_test.go`); `TestChunkControl_NamedSnapshotUsesUrgentFallback` (`core/host/volume/chunk_control_adapter_test.go`) | `HostBudget` (fallback excluded) | ACTIVE | | `INV-HOST-CUT-BUDGET-PACING-001` | A process's upload pacing debt carries across its own leases, and a new process starts with no debt. | M7 admitted (upload pacing) | `core/hostlimit/limiter.go` `WaitUpload` | `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 044a5550d7..13c0502601 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -17,6 +17,9 @@ These notes collect v1.1's changes as they land; v1.1 is not released. across the host's processes, so a mass move puts at most that many in flight. A read of an absent chunk waits for a slot, in no set order and bounded by its read-miss timeout, and is never refused. A process's first fetch checks the host's `configuration.json` as a cut admission does, so a fetch-only process with other flags is refused too. +- A normal cut that has held its host slot for `--host-limit-yield-after` (default 5 min) gives the slot to a waiting + cut at its next staging batch, keeping what it staged; its next attempt queues behind the waiters. A lone cut never + yields, and status counts yields apart from failures (`CutYields`). ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was From 495bbf8fe26a39a19709c009b5840a1b851489fc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:04:08 -0800 Subject: [PATCH 3/3] docs: status schema carries the cut yield counters Regenerated with STATUS_SCHEMA_UPDATE=1: Chunk.Stats.CutsYielded and Chunk.CutSchedule.CutYields. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/status-schema.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index c646dd92df..36c0315fe7 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -255,6 +255,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) | | `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure | | `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached | +| `Volumes[].Chunk.Stats.CutsYielded` | uint64 | attempts that gave their host slot to a waiting cut at a staging batch boundary | | `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload | | `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures | | `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read | @@ -339,6 +340,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.CutSchedule.TicketDueHostNs` | int64 | the waiting cut's host ticket: its due time on the host monotonic clock; absent when not waiting (omitted when empty) | | `Volumes[].Chunk.CutSchedule.TicketsSkipped` | uint64 | earlier tickets the waiting cut passed by the skip rule (omitted when empty) | | `Volumes[].Chunk.CutSchedule.TicketDropReason` | string | why the last ticket was given up before admission, when it was a refusal that waiting cannot fix (omitted when empty) | +| `Volumes[].Chunk.CutSchedule.CutYields` | uint64 | automatic cut attempts that yielded their host slot to a waiting cut (not failures) (omitted when empty) | | `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) |