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